text:
package cn.xishan.oftenporter.oftendb.db.mysql;

import cn.xishan.oftenporter.oftendb.db.*;
import cn.xishan.oftenporter.porter.core.util.WPTool;

import java.util.ArrayList;
import java.util.List;

public class SqlCondition extends Condition
{

    private boolean isAnd = true;
    private Class<?> dealNamesClass;

    /**
     * <pre>
     * 通配符 说明
     * _    与任意单字符匹配
     * %    与包含一个或多个字符的字符串匹配
     * [ ]  与特定范围(例如,[a-f])或特定集(例如,[abcdef])中的任意单字符匹配。
     * [^]  与特定范围(例如,[^a-f])或特定集(例如,[^abcdef])之外的任意单字符匹配。
     * </pre>
     */
    public static final Operator LIKE = new MyOperator("LIKE");

    public static final Operator IS_NULL = new MyOperator("is NULL");

    public static final Operator IS_NOT_NULL = new MyOperator("is not NULL");

    /**
     * 返回为一个Object[]{whereSql,args}
     *
     * @return
     * @throws ConditionException
     */
    @Override
    public Object toFinalObject() throws ConditionException
    {
        return _toFinalObject();
    }

    /**
     * 会进行sql注入处理.
     */
    private Object[] _toFinalObject() throws ConditionException
    {
        StringBuilder stringBuilder = new StringBuilder();
        List<Object> args = new ArrayList<>(size());
        for (int i = 0; i < size(); i++)
        {
            Operator operator = getOperator(i);
            if (operator == NOT || operator == OR||operator==AND)
            {
                deal2(operator, get(i), stringBuilder, args);
            } else
            {
                dealNormal(operator, get(i), stringBuilder, args);
            }
        }

        if (stringBuilder.length() == 0)
        {
            stringBuilder.append(" TRUE ");
        }

        StringBuilder result = new StringBuilder();
        List<Object> list = new ArrayList<>(args.size());

        int index1 = 0, index2 = 0;
        while (true)
        {
            index1 = stringBuilder.indexOf("{", index2);
            if (index1 == -1)
            {
                result.append(stringBuilder.subSequence(index2, stringBuilder.length()));
                break;
            } else
            {
                result.append(stringBuilder.subSequence(index2, index1));
            }

            index2 = stringBuilder.indexOf("}", index1 + 1);
            result.append('?');
            list.add(args.get(Integer.parseInt(stringBuilder.substring(index1 + 1, index2))));
            if (++index2 >= stringBuilder.length())
            {
                break;
            }
        }
        return new Object[]{result.toString(), list.toArray(new Object[0])};
    }

    @Override
    public String toString()
    {
        Object obj = toFinalObject();

        return obj != null ? obj.toString() : super.toString();
    }

    private void deal2(Operator operator, Object object, StringBuilder stringBuilder, List<Object> args)
    {
        if (!(object instanceof SqlCondition))
        {
            throw new ConditionException("value should be type of " + getClass()
                    + ".Current type is "
                    + object.getClass());
        }
        SqlCondition condition = (SqlCondition) object;

        link(stringBuilder);//and或or连接

        if (operator == NOT)
        {
            stringBuilder.append(" NOT ");
        } else if (operator == OR)
        {
            condition.isAnd = false;
        } else if (operator == AND)
        {
            condition.isAnd = true;
        } else
        {
            throw new ConditionException("the operator should be " + NOT
                    + " or "
                    + OR
                    + " for value of " + getClass().getSimpleName() + " type");
        }
        Object[] sqlArgs = (Object[]) condition.toFinalObject();
        Object[] _args = (Object[]) sqlArgs[1];
        String sql = (String) sqlArgs[0];
        stringBuilder.append("(");
        for (int i = 0, k = 0; i < sql.length(); i++)
        {
            char c = sql.charAt(i);
            if (c == '?')
            {
                stringBuilder.append("{").append(args.size()).append("}");
                args.add(_args[k++]);
            } else
            {
                stringBuilder.append(c);
            }
        }
        stringBuilder.append(")");
    }

    /**
     * and 或 or 连接。
     *
     * @param stringBuilder
     */
    private void link(StringBuilder stringBuilder)
    {
        if (stringBuilder.length() > 0)
        {
            stringBuilder.append(isAnd ? " AND " : " OR ");
        }
    }

    /**
     * @param CUnit
     * @Key注解的处理
     */
    private void dealNames(CUnit CUnit)
    {
        if (dealNamesClass == null)
        {
            return;
        }
        if (!CUnit.isParam1Value())
        {
            CUnit.setParam1(BaseEasier.dealWith_Key(dealNamesClass, CUnit.getParam1()));
        }
        if (!CUnit.isParam2Value())
        {
            CUnit.setParam2(BaseEasier.dealWith_Key(dealNamesClass, (String) CUnit.getParam2()));
        }
    }

    /**
     * 从字符串转换出Operator
     *
     * @param op
     * @return
     */
    public static Operator fromStr(String op)
    {
        op = op.toLowerCase();
        Operator operator = Condition.fromStr(op);
        if (operator != null)
        {
            return operator;
        }
        if (op.equals("like"))
        {
            operator = LIKE;
        } else if (op.equals("is null"))
        {
            operator = IS_NULL;
        } else if (op.equals("is not null"))
        {
            operator = IS_NOT_NULL;
        } else
        {
            throw new ConditionException("unknown operator " + op);
        }
        return operator;
    }

    private static void checkName(String name)
    {

        if (WPTool.isEmpty(name) || name.indexOf('{') >= 0 || name.indexOf('}') >= 0)
        {
            throw new RuntimeException("illegal name of '" + name + "'");
        } else if (name.indexOf('`') >= 0)
        {
            throw new DBException("illegal name:" + name);
        }
    }

    private void dealNormal(Operator operator, Object object, StringBuilder stringBuilder, List<Object> args)
    {
        if (!(object instanceof CUnit))
        {
            throw new ConditionException(operator + "-CUnit is accept!");
        }
        CUnit cUnit = (CUnit) object;

        dealNames(cUnit);// @Key注解的处理

        link(stringBuilder);//and或or
        if (cUnit.isParam1Value())
        {
            stringBuilder.append("{").append(args.size()).append("}");
            args.add(cUnit.getParam1());
        } else
        {
            appendName(cUnit.getParam1(), stringBuilder);
        }
        stringBuilder.append(" ");

        if (operator == IS_NOT_NULL || (cUnit.getParam2() == null && operator == NE && !cUnit.isParam1Value() && cUnit
                .isParam2Value()))
        {
            stringBuilder.append("is not NULL ");
            //operator=IS_NOT_NULL;
            return;
        } else if (operator == IS_NULL//添加旁边的或者使得当查询条件的value为null时,使用is NULL
                || (cUnit.getParam2() == null && operator == EQ && !cUnit.isParam1Value() && cUnit.isParam2Value()))
        {
            //operator = IS_NULL;
            stringBuilder.append("is NULL ");
            return;
        }

        if (operator == IN || operator == NIN)
        {
            StringBuilder sBuilder = new StringBuilder("(");
            if (cUnit.getParam2() instanceof Object[] || cUnit.getParam2() instanceof List)
            {
                Object[] objects;
                if (cUnit.getParam2() instanceof List)
                {
                    List list = (List) cUnit.getParam2();
                    objects = list.toArray(new Object[0]);
                } else
                {
                    objects = (Object[]) cUnit.getParam2();
                }
                if (objects != null)
                {
                    for (int i = 0; i < objects.length - 1; i++)
                    {
                        sBuilder.append("{").append(args.size()).append("},");
                        args.add(objects[i]);
                    }
                    if (objects.length > 0)
                    {
                        sBuilder.append("{").append(args.size()).append("}");
                        args.add(objects[objects.length - 1]);
                    }
                }
            } else
            {
                sBuilder.append("{").append(args.size()).append("}");
                args.add(cUnit.getParam2());
            }

            sBuilder.append(") ");
            stringBuilder.append(operator == IN ? "in " : "not in ").append(sBuilder);
            return;
        }

        if (operator == GT)
        {
            stringBuilder.append(">");
        } else if (operator == GTE)
        {
            stringBuilder.append(">=");
        } else if (operator == LT)
        {
            stringBuilder.append("<");
        } else if (operator == LTE)
        {
            stringBuilder.append("<=");
        } else if (operator == NE)
        {
            stringBuilder.append("!=");
        } else if (operator == EQ)
        {
            stringBuilder.append("=");
        } else if (operator == LIKE)
        {
            stringBuilder.append("LIKE");
        } else if (operator == SUBSTR || operator == NOTSUBSTR)
        {
            if (operator == NOTSUBSTR)
            {
                stringBuilder.append("NOT ");
            }
            stringBuilder.append("LIKE ").append("{").append(args.size()).append("}");
            args.add("%" + SqlUtil.filterLike(cUnit.getParam2() + "") + "%");
            return;
        } else if (operator == STARTSWITH || operator == NOTSTARTSWITH)
        {
            if (operator == NOTSTARTSWITH)
            {
                stringBuilder.append("NOT ");
            }
            stringBuilder.append("LIKE ").append("{").append(args.size()).append("}");
            args.add(SqlUtil.filterLike(cUnit.getParam2() + "") + "%");
            return;
        } else if (operator == ENDSSWITH || operator == NOTENDSSWITH)
        {
            if (operator == NOTENDSSWITH)
            {
                stringBuilder.append("NOT ");
            }
            stringBuilder.append("LIKE ").append("{").append(args.size()).append("}");
            args.add("%" + SqlUtil.filterLike(cUnit.getParam2() + ""));
            return;
        } else
        {
            throw new ConditionException("unknown operator " + operator);
        }
        stringBuilder.append(" ");
        if (cUnit.isParam2Value())
        {
            stringBuilder.append("{").append(args.size()).append("}");
            args.add(cUnit.getParam2());
        } else
        {
            appendName(cUnit.getParam2(), stringBuilder);
        }
    }

