text:
static const NSString * const testManagerEnv = @"TESTMANAGERD_SIM_SOCK";

@interface BPTestDaemonConnection()<XCTestManager_IDEInterface>
@property (nonatomic, strong) id<XCTestManager_IDEInterface> interface;
@property (nonatomic, assign) BOOL connected;
@end

@implementation BPTestDaemonConnection

- (instancetype)initWithDevice:(BPSimulator *)simulator andInterface:(id<XCTestManager_IDEInterface>)interface {
    self = [super init];
    if (self) {
        self.simulator = simulator;
        self.interface = interface;
    }
    return self;
}

- (void)connectWithTimeout:(NSTimeInterval)timeout {
    [self connect];
    // Pool connection status till it passes.
    [BPUtils runWithTimeOut:timeout until:^BOOL{
        return self.connected;
    }];
}

- (void)connect {
    DTXTransport *transport = [self connectTransport];
    DTXConnection *connection = [[objc_lookUpClass("DTXConnection") alloc] initWithTransport:transport];
    [connection registerDisconnectHandler:^{
        [BPUtils printInfo:INFO withString:@"Daemon connection Disconnected."];
    }];
    [connection resume];

    DTXProxyChannel *channel = [connection
                                makeProxyChannelWithRemoteInterface:@protocol(XCTestManager_DaemonConnectionInterface)
                                exportedInterface:@protocol(XCTestManager_IDEInterface)];

    [channel setExportedObject:self queue:dispatch_get_main_queue()];
    id<XCTestManager_DaemonConnectionInterface> daemonProxy = (id<XCTestManager_DaemonConnectionInterface>)channel.remoteObjectProxy;
    DTXRemoteInvocationReceipt *receipt = [daemonProxy _IDE_initiateControlSessionForTestProcessID:@(self.testRunnerPid) protocolVersion:@(BP_DAEMON_PROTOCOL_VERSION)];
    [receipt handleCompletion:^(NSNumber *version, NSError *error) {
        if (error) {
            [BPUtils printInfo:ERROR withString:@"Error with daemon connection: %@", [error localizedDescription]];
            return;
        }
        NSInteger daemonProtocolVersion = version.integerValue;
        [BPUtils printInfo:INFO withString:@"Daemon ready to execute test plan (protocol version %ld)", (long)daemonProtocolVersion];
        self.connected = YES;
    }];
}

- (int)testManagerSocket {
    int socketFD = socket(AF_UNIX, SOCK_STREAM, 0);
    NSString *socketString = [self.simulator.device getenv:testManagerEnv error:nil];
    const char *socketPath = socketString.UTF8String;

    struct sockaddr_un remote;
    remote.sun_family = AF_UNIX;
    strncpy(remote.sun_path, socketPath, 104);
    socklen_t length = (socklen_t)(strnlen(remote.sun_path, 1024) + sizeof(remote.sun_family) + sizeof(remote.sun_len));
    if (connect(socketFD, (struct sockaddr *)&remote, length) == -1) {
        [BPUtils printInfo:ERROR withString:@"ERROR connecting socket"];
    }
    return socketFD;
}

- (DTXTransport *)connectTransport {
    int socketFD = [self testManagerSocket];
    DTXTransport *transport = [[objc_lookUpClass("DTXSocketTransport") alloc] initWithConnectedSocket:socketFD disconnectAction:^{
        [BPUtils printInfo:INFO withString:@"DTXSocketTransport disconnected"];
    }];
    return transport;
}

#pragma mark - XCTestManager_IDEInterface protocol

#pragma mark Process Launch Delegation