    static void appendName(Object name, StringBuilder builder)
    {
        String nameStr = (String) name;
        checkName(nameStr);
        int dotIndex = nameStr.lastIndexOf('.');
        if (dotIndex >= 0)
        {
            builder.append(nameStr.substring(0, dotIndex + 1));
            nameStr = nameStr.substring(dotIndex + 1);
        }
        builder.append("`").append(nameStr).append("`");
    }

    @Override
    public void dealNames(Class<?> c)
    {
        this.dealNamesClass = c;
    }
}


text:
(also distributed as Schunk WSG 32)

Forked from: [https://code.google.com/p/wsg50-ros-pkg](https://code.google.com/p/wsg50-ros-pkg)

Modifications of this repository:
Reading back state with high rates, open-loop control via topics, catkinized, modifications for hydro.
Existing features are not discussed here - see original Wiki: [https://code.google.com/p/wsg50-ros-pkg/wiki/wsg_32](https://code.google.com/p/wsg50-ros-pkg/wiki/wsg_32)

Todo: Restructure code

## Node wsg\_50\_ip (was: wsg\_50_tcp)

### Parameters
* *ip*: IP address of gripper
* *port*: Port of gripper
* *local_port*: Local port for UDP
* *protocol*: udp or tcp (default)
* *com_mode*: polling (default), script or auto_update. See communication modes below.
* *rate*: Polling rate in Hz.
* *grasping_force*: Set grasping force limit on startup

### Services
See [https://code.google.com/p/wsg50-ros-pkg/wiki/wsg_32](https://code.google.com/p/wsg50-ros-pkg/wiki/wsg_32). Services currently block the reception of state updates.

### Topics
* *~/goal\_position [IN, wsg_32_common/Cmd]*, in modes script, auto_update:

Position goal; send target position in mm and speed
* *~/goal\_speed [IN, std_msgs/Float32]*, in mode script:

Velocity goal (in mm/s); positive values open the gripper
* *~/moving [OUT, std_msgs/Bool]*, in modes script, auto_update:

Signals a change in the motion state for position control. Can be used to wait for the end of a gripper movement. Does not work correctly yet for velocity control, since the gripper state register does not directly provide this information.
* *~/state [OUT, std_msgs/State]:*

State information (opening width, speed, forces). Note: Not all fields are available with all communication modes.
* */joint_states [OUT, sensor_msgs/JointState]:*

Standard joint state message

### Communication modes (closed-loop control)
Select by *com_mode* parameter.

* **Polling**

Gripper state is polled regularly using built-in commands (original implementaion). Service calls (e.g. move) block polling as long as the gripper moves. The topic interface is not available. Up to 15 Hz could be reached with the WSG-50 hardware revision 2.

* **Script**

Allows for closed-loop control with a custom script (see below) that supports up to 2 FMF finger. Gripper state is read synchronously with the specified rate. Up to 30 Hz could be reached with the WSG-50 hardware revision 2. The gripper can be controlled asynchronously by sending position or velocity goals to the topics listed above. Commands will be sent with the next read command in the timer callback timer_cb().

The service interface can still be used - yet, they are blocking the gripper communication. There are no state updates while the gripper is moved by a service.

* **Auto_update**

Requests periodic updates of the gripper state (position, speed, force; less data than with the script). Up to 140 Hz could be reached with the WSG-50 hardware revision 2. All responses of the gripper must be received by a reading thread which also publishes the ROS messages. Therefore, most commands in functions.cpp cannot be used. Position targets are sent asynchronously to the gripper using the built-in commands.

The services are disabled.

#### Gripper script
The script *cmd_measure.lua* must be running on the gripper for the script mode. It allows for non-blocking position and velocity control and responds with the current position, speed, motor force and up to two FMF finger forces. The custom commands 0xB0 (read only), 0xB1 (read, goal position and speed), 0xB2 (read, goal speed) are used. Tested with firmware version 2.6.4. There have been minor API changes since 1.x.

## Node wsg\_50_can

Remains unchanged; new features not implemented here.

redpajama_set_name: RedPajamaGithub


text:
Spring Data Tutorial

Spring Data JPA demo https://github.com/icnws/spring-data-jpa-demo


text:
import { Event, Emitter } from 'vs/base/common/event';
import { CONTEXT_EXPRESSION_SELECTED, IViewModel, IStackFrame, IDebugSession, IThread, IExpression, IFunctionBreakpoint, CONTEXT_BREAKPOINT_SELECTED, CONTEXT_LOADED_SCRIPTS_SUPPORTED } from 'vs/workbench/parts/debug/common/debug';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';

export class ViewModel implements IViewModel {

	firstSessionStart = true;

	private _focusedStackFrame: IStackFrame;
	private _focusedSession: IDebugSession;
	private _focusedThread: IThread;
	private selectedExpression: IExpression;
	private selectedFunctionBreakpoint: IFunctionBreakpoint;
	private readonly _onDidFocusSession: Emitter<IDebugSession | undefined>;
	private readonly _onDidFocusStackFrame: Emitter<{ stackFrame: IStackFrame, explicit: boolean }>;
	private readonly _onDidSelectExpression: Emitter<IExpression>;
	private multiSessionView: boolean;
	private expressionSelectedContextKey: IContextKey<boolean>;
	private breakpointSelectedContextKey: IContextKey<boolean>;
	private loadedScriptsSupportedContextKey: IContextKey<boolean>;

	constructor(contextKeyService: IContextKeyService) {
		this._onDidFocusSession = new Emitter<IDebugSession | undefined>();
		this._onDidFocusStackFrame = new Emitter<{ stackFrame: IStackFrame, explicit: boolean }>();
		this._onDidSelectExpression = new Emitter<IExpression>();
		this.multiSessionView = false;
		this.expressionSelectedContextKey = CONTEXT_EXPRESSION_SELECTED.bindTo(contextKeyService);
		this.breakpointSelectedContextKey = CONTEXT_BREAKPOINT_SELECTED.bindTo(contextKeyService);
		this.loadedScriptsSupportedContextKey = CONTEXT_LOADED_SCRIPTS_SUPPORTED.bindTo(contextKeyService);
	}

	getId(): string {
		return 'root';
	}

	get focusedSession(): IDebugSession {
		return this._focusedSession;
	}

	get focusedThread(): IThread {
		return this._focusedThread;
	}

	get focusedStackFrame(): IStackFrame {
		return this._focusedStackFrame;
	}

	setFocus(stackFrame: IStackFrame, thread: IThread, session: IDebugSession, explicit: boolean): void {
		const shouldEmitForStackFrame = this._focusedStackFrame !== stackFrame;
		const shouldEmitForSession = this._focusedSession !== session;

		this._focusedStackFrame = stackFrame;
		this._focusedThread = thread;
		this._focusedSession = session;

		this.loadedScriptsSupportedContextKey.set(session && session.capabilities.supportsLoadedSourcesRequest);

		if (shouldEmitForSession) {
			this._onDidFocusSession.fire(session);
		}
		if (shouldEmitForStackFrame) {
			this._onDidFocusStackFrame.fire({ stackFrame, explicit });
		}
	}

	get onDidFocusSession(): Event<IDebugSession> {
		return this._onDidFocusSession.event;
	}

	get onDidFocusStackFrame(): Event<{ stackFrame: IStackFrame, explicit: boolean }> {
		return this._onDidFocusStackFrame.event;
	}

	getSelectedExpression(): IExpression {
		return this.selectedExpression;
	}

	setSelectedExpression(expression: IExpression) {
		this.selectedExpression = expression;
		this.expressionSelectedContextKey.set(!!expression);
		this._onDidSelectExpression.fire(expression);
	}

	get onDidSelectExpression(): Event<IExpression> {
		return this._onDidSelectExpression.event;
	}

	getSelectedFunctionBreakpoint(): IFunctionBreakpoint {
		return this.selectedFunctionBreakpoint;
	}

	setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint): void {
		this.selectedFunctionBreakpoint = functionBreakpoint;
		this.breakpointSelectedContextKey.set(!!functionBreakpoint);
	}

	isMultiSessionView(): boolean {
		return this.multiSessionView;
	}

	setMultiSessionView(isMultiSessionView: boolean): void {
		this.multiSessionView = isMultiSessionView;
	}
}


text:
package org.openbel.framework.api;

import java.util.Set;

/**
 *
 * @author julianjray
 *
 */
public abstract class FilterCriteria {

    private boolean isInclude = true;

    /**
     *
     */
    public FilterCriteria() {
    }

    /**
     *
     * @return
     */
    public boolean isInclude() {
        return isInclude;
    }

    /**
     *
     * @param isInclude
     */
    public void setInclude(boolean isInclude) {
        this.isInclude = isInclude;
    }

    /**
     *
     * @return
     */
    public abstract Set<?> getValues();
}


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

<title>SnapMirrorVolumeInfo</title>
<meta name="date" content="2021-04-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.solidfire.element.api

Class SnapMirrorVolumeInfo

java.lang.Object

com.solidfire.element.api.SnapMirrorVolumeInfo

All Implemented Interfaces:

java.io.Serializable

public class SnapMirrorVolumeInfo
extends java.lang.Object
implements java.io.Serializable

SnapMirrorVolumeInfo
 The snapMirrorVolumeInfo object contains information about a volume location in a SnapMirror relationship, such as its name and type.

See Also:

Serialized Form

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
SnapMirrorVolumeInfo.Builder

Field Summary

Fields

Modifier and Type
Field and Description

static long
serialVersionUID

Constructor Summary

Constructors

Constructor and Description

SnapMirrorVolumeInfo()

SnapMirrorVolumeInfo(java.lang.String type,
                    Optional<java.lang.Long> volumeID,
                    Optional<java.lang.String> vserver,
                    java.lang.String name)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

SnapMirrorVolumeInfo.Builder
asBuilder()

static SnapMirrorVolumeInfo.Builder
builder()

boolean
equals(java.lang.Object o)

java.lang.String
getName()

The name of the volume.

java.lang.String
getType()

The type of volume.

Optional<java.lang.Long>
getVolumeID()

The ID of the volume.

Optional<java.lang.String>
getVserver()

The name of the Vserver that owns this volume.

int
hashCode()

void
setName(java.lang.String name)

void
setType(java.lang.String type)

void
setVolumeID(Optional<java.lang.Long> volumeID)

void
setVserver(Optional<java.lang.String> vserver)

java.util.Map<java.lang.String,java.lang.Object>
toMap()

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

serialVersionUID

public static final long serialVersionUID

See Also:

Constant Field Values

Constructor Detail

SnapMirrorVolumeInfo

@Since(value="7.0")
public SnapMirrorVolumeInfo()

SnapMirrorVolumeInfo

@Since(value="10.0")
public SnapMirrorVolumeInfo(java.lang.String type,
                                                 Optional<java.lang.Long> volumeID,
                                                 Optional<java.lang.String> vserver,
                                                 java.lang.String name)

Method Detail

getType

public java.lang.String getType()

The type of volume.
 Possible values:
 solidfire: The volume resides on a SolidFire cluster.
 ontap:     The volume resides on a remote ONTAP cluster.

setType

public void setType(java.lang.String type)

getVolumeID

public Optional<java.lang.Long> getVolumeID()

The ID of the volume. Only valid if "type" is solidfire.

setVolumeID

public void setVolumeID(Optional<java.lang.Long> volumeID)

getVserver

public Optional<java.lang.String> getVserver()

The name of the Vserver that owns this volume. Only valid if "type" is ONTAP.

setVserver

public void setVserver(Optional<java.lang.String> vserver)

getName

public java.lang.String getName()

The name of the volume.

setName

public void setName(java.lang.String name)

equals

public boolean equals(java.lang.Object o)

Overrides:

equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

toMap

public java.util.Map<java.lang.String,java.lang.Object> toMap()

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

builder

public static SnapMirrorVolumeInfo.Builder builder()

asBuilder

public final SnapMirrorVolumeInfo.Builder asBuilder()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/*!
 * @file
 * @brief Implementation of Ar microkernel queue.
 */

#include "ar_internal.h"
#include <string.h>

using namespace Ar;

//------------------------------------------------------------------------------
// Macros
//------------------------------------------------------------------------------

//! Returns a uint8_t * to the first byte of element @a i of the queue.
//!
//! @param q The queue object.
//! @param i Index of the queue element, base 0.
#define QUEUE_ELEMENT(q, i) (&(q)->m_elements[(q)->m_elementSize * (i)])

//------------------------------------------------------------------------------
// Prototypes
//------------------------------------------------------------------------------

static ar_status_t ar_queue_send_internal(ar_queue_t * queue, const void * element, uint32_t timeout);
static void ar_queue_deferred_send(void * object, void * object2);

//------------------------------------------------------------------------------
// Implementation
//------------------------------------------------------------------------------

// See ar_kernel.h for documentation of this function.
ar_status_t ar_queue_create(ar_queue_t * queue, const char * name, void * storage, unsigned elementSize, unsigned capacity)
{
    if (!queue || !storage || !elementSize || !capacity)
    {
        return kArInvalidParameterError;
    }
    if (ar_port_get_irq_state())
    {
        return kArNotFromInterruptError;
    }

    memset(queue, 0, sizeof(ar_queue_t));

    queue->m_name = name ? name : AR_ANONYMOUS_OBJECT_NAME;
    queue->m_elements = reinterpret_cast<uint8_t *>(storage);
    queue->m_elementSize = elementSize;
    queue->m_capacity = capacity;

    queue->m_runLoopNode.m_obj = queue;

#if AR_GLOBAL_OBJECT_LISTS
    queue->m_createdNode.m_obj = queue;
    g_ar_objects.queues.add(&queue->m_createdNode);
#endif // AR_GLOBAL_OBJECT_LISTS

    return kArSuccess;
}

// See ar_kernel.h for documentation of this function.
ar_status_t ar_queue_delete(ar_queue_t * queue)
{
    if (!queue)
    {
        return kArInvalidParameterError;
    }
    if (ar_port_get_irq_state())
    {
        return kArNotFromInterruptError;
    }

    // Unblock all threads blocked on this queue.
    ar_thread_t * thread;
    while (queue->m_sendBlockedList.m_head)
    {
        thread = queue->m_sendBlockedList.getHead<ar_thread_t>();
        thread->unblockWithStatus(queue->m_sendBlockedList, kArObjectDeletedError);
    }

    while (queue->m_receiveBlockedList.m_head)
    {
        thread = queue->m_receiveBlockedList.getHead<ar_thread_t>();
        thread->unblockWithStatus(queue->m_receiveBlockedList, kArObjectDeletedError);
    }

#if AR_GLOBAL_OBJECT_LISTS
    g_ar_objects.queues.remove(&queue->m_createdNode);
#endif // AR_GLOBAL_OBJECT_LISTS

    return kArSuccess;
}

static ar_status_t ar_queue_send_internal(ar_queue_t * queue, const void * element, uint32_t timeout)
{
    KernelLock guard;

    // Check for full queue.
    while (queue->m_count >= queue->m_capacity)
    {
        // If the queue is full and a zero timeout was given, return immediately.
        if (timeout == kArNoTimeout)
        {
            return kArQueueFullError;
        }

        // Otherwise block until the queue has room.
        ar_thread_t * thread = g_ar.currentThread;
        thread->block(queue->m_sendBlockedList, timeout);

        // We're back from the scheduler.
        // Check for errors and exit early if there was one.
        if (thread->m_unblockStatus != kArSuccess)
        {
            // Probably timed out waiting for room in the queue.
            queue->m_sendBlockedList.remove(&thread->m_blockedNode);
            return thread->m_unblockStatus;
        }
    }

    // Copy queue element into place.
    uint8_t * elementSlot = QUEUE_ELEMENT(queue, queue->m_tail);
    memcpy(elementSlot, element, queue->m_elementSize);

    // Update queue tail pointer and count.
    if (++queue->m_tail >= queue->m_capacity)
    {
        queue->m_tail = 0;
    }
    ++queue->m_count;

    // Are there any threads waiting to receive?
    if (queue->m_receiveBlockedList.m_head)
    {
        // Unblock the head of the blocked list.
        ar_thread_t * thread = queue->m_receiveBlockedList.getHead<ar_thread_t>();
        thread->unblockWithStatus(queue->m_receiveBlockedList, kArSuccess);
    }
    // Is the queue associated with a runloop?
    else if (queue->m_runLoop)
    {
        // Add this queue to the list of pending queues for the runloop, but first check
        // whether the queue is already pending so we don't attempt to add it twice.
        if (!queue->m_runLoop->m_queues.contains(&queue->m_runLoopNode))
        {
            queue->m_runLoop->m_queues.add(queue);
            ar_runloop_wake(queue->m_runLoop);
        }
    }

    return kArSuccess;
}

static void ar_queue_deferred_send(void * object, void * object2)
{
    ar_queue_send_internal(reinterpret_cast<ar_queue_t *>(object), object2, kArNoTimeout);
}

// See ar_kernel.h for documentation of this function.
ar_status_t ar_queue_send(ar_queue_t * queue, const void * element, uint32_t timeout)
{
    if (!queue || !element)
    {
        return kArInvalidParameterError;
    }

    // Handle irq state by deferring the operation.
    if (ar_port_get_irq_state())
    {
        return g_ar.deferredActions.post(ar_queue_deferred_send, queue, const_cast<void *>(element));
    }

    return ar_queue_send_internal(queue, element, timeout);
}

// See ar_kernel.h for documentation of this function.
ar_status_t ar_queue_receive(ar_queue_t * queue, void * element, uint32_t timeout)
{
    if (!queue || !element)
    {
        return kArInvalidParameterError;
    }
    if (ar_port_get_irq_state())
    {
        return kArNotFromInterruptError;
    }

    {
        KernelLock guard;

        // Check for empty queue.
        while (queue->m_count == 0)
        {
            if (timeout == kArNoTimeout)
            {
                return kArQueueEmptyError;
            }

            // Otherwise block until the queue has room.
            ar_thread_t * thread = g_ar.currentThread;
            thread->block(queue->m_receiveBlockedList, timeout);

            // We're back from the scheduler.
            // Check for errors and exit early if there was one.
            if (thread->m_unblockStatus != kArSuccess)
            {
                // Timed out waiting for the queue to not be empty, or another error occurred.
                queue->m_receiveBlockedList.remove(&thread->m_blockedNode);
                return thread->m_unblockStatus;
            }
        }

        // Read out data.
        uint8_t * elementSlot = QUEUE_ELEMENT(queue, queue->m_head);
        memcpy(element, elementSlot, queue->m_elementSize);

        // Update queue head and count.
        if (++queue->m_head >= queue->m_capacity)
        {
            queue->m_head = 0;
        }
        --queue->m_count;

        // Are there any threads waiting to send?
        if (queue->m_sendBlockedList.m_head)
        {
            // Unblock the head of the blocked list.
            ar_thread_t * thread = queue->m_sendBlockedList.getHead<ar_thread_t>();
            thread->unblockWithStatus(queue->m_sendBlockedList, kArSuccess);
        }
    }

    return kArSuccess;
}

// See ar_kernel.h for documentation of this function.
const char * ar_queue_get_name(ar_queue_t * queue)
{
    return queue ? queue->m_name : NULL;
}

//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------


text:
import isPrimitive from './isPrimitive'
import isType from './isType'

export interface CloneInterface extends Date, RegExp, Function {
  [propName: string]: any
  constructor: ObjectConstructor
}

/**
 * 深度克隆一个对象, 即使是包含了日期、正则、函数. 对于函数即使 clone 过, 也能拿到正确的 `this`.
 *
 * @param  {*} obj 待克隆的对象
 * @return {*}     深度克隆对象
 *
 * @example
 *
 * clone({ name: 'tom', range: [60, 80, 75] })
 * // => { name: 'tom', range: [60, 80, 75] }
 *
 * clone({ date: new Date(), regexp: new RegExp('d+', 'g'), call: function () { console.log('sewing') } })
 * // => { date: new Date(), regexp: new RegExp('d+', 'g'), call: function () { console.log('sewing') } }
 *
 * const obj = {
 *   range: 10,
 *   setRange () {
 *     return ++this.range && this
 *   }
 * }
 * clone(obj).setRange().range
 * // => 11
 *
 * obj.range
 * // => 10
 */
export default function clone<T extends CloneInterface> (
  obj: T,
  context?: any
): T {
  if (isPrimitive(obj)) return obj

  const result = isType(obj, 'Date') ? new Date(obj as Date)
    : isType(obj, 'RegExp') ? new RegExp(obj.source, obj.flags)
      : isType(obj, 'Function') ? obj.bind(context)
        : obj.constructor ? new obj.constructor() : Object.create(null)

  return Object.assign(result, ...Object.keys(obj).map(key => ({ [key]: clone(obj[key], result) })))
}


text:
export interface IWelcomeController {}

export class WelcomeController implements IWelcomeController {

    constructor() {
        'ngInject';
    }
}


text:
var Code = require('code');
var Hapi = require('hapi');
var Lab = require('lab');
var Hapier = require('../');

// Declare internals

var internals = {};

var lab = exports.lab = Lab.script();
var beforeEach = lab.beforeEach;
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;

describe('actions registration()', function () {

    var server;
    beforeEach(function (done) {

        server = new Hapi.Server({ debug: { log: ['hapier'] }});
        server.register({register: require('chairo'), options: {}}, function (err) {

            done(err);
        });
    });

    it('should work with initializers configured', function (done) {

        var opts = {
            initializers: {
                _dir: 'test/initializers',
                in1: {
                    hello: 'world'
                }
            }
        };
        server.register({ register: Hapier, options: opts }, function (err) {

            expect(err).not.to.exist();
            expect(server.plugins.hapier.hello).to.equal('world');
            //TODO: It could be nice somehow to ensure that no actions were found
            done();
        });
    });
});

describe('actions registration()', function () {

    var server;
    beforeEach(function (done) {

        server = new Hapi.Server({ debug: { log: ['hapier'] }});
        server.register({register: require('chairo'), options: {}}, function (err) {

            done(err);
        });
    });

    it('should work with empty plugin configuration', function (done) {

        server.register({ register: Hapier, options: {} }, function (err) {

            expect(err).not.to.exist();
            //TODO: It could be nice somehow to ensure that no actions were found
            done();
        });
    });

    it('should fail with corrupted plugin configuration', function (done) {

        server.register({ register: Hapier, options: {foo: 'bar'} }, function (err) {

            expect(err).to.exist();
            //TODO: It could be nice somehow to ensure that no actions were found
            done();
        });
    });

    it('should work with defined action dir', function (done) {

        var opts = {
            actions: {
                _dir: 'test/actions',
                nested: {
                    hello: {
                        color: 'pink'
                    }
                }
            }
        };
        server.connection();
        server.register({ register: Hapier, options: opts }, function (err) {

            expect(err).not.to.exist();
            server.route({
                method: 'GET',
                path: '/',
                handler: function (req, rep) {

                    rep.act({foo: 'bar', hello: 'world'});
                }
            });

            server.inject({
                method: 'GET',
                url: '/'
            }, function (resp) {

                expect(resp.result).to.deep.equal({hello: 'world', color: 'pink'});
                done();
            });
        });
    });
});

describe('routes registration()', function () {

    var server;
    beforeEach(function (done) {

        server = new Hapi.Server({ debug: { log: ['hapier'] }});
        server.register({register: require('chairo'), options: {}}, function (err) {

            done(err);
        });
    });

    it('should register routes', function (done) {

        server.register({ register: Hapier, options: {} }, function (err) {

            var opts = {
                routes: {
                    _dir: 'test/routes'
                }
            };
            server.connection();
            server.register({ register: Hapier, options: opts }, function (err) {

                expect(err).not.to.exist();

                server.inject({method: 'GET', url: '/api/pang'}, function (resp) {

                    expect(resp.result).to.equal('pang!');
                    server.inject({method: 'GET', url: '/api/hello/pong'}, function (resp) {

                        expect(resp.result).to.equal('pong!');
                        server.inject({method: 'GET', url: '/api/hello/world/ping'}, function (resp) {

                            expect(resp.result).to.equal('ping!');
                            server.inject({method: 'GET', url: '/foo/123'}, function (resp) {

                                expect(resp.result).to.equal('pong:123');
                                done();
                            });
                        });
                    });
                });
            });
        });
    });
});

describe('full scenario test', function () {

    var server;
    beforeEach(function (done) {

        server = new Hapi.Server({ debug: { log: ['hapier'] }});
        server.register({register: require('chairo'), options: {}}, function (err) {

            done(err);
        });
    });

    it('should register routes', function (done) {

        server.register({ register: Hapier, options: {} }, function (err) {

            var opts = {
                actions: {
                    _dir: 'test/full/actions',
                    ping: {
                        desc: 'A ping command.'
                    }
                },
                routes: {
                    _prefix: 'api',
                    _dir: 'test/full/routes'
                }
            };
            server.connection();
            server.register({ register: Hapier, options: opts }, function (err) {

                expect(err).not.to.exist();

                server.inject({method: 'GET', url: '/api/ping'}, function (resp) {

                    expect(resp.result).to.deep.equal({resp: 'pong', desc: opts.actions.ping.desc});
                    done();
                });
            });
        });
    });
});


text:
/*
 * service_tracker_test.cpp
 *
 *  \date       Feb 6, 2013
 *  \author     Apache Celix Project Team
 *  \copyright  Apache License, Version 2.0
 */
#include <stdlib.h>
#include <stdio.h>

#include "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"
#include "CppUTest/CommandLineTestRunner.h"
#include "CppUTestExt/MockSupport.h"

extern "C"
{
#include "service_tracker_private.h"
#include "service_reference_private.h"
#include "celix_log.h"

framework_logger_pt logger = (framework_logger_pt) 0x42;
}

int main(int argc, char** argv) {
	return RUN_ALL_TESTS(argc, argv);
}

TEST_GROUP(service_tracker) {
	void setup(void) {
	}

	void teardown() {
		mock().checkExpectations();
		mock().clear();
	}
};

TEST(service_tracker, create) {
	celix_status_t status;
	service_tracker_pt tracker = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x123;
	std::string service = "service";
	status = serviceTracker_create(ctx, (char *) service.c_str(), NULL, &tracker);

	LONGS_EQUAL(CELIX_SUCCESS, status);
	POINTERS_EQUAL(ctx, tracker->context);
	POINTERS_EQUAL(NULL, tracker->customizer);
	POINTERS_EQUAL(NULL, tracker->listener);
	POINTERS_EQUAL(tracker, tracker->tracker);
	STRCMP_EQUAL("(objectClass=service)", tracker->filter);

	serviceTracker_destroy(tracker);
}

TEST(service_tracker, createWithFilter) {
	celix_status_t status;
	service_tracker_pt tracker = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x123;
	std::string filter = "(objectClass=test)";
	status = serviceTracker_createWithFilter(ctx, (char *) filter.c_str(), NULL, &tracker);

	LONGS_EQUAL(CELIX_SUCCESS, status);
	POINTERS_EQUAL(ctx, tracker->context);
	POINTERS_EQUAL(NULL, tracker->customizer);
	POINTERS_EQUAL(NULL, tracker->listener);
	POINTERS_EQUAL(tracker, tracker->tracker);
	STRCMP_EQUAL("(objectClass=test)", tracker->filter);

	serviceTracker_destroy(tracker);
}

TEST(service_tracker, destroy) {
	celix_status_t status;
	service_tracker_pt tracker = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x123;
	std::string filter = "(objectClass=test)";
	status = serviceTracker_createWithFilter(ctx, (char *) filter.c_str(), NULL, &tracker);
	LONGS_EQUAL(CELIX_SUCCESS, status);
	service_listener_pt listener = (service_listener_pt) calloc(1, sizeof(serviceListener));
	tracker->listener = listener;

	mock()
		.expectOneCall("bundleContext_removeServiceListener")
		.withParameter("context", ctx)
		.withParameter("listener", listener)
		.andReturnValue(CELIX_SUCCESS);

	status = serviceTracker_destroy(tracker);
	LONGS_EQUAL(CELIX_SUCCESS, status);
}

TEST(service_tracker, open) {
	// Without initial services and no customizer
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	std::string filter = "(objectClass=service)";
	tracker->filter = (char *) filter.c_str();
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;

	array_list_pt refs = NULL;
	arrayList_create(&refs);

	mock().strictOrder();
	mock()
		.expectOneCall("bundleContext_getServiceReferences")
		.withParameter("context", ctx)
		.withParameter("serviceName", (char *) NULL)
		.withParameter("filter", "(objectClass=service)")
		.withOutputParameterReturning("service_references", &refs, sizeof(refs))
		.andReturnValue(CELIX_SUCCESS);
	mock()
		.expectOneCall("bundleContext_addServiceListener")
		.withParameter("context", ctx)
		.withParameter("filter", "(objectClass=service)")
		.ignoreOtherParameters()
		.andReturnValue(CELIX_SUCCESS);
	serviceTracker_open(tracker);
	CHECK(tracker->listener != NULL);

	// No services should be found
	LONGS_EQUAL(0, arrayList_size(tracker->trackedServices));

	arrayList_destroy(tracked);

	free(tracker->listener);
	free(tracker);
}

TEST(service_tracker, open_withRefs) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	tracker->customizer = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	std::string filter = "(objectClass=service)";
	tracker->filter = (char *) filter.c_str();
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
//	// add tracked to tracker->trackedServices
//	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
//	entry->service = (void *) 0x31;
//	service_reference_pt ref = (service_reference_pt) 0x51;
//	entry->reference = ref;
//	arrayList_add(tracked, entry);
//	tracked_pt entry2 = (tracked_pt) malloc(sizeof(*entry));
//	entry2->service = (void *) 0x32;
//	service_reference_pt ref2 = (service_reference_pt) 0x52;
//	entry2->reference = ref2;
//	arrayList_add(tracked, entry2);

	array_list_pt refs = NULL;
	arrayList_create(&refs);
	service_reference_pt ref = (service_reference_pt) malloc(sizeof(*ref));
	arrayList_add(refs, ref);
	void *src = (void *) 0x345;

//	mock().strictOrder();
	mock()
		.expectOneCall("bundleContext_getServiceReferences")
		.withParameter("context", ctx)
		.withParameter("serviceName", (char *) NULL)
		.withParameter("filter", "(objectClass=service)")
		.withOutputParameterReturning("service_references", &refs, sizeof(refs))
		.andReturnValue(CELIX_SUCCESS);
	mock()
		.expectOneCall("bundleContext_addServiceListener")
		.withParameter("context", ctx)
		.withParameter("filter", "(objectClass=service)")
		.ignoreOtherParameters()
		.andReturnValue(CELIX_SUCCESS);
	mock()
		.expectOneCall("bundleContext_getService")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.withOutputParameterReturning("service_instance", &src, sizeof(src))
		.andReturnValue(CELIX_SUCCESS);
	serviceTracker_open(tracker);
	CHECK(tracker->listener != NULL);

	// One service should be found
	LONGS_EQUAL(1, arrayList_size(tracker->trackedServices));

	free(arrayList_get(tracked, 0));
	arrayList_destroy(tracked);

	free(tracker->listener);
	free(tracker);
	free(ref);
}

TEST(service_tracker, open_withRefsAndTracked) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	tracker->customizer = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	std::string filter = "(objectClass=service)";
	tracker->filter = (char *) filter.c_str();
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	array_list_pt refs = NULL;
	arrayList_create(&refs);
	arrayList_add(refs, ref);

//	mock().strictOrder();
	mock()
		.expectOneCall("bundleContext_getServiceReferences")
		.withParameter("context", ctx)
		.withParameter("serviceName", (char *) NULL)
		.withParameter("filter", "(objectClass=service)")
		.withOutputParameterReturning("service_references", &refs, sizeof(refs))
		.andReturnValue(CELIX_SUCCESS);
	mock()
		.expectOneCall("bundleContext_addServiceListener")
		.withParameter("context", ctx)
		.withParameter("filter", "(objectClass=service)")
		.ignoreOtherParameters()
		.andReturnValue(CELIX_SUCCESS);

	bool equal = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withParameter("compareTo", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		//.ignoreOtherParameters()
		.andReturnValue(CELIX_SUCCESS);

	serviceTracker_open(tracker);
	CHECK(tracker->listener != NULL);

	// One service should be found
	LONGS_EQUAL(1, arrayList_size(tracker->trackedServices));

	arrayList_destroy(tracked);

	free(tracker->listener);
	free(tracker);
	free(entry);
}

TEST(service_tracker, close) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	tracker->customizer = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x345;
	tracker->context = ctx;
	// new tracker->listener
	service_listener_pt listener = (service_listener_pt) 0x42;
	tracker->listener = (service_listener_pt) listener;
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	mock()
		.expectOneCall("bundleContext_removeServiceListener")
		.withParameter("context", ctx)
		.withParameter("listener", listener)
		.andReturnValue(CELIX_SUCCESS);
	bool equal = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withParameter("compareTo", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		.andReturnValue(CELIX_SUCCESS);
	bool result = true;
	mock()
		.expectOneCall("bundleContext_ungetService")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.withOutputParameterReturning("result", &result, sizeof(result))
		.andReturnValue(CELIX_SUCCESS);

	mock()
		.expectOneCall("bundleContext_ungetServiceReference")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.andReturnValue(CELIX_SUCCESS);

	serviceTracker_close(tracker);

	arrayList_destroy(tracked);
	free(tracker);
}

TEST(service_tracker, getServiceReference) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);
	tracked_pt entry2 = (tracked_pt) malloc(sizeof(*entry));
	entry2->service = (void *) 0x32;
	service_reference_pt ref2 = (service_reference_pt) 0x52;
	entry2->reference = ref2;
	arrayList_add(tracked, entry2);

	service_reference_pt reference = serviceTracker_getServiceReference(tracker);
	POINTERS_EQUAL(ref, reference);

	arrayList_destroy(tracked);

	free(tracker);
	free(entry);
	free(entry2);
}

TEST(service_tracker, getServiceReferenceNull) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;

	service_reference_pt reference = serviceTracker_getServiceReference(tracker);
	POINTERS_EQUAL(NULL, reference);

	arrayList_destroy(tracked);
	free(tracker);
}

TEST(service_tracker, getServiceReferences) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);
	tracked_pt entry2 = (tracked_pt) malloc(sizeof(*entry));
	entry2->service = (void *) 0x32;
	service_reference_pt ref2 = (service_reference_pt) 0x52;
	entry2->reference = ref2;
	arrayList_add(tracked, entry2);

	array_list_pt references = serviceTracker_getServiceReferences(tracker);
	LONGS_EQUAL(2, arrayList_size(references));
	POINTERS_EQUAL(ref, arrayList_get(references, 0));
	POINTERS_EQUAL(ref2, arrayList_get(references, 1));

	arrayList_destroy(references);
	arrayList_destroy(tracked);

	free(tracker);
	free(entry);
	free(entry2);
}

TEST(service_tracker, getService) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);
	tracked_pt entry2 = (tracked_pt) malloc(sizeof(*entry));
	entry2->service = (void *) 0x32;
	service_reference_pt ref2 = (service_reference_pt) 0x52;
	entry2->reference = ref2;
	arrayList_add(tracked, entry2);

	void *service = serviceTracker_getService(tracker);
	POINTERS_EQUAL(0x31, service);

	arrayList_destroy(tracked);

	free(entry);
	free(entry2);
	free(tracker);
}