- (id)_XCT_launchProcessWithPath:(NSString *)path bundleID:(NSString *)bundleID arguments:(NSArray *)arguments environmentVariables:(NSDictionary *)environment {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_launchProcessWithPath: %@, bundleID: %@, arguments: %@, environmentVariables: %@", path, bundleID, arguments, environment];
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_getProgressForLaunch:(id)token {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_getProgressForLaunch token: %@", token];
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_terminateProcess:(id)token {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_terminateProcess token: %@", token];
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_didBeginExecutingTestPlan {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_didBeginExecutingTestPlan"];
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_didFinishExecutingTestPlan {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_didFinishExecutingTestPlan"];
    return [self handleUnimplementedXCTRequest:_cmd];
}

#pragma mark iOS 10.x
- (id)_XCT_handleCrashReportData:(NSData *)arg1 fromFileWithName:(NSString *)arg2 {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_handleCrashReportData: %@, fromFileWithName: %@", arg1, arg2];
    return nil;
}

- (id)_XCT_didBeginInitializingForUITesting {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_didBeginInitializingForUITesting"];
    return nil;
}

- (id)_XCT_initializationForUITestingDidFailWithError:(NSError *)error {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_initializationForUITestingDidFailWithError : %@", error];
    return nil;
}

- (id)_XCT_testBundleReadyWithProtocolVersion:(NSNumber *)protocolVersion minimumVersion:(NSNumber *)minimumVersion {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testBundleReadyWithProtocolVersion : %@, minimumVersion: %@", protocolVersion, minimumVersion];
    return nil;
}

#pragma mark Test Suite Progress

- (id)_XCT_testSuite:(NSString *)tests didStartAt:(NSString *)time {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testSuite : %@, didStartAt: %@", tests, time];
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_testCaseDidStartForTestClass:(NSString *)testClass method:(NSString *)method {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testCaseDidStartForTestClass : %@, method: %@", testClass, method];
    return nil;
}

- (id)_XCT_testCaseDidFailForTestClass:(NSString *)testClass method:(NSString *)method withMessage:(NSString *)message file:(NSString *)file line:(NSNumber *)line {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testCaseDidFailForTestClass : %@, method: %@, withMessage: %@, file: %@, line: %@", testClass, method, message, file, line];
    return nil;
}

- (id)_XCT_logDebugMessage:(NSString *)debugMessage {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_logDebugMessage: %@", debugMessage];
    return nil;
}

- (id)_XCT_logMessage:(NSString *)message {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_logMessage: %@", message];
    return nil;
}

- (id)_XCT_testCaseDidFinishForTestClass:(NSString *)testClass method:(NSString *)method withStatus:(NSString *)statusString duration:(NSNumber *)duration {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testCaseDidFinishForTestClass: %@, method: %@, withStatus: %@, duration: %@", testClass, method, statusString, duration];
    return nil;
}

- (id)_XCT_testSuite:(NSString *)arg1 didFinishAt:(NSString *)arg2 runCount:(NSNumber *)arg3 withFailures:(NSNumber *)arg4 unexpected:(NSNumber *)arg5 testDuration:(NSNumber *)arg6 totalDuration:(NSNumber *)arg7 {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testSuite: %@, didFinishAt: %@, runCount: %@, withFailures: %@, unexpected: %@, testDuration: %@, totalDuration: %@", arg1, arg2, arg3, arg4, arg5, arg6, arg7];
    return nil;
}

- (id)_XCT_testCase:(NSString *)arg1 method:(NSString *)arg2 didFinishActivity:(XCActivityRecord *)arg3 {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testCase: %@, method: %@, didFinishActivity: %@", arg1, arg2, arg3];
    return nil;
}

- (id)_XCT_testCase:(NSString *)arg1 method:(NSString *)arg2 willStartActivity:(XCActivityRecord *)arg3 {
    [BPUtils printInfo:DEBUGINFO withString:@"BPTestDaemonConnection_XCT_testCase: %@, method: %@, willStartActivity: %@", arg1, arg2, arg3];
    return nil;
}

#pragma mark - Unimplemented

- (id)_XCT_nativeFocusItemDidChangeAtTime:(NSNumber *)arg1 parameterSnapshot:(XCElementSnapshot *)arg2 applicationSnapshot:(XCElementSnapshot *)arg3 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedEventNames:(NSArray *)arg1 timestamp:(NSNumber *)arg2 duration:(NSNumber *)arg3 startLocation:(NSDictionary *)arg4 startElementSnapshot:(XCElementSnapshot *)arg5 startApplicationSnapshot:(XCElementSnapshot *)arg6 endLocation:(NSDictionary *)arg7 endElementSnapshot:(XCElementSnapshot *)arg8 endApplicationSnapshot:(XCElementSnapshot *)arg9 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedOrientationChange:(NSString *)arg1 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedFirstResponderChangedWithApplicationSnapshot:(XCElementSnapshot *)arg1 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_exchangeCurrentProtocolVersion:(NSNumber *)arg1 minimumVersion:(NSNumber *)arg2 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedKeyEventsWithApplicationSnapshot:(XCElementSnapshot *)arg1 characters:(NSString *)arg2 charactersIgnoringModifiers:(NSString *)arg3 modifierFlags:(NSNumber *)arg4 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedEventNames:(NSArray *)arg1 duration:(NSNumber *)arg2 startLocation:(NSDictionary *)arg3 startElementSnapshot:(XCElementSnapshot *)arg4 startApplicationSnapshot:(XCElementSnapshot *)arg5 endLocation:(NSDictionary *)arg6 endElementSnapshot:(XCElementSnapshot *)arg7 endApplicationSnapshot:(XCElementSnapshot *)arg8 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedKeyEventsWithCharacters:(NSString *)arg1 charactersIgnoringModifiers:(NSString *)arg2 modifierFlags:(NSNumber *)arg3 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedEventNames:(NSArray *)arg1 duration:(NSNumber *)arg2 startElement:(XCAccessibilityElement *)arg3 startApplicationSnapshot:(XCElementSnapshot *)arg4 endElement:(XCAccessibilityElement *)arg5 endApplicationSnapshot:(XCElementSnapshot *)arg6 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedEvent:(NSString *)arg1 targetElementID:(NSDictionary *)arg2 applicationSnapshot:(XCElementSnapshot *)arg3 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_recordedEvent:(NSString *)arg1 forElement:(NSString *)arg2 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_testMethod:(NSString *)arg1 ofClass:(NSString *)arg2 didMeasureMetric:(NSDictionary *)arg3 file:(NSString *)arg4 line:(NSNumber *)arg5 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_testCase:(NSString *)arg1 method:(NSString *)arg2 didStallOnMainThreadInFile:(NSString *)arg3 line:(NSNumber *)arg4 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_testMethod:(NSString *)arg1 ofClass:(NSString *)arg2 didMeasureValues:(NSArray *)arg3 forPerformanceMetricID:(NSString *)arg4 name:(NSString *)arg5 withUnits:(NSString *)arg6 baselineName:(NSString *)arg7 baselineAverage:(NSNumber *)arg8 maxPercentRegression:(NSNumber *)arg9 maxPercentRelativeStandardDeviation:(NSNumber *)arg10 file:(NSString *)arg11 line:(NSNumber *)arg12 {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (id)_XCT_testBundleReady {
    return [self handleUnimplementedXCTRequest:_cmd];
}

- (NSString *)unknownMessageForSelector:(SEL)aSelector
{
    return [NSString stringWithFormat:@"Received call for unhandled method (%@). Probably you should have a look at _IDETestManagerAPIMediator in IDEFoundation.framework and implement it. Good luck!", NSStringFromSelector(aSelector)];
}

// This will add more logs when unimplemented method from XCTestManager_IDEInterface protocol is called
- (id)handleUnimplementedXCTRequest:(SEL)aSelector {
    [BPUtils printInfo:DEBUGINFO withString:@"TMD: unimplemented: %@", aSelector];
    NSAssert(nil, [self unknownMessageForSelector:_cmd]);
    return nil;
}

@end


text:
layout: post
date: 2015-08-03
title: "Jovani Sleeveless Jersey Gown 89983 Sleeveless Sweep/Brush Train Sheath/Column"
category: Jovani
tags: [Jovani ,Jovani,Sheath/Column,Illusion,Sweep/Brush Train,Sleeveless]
---
### Jovani Sleeveless Jersey Gown 89983
Just **$469.98**
###   Sleeveless Sweep/Brush Train Sheath/Column

BRANDS	Jovani

Silhouette	Sheath/Column

Neckline	Illusion

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/jovani-/39965-jovani-sleeveless-jersey-gown-89983.html](https://www.readybrides.com/en/jovani-/39965-jovani-sleeveless-jersey-gown-89983.html)

redpajama_set_name: RedPajamaGithub


text:
namespace storage
{

void CountryNameGetter::SetLocale(string const & locale)
{
  m_getCurLang = platform::GetTextByIdFactory(platform::TextSource::Countries, locale);
}

void CountryNameGetter::SetLocaleForTesting(string const & jsonBuffer, string const & locale)
{
  m_getCurLang = platform::ForTestingGetTextByIdFactory(jsonBuffer, locale);
}

string CountryNameGetter::operator()(TCountryId const & countryId) const
{
  ASSERT(!countryId.empty(), ());

  if (m_getCurLang == nullptr)
    return countryId;

  string name = (*m_getCurLang)(countryId);
  if (name.empty())
    return countryId;

  return name;
}

string CountryNameGetter::GetLocale() const
{
  if (m_getCurLang == nullptr)
    return string();

  return m_getCurLang->GetLocale();
}

}  // namespace storage


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

namespace RealVirtuality.Media.Drawing.PAA.TaggUtil
{
    public class AverageColorTag : TagBase
    {
        internal const string NAME_REVERSED = "GGATCGVA";
        internal const string NAME = "AVGCTAGG";
        internal const int DATALENGTH = 4;

        public Color Color
        {
            get { return Color.FromArgb(this.Data.DataRaw[0], this.Data.DataRaw[3], this.Data.DataRaw[2], this.Data.DataRaw[1]); }
            set
            {
                this.Data.DataRaw[0] = value.A;
                this.Data.DataRaw[1] = value.B;
                this.Data.DataRaw[2] = value.G;
                this.Data.DataRaw[3] = value.R;
            }
        }
        internal AverageColorTag(Tagg t) : base(t, NAME, DATALENGTH)
        {
            if (t.Name != this.Name.Substring(0, NAMELENGTH) || t.DataLength != this.Length)
            {
                throw new ArgumentException("Invalid Tagg provided", "t");
            }
        }
        public static AverageColorTag Create(Color c)
        {
            var t = new Tagg();
            t.Name = NAME;
            t.Signature = Tagg.DEFAULT_SIGNATURE;
            t.SetData(new byte[DATALENGTH]);
            var val = new AverageColorTag(t);
            val.Color = c;
            return val;
        }
    }
}


text:
package br.com.proesis.avaliacoes.view;

import br.com.proesis.avaliacoes.entity.EntityManageable;
import br.com.softop.boletim.util.exception.BusinessException;
import br.com.proesis.avaliacoes.view.AbstractManager.PersistenceAction;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.hibernate.Session;

/**
 *
 * @author Danilo Souza Almeida
 */
public abstract class GenericCrudBean<E extends EntityManageable> extends AbstractManager {

    private static final long serialVersionUID = 1L;

    public static enum CurrentState {
        EDIT,
        INSERT,
        SEARCH
    }

    private Class<E> classEntity;
    private E entity;
    private List<E> entitys;

    private CurrentState currentState;

    public GenericCrudBean(){
        try {
            entity = getClassEntity().newInstance();
            entitys = new ArrayList<E>();
            setCurrentState(CurrentState.SEARCH);
        } catch (InstantiationException ex) {
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void newRegistre(ActionEvent actionEvent){
        try {
            entity = getClassEntity().newInstance();
            setCurrentState(CurrentState.INSERT);
        } catch (InstantiationException ex) {
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void saveWithoutReturnToSearch(ActionEvent actionEvent){
        try {
            save();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Informação", "Salvo com sucesso!"));
        } catch (BusinessException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso", ex.getMessage()));
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", "Desculpe, mas parece que ocorreu ao tentar salvar o objeto!"));
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void save() throws BusinessException, Exception{
            doInTransaction(new PersistenceActionWithoutResult() {
                @Override
                public void execute(Session s) throws BusinessException {
                    entity.setSession(s);
                    entity.save();
                }
            });
            if(entitys == null){
                entitys = new ArrayList<E>();
            }
            if(getEntitys().contains(entity)){
                getEntitys().remove(entity);
            }
            getEntitys().add(0, entity);
            entity = getClassEntity().newInstance();
    }

    public void save(ActionEvent actionEvent){
        try {
            save();
            setCurrentState(CurrentState.SEARCH);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Informação", "Salvo com sucesso!"));
        } catch (BusinessException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso", ex.getMessage()));
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", "Desculpe, mas parece que ocorreu ao tentar salvar o objeto!"));
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void delete(ActionEvent actionEvent){
        try {
            doInTransaction(new PersistenceActionWithoutResult() {
                @Override
                public void execute(Session s) throws BusinessException {
                    entity.setSession(s);
                    entity.remove();
                }
            });
            getEntitys().remove(getEntity());
            newRegistre(actionEvent);
            search(actionEvent);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Removido com sucesso!!"));
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", "Desculpe, mas parece que ocorreu um erro na aplicação!"));
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void edit(E entity){
        this.entity = entity;
        setCurrentState(CurrentState.EDIT);
    }

    public void search(ActionEvent event){
        try {
            if(currentState.equals(CurrentState.SEARCH)){
                entitys = doInTransaction(new PersistenceAction<List<E>>() {
                    @Override
                    public List<E> execute(Session s) throws BusinessException {
                        return s.createCriteria(getClassEntity()).list();
                    }
                });
                if(entitys == null || entitys.isEmpty()){
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso", "Nenhum dado encontrado!"));
                }
            } else {
                    entity = getClassEntity().newInstance();
                    setCurrentState(CurrentState.SEARCH);
            }
        } catch (BusinessException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso", ex.getMessage()));
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", "Desculpe, mas parece que ocorreu um erro na aplicação!"));
            Logger.getLogger(GenericBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //Getters and setters
    public String getCurrentStateName() {
        return currentState.name();
    }
    public CurrentState getCurrentState() {
        return currentState;
    }
    public void setCurrentState(CurrentState currentState) {
        this.currentState = currentState;
    }

    public E getEntity() {
        return entity;
    }
    public void setEntity(E entity) {
        this.entity = entity;
    }

    public List<E> getEntitys() {
        return entitys;
    }
    public void setEntitys(List<E> entitys) {
        this.entitys = entitys;
    }

    public Class<E> getClassEntity() {
        classEntity = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return classEntity;
    }

}


text:
Auto Scroll to Test.

Install the plugin and opening any file using CMD + P would reveal the same in the side bar!


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"
><TITLE
>Yaiba.Sugar</TITLE
><LINK HREF="haddock.css" REL="stylesheet" TYPE="text/css"
>

Yaiba.Sugar

data Sugar ord


text:
package com.arellomobile.mvp.compiler;

import java.io.IOException;
import java.util.regex.Pattern;

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

import org.junit.Test;

import javax.tools.Diagnostic;

import static org.junit.Assert.fail;

/**
 * Date: 26.02.2016
 * Time: 17:38
 *
 * @author Savin Mikhail
 */
public class ViewStateProviderClassTest extends CompilerTest {
	@Test
	public void positiveViewStateProvider() {
		try {
			assertCompilationResultIs(ImmutableTable.<Diagnostic.Kind, Integer, Pattern>of(), ImmutableList.of(getString("com/arellomobile/mvp/presenter/PositiveViewStateProviderPresenter$$ViewStateProvider.java")));
		} catch (IOException e) {
			fail(e.getLocalizedMessage());
		}
	}
}


text:
package com.bct.gpstracker.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2015/9/10 0010.
 */
public class TextMoveLayout extends ViewGroup {
    public TextMoveLayout(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public TextMoveLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public TextMoveLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // TODO Auto-generated method stub

    }
}


text:
//
// Copyright 2011 Kuali Foundation, Inc. Licensed under the
// Educational Community License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may
// obtain a copy of the License at
//
// http://www.opensource.org/licenses/ecl2.php
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
//
package org.kuali.continuity.admin.dao;

import java.util.Map;

import org.kuali.continuity.admin.domain.BaseAdminDomainObject;
import org.kuali.continuity.admin.domain.BaseAdminOrderedDomainObject;
import org.kuali.continuity.admin.main.client.NamedItem;

/**
 * Service Interface for Abstract Factory for DAOs and related family items.
 * @author richkatz
 *
 */
public interface ItemDaoFactory {

	public  BaseAdminOrderedDAO getDao(String itemRootName);
	public  SimpleAdminDao getAdminDao(String itemRootName);
	public  BaseAdminOrderedDomainObject getItem(String itemRootName);

	public  void dispMap();
	public Map getItemMap();
	NamedItem getNamedItem(String rootName);
	BaseAdminDomainObject getDomainItem(String domainName);

}


text:
var editor;
var katex = require('parse-katex');
var hljs = require('highlight.js');
var css = require('css');

Polymer('markdown-editor', {
  syncScrollSetting: true,
  renderKaTeX: false,
  renderKaTeXChanged: function() {
    this.updatePreview();
  },
  markdown: '',
  useMaruku: false,
  highlightSyntax: false,
  customCSS: '',
  theme: '',
  themes: JSON.parse(themes),
  themeNumber: 0,

  customCSSChanged: function() {
    this.parseCSS(this.customCSS);
  },

  highlightSyntaxChanged: function() {
    this.updateHighlighting()
  },

  themeNumberChanged: function(){
    this.updateHighlighting()
  },

  updateHighlighting: function() {
    this.updatePreview();
    this.theme = this.themes[Object.keys(this.themes)[parseInt(this.themeNumber)]]
  },

  useMarukuChanged: function() {
    this.updatePreview();
  },

  convertMarkdown: function(x) {
    if (this.useMaruku === true) {
      return markdown.toHTML(x,'Maruku');
    } else {
      return markdown.toHTML(x);
    }
  },

  parseCode: function(html, pk, sh) {
    // Split
 tags and highlight any code.
    var parsedHtml = splitHtml(html, 'pre')
    for (var i = 0; i < parsedHtml.length; i += 1) {
      if (i % 2 === 0 && pk) {
        parsedHtml[i] = katex.renderLaTeX(parsedHtml[i])
      } else if (i % 2 === 1 && sh) {
        var code = parsedHtml[i].slice(11, -13);
        parsedHtml[i] = '
' + hljs.highlightAuto(code.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&')).value + '
';
      }
    }
    parsedHtml = parsedHtml.join('')
    return parsedHtml
  },

  updatePreview: function() {
    if (this.renderKaTeX === true || this.highlightSyntax === true) {
      this.injectBoundHTML(this.parseCode(this.convertMarkdown(this.markdown), this.renderKaTeX, this.highlightSyntax), this.$.preview);
    } else {
      this.injectBoundHTML(this.convertMarkdown(this.markdown), this.$.preview);
    }

    var cursor = this.$.markdown.selectionStart;
    var n = this.markdown.length;
    var secondLast = this.markdown.slice(n - 2, n - 1);
    if (cursor === n && secondLast === '\n') {
      $(this.$.markdown).scrollTop(this.$.markdown.scrollHeight);
      if (this.syncScrollSetting === true) {
        $(this.$.preview).scrollTop(this.$.preview.scrollHeight);
      }
    }
  },

  markdownChanged: function() {
    this.updatePreview();
  },

  syncScroll: function() {
    if (this.syncScrollSetting === true) {
      var wrapperHeight = this.$.markdown.style.height;
      var innerHeight = this.$.markdown.scrollHeight;
      var previewHeight = this.$.preview.scrollHeight;
      var ratio = (innerHeight - wrapperHeight) / (previewHeight - wrapperHeight);
      var previewPosition = $(this.$.markdown).scrollTop() * ratio;
      $(this.$.preview).scrollTop(previewPosition);
    }
  },
  markdownFont: function(value) {
    if (value === true) {
      return 'Droid Sans Mono';
    } else {
      return 'Open Sans';
    }
  },

  parseCSS: function(originalCSS) {
    // Parse the css and make the selectors apply only to the preview pane
    var parsedCSS = css.parse(originalCSS, {silent: true});
    var rules = parsedCSS.stylesheet.rules;
    for (var i = 0; i < rules.length; ++i) {
      var sel = rules[i].selectors;
      for (var j = 0; j < sel.length; ++j) {
        sel[j] = '#preview ' + sel[j]
      }
      rules[i].selectors = sel;
    }
    parsedCSS.stylesheet.rules = rules;
    var newCSS = css.stringify(parsedCSS);
    // Inject the css into the page
    this.injectBoundHTML(newCSS, this.$.customStyle)
  },

  copyPreview: function() {
    var copyFrom = $('<textarea/>');
    copyFrom.text(this.convertMarkdown(editor.markdown));
    $('body').append(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    copyFrom.remove();
    document.querySelector('#toast').show();
  },
  ready: function() {
    editor = this;
    this.$.preview.addEventListener('click',this.copyPreview.bind(this));
    this.$.markdown.addEventListener('scroll',this.syncScroll.bind(this));

    this.$.markdown.addEventListener('keydown', function(e) {
      var keyCode = e.keyCode || e.which;

      if (keyCode === 9) {
        e.preventDefault();
        var start = $(this).get(0).selectionStart;
        var end = $(this).get(0).selectionEnd;

        // set textarea value to: text before caret + tab + text after caret
        $(this).val($(this).val().substring(0, start) + '    ' + $(this).val().substring(end));

        // put caret at right position again
        $(this).get(0).selectionStart =
        $(this).get(0).selectionEnd = start + 4;
      }
    });
  }
});


text:
require 'rubygems'
require 'rjb'

class_path = Dir[File.expand_path(File.dirname(__FILE__) + '/../../lib/htmlunit') + '/*.jar'].join(':')
Rjb::load(class_path)

# klass = Rjb::import('java.lang.String')
Arrays = Rjb::import('java.util.Arrays')
WebResponseData = Rjb::import('com.gargoylesoftware.htmlunit.WebResponseData')

# WebResponseData.getConstructors.each do |method|
#   params = method.getParameterTypes.map { |type| type.getName }.join(', ')
#   puts "#{method.getName}(#{params})"
# end

headers = Arrays.asList([])

# com.gargoylesoftware.htmlunit.WebResponseData([B, int, java.lang.String, java.util.List)
signature = '[B;I;Ljava.lang.String;Ljava.util.List;'
WebResponseData.new_with_sig(signature, 'foo'.split(/./), 1, "", headers)


text:
package com.evilco.flowerpot.proxy.configuration.xml;

import com.evilco.configuration.xml.annotation.Comment;
import com.evilco.configuration.xml.annotation.Property;
import com.evilco.configuration.xml.annotation.PropertyWrapper;
import com.evilco.flowerpot.proxy.server.listener.ServerListener;

public class XmlServerListener extends ServerListener {

	/**
	 * Indicates whether the proxy is enabled.
	 */
	@Comment ("Defines whether servers are available via this listener.")
	@PropertyWrapper ("protocols")
	@Property ("proxy")
	public Boolean proxyEnabled = false;

	/**
	 * Indicates whether server query is enabled.
	 */
	@Comment ("Defines whether server query is available via this listener.")
	@PropertyWrapper ("protocols")
	@Property ("query")
	public Boolean queryEnabled = false;

	/**
	 * Stores the listener hostname.
	 */
	@Comment ("Specifies the hostname to listen on.")
	@Property ("hostname")
	public String listenerHostname = "0.0.0.0";

	/**
	 * Stores the listener port.
	 */
	@Comment ("Specifies the port to listen on.")
	@Property ("port")
	public Short listenerPort = 25565;

	/**
	 * Serialization Constructor
	 */
	public XmlServerListener () { }

	/**
	 * Constructs a new XmlServerListener.
	 * @param hostname
	 * @param port
	 * @param isProxyEnabled
	 * @param isQueryEnabled
	 */
	public XmlServerListener (String hostname, short port, boolean isProxyEnabled, boolean isQueryEnabled) {
		this.listenerHostname = hostname;
		this.listenerPort = port;
		this.proxyEnabled = isProxyEnabled;
		this.queryEnabled = isQueryEnabled;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isQueryEnabled () {
		return this.queryEnabled;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isProxyEnabled () {
		return this.proxyEnabled;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public short getListenerPort () {
		return this.listenerPort;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getListenerHostname () {
		return this.listenerHostname;
	}
}


text:
app.config(config);
config.$inject=["$routeProvider"];
function config($routeProvider) {
    $routeProvider
        .when("/page_one",{
            templateUrl:"templates/page_one.html",
            controller:"page_one"
        })

        .when("/page_two",{
            templateUrl:"templates/page_two.html",
            controller:"page_two"
        })

        .otherwise("/page_one",{
            templateUrl:"templates/page_one.html",
            controller:"page_one"
        });
}


text:
use super::super::StreamId;
use super::frames::{
    Frame,
    Flag,
    parse_padded_payload,
    pack_header,
    RawFrame,
    FrameHeader
};

/// An enum representing the flags that a `ContinuationFrame` can have.
/// The integer representation associated to each variant is that flag's
/// bitmask.
///
/// HTTP/2 spec, section 6.10.
#[derive(Clone)]
#[derive(PartialEq)]
#[derive(Debug)]
#[derive(Copy)]
pub enum ContinuationFlag {
    EndHeaders = 0x4,
}

impl Flag for ContinuationFlag {
    #[inline]
    fn bitmask(&self) -> u8 {
        *self as u8
    }
}

/// A struct representing the CONTINUATION frame for HTTP/2, as defined in the
/// HTTP/2 spec, section 6.10.
pub struct ContinuationFrame {
    /// The header block fragment bytes stored within the frame.
    pub header_fragment: Vec<u8>,
    /// The ID of the stream with which this frame is associated
    pub stream_id: StreamId,
    /// The set of flags for the frame, packed into a single byte.
    flags: u8,
}

impl ContinuationFrame {
    /// Creates a new `ContinuationFrame` with the given header fragment and stream
    /// ID. No flags are set.
    pub fn new(fragment: Vec<u8>, stream_id: StreamId) -> ContinuationFrame {
        ContinuationFrame {
            header_fragment: fragment,
            stream_id: stream_id,
            flags: 0,
        }
    }

    /// Creates a new `ContinuationFrame` with the given header fragment and stream
    /// ID. End header is set as true.
    pub fn with_end(fragment: Vec<u8>, stream_id: StreamId) -> ContinuationFrame {
        ContinuationFrame {
            header_fragment: fragment,
            stream_id: stream_id,
            flags: 0x4,
        }
    }
    /// Returns whether this frame ends the headers. If not, there MUST be a
    /// number of follow up CONTINUATION frames that send the rest of the
    /// header data.
    pub fn is_headers_end(&self) -> bool {
        self.is_set(ContinuationFlag::EndHeaders)
    }

    /// Returns the length of the payload of the current frame, including any
    /// possible padding in the number of bytes.
    fn payload_len(&self) -> u32 {
        self.header_fragment.len() as u32
    }
}

impl Frame for ContinuationFrame {
    /// The type that represents the flags that the particular `Frame` can take.
    /// This makes sure that only valid `Flag`s are used with each `Frame`.
    type FlagType = ContinuationFlag;

    /// Creates a new `ContinuationFrame` with the given `RawFrame` (i.e. header and
    /// payload), if possible.
    ///
    /// # Returns
    ///
    /// `None` if a valid `ContinuationFrame` cannot be constructed from the given
    /// `RawFrame`. The stream ID *must not* be 0.
    ///
    /// Otherwise, returns a newly constructed `ContinuationFrame`.
    fn from_raw(raw_frame: RawFrame) -> Option<ContinuationFrame> {
        // Unpack the header
        let (len, frame_type, flags, stream_id) = raw_frame.header;
        // Check that the frame type is correct for this frame implementation
        if frame_type != 0x9 {
            return None;
        }
        // Check that the length given in the header matches the payload
        // length; if not, something went wrong and we do not consider this a
        // valid frame.
        if (len as usize) != raw_frame.payload.len() {
            return None;
        }
        // Check that the CONTINUATION frame is not associated to stream 0
        if stream_id == 0 {
            return None;
        }

        // let payload = &raw_frame.payload[..];

        Some(ContinuationFrame {
            header_fragment: raw_frame.payload[..].to_vec(),
            stream_id: stream_id,
            flags: flags
        })
    }

    /// Tests if the given flag is set for the frame.
    fn is_set(&self, flag: ContinuationFlag) -> bool {
        (self.flags & flag.bitmask()) != 0
    }

    // Returns the `StreamId` of the stream to which the frame is associated.
    ///
    /// A `SettingsFrame` always has to be associated to stream `0`.
    fn get_stream_id(&self) -> StreamId {
        self.stream_id
    }

    /// Returns a `FrameHeader` based on the current state of the `Frame`.
    fn get_header(&self) -> FrameHeader {
        (self.payload_len(), 0x9, self.flags, self.stream_id)
    }

    /// Sets the given flag for the frame.
    fn set_flag(&mut self, flag: ContinuationFlag) {
        self.flags |= flag.bitmask();
    }

    /// Returns a `Vec` with the serialized representation of the frame.
    fn serialize(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.payload_len() as usize);
        // First the header...
        buf.extend(pack_header(&self.get_header()).to_vec().into_iter());
        // Now the actual headers fragment
        buf.extend(self.header_fragment.clone().into_iter());

        buf
    }
}


text:
require_relative '../../../../apps/auth/controllers/sessions/failure'

RSpec.describe Auth::Controllers::Sessions::Failure, type: :action do
  let(:action) { described_class.new }
  let(:params) { Hash[] }

  it { expect(action.call(params)).to redirect_to('/') }
end


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entries extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
	}

	public function index() {
		$data = array( 'title'			=> "Entries",
					   'main_content'	=> $this->main_content());
 		$this->load->view('main_template', $data);
	}

	public function main_content(){

		$limit 	 = isset($_GET['psize']) ? $_GET['psize'] : 15;
		$curpage = $this->uri->segment(3, 1);
		$offset  = ($curpage-1)*$limit;
		$paging  = 3;

		/*start search function*/
		$filter = false;
		$search_filters = '1';

		if( isset($_GET['search'])|| isset($_GET['filter']) ){

			foreach($_GET as $k => $v){
				if( $v!=''){
					$filter[$k] = $v;
				}
			}
			//reset pagination by redirecting to page 1
			if(isset($filter['search']))
			{
				/*
				'search' is the trigger for reseting ng pagination
				we unset 'search' to avoid inifinite redirect and add
				'filter' to the array to retrigger the search
				*/
				unset($filter['search']);
				$filter['filter']=1;

				//here goes the reset
				redirect('entries/index/1'.'?'.http_build_query($filter, '', "&"), 'location');
			}
			else
			{
				//add the filters to 'where'(sql) statement
				$search_filters .= isset($filter['fbid']) ? " AND user_id LIKE '".$filter['fbid']."%'" : false;
				$search_filters .= isset($filter['author']) ? " AND author LIKE '%".$filter['author']."%'" : false;
				$search_filters .= isset($filter['hashtag']) ? " AND hashtag LIKE '".$filter['hashtag']."%'" : false;
				$search_filters .= isset($filter['source']) ? " AND source LIKE '".$filter['source']."%'" : false;
				$search_filters .= isset($filter['caption']) ? " AND caption LIKE '".$filter['caption']."%'" : false;
				$search_filters .= isset($filter['status']) ? " AND status='".$filter['status']."'" : false;
				$search_filters .= isset($filter['from'])  ? " AND date(timestamp) >= '".$filter['from']."'" : false;
				$search_filters .= isset($filter['to'])  ? " AND date(timestamp) <= '".$filter['to']."'" : false;

			}

		}
		/*end search function*/

		$params = array('table' => 'tbl_entries',
						'where' => $search_filters,
						'offset'=> $offset,
						'limit' => $limit,
						'order' => 'timestamp DESC'
						);

		$items = $this->mysql_queries->get_data($params);

		$params = array('table' => 'tbl_entries','where' => $search_filters);
		$totalrows = $this->mysql_queries->get_data($params);

		$data = array('items' => $items,
					  'total' => sizeof($totalrows),
					  'pagination'	=> $this->globals->pagination(sizeof($totalrows), $curpage ,site_url('entries/index'), $paging, $limit)
					);

		$main = $this->load->view('entries-content', $data, TRUE);
		return $main;
	}

	public function _remap() {
		$this->index();
	}
}

?>


text:
package net.java.sip.communicator.impl.protocol.sip.xcap.model.presrules;

/**
 * The Presence Rules class element.
 * <p/>
 * Compliant with rfc5025
 *
 * @author Grigorii Balutsel
 */
public class ClassType
{
    /**
     * The element value.
     */
    private String value;

    /**
     * Creates class element with value.
     *
     * @param value the elemenent value to set.
     */
    public ClassType(String value)
    {
        this.value = value;
    }

    /**
     * Gets the value of the value property.
     *
     * @return the value property.
     */
    public String getValue()
    {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value the value to set.
     */
    public void setValue(String value)
    {
        this.value = value;
    }
}


text:
#pragma once
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.

#ifdef __cplusplus
extern "C" {
#endif

typedef enum PATH_EXPAND
{
    PATH_EXPAND_ENVIRONMENT = 0x0001,
    PATH_EXPAND_FULLPATH    = 0x0002,
} PATH_EXPAND;

/*******************************************************************
 PathCommandLineAppend - appends a command line argument on to a
    string such that ::CommandLineToArgv() will shred them correctly
    (i.e. quote arguments with spaces in them).
********************************************************************/
DAPI_(HRESULT) PathCommandLineAppend(
    __deref_out_z LPWSTR* psczCommandLine,
    __in_z LPCWSTR wzArgument
    );

/*******************************************************************
 PathFile -  returns a pointer to the file part of the path.
********************************************************************/
DAPI_(LPWSTR) PathFile(
    __in_z LPCWSTR wzPath
    );

/*******************************************************************
 PathExtension -  returns a pointer to the extension part of the path
                  (including the dot).
********************************************************************/
DAPI_(LPCWSTR) PathExtension(
    __in_z LPCWSTR wzPath
    );

/*******************************************************************
 PathGetDirectory - extracts the directory from a path.
********************************************************************/
DAPI_(HRESULT) PathGetDirectory(
    __in_z LPCWSTR wzPath,
    __out LPWSTR *psczDirectory
    );

/*******************************************************************
PathGetParentPath - extracts the parent directory from a full path.
********************************************************************/
DAPI_(HRESULT) PathGetParentPath(
    __in_z LPCWSTR wzPath,
    __out LPWSTR *psczDirectory
    );

/*******************************************************************
 PathExpand - gets the full path to a file resolving environment
              variables along the way.
********************************************************************/
DAPI_(HRESULT) PathExpand(
    __out LPWSTR *psczFullPath,
    __in_z LPCWSTR wzRelativePath,
    __in DWORD dwResolveFlags
    );

/*******************************************************************
 PathPrefix - prefixes a full path with \\?\ or \\?\UNC as
              appropriate.
********************************************************************/
DAPI_(HRESULT) PathPrefix(
    __inout LPWSTR *psczFullPath
    );

/*******************************************************************
 PathFixedBackslashTerminate - appends a \ if path does not have it
                                 already, but fails if the buffer is
                                 insufficient.
********************************************************************/
DAPI_(HRESULT) PathFixedBackslashTerminate(
    __inout_ecount_z(cchPath) LPWSTR wzPath,
    __in DWORD_PTR cchPath
    );

/*******************************************************************
 PathBackslashTerminate - appends a \ if path does not have it
                                 already.
********************************************************************/
DAPI_(HRESULT) PathBackslashTerminate(
    __inout LPWSTR* psczPath
    );

/*******************************************************************
 PathForCurrentProcess - gets the full path to the currently executing
                         process or (optionally) a module inside the process.
********************************************************************/
DAPI_(HRESULT) PathForCurrentProcess(
    __inout LPWSTR *psczFullPath,
    __in_opt HMODULE hModule
    );

/*******************************************************************
 PathRelativeToModule - gets the name of a file in the same
    directory as the current process or (optionally) a module inside
    the process
********************************************************************/
DAPI_(HRESULT) PathRelativeToModule(
    __inout LPWSTR *psczFullPath,
    __in_opt LPCWSTR wzFileName,
    __in_opt HMODULE hModule
    );

/*******************************************************************
 PathCreateTempFile

 Note: if wzDirectory is null, ::GetTempPath() will be used instead.
       if wzFileNameTemplate is null, GetTempFileName() will be used instead.
*******************************************************************/
DAPI_(HRESULT) PathCreateTempFile(
    __in_opt LPCWSTR wzDirectory,
    __in_opt __format_string LPCWSTR wzFileNameTemplate,
    __in DWORD dwUniqueCount,
    __in DWORD dwFileAttributes,
    __out_opt LPWSTR* psczTempFile,
    __out_opt HANDLE* phTempFile
    );

/*******************************************************************
 PathCreateTimeBasedTempFile - creates an empty temp file based on current
                           system time
********************************************************************/
DAPI_(HRESULT) PathCreateTimeBasedTempFile(
    __in_z_opt LPCWSTR wzDirectory,
    __in_z LPCWSTR wzPrefix,
    __in_z_opt LPCWSTR wzPostfix,
    __in_z LPCWSTR wzExtension,
    __deref_opt_out_z LPWSTR* psczTempFile,
    __out_opt HANDLE* phTempFile
    );

/*******************************************************************
 PathCreateTempDirectory

 Note: if wzDirectory is null, ::GetTempPath() will be used instead.
*******************************************************************/
DAPI_(HRESULT) PathCreateTempDirectory(
    __in_opt LPCWSTR wzDirectory,
    __in __format_string LPCWSTR wzDirectoryNameTemplate,
    __in DWORD dwUniqueCount,
    __out LPWSTR* psczTempDirectory
    );

/*******************************************************************
 PathGetKnownFolder - returns the path to a well-known shell folder

*******************************************************************/
DAPI_(HRESULT) PathGetKnownFolder(
    __in int csidl,
    __out LPWSTR* psczKnownFolder
    );

/*******************************************************************
 PathIsAbsolute - returns true if the path is absolute; false
    otherwise.
*******************************************************************/
DAPI_(BOOL) PathIsAbsolute(
    __in_z LPCWSTR wzPath
    );

/*******************************************************************
 PathConcat - like .NET's Path.Combine, lets you build up a path
    one piece -- file or directory -- at a time.
*******************************************************************/
DAPI_(HRESULT) PathConcat(
    __in_opt LPCWSTR wzPath1,
    __in_opt LPCWSTR wzPath2,
    __deref_out_z LPWSTR* psczCombined
    );

/*******************************************************************
 PathEnsureQuoted - ensures that a path is quoted; optionally,
     this function also terminates a directory with a backslash
     if it is not already.
*******************************************************************/
DAPI_(HRESULT) PathEnsureQuoted(
    __inout LPWSTR* ppszPath,
    __in BOOL fDirectory
    );

/*******************************************************************
 PathCompare - compares the fully expanded path of the two paths using
               ::CompareStringW().
*******************************************************************/
DAPI_(HRESULT) PathCompare(
    __in_z LPCWSTR wzPath1,
    __in_z LPCWSTR wzPath2,
    __out int* pnResult
    );

/*******************************************************************
 PathCompress - sets the compression state on an existing file or
                directory. A no-op on file systems that don't
                support compression.
*******************************************************************/
DAPI_(HRESULT) PathCompress(
    __in_z LPCWSTR wzPath
    );

/*******************************************************************
PathCanonicalizePath - wrapper around PathCanonicalizeW.
*******************************************************************/
DAPI_(HRESULT) PathCanonicalizePath(
    __in_z LPCWSTR wzPath,
    __deref_out_z LPWSTR* psczCanonicalized
    );

/*******************************************************************
PathDirectoryContainsPath - checks if wzPath is located inside
                            wzDirectory.
*******************************************************************/
DAPI_(HRESULT) PathDirectoryContainsPath(
    __in_z LPCWSTR wzDirectory,
    __in_z LPCWSTR wzPath
    );

#ifdef __cplusplus
}
#endif


text:
RSpec.describe Extensions::DataUtils do
  class StorageUtils
    extend Extensions::DataUtils
  end

  describe "public methods defined" do
    it "has 'get_yaml'" do
      expect(StorageUtils.respond_to?("get_yaml"))
    end

    it "has 'get_json'" do
      expect(StorageUtils.respond_to?("get_json"))
    end

    it "has 'save_yaml'" do
      expect(StorageUtils.respond_to?("save_yam;"))
    end
  end

  describe "#get_yaml" do
    subject { StorageUtils.get_yaml(file_name) }

    let(:file_name) { File.join(File.dirname(__FILE__), "../support/data/yaml_test.yml") }
    it_behaves_like "extension data object class"
  end

  describe "#get_json" do
    subject { StorageUtils.get_json(file_name) }

    let(:file_name) { File.join(File.dirname(__FILE__), "../support/data/json_test.json") }
    it_behaves_like "extension data object class"
  end

end


text:
/*
 * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
 * Use is subject to license terms.
 *
 * Copyright (c) 2011, Intel Corporation.
 */
/*
 * This file is part of Lustre, http://www.lustre.org/
 * Lustre is a trademark of Sun Microsystems, Inc.
 *
 * /lnet/selftest/conrpc.h
 *
 * Console rpc
 *
 * Author: Liang Zhen <liang@whamcloud.com>
 */

#ifndef __LST_CONRPC_H__
#define __LST_CONRPC_H__

#include "../../include/linux/libcfs/libcfs.h"
#include "../../include/linux/lnet/lnet.h"
#include "../../include/linux/lnet/lib-types.h"
#include "../../include/linux/lnet/lnetst.h"
#include "rpc.h"
#include "selftest.h"

/* Console rpc and rpc transaction */
#define LST_TRANS_TIMEOUT       30
#define LST_TRANS_MIN_TIMEOUT   3

#define LST_VALIDATE_TIMEOUT(t) min(max(t, LST_TRANS_MIN_TIMEOUT), LST_TRANS_TIMEOUT)

#define LST_PING_INTERVAL       8

struct lstcon_rpc_trans;
struct lstcon_tsb_hdr;
struct lstcon_test;
struct lstcon_node;

typedef struct lstcon_rpc {
	struct list_head        crp_link;       /* chain on rpc transaction */
	srpc_client_rpc_t       *crp_rpc;	/* client rpc */
	struct lstcon_node      *crp_node;      /* destination node */
	struct lstcon_rpc_trans *crp_trans;     /* conrpc transaction */

	unsigned int            crp_posted:1;   /* rpc is posted */
	unsigned int            crp_finished:1; /* rpc is finished */
	unsigned int            crp_unpacked:1; /* reply is unpacked */
	/** RPC is embedded in other structure and can't free it */
	unsigned int            crp_embedded:1;
	int                     crp_status;     /* console rpc errors */
	unsigned long           crp_stamp;      /* replied time stamp */
} lstcon_rpc_t;

typedef struct lstcon_rpc_trans {
	struct list_head  tas_olink;         /* link chain on owner list */
	struct list_head  tas_link;          /* link chain on global list */
	int               tas_opc;           /* operation code of transaction */
	unsigned          tas_feats_updated; /* features mask is uptodate */
	unsigned          tas_features;      /* test features mask */
	wait_queue_head_t tas_waitq;         /* wait queue head */
	atomic_t          tas_remaining;     /* # of un-scheduled rpcs */
	struct list_head  tas_rpcs_list;     /* queued requests */
} lstcon_rpc_trans_t;

#define LST_TRANS_PRIVATE       0x1000

#define LST_TRANS_SESNEW	(LST_TRANS_PRIVATE | 0x01)
#define LST_TRANS_SESEND	(LST_TRANS_PRIVATE | 0x02)
#define LST_TRANS_SESQRY	0x03
#define LST_TRANS_SESPING       0x04

#define LST_TRANS_TSBCLIADD     (LST_TRANS_PRIVATE | 0x11)
#define LST_TRANS_TSBSRVADD     (LST_TRANS_PRIVATE | 0x12)
#define LST_TRANS_TSBRUN	(LST_TRANS_PRIVATE | 0x13)
#define LST_TRANS_TSBSTOP       (LST_TRANS_PRIVATE | 0x14)
#define LST_TRANS_TSBCLIQRY     0x15
#define LST_TRANS_TSBSRVQRY     0x16

#define LST_TRANS_STATQRY       0x21

typedef int (*lstcon_rpc_cond_func_t)(int, struct lstcon_node *, void *);
typedef int (*lstcon_rpc_readent_func_t)(int, srpc_msg_t *, lstcon_rpc_ent_t *);

int  lstcon_sesrpc_prep(struct lstcon_node *nd, int transop,
			unsigned version, lstcon_rpc_t **crpc);
int  lstcon_dbgrpc_prep(struct lstcon_node *nd,
			unsigned version, lstcon_rpc_t **crpc);
int  lstcon_batrpc_prep(struct lstcon_node *nd, int transop, unsigned version,
			struct lstcon_tsb_hdr *tsb, lstcon_rpc_t **crpc);
int  lstcon_testrpc_prep(struct lstcon_node *nd, int transop, unsigned version,
			 struct lstcon_test *test, lstcon_rpc_t **crpc);
int  lstcon_statrpc_prep(struct lstcon_node *nd, unsigned version,
			 lstcon_rpc_t **crpc);
void lstcon_rpc_put(lstcon_rpc_t *crpc);
int  lstcon_rpc_trans_prep(struct list_head *translist,
			   int transop, lstcon_rpc_trans_t **transpp);
int  lstcon_rpc_trans_ndlist(struct list_head *ndlist,
			     struct list_head *translist, int transop,
			     void *arg, lstcon_rpc_cond_func_t condition,
			     lstcon_rpc_trans_t **transpp);
void lstcon_rpc_trans_stat(lstcon_rpc_trans_t *trans,
			   lstcon_trans_stat_t *stat);
int  lstcon_rpc_trans_interpreter(lstcon_rpc_trans_t *trans,
				  struct list_head *head_up,
				  lstcon_rpc_readent_func_t readent);
void lstcon_rpc_trans_abort(lstcon_rpc_trans_t *trans, int error);
void lstcon_rpc_trans_destroy(lstcon_rpc_trans_t *trans);
void lstcon_rpc_trans_addreq(lstcon_rpc_trans_t *trans, lstcon_rpc_t *req);
int  lstcon_rpc_trans_postwait(lstcon_rpc_trans_t *trans, int timeout);
int  lstcon_rpc_pinger_start(void);
void lstcon_rpc_pinger_stop(void);
void lstcon_rpc_cleanup_wait(void);
int  lstcon_rpc_module_init(void);
void lstcon_rpc_module_fini(void);

#endif


text:
@implementation GPXTrack {
    NSMutableArray *_links;
    NSMutableArray *_tracksegments;
    NSString *_numberValue;
}

@synthesize name = _name;
@synthesize comment = _comment;
@synthesize desc = _desc;
@synthesize source = _source;
@synthesize links = _links;
@synthesize number = _number;
@synthesize type = _type;
@synthesize extensions = _extensions;
@synthesize tracksegments = _tracksegments;

#pragma mark - Instance

- (id)init
{
    self = [super init];
    if (self) {
        _links = [NSMutableArray array];
        _tracksegments = [NSMutableArray array];
    }
    return self;
}

- (id)initWithXMLElement:(GPXXMLElement *)element parent:(GPXElement *)parent
{
    self = [super initWithXMLElement:element parent:parent];
    if (self) {
        _name = [self textForSingleChildElementNamed:@"name" xmlElement:element];
        _comment = [self textForSingleChildElementNamed:@"cmt" xmlElement:element];
        _desc = [self textForSingleChildElementNamed:@"desc" xmlElement:element];
        _source = [self textForSingleChildElementNamed:@"src" xmlElement:element];

        NSMutableArray *array1 = [NSMutableArray array];
        [self childElementsOfClass:[GPXLink class]
                        xmlElement:element
                         eachBlock:^(GPXElement *element) {
                             [array1 addObject:element];
                         }];
        _links = array1;

        _numberValue = [self textForSingleChildElementNamed:@"number" xmlElement:element];
        _type = [self textForSingleChildElementNamed:@"type" xmlElement:element];
        _extensions = (GPXExtensions *)[self childElementOfClass:[GPXExtensions class] xmlElement:element];

        NSMutableArray *array2 = [NSMutableArray array];
        [self childElementsOfClass:[GPXTrackSegment class]
                        xmlElement:element
                         eachBlock:^(GPXElement *element) {
                             [array2 addObject:element];
                         }];
        _tracksegments = array2;
    }
    return self;
}

#pragma mark - Public methods

- (NSInteger)number
{
    return [GPXType nonNegativeInteger:_numberValue];
}

- (void)setNumber:(NSInteger)number
{
    _numberValue = [GPXType valueForNonNegativeInteger:number];
}

- (GPXLink *)newLinkWithHref:(NSString *)href
{
    GPXLink *link = [GPXLink linkWithHref:href];
    [self addLink:link];
    return link;
}

- (void)addLink:(GPXLink *)link
{
    if (link) {
        NSUInteger index = [_links indexOfObject:link];
        if (index == NSNotFound) {
            link.parent = self;
            [_links addObject:link];
        }
    }
}

- (void)addLinks:(NSArray *)array
{
    for (GPXLink *link in array) {
        [self addLink:link];
    }
}

- (void)removeLink:(GPXLink *)link
{
    NSUInteger index = [_links indexOfObject:link];
    if (index != NSNotFound) {
        link.parent = nil;
        [_links removeObject:link];
    }
}

- (GPXTrackSegment *)newTrackSegment
{
    GPXTrackSegment *tracksegment = [GPXTrackSegment new];
    [self addTracksegment:tracksegment];
    return tracksegment;
}

- (void)addTracksegment:(GPXTrackSegment *)tracksegment
{
    if (tracksegment) {
        NSUInteger index = [_tracksegments indexOfObject:tracksegment];
        if (index == NSNotFound) {
            tracksegment.parent = self;
            [_tracksegments addObject:tracksegment];
        }
    }
}

- (void)addTracksegments:(NSArray *)array
{
    for (GPXTrackSegment *tracksegment in array) {
        [self addTracksegment:tracksegment];
    }
}

- (void)removeTracksegment:(GPXTrackSegment *)tracksegment
{
    NSUInteger index = [_tracksegments indexOfObject:tracksegment];
    if (index != NSNotFound) {
        tracksegment.parent = nil;
        [_tracksegments removeObject:tracksegment];
    }
}

- (GPXTrackPoint *)newTrackpointWithLatitude:(CGFloat)latitude longitude:(CGFloat)longitude
{
    GPXTrackSegment *tracksegment;

    // create a new segment if needed
    if (_tracksegments.count == 0) {
        [self newTrackSegment];
    }

    // get latest segment
    tracksegment = [_tracksegments lastObject];

    return [tracksegment newTrackpointWithLatitude:latitude longitude:longitude];
}

#pragma mark - tag

+ (NSString *)tagName
{
    return @"trk";
}

#pragma mark - GPX

- (void)addChildTagToGpx:(NSMutableString *)gpx indentationLevel:(NSInteger)indentationLevel
{
    [super addChildTagToGpx:gpx indentationLevel:indentationLevel];

    [self gpx:gpx addPropertyForValue:_name tagName:@"name" indentationLevel:indentationLevel];
    [self gpx:gpx addPropertyForValue:_comment tagName:@"cmt" indentationLevel:indentationLevel];
    [self gpx:gpx addPropertyForValue:_desc tagName:@"desc" indentationLevel:indentationLevel];
    [self gpx:gpx addPropertyForValue:_source tagName:@"src" indentationLevel:indentationLevel];

    for (GPXLink *link in self.links) {
        [link gpx:gpx indentationLevel:indentationLevel];
    }

    [self gpx:gpx addPropertyForValue:_numberValue tagName:@"number" indentationLevel:indentationLevel];
    [self gpx:gpx addPropertyForValue:_type tagName:@"type" indentationLevel:indentationLevel];

    if (self.extensions) {
        [self.extensions gpx:gpx indentationLevel:indentationLevel];
    }

    for (GPXTrackSegment *tracksegment in self.tracksegments) {
        [tracksegment gpx:gpx indentationLevel:indentationLevel];
    }
}

@end


text:
import '@angular/core/test/bundling/util/src/reflect_metadata';

import {CommonModule} from '@angular/common';
import {Component, ElementRef, NgModule, ɵPlayState as PlayState, ɵPlayer as Player, ɵPlayerHandler as PlayerHandler, ɵaddPlayer as addPlayer, ɵbindPlayerFactory as bindPlayerFactory, ɵmarkDirty as markDirty, ɵrenderComponent as renderComponent} from '@angular/core';

@Component({
  selector: 'animation-world',
  template: `
    <nav>
      <button (click)="animateWithCustomPlayer()">Animate List (custom player)</button>
      <button (click)="animateWithStyles()">Populate List (style bindings)</button>
    </nav>
    <div class="list">
      <div
        *ngFor="let item of items" class="record" [class]="makeClass(item)" style="border-radius: 10px"
        [style]="styles">
        {{ item }}
      </div>
    </div>
  `,
})
class AnimationWorldComponent {
  items: any[] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  private _hostElement: HTMLElement;
  public styles: {[key: string]: any}|null = null;

  constructor(element: ElementRef) { this._hostElement = element.nativeElement; }

  makeClass(index: number) { return `record-${index}`; }

  animateWithStyles() {
    this.styles = animateStyleFactory([{opacity: 0}, {opacity: 1}], 300, 'ease-out');
    markDirty(this);
  }

  animateWithCustomPlayer() {
    const elements = this._hostElement.querySelectorAll('div.record') as any as HTMLElement[];
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      const delay = i * 100;
      const player = buildAnimationPlayer(element, 'fadeInOut', `500ms ease-out ${delay}ms both`);
      addPlayer(element, player);
    }
  }
}

@NgModule({declarations: [AnimationWorldComponent], imports: [CommonModule]})
class AnimationWorldModule {
}

function buildAnimationPlayer(element: HTMLElement, animationName: string, time: string): Player {
  return new SimpleKeyframePlayer(element, animationName, time);
}

class SimpleKeyframePlayer implements Player {
  state = PlayState.Pending;
  parent: Player|null = null;
  private _animationStyle: string = '';
  private _listeners: {[stateName: string]: (() => any)[]} = {};
  constructor(private _element: HTMLElement, private _animationName: string, time: string) {
    this._animationStyle = `${time} ${_animationName}`;
  }
  private _start() {
    (this._element as any).style.animation = this._animationStyle;
    const animationFn = (event: AnimationEvent) => {
      if (event.animationName == this._animationName) {
        this._element.removeEventListener('animationend', animationFn);
        this.finish();
      }
    };
    this._element.addEventListener('animationend', animationFn);
  }
  addEventListener(state: PlayState|string, cb: () => any): void {
    const key = state.toString();
    const arr = this._listeners[key] = (this._listeners[key] || []);
    arr.push(cb);
  }
  play(): void {
    if (this.state <= PlayState.Pending) {
      this._start();
    }
    if (this.state != PlayState.Running) {
      setAnimationPlayState(this._element, 'running');
      this.state = PlayState.Running;
      this._emit(this.state);
    }
  }
  pause(): void {
    if (this.state != PlayState.Paused) {
      setAnimationPlayState(this._element, 'paused');
      this.state = PlayState.Paused;
      this._emit(this.state);
    }
  }
  finish(): void {
    if (this.state < PlayState.Finished) {
      this._element.style.animation = '';
      this.state = PlayState.Finished;
      this._emit(this.state);
    }
  }
  destroy(): void {
    if (this.state < PlayState.Destroyed) {
      this.finish();
      this.state = PlayState.Destroyed;
      this._emit(this.state);
    }
  }
  capture(): any {}
  private _emit(state: PlayState) {
    const arr = this._listeners[state.toString()] || [];
    arr.forEach(cb => cb());
  }
}

function setAnimationPlayState(element: HTMLElement, state: string) {
  element.style.animationPlayState = state;
}

class AnimationDebugger implements PlayerHandler {
  private _players: Player[] = [];

  flushPlayers() {
    this._players.forEach(player => {
      if (!player.parent) {
        player.play();
      }
    });
    this._players.length = 0;
  }

  queuePlayer(player: Player): void { this._players.push(player); }
}

const playerHandler = new AnimationDebugger();
renderComponent(AnimationWorldComponent, {playerHandler});

function animateStyleFactory(keyframes: any[], duration: number, easing: string) {
  const limit = keyframes.length - 1;
  const finalKeyframe = keyframes[limit];
  return bindPlayerFactory(
      (element: HTMLElement, type: number, values: {[key: string]: any},
       isFirstRender: boolean) => {
        const kf = keyframes.slice(0, limit);
        kf.push(values);
        return new WebAnimationsPlayer(element, keyframes, duration, easing);
      },
      finalKeyframe);
}

class WebAnimationsPlayer implements Player {
  state = PlayState.Pending;
  parent: Player|null = null;
  private _listeners: {[stateName: string]: (() => any)[]} = {};
  constructor(
      private _element: HTMLElement, private _keyframes: {[key: string]: any}[],
      private _duration: number, private _easing: string) {}
  private _start() {
    const player = this._element.animate(
        this._keyframes as any[], {duration: this._duration, easing: this._easing, fill: 'both'});
    player.addEventListener('finish', e => { this.finish(); });
  }
  addEventListener(state: PlayState|string, cb: () => any): void {
    const key = state.toString();
    const arr = this._listeners[key] = (this._listeners[key] || []);
    arr.push(cb);
  }
  play(): void {
    if (this.state <= PlayState.Pending) {
      this._start();
    }
    if (this.state != PlayState.Running) {
      this.state = PlayState.Running;
      this._emit(this.state);
    }
  }
  pause(): void {
    if (this.state != PlayState.Paused) {
      this.state = PlayState.Paused;
      this._emit(this.state);
    }
  }
  finish(): void {
    if (this.state < PlayState.Finished) {
      this._element.style.animation = '';
      this.state = PlayState.Finished;
      this._emit(this.state);
    }
  }
  destroy(): void {
    if (this.state < PlayState.Destroyed) {
      this.finish();
      this.state = PlayState.Destroyed;
      this._emit(this.state);
    }
  }
  capture(): any {}
  private _emit(state: PlayState) {
    const arr = this._listeners[state.toString()] || [];
    arr.forEach(cb => cb());
  }
}


text:
#include <asm/unaligned.h>
#include <linux/device.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/usb/input.h>
#include <media/rc-core.h>

/* Driver Information */
#define DRIVER_AUTHOR "Jarod Wilson <jarod@redhat.com>"
#define DRIVER_AUTHOR2 "The Dweller, Stephen Cox"
#define DRIVER_DESC "RedRat3 USB IR Transceiver Driver"
#define DRIVER_NAME "redrat3"

/* bulk data transfer types */
#define RR3_ERROR		0x01
#define RR3_MOD_SIGNAL_IN	0x20
#define RR3_MOD_SIGNAL_OUT	0x21

/* Get the RR firmware version */
#define RR3_FW_VERSION		0xb1
#define RR3_FW_VERSION_LEN	64
/* Send encoded signal bulk-sent earlier*/
#define RR3_TX_SEND_SIGNAL	0xb3
#define RR3_SET_IR_PARAM	0xb7
#define RR3_GET_IR_PARAM	0xb8
/* Blink the red LED on the device */
#define RR3_BLINK_LED		0xb9
/* Read serial number of device */
#define RR3_READ_SER_NO		0xba
#define RR3_SER_NO_LEN		4
/* Start capture with the RC receiver */
#define RR3_RC_DET_ENABLE	0xbb
/* Stop capture with the RC receiver */
#define RR3_RC_DET_DISABLE	0xbc
/* Return the status of RC detector capture */
#define RR3_RC_DET_STATUS	0xbd
/* Reset redrat */
#define RR3_RESET		0xa0

/* Max number of lengths in the signal. */
#define RR3_IR_IO_MAX_LENGTHS	0x01
/* Periods to measure mod. freq. */
#define RR3_IR_IO_PERIODS_MF	0x02
/* Size of memory for main signal data */
#define RR3_IR_IO_SIG_MEM_SIZE	0x03
/* Delta value when measuring lengths */
#define RR3_IR_IO_LENGTH_FUZZ	0x04
/* Timeout for end of signal detection */
#define RR3_IR_IO_SIG_TIMEOUT	0x05
/* Minimum value for pause recognition. */
#define RR3_IR_IO_MIN_PAUSE	0x06

/* Clock freq. of EZ-USB chip */
#define RR3_CLK			24000000
/* Clock periods per timer count */
#define RR3_CLK_PER_COUNT	12
/* (RR3_CLK / RR3_CLK_PER_COUNT) */
#define RR3_CLK_CONV_FACTOR	2000000
/* USB bulk-in IR data endpoint address */
#define RR3_BULK_IN_EP_ADDR	0x82

/* Size of the fixed-length portion of the signal */
#define RR3_DRIVER_MAXLENS	128
#define RR3_MAX_SIG_SIZE	512
#define RR3_TIME_UNIT		50
#define RR3_END_OF_SIGNAL	0x7f
#define RR3_TX_TRAILER_LEN	2
#define RR3_RX_MIN_TIMEOUT	5
#define RR3_RX_MAX_TIMEOUT	2000

/* The 8051's CPUCS Register address */
#define RR3_CPUCS_REG_ADDR	0x7f92

#define USB_RR3USB_VENDOR_ID	0x112a
#define USB_RR3USB_PRODUCT_ID	0x0001
#define USB_RR3IIUSB_PRODUCT_ID	0x0005

struct redrat3_header {
	__be16 length;
	__be16 transfer_type;
} __packed;

/* sending and receiving irdata */
struct redrat3_irdata {
	struct redrat3_header header;
	__be32 pause;
	__be16 mod_freq_count;
	__be16 num_periods;
	__u8 max_lengths;
	__u8 no_lengths;
	__be16 max_sig_size;
	__be16 sig_size;
	__u8 no_repeats;
	__be16 lens[RR3_DRIVER_MAXLENS]; /* not aligned */
	__u8 sigdata[RR3_MAX_SIG_SIZE];
} __packed;

/* firmware errors */
struct redrat3_error {
	struct redrat3_header header;
	__be16 fw_error;
} __packed;

/* table of devices that work with this driver */
static struct usb_device_id redrat3_dev_table[] = {
	/* Original version of the RedRat3 */
	{USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3USB_PRODUCT_ID)},
	/* Second Version/release of the RedRat3 - RetRat3-II */
	{USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3IIUSB_PRODUCT_ID)},
	{}			/* Terminating entry */
};

/* Structure to hold all of our device specific stuff */
struct redrat3_dev {
	/* core device bits */
	struct rc_dev *rc;
	struct device *dev;

	/* led control */
	struct led_classdev led;
	atomic_t flash;
	struct usb_ctrlrequest flash_control;
	struct urb *flash_urb;
	u8 flash_in_buf;

	/* save off the usb device pointer */
	struct usb_device *udev;

	/* the receive endpoint */
	struct usb_endpoint_descriptor *ep_in;
	/* the buffer to receive data */
	void *bulk_in_buf;
	/* urb used to read ir data */
	struct urb *read_urb;

	/* the send endpoint */
	struct usb_endpoint_descriptor *ep_out;

	/* usb dma */
	dma_addr_t dma_in;

	/* rx signal timeout timer */
	struct timer_list rx_timeout;
	u32 hw_timeout;

	/* Is the device currently transmitting?*/
	bool transmitting;

	/* store for current packet */
	struct redrat3_irdata irdata;
	u16 bytes_read;

	u32 carrier;

	char name[64];
	char phys[64];
};

/*
 * redrat3_issue_async
 *
 *  Issues an async read to the ir data in port..
 *  sets the callback to be redrat3_handle_async
 */
static void redrat3_issue_async(struct redrat3_dev *rr3)
{
	int res;

	res = usb_submit_urb(rr3->read_urb, GFP_ATOMIC);
	if (res)
		dev_dbg(rr3->dev,
			"%s: receive request FAILED! (res %d, len %d)\n",
			__func__, res, rr3->read_urb->transfer_buffer_length);
}

static void redrat3_dump_fw_error(struct redrat3_dev *rr3, int code)
{
	if (!rr3->transmitting && (code != 0x40))
		dev_info(rr3->dev, "fw error code 0x%02x: ", code);

	switch (code) {
	case 0x00:
		pr_cont("No Error\n");
		break;

	/* Codes 0x20 through 0x2f are IR Firmware Errors */
	case 0x20:
		pr_cont("Initial signal pulse not long enough "
			"to measure carrier frequency\n");
		break;
	case 0x21:
		pr_cont("Not enough length values allocated for signal\n");
		break;
	case 0x22:
		pr_cont("Not enough memory allocated for signal data\n");
		break;
	case 0x23:
		pr_cont("Too many signal repeats\n");
		break;
	case 0x28:
		pr_cont("Insufficient memory available for IR signal "
			"data memory allocation\n");
		break;
	case 0x29:
		pr_cont("Insufficient memory available "
			"for IrDa signal data memory allocation\n");
		break;

	/* Codes 0x30 through 0x3f are USB Firmware Errors */
	case 0x30:
		pr_cont("Insufficient memory available for bulk "
			"transfer structure\n");
		break;

	/*
	 * Other error codes... These are primarily errors that can occur in
	 * the control messages sent to the redrat
	 */
	case 0x40:
		if (!rr3->transmitting)
			pr_cont("Signal capture has been terminated\n");
		break;
	case 0x41:
		pr_cont("Attempt to set/get and unknown signal I/O "
			"algorithm parameter\n");
		break;
	case 0x42:
		pr_cont("Signal capture already started\n");
		break;

	default:
		pr_cont("Unknown Error\n");
		break;
	}
}

static u32 redrat3_val_to_mod_freq(struct redrat3_irdata *irdata)
{
	u32 mod_freq = 0;
	u16 mod_freq_count = be16_to_cpu(irdata->mod_freq_count);

	if (mod_freq_count != 0)
		mod_freq = (RR3_CLK * be16_to_cpu(irdata->num_periods)) /
			(mod_freq_count * RR3_CLK_PER_COUNT);

	return mod_freq;
}

/* this function scales down the figures for the same result... */
static u32 redrat3_len_to_us(u32 length)
{
	u32 biglen = length * 1000;
	u32 divisor = (RR3_CLK_CONV_FACTOR) / 1000;
	u32 result = (u32) (biglen / divisor);

	/* don't allow zero lengths to go back, breaks lirc */
	return result ? result : 1;
}

/*
 * convert us back into redrat3 lengths
 *
 * length * 1000   length * 1000000
 * ------------- = ---------------- = micro
 * rr3clk / 1000       rr3clk

 * 6 * 2       4 * 3        micro * rr3clk          micro * rr3clk / 1000
 * ----- = 4   ----- = 6    -------------- = len    ---------------------
 *   3           2             1000000                    1000
 */
static u32 redrat3_us_to_len(u32 microsec)
{
	u32 result;
	u32 divisor;

	microsec = (microsec > IR_MAX_DURATION) ? IR_MAX_DURATION : microsec;
	divisor = (RR3_CLK_CONV_FACTOR / 1000);
	result = (u32)(microsec * divisor) / 1000;

	/* don't allow zero lengths to go back, breaks lirc */
	return result ? result : 1;
}

/* timer callback to send reset event */
static void redrat3_rx_timeout(unsigned long data)
{
	struct redrat3_dev *rr3 = (struct redrat3_dev *)data;

	dev_dbg(rr3->dev, "calling ir_raw_event_reset\n");
	ir_raw_event_reset(rr3->rc);
}

static void redrat3_process_ir_data(struct redrat3_dev *rr3)
{
	DEFINE_IR_RAW_EVENT(rawir);
	struct device *dev;
	unsigned i, trailer = 0;
	unsigned sig_size, single_len, offset, val;
	unsigned long delay;
	u32 mod_freq;

	if (!rr3) {
		pr_err("%s called with no context!\n", __func__);
		return;
	}

	dev = rr3->dev;

	/* Make sure we reset the IR kfifo after a bit of inactivity */
	delay = usecs_to_jiffies(rr3->hw_timeout);
	mod_timer(&rr3->rx_timeout, jiffies + delay);

	mod_freq = redrat3_val_to_mod_freq(&rr3->irdata);
	dev_dbg(dev, "Got mod_freq of %u\n", mod_freq);

	/* process each rr3 encoded byte into an int */
	sig_size = be16_to_cpu(rr3->irdata.sig_size);
	for (i = 0; i < sig_size; i++) {
		offset = rr3->irdata.sigdata[i];
		val = get_unaligned_be16(&rr3->irdata.lens[offset]);
		single_len = redrat3_len_to_us(val);

		/* we should always get pulse/space/pulse/space samples */
		if (i % 2)
			rawir.pulse = false;
		else
			rawir.pulse = true;

		rawir.duration = US_TO_NS(single_len);
		/* Save initial pulse length to fudge trailer */
		if (i == 0)
			trailer = rawir.duration;
		/* cap the value to IR_MAX_DURATION */
		rawir.duration = (rawir.duration > IR_MAX_DURATION) ?
				 IR_MAX_DURATION : rawir.duration;

		dev_dbg(dev, "storing %s with duration %d (i: %d)\n",
			rawir.pulse ? "pulse" : "space", rawir.duration, i);
		ir_raw_event_store_with_filter(rr3->rc, &rawir);
	}

	/* add a trailing space, if need be */
	if (i % 2) {
		rawir.pulse = false;
		/* this duration is made up, and may not be ideal... */
		if (trailer < US_TO_NS(1000))
			rawir.duration = US_TO_NS(2800);
		else
			rawir.duration = trailer;
		dev_dbg(dev, "storing trailing space with duration %d\n",
			rawir.duration);
		ir_raw_event_store_with_filter(rr3->rc, &rawir);
	}

	dev_dbg(dev, "calling ir_raw_event_handle\n");
	ir_raw_event_handle(rr3->rc);
}

/* Util fn to send rr3 cmds */
static int redrat3_send_cmd(int cmd, struct redrat3_dev *rr3)
{
	struct usb_device *udev;
	u8 *data;
	int res;

	data = kzalloc(sizeof(u8), GFP_KERNEL);
	if (!data)
		return -ENOMEM;

	udev = rr3->udev;
	res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), cmd,
			      USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
			      0x0000, 0x0000, data, sizeof(u8), HZ * 10);

	if (res < 0) {
		dev_err(rr3->dev, "%s: Error sending rr3 cmd res %d, data %d",
			__func__, res, *data);
		res = -EIO;
	} else
		res = data[0];

	kfree(data);

	return res;
}

/* Enables the long range detector and starts async receive */
static int redrat3_enable_detector(struct redrat3_dev *rr3)
{
	struct device *dev = rr3->dev;
	u8 ret;

	ret = redrat3_send_cmd(RR3_RC_DET_ENABLE, rr3);
	if (ret != 0)
		dev_dbg(dev, "%s: unexpected ret of %d\n",
			__func__, ret);

	ret = redrat3_send_cmd(RR3_RC_DET_STATUS, rr3);
	if (ret != 1) {
		dev_err(dev, "%s: detector status: %d, should be 1\n",
			__func__, ret);
		return -EIO;
	}

	redrat3_issue_async(rr3);

	return 0;
}

static inline void redrat3_delete(struct redrat3_dev *rr3,
				  struct usb_device *udev)
{
	usb_kill_urb(rr3->read_urb);
	usb_kill_urb(rr3->flash_urb);
	usb_free_urb(rr3->read_urb);
	usb_free_urb(rr3->flash_urb);
	usb_free_coherent(udev, le16_to_cpu(rr3->ep_in->wMaxPacketSize),
			  rr3->bulk_in_buf, rr3->dma_in);

	kfree(rr3);
}

static u32 redrat3_get_timeout(struct redrat3_dev *rr3)
{
	__be32 *tmp;
	u32 timeout = MS_TO_US(150); /* a sane default, if things go haywire */
	int len, ret, pipe;

	len = sizeof(*tmp);
	tmp = kzalloc(len, GFP_KERNEL);
	if (!tmp) {
		dev_warn(rr3->dev, "Memory allocation faillure\n");
		return timeout;
	}

	pipe = usb_rcvctrlpipe(rr3->udev, 0);
	ret = usb_control_msg(rr3->udev, pipe, RR3_GET_IR_PARAM,
			      USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
			      RR3_IR_IO_SIG_TIMEOUT, 0, tmp, len, HZ * 5);
	if (ret != len)
		dev_warn(rr3->dev, "Failed to read timeout from hardware\n");
	else {
		timeout = redrat3_len_to_us(be32_to_cpup(tmp));

		dev_dbg(rr3->dev, "Got timeout of %d ms\n", timeout / 1000);
	}

	kfree(tmp);

	return timeout;
}

static void redrat3_reset(struct redrat3_dev *rr3)
{
	struct usb_device *udev = rr3->udev;
	struct device *dev = rr3->dev;
	int rc, rxpipe, txpipe;
	u8 *val;
	int len = sizeof(u8);

	rxpipe = usb_rcvctrlpipe(udev, 0);
	txpipe = usb_sndctrlpipe(udev, 0);

	val = kmalloc(len, GFP_KERNEL);
	if (!val) {
		dev_err(dev, "Memory allocation failure\n");
		return;
	}

	*val = 0x01;
	rc = usb_control_msg(udev, rxpipe, RR3_RESET,
			     USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
			     RR3_CPUCS_REG_ADDR, 0, val, len, HZ * 25);
	dev_dbg(dev, "reset returned 0x%02x\n", rc);

	*val = 5;
	rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
			     USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
			     RR3_IR_IO_LENGTH_FUZZ, 0, val, len, HZ * 25);
	dev_dbg(dev, "set ir parm len fuzz %d rc 0x%02x\n", *val, rc);

	*val = RR3_DRIVER_MAXLENS;
	rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
			     USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
			     RR3_IR_IO_MAX_LENGTHS, 0, val, len, HZ * 25);
	dev_dbg(dev, "set ir parm max lens %d rc 0x%02x\n", *val, rc);

	kfree(val);
}

static void redrat3_get_firmware_rev(struct redrat3_dev *rr3)
{
	int rc = 0;
	char *buffer;

	buffer = kzalloc(sizeof(char) * (RR3_FW_VERSION_LEN + 1), GFP_KERNEL);
	if (!buffer) {
		dev_err(rr3->dev, "Memory allocation failure\n");
		return;
	}

	rc = usb_control_msg(rr3->udev, usb_rcvctrlpipe(rr3->udev, 0),
			     RR3_FW_VERSION,
			     USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
			     0, 0, buffer, RR3_FW_VERSION_LEN, HZ * 5);

	if (rc >= 0)
		dev_info(rr3->dev, "Firmware rev: %s", buffer);
	else
		dev_err(rr3->dev, "Problem fetching firmware ID\n");

	kfree(buffer);
}

static void redrat3_read_packet_start(struct redrat3_dev *rr3, unsigned len)
{
	struct redrat3_header *header = rr3->bulk_in_buf;
	unsigned pktlen, pkttype;

	/* grab the Length and type of transfer */
	pktlen = be16_to_cpu(header->length);
	pkttype = be16_to_cpu(header->transfer_type);

	if (pktlen > sizeof(rr3->irdata)) {
		dev_warn(rr3->dev, "packet length %u too large\n", pktlen);
		return;
	}

	switch (pkttype) {
	case RR3_ERROR:
		if (len >= sizeof(struct redrat3_error)) {
			struct redrat3_error *error = rr3->bulk_in_buf;
			unsigned fw_error = be16_to_cpu(error->fw_error);
			redrat3_dump_fw_error(rr3, fw_error);
		}
		break;

	case RR3_MOD_SIGNAL_IN:
		memcpy(&rr3->irdata, rr3->bulk_in_buf, len);
		rr3->bytes_read = len;
		dev_dbg(rr3->dev, "bytes_read %d, pktlen %d\n",
			rr3->bytes_read, pktlen);
		break;

	default:
		dev_dbg(rr3->dev, "ignoring packet with type 0x%02x, len of %d, 0x%02x\n",
						pkttype, len, pktlen);
		break;
	}
}

static void redrat3_read_packet_continue(struct redrat3_dev *rr3, unsigned len)
{
	void *irdata = &rr3->irdata;

	if (len + rr3->bytes_read > sizeof(rr3->irdata)) {
		dev_warn(rr3->dev, "too much data for packet\n");
		rr3->bytes_read = 0;
		return;
	}

	memcpy(irdata + rr3->bytes_read, rr3->bulk_in_buf, len);

	rr3->bytes_read += len;
	dev_dbg(rr3->dev, "bytes_read %d, pktlen %d\n", rr3->bytes_read,
				 be16_to_cpu(rr3->irdata.header.length));
}

/* gather IR data from incoming urb, process it when we have enough */
static int redrat3_get_ir_data(struct redrat3_dev *rr3, unsigned len)
{
	struct device *dev = rr3->dev;
	unsigned pkttype;
	int ret = 0;

	if (rr3->bytes_read == 0 && len >= sizeof(struct redrat3_header)) {
		redrat3_read_packet_start(rr3, len);
	} else if (rr3->bytes_read != 0) {
		redrat3_read_packet_continue(rr3, len);
	} else if (rr3->bytes_read == 0) {
		dev_err(dev, "error: no packet data read\n");
		ret = -ENODATA;
		goto out;
	}

	if (rr3->bytes_read < be16_to_cpu(rr3->irdata.header.length) +
						sizeof(struct redrat3_header))
		/* we're still accumulating data */
		return 0;

	/* if we get here, we've got IR data to decode */
	pkttype = be16_to_cpu(rr3->irdata.header.transfer_type);
	if (pkttype == RR3_MOD_SIGNAL_IN)
		redrat3_process_ir_data(rr3);
	else
		dev_dbg(dev, "discarding non-signal data packet (type 0x%02x)\n",
								pkttype);

out:
	rr3->bytes_read = 0;
	return ret;
}

/* callback function from USB when async USB request has completed */
static void redrat3_handle_async(struct urb *urb)
{
	struct redrat3_dev *rr3;
	int ret;

	if (!urb)
		return;

	rr3 = urb->context;
	if (!rr3) {
		pr_err("%s called with invalid context!\n", __func__);
		usb_unlink_urb(urb);
		return;
	}

	switch (urb->status) {
	case 0:
		ret = redrat3_get_ir_data(rr3, urb->actual_length);
		if (!ret) {
			/* no error, prepare to read more */
			redrat3_issue_async(rr3);
		}
		break;

	case -ECONNRESET:
	case -ENOENT:
	case -ESHUTDOWN:
		usb_unlink_urb(urb);
		return;

	case -EPIPE:
	default:
		dev_warn(rr3->dev, "Error: urb status = %d\n", urb->status);
		rr3->bytes_read = 0;
		break;
	}
}

static u16 mod_freq_to_val(unsigned int mod_freq)
{
	int mult = 6000000;

	/* Clk used in mod. freq. generation is CLK24/4. */
	return 65536 - (mult / mod_freq);
}

static int redrat3_set_tx_carrier(struct rc_dev *rcdev, u32 carrier)
{
	struct redrat3_dev *rr3 = rcdev->priv;
	struct device *dev = rr3->dev;

	dev_dbg(dev, "Setting modulation frequency to %u", carrier);
	if (carrier == 0)
		return -EINVAL;

	rr3->carrier = carrier;

	return carrier;
}

static int redrat3_transmit_ir(struct rc_dev *rcdev, unsigned *txbuf,
				unsigned count)
{
	struct redrat3_dev *rr3 = rcdev->priv;
	struct device *dev = rr3->dev;
	struct redrat3_irdata *irdata = NULL;
	int ret, ret_len;
	int lencheck, cur_sample_len, pipe;
	int *sample_lens = NULL;
	u8 curlencheck = 0;
	unsigned i, sendbuf_len;

	if (rr3->transmitting) {
		dev_warn(dev, "%s: transmitter already in use\n", __func__);
		return -EAGAIN;
	}

	if (count > RR3_MAX_SIG_SIZE - RR3_TX_TRAILER_LEN)
		return -EINVAL;

	/* rr3 will disable rc detector on transmit */
	rr3->transmitting = true;

	sample_lens = kzalloc(sizeof(int) * RR3_DRIVER_MAXLENS, GFP_KERNEL);
	if (!sample_lens) {
		ret = -ENOMEM;
		goto out;
	}

	irdata = kzalloc(sizeof(*irdata), GFP_KERNEL);
	if (!irdata) {
		ret = -ENOMEM;
		goto out;
	}

	for (i = 0; i < count; i++) {
		cur_sample_len = redrat3_us_to_len(txbuf[i]);
		if (cur_sample_len > 0xffff) {
			dev_warn(dev, "transmit period of %uus truncated to %uus\n",
					txbuf[i], redrat3_len_to_us(0xffff));
			cur_sample_len = 0xffff;
		}
		for (lencheck = 0; lencheck < curlencheck; lencheck++) {
			if (sample_lens[lencheck] == cur_sample_len)
				break;
		}
		if (lencheck == curlencheck) {
			dev_dbg(dev, "txbuf[%d]=%u, pos %d, enc %u\n",
				i, txbuf[i], curlencheck, cur_sample_len);
			if (curlencheck < RR3_DRIVER_MAXLENS) {
				/* now convert the value to a proper
				 * rr3 value.. */
				sample_lens[curlencheck] = cur_sample_len;
				put_unaligned_be16(cur_sample_len,
						&irdata->lens[curlencheck]);
				curlencheck++;
			} else {
				ret = -EINVAL;
				goto out;
			}
		}
		irdata->sigdata[i] = lencheck;
	}

	irdata->sigdata[count] = RR3_END_OF_SIGNAL;
	irdata->sigdata[count + 1] = RR3_END_OF_SIGNAL;

	sendbuf_len = offsetof(struct redrat3_irdata,
					sigdata[count + RR3_TX_TRAILER_LEN]);
	/* fill in our packet header */
	irdata->header.length = cpu_to_be16(sendbuf_len -
						sizeof(struct redrat3_header));
	irdata->header.transfer_type = cpu_to_be16(RR3_MOD_SIGNAL_OUT);
	irdata->pause = cpu_to_be32(redrat3_len_to_us(100));
	irdata->mod_freq_count = cpu_to_be16(mod_freq_to_val(rr3->carrier));
	irdata->no_lengths = curlencheck;
	irdata->sig_size = cpu_to_be16(count + RR3_TX_TRAILER_LEN);

	pipe = usb_sndbulkpipe(rr3->udev, rr3->ep_out->bEndpointAddress);
	ret = usb_bulk_msg(rr3->udev, pipe, irdata,
			    sendbuf_len, &ret_len, 10 * HZ);
	dev_dbg(dev, "sent %d bytes, (ret %d)\n", ret_len, ret);

	/* now tell the hardware to transmit what we sent it */
	pipe = usb_rcvctrlpipe(rr3->udev, 0);
	ret = usb_control_msg(rr3->udev, pipe, RR3_TX_SEND_SIGNAL,
			      USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
			      0, 0, irdata, 2, HZ * 10);

	if (ret < 0)
		dev_err(dev, "Error: control msg send failed, rc %d\n", ret);
	else
		ret = count;

out:
	kfree(sample_lens);
	kfree(irdata);

	rr3->transmitting = false;
	/* rr3 re-enables rc detector because it was enabled before */

	return ret;
}

static void redrat3_brightness_set(struct led_classdev *led_dev, enum
						led_brightness brightness)
{
	struct redrat3_dev *rr3 = container_of(led_dev, struct redrat3_dev,
									led);

	if (brightness != LED_OFF && atomic_cmpxchg(&rr3->flash, 0, 1) == 0) {
		int ret = usb_submit_urb(rr3->flash_urb, GFP_ATOMIC);
		if (ret != 0) {
			dev_dbg(rr3->dev, "%s: unexpected ret of %d\n",
				__func__, ret);
			atomic_set(&rr3->flash, 0);
		}
	}
}

static void redrat3_led_complete(struct urb *urb)
{
	struct redrat3_dev *rr3 = urb->context;

	switch (urb->status) {
	case 0:
		break;
	case -ECONNRESET:
	case -ENOENT:
	case -ESHUTDOWN:
		usb_unlink_urb(urb);
		return;
	case -EPIPE:
	default:
		dev_dbg(rr3->dev, "Error: urb status = %d\n", urb->status);
		break;
	}

	rr3->led.brightness = LED_OFF;
	atomic_dec(&rr3->flash);
}

static struct rc_dev *redrat3_init_rc_dev(struct redrat3_dev *rr3)
{
	struct device *dev = rr3->dev;
	struct rc_dev *rc;
	int ret = -ENODEV;
	u16 prod = le16_to_cpu(rr3->udev->descriptor.idProduct);

	rc = rc_allocate_device();
	if (!rc) {
		dev_err(dev, "remote input dev allocation failed\n");
		goto out;
	}

	snprintf(rr3->name, sizeof(rr3->name), "RedRat3%s "
		 "Infrared Remote Transceiver (%04x:%04x)",
		 prod == USB_RR3IIUSB_PRODUCT_ID ? "-II" : "",
		 le16_to_cpu(rr3->udev->descriptor.idVendor), prod);

	usb_make_path(rr3->udev, rr3->phys, sizeof(rr3->phys));

	rc->input_name = rr3->name;
	rc->input_phys = rr3->phys;
	usb_to_input_id(rr3->udev, &rc->input_id);
	rc->dev.parent = dev;
	rc->priv = rr3;
	rc->driver_type = RC_DRIVER_IR_RAW;
	rc->allowed_protocols = RC_BIT_ALL;
	rc->timeout = US_TO_NS(2750);
	rc->tx_ir = redrat3_transmit_ir;
	rc->s_tx_carrier = redrat3_set_tx_carrier;
	rc->driver_name = DRIVER_NAME;
	rc->rx_resolution = US_TO_NS(2);
	rc->map_name = RC_MAP_HAUPPAUGE;

	ret = rc_register_device(rc);
	if (ret < 0) {
		dev_err(dev, "remote dev registration failed\n");
		goto out;
	}

	return rc;

out:
	rc_free_device(rc);
	return NULL;
}

static int redrat3_dev_probe(struct usb_interface *intf,
			     const struct usb_device_id *id)
{
	struct usb_device *udev = interface_to_usbdev(intf);
	struct device *dev = &intf->dev;
	struct usb_host_interface *uhi;
	struct redrat3_dev *rr3;
	struct usb_endpoint_descriptor *ep;
	struct usb_endpoint_descriptor *ep_in = NULL;
	struct usb_endpoint_descriptor *ep_out = NULL;
	u8 addr, attrs;
	int pipe, i;
	int retval = -ENOMEM;

	uhi = intf->cur_altsetting;

	/* find our bulk-in and bulk-out endpoints */
	for (i = 0; i < uhi->desc.bNumEndpoints; ++i) {
		ep = &uhi->endpoint[i].desc;
		addr = ep->bEndpointAddress;
		attrs = ep->bmAttributes;

		if ((ep_in == NULL) &&
		    ((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) &&
		    ((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
		     USB_ENDPOINT_XFER_BULK)) {
			dev_dbg(dev, "found bulk-in endpoint at 0x%02x\n",
				ep->bEndpointAddress);
			/* data comes in on 0x82, 0x81 is for other data... */
			if (ep->bEndpointAddress == RR3_BULK_IN_EP_ADDR)
				ep_in = ep;
		}

		if ((ep_out == NULL) &&
		    ((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) &&
		    ((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
		     USB_ENDPOINT_XFER_BULK)) {
			dev_dbg(dev, "found bulk-out endpoint at 0x%02x\n",
				ep->bEndpointAddress);
			ep_out = ep;
		}
	}

	if (!ep_in || !ep_out) {
		dev_err(dev, "Couldn't find both in and out endpoints\n");
		retval = -ENODEV;
		goto no_endpoints;
	}

	/* allocate memory for our device state and initialize it */
	rr3 = kzalloc(sizeof(*rr3), GFP_KERNEL);
	if (rr3 == NULL) {
		dev_err(dev, "Memory allocation failure\n");
		goto no_endpoints;
	}

	rr3->dev = &intf->dev;

	/* set up bulk-in endpoint */
	rr3->read_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!rr3->read_urb) {
		dev_err(dev, "Read urb allocation failure\n");
		goto error;
	}

	rr3->ep_in = ep_in;
	rr3->bulk_in_buf = usb_alloc_coherent(udev,
		le16_to_cpu(ep_in->wMaxPacketSize), GFP_KERNEL, &rr3->dma_in);
	if (!rr3->bulk_in_buf) {
		dev_err(dev, "Read buffer allocation failure\n");
		goto error;
	}

	pipe = usb_rcvbulkpipe(udev, ep_in->bEndpointAddress);
	usb_fill_bulk_urb(rr3->read_urb, udev, pipe, rr3->bulk_in_buf,
		le16_to_cpu(ep_in->wMaxPacketSize), redrat3_handle_async, rr3);
	rr3->read_urb->transfer_dma = rr3->dma_in;
	rr3->read_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;

	rr3->ep_out = ep_out;
	rr3->udev = udev;

	redrat3_reset(rr3);
	redrat3_get_firmware_rev(rr3);

	/* might be all we need to do? */
	retval = redrat3_enable_detector(rr3);
	if (retval < 0)
		goto error;

	/* store current hardware timeout, in us, will use for kfifo resets */
	rr3->hw_timeout = redrat3_get_timeout(rr3);

	/* default.. will get overridden by any sends with a freq defined */
	rr3->carrier = 38000;

	/* led control */
	rr3->led.name = "redrat3:red:feedback";
	rr3->led.default_trigger = "rc-feedback";
	rr3->led.brightness_set = redrat3_brightness_set;
	retval = led_classdev_register(&intf->dev, &rr3->led);
	if (retval)
		goto error;

	atomic_set(&rr3->flash, 0);
	rr3->flash_urb = usb_alloc_urb(0, GFP_KERNEL);
	if (!rr3->flash_urb) {
		retval = -ENOMEM;
		goto led_free_error;
	}

	/* setup packet is 'c0 b9 0000 0000 0001' */
	rr3->flash_control.bRequestType = 0xc0;
	rr3->flash_control.bRequest = RR3_BLINK_LED;
	rr3->flash_control.wLength = cpu_to_le16(1);

	usb_fill_control_urb(rr3->flash_urb, udev, usb_rcvctrlpipe(udev, 0),
			(unsigned char *)&rr3->flash_control,
			&rr3->flash_in_buf, sizeof(rr3->flash_in_buf),
			redrat3_led_complete, rr3);

	rr3->rc = redrat3_init_rc_dev(rr3);
	if (!rr3->rc) {
		retval = -ENOMEM;
		goto led_free_error;
	}
	setup_timer(&rr3->rx_timeout, redrat3_rx_timeout, (unsigned long)rr3);

	/* we can register the device now, as it is ready */
	usb_set_intfdata(intf, rr3);

	return 0;

led_free_error:
	led_classdev_unregister(&rr3->led);
error:
	redrat3_delete(rr3, rr3->udev);

no_endpoints:
	dev_err(dev, "%s: retval = %x", __func__, retval);

	return retval;
}

static void redrat3_dev_disconnect(struct usb_interface *intf)
{
	struct usb_device *udev = interface_to_usbdev(intf);
	struct redrat3_dev *rr3 = usb_get_intfdata(intf);

	if (!rr3)
		return;

	usb_set_intfdata(intf, NULL);
	rc_unregister_device(rr3->rc);
	led_classdev_unregister(&rr3->led);
	del_timer_sync(&rr3->rx_timeout);
	redrat3_delete(rr3, udev);
}

static int redrat3_dev_suspend(struct usb_interface *intf, pm_message_t message)
{
	struct redrat3_dev *rr3 = usb_get_intfdata(intf);

	led_classdev_suspend(&rr3->led);
	usb_kill_urb(rr3->read_urb);
	usb_kill_urb(rr3->flash_urb);
	return 0;
}

static int redrat3_dev_resume(struct usb_interface *intf)
{
	struct redrat3_dev *rr3 = usb_get_intfdata(intf);

	if (usb_submit_urb(rr3->read_urb, GFP_ATOMIC))
		return -EIO;
	led_classdev_resume(&rr3->led);
	return 0;
}

static struct usb_driver redrat3_dev_driver = {
	.name		= DRIVER_NAME,
	.probe		= redrat3_dev_probe,
	.disconnect	= redrat3_dev_disconnect,
	.suspend	= redrat3_dev_suspend,
	.resume		= redrat3_dev_resume,
	.reset_resume	= redrat3_dev_resume,
	.id_table	= redrat3_dev_table
};

module_usb_driver(redrat3_dev_driver);

MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_AUTHOR(DRIVER_AUTHOR2);
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(usb, redrat3_dev_table);