TEST(service_tracker, getServiceNull) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;

	void *service = serviceTracker_getService(tracker);
	POINTERS_EQUAL(NULL, service);

	arrayList_destroy(tracked);
	free(tracker);
}

TEST(service_tracker, getServices) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);
	tracked_pt entry2 = (tracked_pt) malloc(sizeof(*entry));
	entry2->service = (void *) 0x32;
	service_reference_pt ref2 = (service_reference_pt) 0x52;
	entry2->reference = ref2;
	arrayList_add(tracked, entry2);

	array_list_pt services = serviceTracker_getServices(tracker);
	LONGS_EQUAL(2, arrayList_size(services));
	POINTERS_EQUAL(0x31, arrayList_get(services, 0));
	POINTERS_EQUAL(0x32, arrayList_get(services, 1));

	arrayList_destroy(services);
	arrayList_destroy(tracked);

	free(entry);
	free(entry2);
	free(tracker);
}

TEST(service_tracker, getServiceByReference) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	bool equal = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withParameter("compareTo", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		.andReturnValue(4);
		//.ignoreOtherParameters();
	void *service = serviceTracker_getServiceByReference(tracker, ref);
	POINTERS_EQUAL(0x31, service);

	arrayList_destroy(tracked);

	free(tracker);
	free(entry);
}

TEST(service_tracker, getServiceByReferenceNull) {
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	bool equal = false;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		.ignoreOtherParameters()
		.andReturnValue(CELIX_SUCCESS)
		.withCallOrder(1);
	void *service = serviceTracker_getServiceByReference(tracker, ref);
	POINTERS_EQUAL(NULL, service);

	arrayList_destroy(tracked);

	free(tracker);
	free(entry);
}

TEST(service_tracker, serviceChangedRegistered) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	tracker->customizer = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;

	service_reference_pt ref = (service_reference_pt) 0x51;

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_REGISTERED;
	event->reference = ref;

	void *src = (void *) 0x345;
	mock()
		.expectOneCall("bundleContext_getService")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.withOutputParameterReturning("service_instance", &src, sizeof(src))
		.andReturnValue(CELIX_SUCCESS);
	serviceTracker_serviceChanged(listener, event);

	free(arrayList_get(tracked, 0));
	arrayList_destroy(tracked);

	free(event);
	free(tracker);
	free(listener);
}

TEST(service_tracker, serviceChangedModified) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	tracker->customizer = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;

	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
//	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_MODIFIED;
	event->reference = ref;

	bool equal = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		.ignoreOtherParameters()
		.andReturnValue(CELIX_SUCCESS);

	serviceTracker_serviceChanged(listener, event);

	free(arrayList_get(tracked, 0));
	free(arrayList_get(tracked, 1));
	arrayList_destroy(tracked);

	free(event);
	free(listener);
	free(tracker);
}

TEST(service_tracker, serviceChangedUnregistering) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	tracker->customizer = NULL;
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;

	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
//	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_UNREGISTERING;
	event->reference = ref;

	bool equal = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withParameter("compareTo", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		.andReturnValue(CELIX_SUCCESS);
	bool result = true;
	mock()
		.expectOneCall("bundleContext_ungetService")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.withOutputParameterReturning("result", &result, sizeof(result))
		.andReturnValue(CELIX_SUCCESS);

	mock()
		.expectOneCall("bundleContext_ungetServiceReference")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.andReturnValue(CELIX_SUCCESS);

	serviceTracker_serviceChanged(listener, event);

	arrayList_destroy(tracked);

	free(listener);
	free(event);
	free(tracker);
}

TEST(service_tracker, serviceChangedModifiedEndmatch) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;

	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
//	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_MODIFIED_ENDMATCH;
	event->reference = ref;

	serviceTracker_serviceChanged(listener, event);

	arrayList_destroy(tracked);

	free(entry);
	free(listener);
	free(tracker);
	free(event);
}

extern "C" {
	celix_status_t serviceDependency_addingService(void * handle, service_reference_pt reference, void **service) {
		*service = (void*) 0x45;
		return CELIX_SUCCESS;
	}

	celix_status_t serviceDependency_addedService(void * handle, service_reference_pt reference, void *service) {
		return CELIX_SUCCESS;
	}
}

TEST(service_tracker, serviceChangedRegisteredCustomizer) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
	service_tracker_customizer_pt customizer = (service_tracker_customizer_pt) 0x20;
	tracker->customizer = customizer;

	service_reference_pt ref = (service_reference_pt) 0x51;

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_REGISTERED;
	event->reference = ref;

	void * handle = (void*) 0x60;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getHandle")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("handle", &handle, sizeof(handle))
		.andReturnValue(CELIX_SUCCESS);
	void *function = (void *) serviceDependency_addingService;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getAddingFunction")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("function", &function, sizeof(function))
		.andReturnValue(CELIX_SUCCESS);
	mock()
		.expectOneCall("serviceTrackerCustomizer_getHandle")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("handle", &handle, sizeof(handle))
		.andReturnValue(CELIX_SUCCESS);
	void *function2 = (void *) serviceDependency_addedService;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getAddedFunction")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("function", &function2, sizeof(function))
		.andReturnValue(CELIX_SUCCESS);
	serviceTracker_serviceChanged(listener, event);

	free(arrayList_get(tracked, 0));
	arrayList_destroy(tracked);

	free(event);
	free(tracker);
	free(listener);
}

extern "C" {
	celix_status_t serviceDependency_modifiedService(void * handle, service_reference_pt reference, void * service) {
		return CELIX_SUCCESS;
	}
}

TEST(service_tracker, serviceChangedModifiedCustomizer) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;
	service_tracker_customizer_pt customizer = (service_tracker_customizer_pt) 0x20;
	tracker->customizer = customizer;
	//adding_callback_pt adding_func = NULL;
	//added_callback_pt added_func = NULL;

	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
//	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_MODIFIED;
	event->reference = ref;

	bool equal = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		.ignoreOtherParameters()
		.andReturnValue(CELIX_SUCCESS);
	void * handle = (void*) 0x60;

/*	this branch is not covered here, unlike earlier faulty tests
	mock()
		.expectOneCall("serviceTrackerCustomizer_getHandle")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("handle", &handle, sizeof(handle))
		.andReturnValue(CELIX_SUCCESS);

	mock()
		.expectOneCall("serviceTrackerCustomizer_getAddingFunction")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("function", &adding_func, sizeof(adding_func))
		.andReturnValue(CELIX_SUCCESS);

	mock()
		.expectOneCall("serviceTrackerCustomizer_getAddedFunction")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("function", &added_func, sizeof(added_func));

	mock()
		.expectOneCall("bundleContext_getService")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.withOutputParameterReturning("service_instance", &entry->service, sizeof(entry->service));
*/

	mock()
			.expectOneCall("serviceTrackerCustomizer_getHandle")
			.withParameter("customizer", customizer)
			.withOutputParameterReturning("handle", &handle, sizeof(handle))
			.andReturnValue(CELIX_SUCCESS);

	void *function = (void *) serviceDependency_modifiedService;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getModifiedFunction")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("function", &function, sizeof(function))
		.andReturnValue(CELIX_SUCCESS);

	serviceTracker_serviceChanged(listener, event);

	free(arrayList_get(tracked, 0));
	free(arrayList_get(tracked, 1));
	arrayList_destroy(tracked);

	free(event);
	free(listener);
	free(tracker);
}

extern "C" {
	celix_status_t serviceDependency_removedService(void * handle, service_reference_pt reference, void * service) {
		return CELIX_SUCCESS;
	}
}

TEST(service_tracker, serviceChangedUnregisteringCustomizer) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;
	service_tracker_customizer_pt customizer = (service_tracker_customizer_pt) 0x20;
	tracker->customizer = customizer;

	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
//	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_UNREGISTERING;
	event->reference = ref;

	bool equal = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withParameter("compareTo", ref)
		.withOutputParameterReturning("equal", &equal, sizeof(equal))
		.andReturnValue(CELIX_SUCCESS);
	void * handle = (void*) 0x60;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getHandle")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("handle", &handle, sizeof(handle))
		.andReturnValue(CELIX_SUCCESS);
	void *function = (void*) serviceDependency_removedService;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getRemovedFunction")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("function", &function , sizeof(function))
		.andReturnValue(CELIX_SUCCESS);

	mock()
		.expectOneCall("bundleContext_ungetServiceReference")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.andReturnValue(CELIX_SUCCESS);
	serviceTracker_serviceChanged(listener, event);

	arrayList_destroy(tracked);

	free(listener);
	free(event);
	free(tracker);
}

TEST(service_tracker, serviceChangedUnregisteringCustomizerNoFunc) {
	// With one initial service
	// new tracker
	service_tracker_pt tracker = (service_tracker_pt) malloc(sizeof(*tracker));
	bundle_context_pt ctx = (bundle_context_pt) 0x10;
	tracker->context = ctx;
	service_listener_pt listener = (service_listener_pt) malloc(sizeof(*listener));
	tracker->listener = listener;
	listener->handle = tracker;
	service_tracker_customizer_pt customizer = (service_tracker_customizer_pt) 0x20;
	tracker->customizer = customizer;

	// new tracker->trackedServices
	array_list_pt tracked = NULL;
	arrayList_create(&tracked);
	tracker->trackedServices = tracked;
//	// add tracked to tracker->trackedServices
	tracked_pt entry = (tracked_pt) malloc(sizeof(*entry));
	entry->service = (void *) 0x31;
	service_reference_pt ref = (service_reference_pt) 0x51;
	entry->reference = ref;
	arrayList_add(tracked, entry);

	service_event_pt event = (service_event_pt) malloc(sizeof(*event));
	event->type = OSGI_FRAMEWORK_SERVICE_EVENT_UNREGISTERING;
	event->reference = ref;

	bool equals = true;
	mock()
		.expectOneCall("serviceReference_equals")
		.withParameter("reference", ref)
		.withParameter("compareTo", ref)
		.withOutputParameterReturning("equal", &equals, sizeof(equals))
		.andReturnValue(CELIX_SUCCESS);
	void * handle = (void*) 0x60;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getHandle")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("handle", &handle, sizeof(handle))
		.andReturnValue(CELIX_SUCCESS);
	void *function = NULL;
	mock()
		.expectOneCall("serviceTrackerCustomizer_getRemovedFunction")
		.withParameter("customizer", customizer)
		.withOutputParameterReturning("function", &function, sizeof(function))
		.andReturnValue(CELIX_SUCCESS);
	bool result = true;
	mock()
		.expectOneCall("bundleContext_ungetService")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.withOutputParameterReturning("result", &result, sizeof(result))
		.andReturnValue(CELIX_SUCCESS);

	mock()
		.expectOneCall("bundleContext_ungetServiceReference")
		.withParameter("context", ctx)
		.withParameter("reference", ref)
		.andReturnValue(CELIX_SUCCESS);

	serviceTracker_serviceChanged(listener, event);

	arrayList_destroy(tracked);
	free(listener);
	free(tracker);
	free(event);
}


text:
namespace SkypeMessageSearch
{
    public class SkypeContact
    {
        public string SkypeName { get; set; }
        public string Name { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, SkypeName);
        }
    }
}


text:
"""Utilities for generating code coverage reports for Android tests."""

# Python imports
import glob
import optparse
import os

# local imports
import android_build
import android_mk
import coverage_target
import coverage_targets
import errors
import logger
import run_command

class CoverageGenerator(object):
  """Helper utility for obtaining code coverage results on Android.

  Intended to simplify the process of building,running, and generating code
  coverage results for a pre-defined set of tests and targets
  """

    # path to EMMA host jar, relative to Android build root
  _EMMA_JAR = os.path.join("external", "emma", "lib", "emma.jar")
  _TEST_COVERAGE_EXT = "ec"
  # root path of generated coverage report files, relative to Android build root
  _COVERAGE_REPORT_PATH = "emma"
  _TARGET_DEF_FILE = "coverage_targets.xml"
  _CORE_TARGET_PATH = os.path.join("development", "testrunner",
                                   _TARGET_DEF_FILE)
  # vendor glob file path patterns to tests, relative to android
  # build root
  _VENDOR_TARGET_PATH = os.path.join("vendor", "*", "tests", "testinfo",
                                     _TARGET_DEF_FILE)

  # path to root of target build intermediates
  _TARGET_INTERMEDIATES_BASE_PATH = os.path.join("target", "common",
                                                 "obj")

  def __init__(self, adb_interface):
    self._root_path = android_build.GetTop()
    self._out_path = android_build.GetOut()
    self._output_root_path = os.path.join(self._out_path,
                                          self._COVERAGE_REPORT_PATH)
    self._emma_jar_path = os.path.join(self._root_path, self._EMMA_JAR)
    self._adb = adb_interface
    self._targets_manifest = self._ReadTargets()

  def ExtractReport(self,
                    test_suite_name,
                    target,
                    device_coverage_path,
                    output_path=None,
                    test_qualifier=None):
    """Extract runtime coverage data and generate code coverage report.

    Assumes test has just been executed.
    Args:
      test_suite_name: name of TestSuite to generate coverage data for
      target: the CoverageTarget to use as basis for coverage calculation
      device_coverage_path: location of coverage file on device
      output_path: path to place output files in. If None will use
        <android_out_path>/<_COVERAGE_REPORT_PATH>/<target>/<test[-qualifier]>
      test_qualifier: designates mode test was run with. e.g size=small.
        If not None, this will be used to customize output_path as shown above.

    Returns:
      absolute file path string of generated html report file.
    """
    if output_path is None:
      report_name = test_suite_name
      if test_qualifier:
        report_name = report_name + "-" + test_qualifier
      output_path = os.path.join(self._out_path,
                                 self._COVERAGE_REPORT_PATH,
                                 target.GetName(),
                                 report_name)

    coverage_local_name = "%s.%s" % (report_name,
                                     self._TEST_COVERAGE_EXT)
    coverage_local_path = os.path.join(output_path,
                                       coverage_local_name)
    if self._adb.Pull(device_coverage_path, coverage_local_path):

      report_path = os.path.join(output_path,
                                 report_name)
      return self._GenerateReport(report_path, coverage_local_path, [target],
                                  do_src=True)
    return None

  def _GenerateReport(self, report_path, coverage_file_path, targets,
                      do_src=True):
    """Generate the code coverage report.

    Args:
      report_path: absolute file path of output file, without extension
      coverage_file_path: absolute file path of code coverage result file
      targets: list of CoverageTargets to use as base for code coverage
          measurement.
      do_src: True if generate coverage report with source linked in.
          Note this will increase size of generated report.

    Returns:
      absolute file path to generated report file.
    """
    input_metadatas = self._GatherMetadatas(targets)

    if do_src:
      src_arg = self._GatherSrcs(targets)
    else:
      src_arg = ""

    report_file = "%s.html" % report_path
    cmd1 = ("java -cp %s emma report -r html -in %s %s %s " %
            (self._emma_jar_path, coverage_file_path, input_metadatas, src_arg))
    cmd2 = "-Dreport.html.out.file=%s" % report_file
    self._RunCmd(cmd1 + cmd2)
    return report_file

  def _GatherMetadatas(self, targets):
    """Builds the emma input metadata argument from provided targets.

    Args:
      targets: list of CoverageTargets

    Returns:
      input metadata argument string
    """
    input_metadatas = ""
    for target in targets:
      input_metadata = os.path.join(self._GetBuildIntermediatePath(target),
                                    "coverage.em")
      input_metadatas += " -in %s" % input_metadata
    return input_metadatas

  def _GetBuildIntermediatePath(self, target):
    return os.path.join(
        self._out_path, self._TARGET_INTERMEDIATES_BASE_PATH, target.GetType(),
        "%s_intermediates" % target.GetName())

  def _GatherSrcs(self, targets):
    """Builds the emma input source path arguments from provided targets.

    Args:
      targets: list of CoverageTargets
    Returns:
      source path arguments string
    """
    src_list = []
    for target in targets:
      target_srcs = target.GetPaths()
      for path in target_srcs:
        src_list.append("-sp %s" %  os.path.join(self._root_path, path))
    return " ".join(src_list)

  def _MergeFiles(self, input_paths, dest_path):
    """Merges a set of emma coverage files into a consolidated file.

    Args:
      input_paths: list of string absolute coverage file paths to merge
      dest_path: absolute file path of destination file
    """
    input_list = []
    for input_path in input_paths:
      input_list.append("-in %s" % input_path)
    input_args = " ".join(input_list)
    self._RunCmd("java -cp %s emma merge %s -out %s" % (self._emma_jar_path,
                                                        input_args, dest_path))

  def _RunCmd(self, cmd):
    """Runs and logs the given os command."""
    run_command.RunCommand(cmd, return_output=False)

  def _CombineTargetCoverage(self):
    """Combines all target mode code coverage results.

    Will find all code coverage data files in direct sub-directories of
    self._output_root_path, and combine them into a single coverage report.
    Generated report is placed at self._output_root_path/android.html
    """
    coverage_files = self._FindCoverageFiles(self._output_root_path)
    combined_coverage = os.path.join(self._output_root_path,
                                     "android.%s" % self._TEST_COVERAGE_EXT)
    self._MergeFiles(coverage_files, combined_coverage)
    report_path = os.path.join(self._output_root_path, "android")
    # don't link to source, to limit file size
    self._GenerateReport(report_path, combined_coverage,
                         self._targets_manifest.GetTargets(), do_src=False)

  def _CombineTestCoverage(self):
    """Consolidates code coverage results for all target result directories."""
    target_dirs = os.listdir(self._output_root_path)
    for target_name in target_dirs:
      output_path = os.path.join(self._output_root_path, target_name)
      target = self._targets_manifest.GetTarget(target_name)
      if os.path.isdir(output_path) and target is not None:
        coverage_files = self._FindCoverageFiles(output_path)
        combined_coverage = os.path.join(output_path, "%s.%s" %
                                         (target_name, self._TEST_COVERAGE_EXT))
        self._MergeFiles(coverage_files, combined_coverage)
        report_path = os.path.join(output_path, target_name)
        self._GenerateReport(report_path, combined_coverage, [target])
      else:
        logger.Log("%s is not a valid target directory, skipping" % output_path)

  def _FindCoverageFiles(self, root_path):
    """Finds all files in <root_path>/*/*.<_TEST_COVERAGE_EXT>.

    Args:
      root_path: absolute file path string to search from
    Returns:
      list of absolute file path strings of coverage files
    """
    file_pattern = os.path.join(root_path, "*", "*.%s" %
                                self._TEST_COVERAGE_EXT)
    coverage_files = glob.glob(file_pattern)
    return coverage_files

  def _ReadTargets(self):
    """Parses the set of coverage target data.

    Returns:
       a CoverageTargets object that contains set of parsed targets.
    Raises:
       AbortError if a fatal error occurred when parsing the target files.
    """
    core_target_path = os.path.join(self._root_path, self._CORE_TARGET_PATH)
    try:
      targets = coverage_targets.CoverageTargets()
      targets.Parse(core_target_path)
      vendor_targets_pattern = os.path.join(self._root_path,
                                            self._VENDOR_TARGET_PATH)
      target_file_paths = glob.glob(vendor_targets_pattern)
      for target_file_path in target_file_paths:
        targets.Parse(target_file_path)
      return targets
    except errors.ParseError:
      raise errors.AbortError

  def TidyOutput(self):
    """Runs tidy on all generated html files.

    This is needed to the html files can be displayed cleanly on a web server.
    Assumes tidy is on current PATH.
    """
    logger.Log("Tidying output files")
    self._TidyDir(self._output_root_path)

  def _TidyDir(self, dir_path):
    """Recursively tidy all html files in given dir_path."""
    html_file_pattern = os.path.join(dir_path, "*.html")
    html_files_iter = glob.glob(html_file_pattern)
    for html_file_path in html_files_iter:
      os.system("tidy -m -errors -quiet %s" % html_file_path)
    sub_dirs = os.listdir(dir_path)
    for sub_dir_name in sub_dirs:
      sub_dir_path = os.path.join(dir_path, sub_dir_name)
      if os.path.isdir(sub_dir_path):
        self._TidyDir(sub_dir_path)

  def CombineCoverage(self):
    """Create combined coverage reports for all targets and tests."""
    self._CombineTestCoverage()
    self._CombineTargetCoverage()

  def GetCoverageTarget(self, name):
    """Find the CoverageTarget for given name"""
    target = self._targets_manifest.GetTarget(name)
    if target is None:
      msg = ["Error: test references undefined target %s." % name]
      msg.append(" Ensure target is defined in %s" % self._TARGET_DEF_FILE)
      raise errors.AbortError(msg)
    return target

  def GetCoverageTargetForPath(self, path):
    """Find the CoverageTarget for given file system path"""
    android_mk_path = os.path.join(path, "Android.mk")
    if os.path.exists(android_mk_path):
      android_mk_parser = android_mk.CreateAndroidMK(path)
      target = coverage_target.CoverageTarget()
      target.SetBuildPath(os.path.join(path, "src"))
      target.SetName(android_mk_parser.GetVariable(android_mk_parser.PACKAGE_NAME))
      target.SetType("APPS")
      return target
    else:
      msg = "No Android.mk found at %s" % path
      raise errors.AbortError(msg)

def EnableCoverageBuild():
  """Enable building an Android target with code coverage instrumentation."""
  os.environ["EMMA_INSTRUMENT"] = "true"

def Run():
  """Does coverage operations based on command line args."""
  # TODO: do we want to support combining coverage for a single target

  try:
    parser = optparse.OptionParser(usage="usage: %prog --combine-coverage")
    parser.add_option(
        "-c", "--combine-coverage", dest="combine_coverage", default=False,
        action="store_true", help="Combine coverage results stored given "
        "android root path")
    parser.add_option(
        "-t", "--tidy", dest="tidy", default=False, action="store_true",
        help="Run tidy on all generated html files")

    options, args = parser.parse_args()

    coverage = CoverageGenerator(None)
    if options.combine_coverage:
      coverage.CombineCoverage()
    if options.tidy:
      coverage.TidyOutput()
  except errors.AbortError:
    logger.SilentLog("Exiting due to AbortError")

if __name__ == "__main__":
  Run()


text:
(function() {

    _T.createModuleTest('wt.home')
        .describe(function() {
            var moduleTest = this;

            moduleTest
                .createControllerTest('wtHome')
                .describe(function() {

                });
        });
})();


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Able Polecat: AblePolecat_Message_RequestInterface Interface Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Able Polecat
    0.7.0

Able Polecat Core Class Library

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Class Hierarchy

Data Fields

Public Member Functions |
Data Fields

AblePolecat_Message_RequestInterface Interface Reference

Inheritance diagram for AblePolecat_Message_RequestInterface:

  <map id="AblePolecat_Message_RequestInterface_map" name="AblePolecat_Message_RequestInterface_map">
<area href="interface_able_polecat___message_interface.html" alt="AblePolecat_MessageInterface" shape="rect" coords="554,112,821,136"/>
<area href="interface_able_polecat___dynamic_object_interface.html" alt="AblePolecat_DynamicObjectInterface" shape="rect" coords="415,56,682,80"/>
<area href="interface_able_polecat___overloadable_interface.html" alt="AblePolecat_OverloadableInterface" shape="rect" coords="692,56,959,80"/>
<area href="interface_able_polecat___std_object_interface.html" alt="AblePolecat_StdObjectInterface" shape="rect" coords="415,0,682,24"/>
<area href="class_able_polecat___message___request_abstract.html" alt="AblePolecat_Message_RequestAbstract" shape="rect" coords="554,224,821,248"/>
<area href="class_able_polecat___message___request___delete.html" alt="AblePolecat_Message_Request_Delete" shape="rect" coords="0,280,267,304"/>
<area href="class_able_polecat___message___request___get.html" alt="AblePolecat_Message_Request_Get" shape="rect" coords="277,280,544,304"/>
<area href="class_able_polecat___message___request___post.html" alt="AblePolecat_Message_Request_Post" shape="rect" coords="554,280,821,304"/>
<area href="class_able_polecat___message___request___put.html" alt="AblePolecat_Message_Request_Put" shape="rect" coords="831,280,1098,304"/>
<area href="class_able_polecat___message___request___unsupported.html" alt="AblePolecat_Message_Request_Unsupported" shape="rect" coords="1108,280,1375,304"/>
</map>

Public Member Functions

 	getHostName ()

 	getMethod ()

 	getResource ()

 	getRequestPathInfo ()

 	getRequestPath ($asString=TRUE)

 	getRequestQueryString ($asString=TRUE)

 	getBaseUrl ($trailing_slash=TRUE)

 	getRawRequestLogRecordId ()

 	getRedirectUrl ()

 	validateResourceName ($requestedResourceName)

 Public Member Functions inherited from AblePolecat_StdObjectInterface

 	__set ($name, $value)

 	__get ($name)

 	__isset ($name)

 	__unset ($name)

 	getPropertyValue ($name, $default=NULL)

Data Fields

const 	URI = 'uri'

const 	URI_SLASH = URI_SLASH

const 	URI_PATH = 'path'

const 	URI_RESOURCE_NAME = 'resource_name'

const 	URI_REDIRECT = 'uri_redirect'

const 	URI_SEARCH_PARAM = 'q'

const 	RESOURCE_NAME_ACK = 'ack'

const 	RESOURCE_NAME_HOME = 'home'

const 	RESOURCE_NAME_ERROR = 'error'

const 	RESOURCE_NAME_FORM = 'form'

const 	RESOURCE_NAME_INSTALL = 'install'

const 	RESOURCE_NAME_SEARCH = 'search'

const 	RESOURCE_NAME_TEST = 'test'

const 	RESOURCE_NAME_UPDATE = 'update'

const 	RESOURCE_NAME_UTIL = 'util'

 Data Fields inherited from AblePolecat_MessageInterface

const 	ENTITY_BODY = 'BODY'

const 	HEAD = 'HEAD'

Additional Inherited Members

 Static Public Member Functions inherited from AblePolecat_DynamicObjectInterface

static 	create ()

 Static Public Member Functions inherited from AblePolecat_OverloadableInterface

static 	unmarshallArgsList ($method_name, $args, $options=NULL)

Member Function Documentation

          getBaseUrl
          (

          $trailing_slash = TRUE	)

Returns

string Base URL (host name[/alias]).

Implemented in AblePolecat_Message_RequestAbstract.

          getHostName
          (
          	)

Returns

string

Implemented in AblePolecat_Message_RequestAbstract.

          getMethod
          (
          	)

Returns

string Request method.

Implemented in AblePolecat_Message_Request_Delete, AblePolecat_Message_Request_Put, AblePolecat_Message_Request_Get, AblePolecat_Message_Request_Post, and AblePolecat_Message_Request_Unsupported.

          getRawRequestLogRecordId
          (
          	)

Returns

mixed ID corresponding to record of raw request in database.

Implemented in AblePolecat_Message_RequestAbstract.

          getRedirectUrl
          (
          	)

Returns

mixed Redirect URL or FALSE.

Implemented in AblePolecat_Message_RequestAbstract.

          getRequestPath
          (

          $asString = TRUE	)

Return the path part of request URI.

Parameters

bool	$asString	If TRUE return path as string, otherwise return parts in array.

Returns

mixed return type depends on value of $asString

Implemented in AblePolecat_Message_RequestAbstract.

          getRequestPathInfo
          (
          	)

Return info relating to analysis of URI request path.

Returns

Array.

Implemented in AblePolecat_Message_RequestAbstract.

          getRequestQueryString
          (

          $asString = TRUE	)

Return the query string part of request URI.

Parameters

bool	$asString	If TRUE return query string as URL encoded string, otherwise return parts in array.

Returns

mixed return type depends on value of $asString

Implemented in AblePolecat_Message_RequestAbstract.

          getResource
          (
          	)

Returns

string Request resource (URI/URL).

Implemented in AblePolecat_Message_RequestAbstract.

          validateResourceName
          (

          $requestedResourceName	)

Check resource name against list of allowable characters etc.

Parameters

string	$requestedResourceName	Name of requested resource.

Returns

string Sanitized/normalized version of resource name.

Implemented in AblePolecat_Message_RequestAbstract.

Field Documentation

          const RESOURCE_NAME_ACK = 'ack'

Core (built-in) resource names (e.g. 'reserved').

The documentation for this interface was generated from the following file:

C:/wamp/www/polecat/public/core/Message/Request.php

AblePolecat_Message_RequestInterface

Generated on Fri Apr 10 2015 11:24:49 for Able Polecat by

     1.8.9.1


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
const core_1 = require('@angular/core');
const router_1 = require('@angular/router');
const crisis_service_1 = require('./crisis.service');
let CrisisDetailResolve = class CrisisDetailResolve {
    constructor(cs, router) {
        this.cs = cs;
        this.router = router;
    }
    resolve(route) {
        let id = +route.params['id'];
        return this.cs.getCrisis(id).then(crisis => {
            if (crisis) {
                return crisis;
            }
            else {
                this.router.navigate(['/crisis-center']);
                return false;
            }
        });
    }
};
CrisisDetailResolve = __decorate([
    core_1.Injectable(),
    __metadata('design:paramtypes', [crisis_service_1.CrisisService, router_1.Router])
], CrisisDetailResolve);
exports.CrisisDetailResolve = CrisisDetailResolve;

//# sourceMappingURL=crisis-detail-resolve.service.js.map


text:
namespace sharing {

// IpcPacketSocketFactory implements rtc::PacketSocketFactory
// interface for libjingle using IPC-based P2P sockets. The class must
// be used on a thread that is a libjingle thread (implements
// rtc::Thread) and also has associated base::MessageLoop. Each
// socket created by the factory must be used on the thread it was
// created on.
// TODO(crbug.com/1044522): reuse code from blink instead.
class IpcPacketSocketFactory : public rtc::PacketSocketFactory {
 public:
  IpcPacketSocketFactory(
      const mojo::SharedRemote<network::mojom::P2PSocketManager>&
          socket_manager,
      const net::NetworkTrafficAnnotationTag& traffic_annotation);
  IpcPacketSocketFactory(const IpcPacketSocketFactory&) = delete;
  IpcPacketSocketFactory& operator=(const IpcPacketSocketFactory&) = delete;
  ~IpcPacketSocketFactory() override;

  rtc::AsyncPacketSocket* CreateUdpSocket(
      const rtc::SocketAddress& local_address,
      uint16_t min_port,
      uint16_t max_port) override;
  rtc::AsyncListenSocket* CreateServerTcpSocket(
      const rtc::SocketAddress& local_address,
      uint16_t min_port,
      uint16_t max_port,
      int opts) override;
  rtc::AsyncPacketSocket* CreateClientTcpSocket(
      const rtc::SocketAddress& local_address,
      const rtc::SocketAddress& remote_address,
      const rtc::ProxyInfo& proxy_info,
      const std::string& user_agent,
      const rtc::PacketSocketTcpOptions& opts) override;
  rtc::AsyncResolverInterface* CreateAsyncResolver() override;

 private:
  mojo::SharedRemote<network::mojom::P2PSocketManager> socket_manager_;
  const net::NetworkTrafficAnnotationTag traffic_annotation_;
};

}  // namespace sharing

#endif  // CHROME_SERVICES_SHARING_WEBRTC_IPC_PACKET_SOCKET_FACTORY_H_