text:
package org.myrobotlab.service;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.myrobotlab.framework.Registration;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.LeapData;
import org.myrobotlab.service.data.LeapHand;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.LeapDataListener;
import org.myrobotlab.service.interfaces.PinArrayListener;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;

/**
 * InMoovHand - The Hand sub service for the InMoov Robot. This service has 6
 * servos controlled by an ServoController.
 * thumb,index,majeure,ringFinger,pinky, and wrist
 *
 * There is also leap motion support.
 */
public class InMoov2Hand extends Service implements LeapDataListener, PinArrayListener {

  public final static Logger log = LoggerFactory.getLogger(InMoov2Hand.class);

  private static final long serialVersionUID = 1L;

  /**
   * peer services FIXME - need to be protected !
   */
  transient public LeapMotion leap;
  transient public ServoController controller;
  transient public ServoControl thumb;
  transient public ServoControl index;
  transient public ServoControl majeure;
  transient public ServoControl ringFinger;
  transient public ServoControl pinky;
  transient public ServoControl wrist;

  // The pins for the finger tip sensors
  public String[] sensorPins = new String[] { "A0", "A1", "A2", "A3", "A4" };
  // public int[] sensorLastValues = new int[] {0,0,0,0,0};
  public boolean sensorsEnabled = false;
  public int[] sensorThresholds = new int[] { 500, 500, 500, 500, 500 };

  /**
   * list of names of possible controllers
   */
  public List<String> controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
  public String controllerName;

  boolean isAttached = false;

  public InMoov2Hand(String n, String id) {
    super(n, id);
  }

  @Override
  public void startService() {
    super.startService();
    thumb = (ServoControl) startPeer("thumb");
    index = (ServoControl) startPeer("index");
    majeure = (ServoControl) startPeer("majeure");
    ringFinger = (ServoControl) startPeer("ringFinger");
    pinky = (ServoControl) startPeer("pinky");
    wrist = (ServoControl) startPeer("wrist");
  }

  public void bird() {
    moveTo(150.0, 180.0, 0.0, 180.0, 180.0, 90.0);
  }

  public void onRegistered(Registration s) {
    refreshControllers();
    broadcastState();
  }

  public List<String> refreshControllers() {
    controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
    return controllers;
  }

  // @Override
  public ServoController getController() {
    return controller;
  }

  public String getControllerName() {
    String controlerName = null;
    if (controller != null) {
      controlerName = controller.getName();
    }
    return controlerName;
  }

  public boolean isAttached() {
    if (controller != null) {
      if (((Arduino) controller).getDeviceId(this) != null) {
        isAttached = true;
        return true;
      }
      controller = null;
    }
    isAttached = false;
    return false;
  }

  @Override
  public void broadcastState() {
    if (thumb != null)
      thumb.broadcastState();
    if (index != null)
      index.broadcastState();
    if (majeure != null)
      majeure.broadcastState();
    if (ringFinger != null)
      ringFinger.broadcastState();
    if (pinky != null)
      pinky.broadcastState();
    if (wrist != null)
      wrist.broadcastState();
  }

  public void close() {
    moveTo(130, 180, 180, 180, 180);
  }

  public void closePinch() {
    moveTo(130, 140, 180, 180, 180);
  }

  @Override
  public void releaseService() {
    try {
      disable();
      super.releaseService();
    } catch (Exception e) {
      error(e);
    }
  }

  public void count() {
    one();
    sleep(1);
    two();
    sleep(1);
    three();
    sleep(1);
    four();
    sleep(1);
    five();
  }

  public void devilHorns() {
    moveTo(150.0, 0.0, 180.0, 180.0, 0.0, 90.0);
  }

  public void disable() {
    if (thumb != null)
      thumb.disable();
    if (index != null)
      index.disable();
    if (majeure != null)
      majeure.disable();
    if (ringFinger != null)
      ringFinger.disable();
    if (pinky != null)
      pinky.disable();
    if (wrist != null)
      wrist.disable();
  }

  public boolean enable() {
    if (thumb != null)
      thumb.enable();
    if (index != null)
      index.enable();
    if (majeure != null)
      majeure.enable();
    if (ringFinger != null)
      ringFinger.enable();
    if (pinky != null)
      pinky.enable();
    if (wrist != null)
      wrist.enable();
    return true;
  }

  @Deprecated
  public void enableAutoDisable(Boolean param) {
    setAutoDisable(param);
  }

  @Deprecated
  public void enableAutoEnable(Boolean param) {
  }

  public void five() {
    open();
  }

  public void four() {
    moveTo(150.0, 0.0, 0.0, 0.0, 0.0, 90.0);
  }

  public void fullSpeed() {
    if (thumb != null)
      thumb.fullSpeed();
    if (index != null)
      index.fullSpeed();
    if (majeure != null)
      majeure.fullSpeed();
    if (ringFinger != null)
      ringFinger.fullSpeed();
    if (pinky != null)
      pinky.fullSpeed();
    if (wrist != null)
      wrist.fullSpeed();
  }

  /**
   * this method returns the analog pins that the hand is listening to. The
   * InMoovHand listens on analog pins A0-A4 for the finger tip sensors.
   *
   */
  @Override
  public String[] getActivePins() {
    // TODO Auto-generated method stub
    // for the InMoov hand, we're just going to say A0 - A4 ... for now..
    return sensorPins;
  }

  public long getLastActivityTime() {

    long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime());
    lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime());
    lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime());
    lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime());
    lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime());
    lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime());

    return lastActivityTime;

  }

  @Deprecated /* use LangUtils */
  public String getScript(String inMoovServiceName) {
    String side = getName().contains("left") ? "left" : "right";
    return String.format(Locale.ENGLISH, "%s.moveHand(\"%s\",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, side, thumb.getCurrentInputPos(), index.getCurrentInputPos(),
        majeure.getCurrentInputPos(), ringFinger.getCurrentInputPos(), pinky.getCurrentInputPos(), wrist.getCurrentInputPos());
  }

  public void hangTen() {
    moveTo(0.0, 180.0, 180.0, 180.0, 0.0, 90.0);
  }

  public void map(double minX, double maxX, double minY, double maxY) {
    if (thumb != null) {
      thumb.map(minX, maxX, minY, maxY);
    }
    if (index != null) {
      index.map(minX, maxX, minY, maxY);
    }
    if (majeure != null) {
      majeure.map(minX, maxX, minY, maxY);
    }
    if (ringFinger != null) {
      ringFinger.map(minX, maxX, minY, maxY);
    }
    if (pinky != null) {
      pinky.map(minX, maxX, minY, maxY);
    }
  }

  // TODO - waving thread fun
  public void moveTo(double thumb, double index, double majeure, double ringFinger, double pinky) {
    moveTo(thumb, index, majeure, ringFinger, pinky, null);
  }

  public void moveTo(Double thumbPos, Double indexPos, Double majeurePos, Double ringFingerPos, Double pinkyPos, Double wristPos) {
    if (log.isDebugEnabled()) {
      log.debug("{}.moveTo {} {} {} {} {} {}", getName(), thumbPos, indexPos, majeurePos, ringFingerPos, pinkyPos, wristPos);
    }
    if (thumb != null && thumbPos != null) {
      thumb.moveTo(thumbPos);
    }
    if (index != null && indexPos != null) {
      index.moveTo(indexPos);
    }
    if (majeure != null && majeurePos != null) {
      majeure.moveTo(majeurePos);
    }
    if (ringFinger != null && ringFingerPos != null) {
      ringFinger.moveTo(ringFingerPos);
    }
    if (pinky != null && pinkyPos != null) {
      pinky.moveTo(pinkyPos);
    }
    if (wrist != null && wristPos != null) {
      wrist.moveTo(wristPos);
    }
  }

  public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky) {
    moveToBlocking(thumb, index, majeure, ringFinger, pinky, null);
  }

  public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky, Double wrist) {
    log.info("init {} moveToBlocking ", getName());
    moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
    waitTargetPos();
    log.info("end {} moveToBlocking ", getName());
  }

  public void ok() {
    moveTo(150.0, 180.0, 0.0, 0.0, 0.0, 90.0);
  }

  public void one() {
    moveTo(150.0, 0.0, 180.0, 180.0, 180.0, 90.0);
  }

  public void attach(String controllerName, int sensorPin) throws Exception {
    attach((ServoController) Runtime.getService(controllerName), sensorPin);
  }

  public void attach(String controllerName, String sensorPin) throws Exception {
    attach((ServoController) Runtime.getService(controllerName), Integer.parseInt(sensorPin));
  }

  public void attach(ServoController controller, int sensorPin) {
    try {
      if (controller == null) {
        error("setting null as controller");
        return;
      }
      if (isAttached) {
        log.info("Sensor already attached");
        return;
      }

      controller.attach(controller);

      log.info("{} setController {}", getName(), controller.getName());
      this.controller = controller;
      controllerName = this.controller.getName();
      isAttached = true;
      broadcastState();
    } catch (Exception e) {
      error(e);
    }
  }

  public void detach(ServoController controller) {
    // let the controller you want to detach this device
    if (controller != null) {
      controller.detach(this);
    }
    // setting controller reference to null
    this.controller = null;
    isAttached = false;
    refreshControllers();
    broadcastState();
  }

  public void refresh() {
    broadcastState();
  }

  @Override
  public LeapData onLeapData(LeapData data) {
    String side = getName().contains("left") ? "left" : "right";
    if (!data.frame.isValid()) {
      // TODO: we could return void here? not sure
      // who wants the return value form this method.
      log.info("Leap data frame not valid.");
      return data;
    }
    LeapHand h;
    if ("right".equalsIgnoreCase(side)) {
      if (data.frame.hands().rightmost().isValid()) {
        h = data.rightHand;
      } else {
        log.info("Right hand frame not valid.");
        // return this hand isn't valid
        return data;
      }
    } else if ("left".equalsIgnoreCase(side)) {
      if (data.frame.hands().leftmost().isValid()) {
        h = data.leftHand;
      } else {
        log.info("Left hand frame not valid.");
        // return this frame isn't valid.
        return data;
      }
    } else {
      // side could be null?
      log.info("Unknown Side or side not set on hand (Side = {})", side);
      // we can default to the right side?
      // TODO: come up with a better default or at least document this
      // behavior.
      if (data.frame.hands().rightmost().isValid()) {
        h = data.rightHand;
      } else {
        log.info("Right(unknown) hand frame not valid.");
        // return this hand isn't valid
        return data;
      }
    }

    // If the hand data came from a valid frame, update the finger postions.
    // move all fingers
    if (index != null) {
      index.moveTo(h.index);
    } else {
      log.debug("Index finger isn't attached or is null.");
    }
    if (thumb != null) {
      thumb.moveTo(h.thumb);
    } else {
      log.debug("Thumb isn't attached or is null.");
    }
    if (pinky != null) {
      pinky.moveTo(h.pinky);
    } else {
      log.debug("Pinky finger isn't attached or is null.");
    }
    if (ringFinger != null) {
      ringFinger.moveTo(h.ring);
    } else {
      log.debug("Ring finger isn't attached or is null.");
    }
    if (majeure != null) {
      majeure.moveTo(h.middle);
    } else {
      log.debug("Middle(Majeure) finger isn't attached or is null.");
    }

    return data;
  }

  // FIXME - use pub/sub attach to set this up without having this method !
  @Override
  public void onPinArray(PinData[] pindata) {

    log.info("On Pin Data: {}", pindata.length);
    if (!sensorsEnabled)
      return;
    // just return ? TOOD: maybe still track the last read values...
    // TODO : change the interface to get a map of pin data, keyed off the name.
    // ?
    for (PinData pin : pindata) {
      log.info("Pin Data: {}", pin);
      // p
      // if (sensorPins.contains(pin.pin)) {
      // // it's one of our finger pins.. let's operate on it.
      // log.info("Pin Data : {} value {}", pin.pin, pin.value );
      // if (sensorPins[0].equalsIgnoreCase(pin.pin)) {
      // // thumb / A0
      // // here we want to test the pin state.. and potentially take an action
      // // based on the updated sensor pin state
      // if (pin.value > sensorThresholds[0])
      // thumb.stop();
      // } else if (sensorPins[1].equalsIgnoreCase(pin.pin)) {
      // // index / A1
      // if (pin.value > sensorThresholds[1])
      // index.stop();
      //
      // } else if (sensorPins[2].equalsIgnoreCase(pin.pin)) {
      // // middle / A2
      // if (pin.value > sensorThresholds[2])
      // majeure.stop();
      //
      // } else if (sensorPins[3].equalsIgnoreCase(pin.pin)) {
      // // ring / A3
      // if (pin.value > sensorThresholds[3])
      // ringFinger.stop();
      //
      // } else if (sensorPins[4].equalsIgnoreCase(pin.pin)) {
      // // pinky / A4
      // if (pin.value > sensorThresholds[4])
      // pinky.stop();
      // }
      // }
    }
  }

  public void open() {
    rest();
  }

  public void openPinch() {
    moveTo(0, 0, 180, 180, 180);
  }

  public void release() {
    disable();
  }

  public void rest() {
    if (thumb != null)
      thumb.rest();
    if (index != null)
      index.rest();
    if (majeure != null)
      majeure.rest();
    if (ringFinger != null)
      ringFinger.rest();
    if (pinky != null)
      pinky.rest();
    if (wrist != null)
      wrist.rest();
  }

  @Override
  public boolean save() {
    super.save();
    if (thumb != null)
      thumb.save();
    if (index != null)
      index.save();
    if (majeure != null)
      majeure.save();
    if (ringFinger != null)
      ringFinger.save();
    if (pinky != null)
      pinky.save();
    if (wrist != null)
      wrist.save();
    return true;
  }

  @Deprecated
  public boolean loadFile(String file) {
    File f = new File(file);
    Python p = (Python) Runtime.getService("python");
    log.info("Loading  Python file {}", f.getAbsolutePath());
    if (p == null) {
      log.error("Python instance not found");
      return false;
    }
    String script = null;
    try {
      script = FileIO.toString(f.getAbsolutePath());
    } catch (IOException e) {
      log.error("IO Error loading file : ", e);
      return false;
    }
    // evaluate the scripts in a blocking way.
    boolean result = p.exec(script, true);
    if (!result) {
      log.error("Error while loading file {}", f.getAbsolutePath());
      return false;
    } else {
      log.debug("Successfully loaded {}", f.getAbsolutePath());
    }
    return true;
  }

  public void setAutoDisable(Boolean param) {
    if (thumb != null)
      thumb.setAutoDisable(param);
    if (index != null)
      index.setAutoDisable(param);
    if (majeure != null)
      majeure.setAutoDisable(param);
    if (ringFinger != null)
      ringFinger.setAutoDisable(param);
    if (pinky != null)
      pinky.setAutoDisable(param);
    if (wrist != null)
      wrist.setAutoDisable(param);
  }

  public void setPins(int thumbPin, int indexPin, int majeurePin, int ringFingerPin, int pinkyPin, int wristPin) {
    log.info("setPins {} {} {} {} {} {}", thumbPin, indexPin, majeurePin, ringFingerPin, pinkyPin, wristPin);
    if (thumb != null)
      thumb.setPin(thumbPin);
    if (index != null)
      index.setPin(indexPin);
    if (majeure != null)
      majeure.setPin(majeurePin);
    if (ringFinger != null)
      ringFinger.setPin(ringFingerPin);
    if (pinky != null)
      pinky.setPin(pinkyPin);
    if (wrist != null)
      wrist.setPin(wristPin);
  }

  public void setRest(double thumb, double index, double majeure, double ringFinger, double pinky) {
    setRest(thumb, index, majeure, ringFinger, pinky, null);
  }

  public void setRest(double thumbRest, double indexRest, double majeureRest, double ringFingerRest, double pinkyRest, Double wristRest) {
    log.info("setRest {} {} {} {} {} {}", thumb, index, majeure, ringFinger, pinky, wrist);
    if (thumb != null)
      thumb.setRest(thumbRest);
    if (index != null)
      index.setRest(indexRest);
    if (majeure != null)
      majeure.setRest(majeureRest);
    if (ringFinger != null)
      ringFinger.setRest(ringFingerRest);
    if (pinky != null)
      pinky.setRest(pinkyRest);
    if (wrist != null) {
      wrist.setRest(wristRest);
    }
  }

  /**
   * @param pins
   *          Set the array of pins that should be listened to.
   *
   */
  public void setSensorPins(String[] pins) {
    // TODO, this should probably be a sorted set.. and sensorPins itself should
    // probably be a map to keep the mapping of pin to finger
    this.sensorPins = pins;
  }

  public void setSpeed(Double thumbSpeed, Double indexSpeed, Double majeureSpeed, Double ringFingerSpeed, Double pinkySpeed, Double wristSpeed) {

    if (thumb != null)
      thumb.setSpeed(thumbSpeed);
    if (index != null)
      index.setSpeed(indexSpeed);
    if (majeure != null)
      majeure.setSpeed(majeureSpeed);
    if (ringFinger != null)
      ringFinger.setSpeed(ringFingerSpeed);
    if (pinky != null)
      pinky.setSpeed(pinkySpeed);
    if (wrist != null)
      wrist.setSpeed(wristSpeed);
  }

  @Deprecated
  public void setVelocity(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
    log.warn("setspeed deprecated please use setSpeed");
    setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
  }

  // FIXME - if multiple systems are dependent on the ServoControl map and
  // limits to be a certain value
  // leap should change its output, and leave the map and limits here alone
  // FIXME !!! - should not have LeapMotion defined here at all - it should be
  // pub/sub !!!
  public void startLeapTracking() throws Exception {
    if (leap == null) {
      leap = (LeapMotion) startPeer("leap");
    }
    this.index.map(90.0, 0.0, this.index.getMin(), this.index.getMax());
    this.thumb.map(90.0, 50.0, this.thumb.getMin(), this.thumb.getMax());
    this.majeure.map(90.0, 0.0, this.majeure.getMin(), this.majeure.getMax());
    this.ringFinger.map(90.0, 0.0, this.ringFinger.getMin(), this.ringFinger.getMax());
    this.pinky.map(90.0, 0.0, this.pinky.getMin(), this.pinky.getMax());
    leap.addLeapDataListener(this);
    leap.startTracking();
    return;
  }

  public void stop() {
    if (thumb != null)
      thumb.stop();
    if (index != null)
      index.stop();
    if (majeure != null)
      majeure.stop();
    if (ringFinger != null)
      ringFinger.stop();
    if (pinky != null)
      pinky.stop();
    if (wrist != null)
      wrist.stop();
  }

  // FIXME !!! - should not have LeapMotion defined here at all - it should be
  // pub/sub !!!
  public void stopLeapTracking() {
    leap.stopTracking();
    index.map(index.getMin(), index.getMax(), index.getMin(), index.getMax());
    thumb.map(thumb.getMin(), thumb.getMax(), thumb.getMin(), thumb.getMax());
    majeure.map(majeure.getMin(), majeure.getMax(), majeure.getMin(), majeure.getMax());
    ringFinger.map(ringFinger.getMin(), ringFinger.getMax(), ringFinger.getMin(), ringFinger.getMax());
    pinky.map(pinky.getMin(), pinky.getMax(), pinky.getMin(), pinky.getMax());
    rest();
    return;
  }

  public void test() {
    if (thumb != null)
      thumb.moveTo(thumb.getCurrentInputPos() + 2);
    if (index != null)
      index.moveTo(index.getCurrentInputPos() + 2);
    if (majeure != null)
      majeure.moveTo(majeure.getCurrentInputPos() + 2);
    if (ringFinger != null)
      ringFinger.moveTo(ringFinger.getCurrentInputPos() + 2);
    if (pinky != null)
      pinky.moveTo(pinky.getCurrentInputPos() + 2);
    if (wrist != null)
      wrist.moveTo(wrist.getCurrentInputPos() + 2);

    info("test completed");
  }

  public void three() {
    moveTo(150.0, 0.0, 0.0, 0.0, 180.0, 90.0);
  }

  public void thumbsUp() {
    moveTo(0.0, 180.0, 180.0, 180.0, 180.0, 90.0);
  }

  public void two() {
    victory();
  }

  public void victory() {
    moveTo(150.0, 0.0, 0.0, 180.0, 180.0, 90.0);
  }

  public void waitTargetPos() {
    if (thumb != null)
      thumb.waitTargetPos();
    if (index != null)
      index.waitTargetPos();
    if (majeure != null)
      majeure.waitTargetPos();
    if (ringFinger != null)
      ringFinger.waitTargetPos();
    if (pinky != null)
      pinky.waitTargetPos();
    if (wrist != null)
      wrist.waitTargetPos();
  }

  @Override
  public boolean isAttached(String name) {
    return controller != null && name.equals(controller.getName());
  }

  @Override
  public Set<String> getAttached() {
    Set<String> ret = new HashSet<String>();
    if (controller != null) {
      ret.add(controller.getName());
    }
    return ret;
  }

  public static void main(String[] args) {
    LoggingFactory.init(Level.INFO);

    try {

      InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2");
      i01.startPeer("rightHand");

      ServoController controller = (ServoController) Runtime.getService("i01.right");

      InMoov2Hand rightHand = (InMoov2Hand) Runtime.start("r01", "InMoov2Hand");// InMoovHand("r01");
      rightHand.close();
      rightHand.open();
      rightHand.openPinch();
      rightHand.closePinch();
      rightHand.rest();

    } catch (Exception e) {
      log.error("main threw", e);
    }
  }
}


text:
//==================================================================================================
//	Includes
//==================================================================================================

//	Self Include
#include "HP_PreferredChannels.h"

//	Local Includes
#include "HP_Device.h"

//	PublicUtility Includes
#include "CAAudioChannelLayout.h"
#include "CACFArray.h"
#include "CACFDictionary.h"
#include "CACFDistributedNotification.h"
#include "CACFPreferences.h"
#include "CACFString.h"
#include "CADebugMacros.h"
#include "CAException.h"

//==================================================================================================
//	HP_PreferredChannels
//==================================================================================================

static void	HP_PreferredChannels_ConstructDictionaryFromLayout(const AudioChannelLayout& inLayout, CACFDictionary& outLayoutDictionary)
{
	//	stick in the tag
	outLayoutDictionary.AddUInt32(CFSTR("channel layout tag"), inLayout.mChannelLayoutTag);

	//	stick in the bitmap
	outLayoutDictionary.AddUInt32(CFSTR("channel bitmap"), inLayout.mChannelBitmap);

	//	stick in the number channels
	outLayoutDictionary.AddUInt32(CFSTR("number channels"), inLayout.mNumberChannelDescriptions);

	//	add the channel descriptions, if necessary
	if(inLayout.mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions)
	{
		//	create an array to hold the channel descriptions
		CACFArray theChannelDescriptions(true);
		if(theChannelDescriptions.IsValid())
		{
			//	iterate through the descriptions and stick them in the array
			for(UInt32 theChannelIndex = 0; theChannelIndex < inLayout.mNumberChannelDescriptions; ++theChannelIndex)
			{
				//	create a dictionary to hold the description
				CACFDictionary theDescription(true);
				if(theDescription.IsValid())
				{
					//	stick in the easy values
					theDescription.AddUInt32(CFSTR("channel label"), inLayout.mChannelDescriptions[theChannelIndex].mChannelLabel);
					theDescription.AddUInt32(CFSTR("channel flags"), inLayout.mChannelDescriptions[theChannelIndex].mChannelFlags);

					//	create an array to hold the coordinates
					CACFArray theCoordinates(true);
					if(theCoordinates.IsValid())
					{
						//	add the coordinates to the array
						for(UInt32 theCoordinateIndex = 0; theCoordinateIndex < 3; ++theCoordinateIndex)
						{
							theCoordinates.AppendFloat32(inLayout.mChannelDescriptions[theChannelIndex].mCoordinates[theCoordinateIndex]);
						}

						//	add the array of coordinates to the description
						theDescription.AddArray(CFSTR("coordinates"), theCoordinates.GetCFArray());
					}

					//	add the description to the array of descriptions
					theChannelDescriptions.AppendDictionary(theDescription.GetCFDictionary());
				}
			}

			//	add the array of descriptions to the layout dictionary
			outLayoutDictionary.AddArray(CFSTR("channel descriptions"), theChannelDescriptions.GetCFArray());
		}
	}
}

static void	HP_PreferredChannels_ConstructLayoutFromDictionary(const CACFDictionary& inLayoutDictionary, AudioChannelLayout& outLayout)
{
	//	get the tag, bitmap
	inLayoutDictionary.GetUInt32(CFSTR("channel layout tag"), outLayout.mChannelLayoutTag);
	inLayoutDictionary.GetUInt32(CFSTR("channel bitmap"), outLayout.mChannelBitmap);

	//	get the number of channels specified in the dictionary
	UInt32 theNumberChannelsInDictionary = 0;
	inLayoutDictionary.GetUInt32(CFSTR("number channels"), theNumberChannelsInDictionary);

	//	get the descriptions if they are present and required
	CFArrayRef __theDescriptions;
	if((outLayout.mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) && inLayoutDictionary.GetArray(CFSTR("channel descriptions"), __theDescriptions))
	{
		//	don't release this array because it came straight out of the dictionary
		CACFArray theDescriptions(__theDescriptions, false);

		//	get the number of items in the array
		UInt32 theNumberItems = theDescriptions.GetNumberItems();

		//	iterate through the array and fill out the struct
		for(UInt32 theItemIndex = 0; (theItemIndex < theNumberItems) && (theItemIndex < outLayout.mNumberChannelDescriptions); ++theItemIndex)
		{
			//	get the description
			CFDictionaryRef __theDescription;
			if(theDescriptions.GetDictionary(theItemIndex, __theDescription))
			{
				//	don't release this dictionary because it came straight out of the array
				CACFDictionary theDescription(__theDescription, false);

				//	get the channel label and flags
				theDescription.GetUInt32(CFSTR("channel label"), outLayout.mChannelDescriptions[theItemIndex].mChannelLabel);
				theDescription.GetUInt32(CFSTR("channel flags"), outLayout.mChannelDescriptions[theItemIndex].mChannelFlags);

				//	get the coordinates
				CFArrayRef __theCoordinates;
				if(theDescription.GetArray(CFSTR("coordinates"), __theCoordinates))
				{
					//	don't release this array because it came straight out of the dictionary
					CACFArray theCoordinates(__theCoordinates, false);

					//	iterate through the array and get the coordinates
					UInt32 theNumberCoordinates = theCoordinates.GetNumberItems();
					for(UInt32 theCoordinateIndex = 0; (theCoordinateIndex < 3) && (theCoordinateIndex < theNumberCoordinates); ++theCoordinateIndex)
					{
						theCoordinates.GetFloat32(theCoordinateIndex, outLayout.mChannelDescriptions[theItemIndex].mCoordinates[theCoordinateIndex]);
					}
				}
			}
		}
	}
}

HP_PreferredChannels::HP_PreferredChannels(HP_Device* inDevice)
:
	HP_Property(),
	mDevice(inDevice),
	mToken(0),
	mInputStereoPrefsKey(NULL),
	mOutputStereoPrefsKey(NULL),
	mInputChannelLayoutPrefsKey(NULL),
	mOutputChannelLayoutPrefsKey(NULL),
	mPreferredInputStereoChannels(NULL),
	mPreferredOutputStereoChannels(NULL),
	mOutputStereoPair(),
	mPreferredInputChannelLayout(NULL),
	mPreferredOutputChannelLayout(NULL)
{
	//	get our token
	if(sTokenMap == NULL)
	{
		sTokenMap = new CATokenMap<HP_PreferredChannels>();
	}
	mToken = sTokenMap->MapObject(this);
}

HP_PreferredChannels::~HP_PreferredChannels()
{
	sTokenMap->RemoveMapping(mToken, this);
}

void	HP_PreferredChannels::Initialize()
{
	//	construct the name of the preferences
	CACFString theUID(mDevice->CopyDeviceUID());

	mInputStereoPrefsKey = CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.audio.CoreAudio.PreferredStereoChannels.%s.%@"), "Input", theUID.GetCFString());
	ThrowIfNULL(mInputStereoPrefsKey, CAException(kAudioHardwareIllegalOperationError), "HP_PreferredChannels::Initialize: couldn't create the input stereo prefs key");

	mOutputStereoPrefsKey = CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.audio.CoreAudio.PreferredStereoChannels.%s.%@"), "Output", theUID.GetCFString());
	ThrowIfNULL(mOutputStereoPrefsKey, CAException(kAudioHardwareIllegalOperationError), "HP_PreferredChannels::Initialize: couldn't create the output stereo prefs key");

	mInputChannelLayoutPrefsKey = CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.audio.CoreAudio.PreferredChannelLayout.%s.%@"), "Input", theUID.GetCFString());
	ThrowIfNULL(mInputChannelLayoutPrefsKey, CAException(kAudioHardwareIllegalOperationError), "HP_PreferredChannels::Initialize: couldn't create the input channel layout prefs key");

	mOutputChannelLayoutPrefsKey = CFStringCreateWithFormat(NULL, NULL, CFSTR("com.apple.audio.CoreAudio.PreferredChannelLayout.%s.%@"), "Output", theUID.GetCFString());
	ThrowIfNULL(mOutputChannelLayoutPrefsKey, CAException(kAudioHardwareIllegalOperationError), "HP_PreferredChannels::Initialize: couldn't create the output channel layout prefs key");

	//	cache the prefs
	mPreferredInputStereoChannels = CACFPreferences::CopyArrayValue(mInputStereoPrefsKey, false, true);
	mPreferredOutputStereoChannels = CACFPreferences::CopyArrayValue(mOutputStereoPrefsKey, false, true);
	mPreferredInputChannelLayout = CACFPreferences::CopyDictionaryValue(mInputChannelLayoutPrefsKey, false, true);
	mPreferredOutputChannelLayout = CACFPreferences::CopyDictionaryValue(mOutputChannelLayoutPrefsKey, false, true);

	//	cache the actual CFArray values for the output preferred stereo pair
	CACFArray thePrefStereoChannels(mPreferredOutputStereoChannels, false);
	if(thePrefStereoChannels.IsValid())
	{
		thePrefStereoChannels.GetUInt32(0, mOutputStereoPair[0]);
		thePrefStereoChannels.GetUInt32(1, mOutputStereoPair[1]);
	}
	else
	{
		mOutputStereoPair[0] = 1;
		mOutputStereoPair[1] = 2;
	}

	//	sign up for notifications
	CACFDistributedNotification::AddObserver((const void*)mToken, (CFNotificationCallback)ChangeNotification, mInputStereoPrefsKey);
	CACFDistributedNotification::AddObserver((const void*)mToken, (CFNotificationCallback)ChangeNotification, mOutputStereoPrefsKey);
	CACFDistributedNotification::AddObserver((const void*)mToken, (CFNotificationCallback)ChangeNotification, mInputChannelLayoutPrefsKey);
	CACFDistributedNotification::AddObserver((const void*)mToken, (CFNotificationCallback)ChangeNotification, mOutputChannelLayoutPrefsKey);
}

void	HP_PreferredChannels::Teardown()
{
	CACFDistributedNotification::RemoveObserver((const void*)mToken, mInputStereoPrefsKey);
	CACFDistributedNotification::RemoveObserver((const void*)mToken, mOutputStereoPrefsKey);
	CACFDistributedNotification::RemoveObserver((const void*)mToken, mInputChannelLayoutPrefsKey);
	CACFDistributedNotification::RemoveObserver((const void*)mToken, mOutputChannelLayoutPrefsKey);
	if(mPreferredInputStereoChannels != NULL)
	{
		CFRelease(mPreferredInputStereoChannels);
	}
	if(mPreferredOutputStereoChannels != NULL)
	{
		CFRelease(mPreferredOutputStereoChannels);
	}
	if(mPreferredInputChannelLayout != NULL)
	{
		CFRelease(mPreferredInputChannelLayout);
	}
	if(mPreferredOutputChannelLayout != NULL)
	{
		CFRelease(mPreferredOutputChannelLayout);
	}
	CFRelease(mOutputChannelLayoutPrefsKey);
	CFRelease(mInputChannelLayoutPrefsKey);
	CFRelease(mOutputStereoPrefsKey);
	CFRelease(mInputStereoPrefsKey);
}

bool	HP_PreferredChannels::IsActive(const AudioObjectPropertyAddress& inAddress) const
{
	bool theAnswer = false;

	switch(inAddress.mSelector)
	{
		case kAudioDevicePropertyPreferredChannelsForStereo:
			theAnswer = ((inAddress.mScope == kAudioDevicePropertyScopeInput) && (mDevice->GetTotalNumberChannels(true) > 1)) || ((inAddress.mScope == kAudioDevicePropertyScopeOutput) && (mDevice->GetTotalNumberChannels(false) > 1));
			break;

		case kAudioDevicePropertyPreferredChannelLayout:
			theAnswer = ((inAddress.mScope == kAudioDevicePropertyScopeInput) && mDevice->HasInputStreams()) || ((inAddress.mScope == kAudioDevicePropertyScopeOutput) && mDevice->HasOutputStreams());
			break;

		case 'srdd':
			theAnswer = ((inAddress.mScope == kAudioDevicePropertyScopeInput) && mDevice->HasInputStreams()) || ((inAddress.mScope == kAudioDevicePropertyScopeOutput) && mDevice->HasOutputStreams());
			break;
	};

	return theAnswer;
}

bool	HP_PreferredChannels::IsPropertySettable(const AudioObjectPropertyAddress& inAddress) const
{
	bool theAnswer = false;

	switch(inAddress.mSelector)
	{
		case kAudioDevicePropertyPreferredChannelsForStereo:
			theAnswer = true;
			break;

		case kAudioDevicePropertyPreferredChannelLayout:
			theAnswer = true;
			break;

		case 'srdd':
			theAnswer = false;
			break;
	};

	return theAnswer;
}

UInt32	HP_PreferredChannels::GetPropertyDataSize(const AudioObjectPropertyAddress& inAddress, UInt32 /*inQualifierDataSize*/, const void* /*inQualifierData*/) const
{
	UInt32 theAnswer = 0;

	switch(inAddress.mSelector)
	{
		case kAudioDevicePropertyPreferredChannelsForStereo:
			theAnswer = 2 * SizeOf32(UInt32);
			break;

		case kAudioDevicePropertyPreferredChannelLayout:
			theAnswer = CAAudioChannelLayout::CalculateByteSize(mDevice->GetTotalNumberChannels(inAddress.mScope == kAudioDevicePropertyScopeInput));
			break;

		case 'srdd':
			theAnswer = CAAudioChannelLayout::CalculateByteSize(mDevice->GetTotalNumberChannels(inAddress.mScope == kAudioDevicePropertyScopeInput));
			break;
	};

	return theAnswer;
}

void	HP_PreferredChannels::GetPropertyData(const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32& ioDataSize, void* outData) const
{
	bool isInput = inAddress.mScope == kAudioDevicePropertyScopeInput;
	switch(inAddress.mSelector)
	{
		case kAudioDevicePropertyPreferredChannelsForStereo:
			{
				ThrowIf(ioDataSize != GetPropertyDataSize(inAddress, inQualifierDataSize, inQualifierData), CAException(kAudioHardwareBadPropertySizeError), "HP_PreferredChannels::GetPropertyData: wrong data size for kAudioDevicePropertyPreferredChannelsForStereo");
				UInt32* theStereoChannels = static_cast<UInt32*>(outData);

				//	initialize the output
				theStereoChannels[0] = 1;
				theStereoChannels[1] = 2;

				//	get the preference
				CACFArray thePrefStereoChannels(isInput ? mPreferredInputStereoChannels : mPreferredOutputStereoChannels, false);
				if(thePrefStereoChannels.IsValid())
				{
					//	get the values from the array
					thePrefStereoChannels.GetUInt32(0, theStereoChannels[0]);
					thePrefStereoChannels.GetUInt32(1, theStereoChannels[1]);
				}

				if (!isInput)
				{
					// update the cached value if necessary
					memcpy(const_cast<HP_PreferredChannels*>(this)->mOutputStereoPair, theStereoChannels, sizeof(UInt32)*2);
				}
			}
			break;

		case kAudioDevicePropertyPreferredChannelLayout:
			{
				ThrowIf(ioDataSize != GetPropertyDataSize(inAddress, inQualifierDataSize, inQualifierData), CAException(kAudioHardwareBadPropertySizeError), "HP_PreferredChannels::GetPropertyData: wrong data size for kAudioDevicePropertyPreferredChannelLayout");
				AudioChannelLayout* theChannelLayout = static_cast<AudioChannelLayout*>(outData);

				//	fetch the default layout from the device
				mDevice->GetDefaultChannelLayout(isInput, *theChannelLayout);

				//	get the pref
				CACFDictionary thePrefChannelLayout(isInput ? mPreferredInputChannelLayout : mPreferredOutputChannelLayout, false);
				if(thePrefChannelLayout.IsValid())
				{
					HP_PreferredChannels_ConstructLayoutFromDictionary(thePrefChannelLayout, *theChannelLayout);
				}
			}
			break;

		case 'srdd':
			{
				ThrowIf(ioDataSize != GetPropertyDataSize(inAddress, inQualifierDataSize, inQualifierData), CAException(kAudioHardwareBadPropertySizeError), "HP_PreferredChannels::GetPropertyData: wrong data size for 'srdd'");
				AudioChannelLayout* theChannelLayout = static_cast<AudioChannelLayout*>(outData);

				//	fetch the default layout from the device
				mDevice->GetDefaultChannelLayout(isInput, *theChannelLayout);
			}
			break;
	};
}

void	HP_PreferredChannels::SetPropertyData(const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData, const AudioTimeStamp* /*inWhen*/)
{
	CFStringRef thePrefsKey = NULL;
	bool isInput = inAddress.mScope == kAudioDevicePropertyScopeInput;
	UInt32 theTotalNumberChannels = mDevice->GetTotalNumberChannels(isInput);
	switch(inAddress.mSelector)
	{
		case kAudioDevicePropertyPreferredChannelsForStereo:
			{
				ThrowIf(inDataSize != GetPropertyDataSize(inAddress, inQualifierDataSize, inQualifierData), CAException(kAudioHardwareBadPropertySizeError), "HP_PreferredChannels::SetPropertyData: wrong data size for kAudioDevicePropertyPreferredChannelsForStereo");
				const UInt32* theStereoChannels = static_cast<const UInt32*>(inData);

				//	create an array to hold the prefs value
				CACFArray thePrefStereoChannels(true);

				//	put in the left channel
				thePrefStereoChannels.AppendUInt32(std::min(std::max(theStereoChannels[0], (UInt32)1), theTotalNumberChannels));

				//	put in the right channel
				thePrefStereoChannels.AppendUInt32(std::min(std::max(theStereoChannels[1], (UInt32)1), theTotalNumberChannels));

				//	set the value in the prefs
				thePrefsKey = (isInput ? mInputStereoPrefsKey : mOutputStereoPrefsKey);
				CACFPreferences::SetValue(thePrefsKey, thePrefStereoChannels.GetCFArray(), false, true, true);

				CFArrayRef theStereoChannelsArray = isInput ? mPreferredInputStereoChannels : mPreferredOutputStereoChannels;

				//	if the value changed re-cache it and send notifications
				CFArrayRef array = CACFPreferences::CopyArrayValue(thePrefsKey, false, true);
				//	release the old array
				if (theStereoChannelsArray != NULL)
					CFRelease(theStereoChannelsArray);

				//	save the new one
				if (isInput)
					mPreferredInputStereoChannels = array;
				else
					mPreferredOutputStereoChannels = array;

				//	send property changed
				mDevice->PropertiesChanged(1, &inAddress);

				//	send the notification
				SendChangeNotification(thePrefsKey);
			}
			break;

		case kAudioDevicePropertyPreferredChannelLayout:
			{
				ThrowIf(inDataSize != GetPropertyDataSize(inAddress, inQualifierDataSize, inQualifierData), CAException(kAudioHardwareBadPropertySizeError), "HP_PreferredChannels::SetPropertyData: wrong data size for kAudioDevicePropertyPreferredChannelLayout");
				const AudioChannelLayout* theChannelLayout = static_cast<const AudioChannelLayout*>(inData);

				//	create a dictionary to hold the prefs value
				CACFDictionary thePrefChannelLayout(true);

				//	fill out the dictionary
				HP_PreferredChannels_ConstructDictionaryFromLayout(*theChannelLayout, thePrefChannelLayout);

				//	set the value in the prefs
				thePrefsKey = (isInput ? mInputChannelLayoutPrefsKey : mOutputChannelLayoutPrefsKey);
				CACFPreferences::SetValue(thePrefsKey, thePrefChannelLayout.GetDict(), false, true, true);

				CFDictionaryRef theChannelLayoutDict = isInput ? mPreferredInputChannelLayout : mPreferredOutputChannelLayout;

				//	if the value changed re-cache it and send notifications
				CFDictionaryRef dictionary = CACFPreferences::CopyDictionaryValue(thePrefsKey, false, true);

				//	release the old dict
				if (theChannelLayoutDict != NULL)
					CFRelease(theChannelLayoutDict);

				//	save the new one
				if (isInput)
					mPreferredInputChannelLayout = dictionary;
				else
					mPreferredOutputChannelLayout = dictionary;

				//	send property changed
				mDevice->PropertiesChanged(1, &inAddress);

				//	send the notification
				SendChangeNotification(thePrefsKey);
			}
			break;
	};
}

void	HP_PreferredChannels::ClearPrefs()
{
	CACFPreferences::DeleteValue(mInputStereoPrefsKey, false, true, true);
	CACFPreferences::DeleteValue(mOutputStereoPrefsKey, false, true, true);
	CACFPreferences::DeleteValue(mInputChannelLayoutPrefsKey, false, true, true);
	CACFPreferences::DeleteValue(mOutputChannelLayoutPrefsKey, false, true, true);
	CACFPreferences::Synchronize(false, true, true);
}

UInt32	HP_PreferredChannels::GetNumberAddressesImplemented() const
{
	return 3;
}

void	HP_PreferredChannels::GetImplementedAddressByIndex(UInt32 inIndex, AudioObjectPropertyAddress& outAddress) const
{
	switch(inIndex)
	{
		case 0:
			outAddress.mSelector = kAudioDevicePropertyPreferredChannelsForStereo;
			break;

		case 1:
			outAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout;
			break;

		case 2:
			outAddress.mSelector = 'srdd';
			break;
	};
	outAddress.mScope = kAudioObjectPropertyScopeWildcard;
	outAddress.mElement = kAudioObjectPropertyElementWildcard;
}

void	HP_PreferredChannels::SendChangeNotification(CFStringRef inNotificationName) const
{
	CACFPreferences::SendNotification(inNotificationName);
}

void	HP_PreferredChannels::ChangeNotification(CFNotificationCenterRef /*inCenter*/, const void* inToken, CFStringRef inNotificationName, const void* /*inObject*/, CFDictionaryRef /*inUserInfo*/)
{
	try
	{
		if(sTokenMap != NULL)
		{
			HP_PreferredChannels* thePreferredChannelProperty = sTokenMap->GetObject(inToken);
			if(thePreferredChannelProperty != NULL)
			{
				AudioObjectPropertyAddress theAddress;
				theAddress.mElement = kAudioObjectPropertyElementMaster;

				//	mark the prefs as dirty
				CACFPreferences::MarkPrefsOutOfDate(false, true);

				//	figure out what changed
				if(CFStringCompare(inNotificationName, thePreferredChannelProperty->mInputStereoPrefsKey, 0) == kCFCompareEqualTo)
				{
					theAddress.mSelector = kAudioDevicePropertyPreferredChannelsForStereo;
					theAddress.mScope = kAudioDevicePropertyScopeInput;

					CFArrayRef array = CACFPreferences::CopyArrayValue(thePreferredChannelProperty->mInputStereoPrefsKey, false, true);
					if (array != NULL)
					{
						if (thePreferredChannelProperty->mPreferredInputStereoChannels != NULL && CFEqual(array, thePreferredChannelProperty->mPreferredInputStereoChannels))
						{
							//	nothing to do, except release array
							CFRelease(array);
						}
						else
						{
							//	re-cache the value
							if (thePreferredChannelProperty->mPreferredInputStereoChannels != NULL)
								CFRelease(thePreferredChannelProperty->mPreferredInputStereoChannels);
							thePreferredChannelProperty->mPreferredInputStereoChannels = array;

							thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);

						}
					}
					else if (thePreferredChannelProperty->mPreferredInputStereoChannels != NULL)
					{
						CFRelease(thePreferredChannelProperty->mPreferredInputStereoChannels);
						thePreferredChannelProperty->mPreferredInputStereoChannels = NULL;

						thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);
					}
				}
				else if(CFStringCompare(inNotificationName, thePreferredChannelProperty->mOutputStereoPrefsKey, 0) == kCFCompareEqualTo)
				{
					theAddress.mSelector = kAudioDevicePropertyPreferredChannelsForStereo;
					theAddress.mScope = kAudioDevicePropertyScopeOutput;

					CFArrayRef array = CACFPreferences::CopyArrayValue(thePreferredChannelProperty->mOutputStereoPrefsKey, false, true);
					if (array != NULL)
					{
						if (thePreferredChannelProperty->mPreferredOutputStereoChannels != NULL && CFEqual(array, thePreferredChannelProperty->mPreferredOutputStereoChannels))
						{
							//	nothing to do, except release array
							CFRelease(array);
						}
						else
						{
							//	re-cache the value
							if (thePreferredChannelProperty->mPreferredOutputStereoChannels != NULL)
								CFRelease(thePreferredChannelProperty->mPreferredOutputStereoChannels);
							thePreferredChannelProperty->mPreferredOutputStereoChannels = array;

							thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);

						}
					}
					else if (thePreferredChannelProperty->mPreferredOutputStereoChannels != NULL)
					{
						CFRelease(thePreferredChannelProperty->mPreferredOutputStereoChannels);
						thePreferredChannelProperty->mPreferredOutputStereoChannels = NULL;

						thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);
					}
				}
				else if(CFStringCompare(inNotificationName, thePreferredChannelProperty->mInputChannelLayoutPrefsKey, 0) == kCFCompareEqualTo)
				{
					theAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout;
					theAddress.mScope = kAudioDevicePropertyScopeInput;

					CFDictionaryRef dictionary = CACFPreferences::CopyDictionaryValue(thePreferredChannelProperty->mInputChannelLayoutPrefsKey, false, true);
					if (dictionary != NULL)
					{
						if (thePreferredChannelProperty->mPreferredInputChannelLayout != NULL && CFEqual(dictionary, thePreferredChannelProperty->mPreferredInputChannelLayout))
						{
							//	nothing to do, except release dictionary
							CFRelease(dictionary);
						}
						else
						{
							//	re-cache the value
							if (thePreferredChannelProperty->mPreferredInputChannelLayout != NULL)
								CFRelease(thePreferredChannelProperty->mPreferredInputChannelLayout);
							thePreferredChannelProperty->mPreferredInputChannelLayout = dictionary;

							thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);

						}
					}
					else if (thePreferredChannelProperty->mPreferredInputChannelLayout != NULL)
					{
						CFRelease(thePreferredChannelProperty->mPreferredInputChannelLayout);
						thePreferredChannelProperty->mPreferredInputChannelLayout = NULL;

						thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);
					}
				}
				else if(CFStringCompare(inNotificationName, thePreferredChannelProperty->mOutputChannelLayoutPrefsKey, 0) == kCFCompareEqualTo)
				{
					theAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout;
					theAddress.mScope = kAudioDevicePropertyScopeOutput;

					CFDictionaryRef dictionary = CACFPreferences::CopyDictionaryValue(thePreferredChannelProperty->mOutputChannelLayoutPrefsKey, false, true);
					if (dictionary != NULL)
					{
						if (thePreferredChannelProperty->mPreferredOutputChannelLayout != NULL && CFEqual(dictionary, thePreferredChannelProperty->mPreferredOutputChannelLayout))
						{
							//	nothing to do, except release dictionary
							CFRelease(dictionary);
						}
						else
						{
							//	re-cache the value
							if (thePreferredChannelProperty->mPreferredOutputChannelLayout != NULL)
								CFRelease(thePreferredChannelProperty->mPreferredOutputChannelLayout);
							thePreferredChannelProperty->mPreferredOutputChannelLayout = dictionary;

							thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);

						}
					}
					else if (thePreferredChannelProperty->mPreferredOutputChannelLayout != NULL)
					{
						CFRelease(thePreferredChannelProperty->mPreferredOutputChannelLayout);
						thePreferredChannelProperty->mPreferredOutputChannelLayout = NULL;

						thePreferredChannelProperty->mDevice->PropertiesChanged(1, &theAddress);
					}
				}
			}
		}
	}
	catch(...)
	{
	}
}

CATokenMap<HP_PreferredChannels>*	HP_PreferredChannels::sTokenMap = NULL;

redpajama_set_name: RedPajamaGithub


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_Instances_SetMachineType_async_flattened]
    using Google.Cloud.Compute.V1;
    using System.Threading.Tasks;
    using lro = Google.LongRunning;

    public sealed partial class GeneratedInstancesClientSnippets
    {
        /// <summary>Snippet for SetMachineTypeAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task SetMachineTypeAsync()
        {
            // Create client
            InstancesClient instancesClient = await InstancesClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            string zone = "";
            string instance = "";
            InstancesSetMachineTypeRequest instancesSetMachineTypeRequestResource = new InstancesSetMachineTypeRequest();
            // Make the request
            lro::Operation<Operation, Operation> response = await instancesClient.SetMachineTypeAsync(project, zone, instance, instancesSetMachineTypeRequestResource);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await instancesClient.PollOnceSetMachineTypeAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END compute_v1_generated_Instances_SetMachineType_async_flattened]
}


text:
package org.wso2.es.ui.integration.extension.test.publisher;

import org.openqa.selenium.By;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.es.ui.integration.extension.util.BaseUITestCase;
import org.wso2.es.ui.integration.extension.util.ESUtil;
import org.wso2.es.ui.integration.extension.util.ESWebDriver;

import static org.testng.Assert.assertTrue;

public class ESPublisherOverridenGlobalPageTestCase extends BaseUITestCase {

    @BeforeClass(alwaysRun = true)
    public void setUp() throws Exception {
        super.init();
        driver = new ESWebDriver();
        baseUrl = getWebAppURL();
        ESUtil.login(driver, baseUrl, publisherApp, userInfo.getUserName(), userInfo.getPassword());
    }

    @Test(groups = "wso2.es", description = "")
    public void testESPublisherOverridenGlobalPageTestCase() throws Exception {
        driver.get(baseUrl + "/publisher/pages/splash");
        assertTrue(isElementPresent(By.id("assetOverridenGlobalPage")));
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
        driver.get("/publisher/logout");
        driver.quit();
    }

}


text:
<!DOCTYPE html>

	<title>Login Page</title>

<?php  ?>

	<form action="account/validate" method="POST">
		Username: <input type="text" name="username" placeholder="Enter username" class="form-control">

		Password: <input type="password" name="password" class="form-control">

		<input type="submit" value="Login">
	</form>


text:
#ifndef __DFG_SERVICE__
#define __DFG_SERVICE__

/** @class Service service.h "services/service.h"
 *	@brief %Service base class.
 *
 *	@author Andrew "RevEn" Karpushin
 */

class Service : Noncopyable
{
    friend class ServiceManager;

public:
    enum State
    {
        PRE_INIT,
        INITIALIZING,
        RUNNING,
        SHUTTING_DOWN,
        COMPLETED,
    };

public:
    virtual ~Service();

    const State& getState() const { return _state; };
    const class ServiceManager * getManager() const { return _manager; };

    // state changing functions.
    // each function returns True if service is ready to transit to next state.

    /**
     * Pre initializing state function.
     *
     * Use this function to make some lightweight initialization actions, e.g.
     * to store pointers to services this service depends on.
     */
    virtual bool onPreInit() { return true; };

    /**
     * Initialization state function.
     *
     * Use this function to load all necessary resources and assets. This method
     * will be called every frame until true is returned (as any other state method).
     */
    virtual bool onInit() { return true; };

    /**
     * Tick state function.
     *
     * Use this function if your service is needed to make some actions every frame.
     */
    virtual bool onTick() { return true; };

    /**
     * Shutdown state function.
     *
     * Use this function to free all service's resources.
     */
    virtual bool onShutdown() { return true; };

protected:
    Service(const ServiceManager * manager);

    void setState(const State& state) { _state = state; };

    State _state;
    const class ServiceManager * _manager;
};

#endif


text:
Date: 2014/12/01

Authors: [Rene Wagner](http://rene-wagner.tumblr.com)

---
---

![](volkswagen-passat-dfgvariant.jpg)

![](volkswadfggen-passat-variant.jpg)

![](volkswagen-passat-variant.jpg)


text:
import os

# Devilry imports
from devilry.devilry_compressionutil.backends import backends_base

class DevilryGroupZipBackend(backends_base.PythonZipFileBackend):
    """
    Implementation of backend used by devilry group.
    """
    backend_id = 'devilry_group_local'

    def __init__(self, **kwargs):
        super(DevilryGroupZipBackend, self).__init__(**kwargs)

    @classmethod
    def delete_archive(cls, full_path):
        if not os.path.exists(full_path):
            return False
        try:
            os.remove(full_path)
        except OSError:
            return False
        return True


text:
int g(int);

void f() {
  int i;
  int &r = i;
  r = 1;
  int *p = &r;
  int &rr = r;
  int (&rg)(int) = g;
  rg(i);
  int a[3];
  int (&ra)[3] = a;
  ra[1] = i;
  int *Q;
  int *& P = Q;
  P[1] = 1;
}

typedef int t[1];
void test2() {
    t a;
    t& b = a;

    int c[3];
    int (&rc)[3] = c;
}

// C++ [dcl.init.ref]p5b1
struct A { };
struct B : A { } b;

void test3() {
  double d = 2.0;
  double& rd = d; // rd refers to d
  const double& rcd = d; // rcd refers to d

  A& ra = b; // ra refers to A subobject in b
  const A& rca = b; // rca refers to A subobject in b
}

B fB();

// C++ [dcl.init.ref]p5b2
void test4() {
  double& rd2 = 2.0; // expected-error{{non-const lvalue reference to type 'double' cannot bind to a temporary of type 'double'}}
  int i = 2;
  double& rd3 = i; // expected-error{{non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'}}

  const A& rca = fB();
}

void test5() {
  //  const double& rcd2 = 2; // rcd2 refers to temporary with value 2.0
  const volatile int cvi = 1;
  const int& r = cvi; // expected-error{{binding of reference to type 'const int' to a value of type 'const volatile int' drops qualifiers}}
}

// C++ [dcl.init.ref]p3
int& test6(int& x) {
  int& yo; // expected-error{{declaration of reference variable 'yo' requires an initializer}}

  return x;
}
int& not_initialized_error; // expected-error{{declaration of reference variable 'not_initialized_error' requires an initializer}}
extern int& not_initialized_okay;

class Test6 { // expected-warning{{class 'Test6' does not declare any constructor to initialize its non-modifiable members}}
  int& okay; // expected-note{{reference member 'okay' will never be initialized}}
};

struct C : B, A { };

void test7(C& c) {
  A& a1 = c; // expected-error {{ambiguous conversion from derived class 'C' to base class 'A':}}
}

// C++ [dcl.ref]p1, C++ [dcl.ref]p4
void test8(int& const,// expected-error{{'const' qualifier may not be applied to a reference}}

           void&,     // expected-error{{cannot form a reference to 'void'}}
           int& &)    // expected-error{{type name declared as a reference to a reference}}
{
  typedef int& intref;
  typedef intref& intrefref; // C++ DR 106: reference collapsing

  typedef intref const intref_c; // okay. FIXME: how do we verify that this is the same type as intref?
}

class string {
  char *Data;
  unsigned Length;
public:
  string();
  ~string();
};

string getInput();

void test9() {
  string &s = getInput(); // expected-error{{lvalue reference}}
}

void test10() {
  __attribute((vector_size(16))) typedef int vec4;
  typedef __attribute__(( ext_vector_type(4) )) int ext_vec4;

  vec4 v;
  int &a = v[0]; // expected-error{{non-const reference cannot bind to vector element}}
  const int &b = v[0];

  ext_vec4 ev;
  int &c = ev.x; // expected-error{{non-const reference cannot bind to vector element}}
  const int &d = ev.x;
}

namespace PR7149 {
  template<typename T> struct X0
  {
    T& first;
    X0(T& p1) : first(p1) { }
  };

  void f()
  {
    int p1[1];
    X0< const int[1]> c(p1);
  }
}

namespace PR8608 {
  bool& f(unsigned char& c) { return (bool&)c; }
}

// The following crashed trying to recursively evaluate the LValue.
const int &do_not_crash = do_not_crash; // expected-warning{{reference 'do_not_crash' is not yet bound to a value when used within its own initialization}}

namespace ExplicitRefInit {
  // This is invalid: we can't copy-initialize an 'A' temporary using an
  // explicit constructor.
  struct A { explicit A(int); };
  const A &a(0); // expected-error {{reference to type 'const ExplicitRefInit::A' could not bind to an rvalue of type 'int'}}
}


text:
"""Module with some helpers for tests."""
import os
import sys
import time
from socket import socket

from pyof.v0x01.common.header import Header
from pyof.v0x01.symmetric.hello import Hello

from kytos.core import Controller
from kytos.core.config import KytosConfig

__all__ = ('do_handshake', 'new_controller', 'new_client',
           'new_handshaked_client')

def do_handshake(client):
    """Get a client (socket) and do the handshake of it.

    This method receives a client (socket) that simulates a switch on the
    network and do the OpenFlow handshake process with a running controller
    on the network.

    Args:
        client (socket): a socket object connected on the controller.

    Returns:
        The client with the handshake process done.

    """
    # -- STEP 1: Sending Hello message
    client.send(Hello(xid=3).pack())

    # -- STEP 2: Whait for Hello response
    binary_packet = b''
    while len(binary_packet) < 8:
        binary_packet = client.recv(8)
    header = Header()
    header.unpack(binary_packet)

    # -- STEP 3: Wait for features_request message
    binary_packet = b''
    # len() < 8 here because we just expect a Hello as response
    while len(binary_packet) < 8:
        binary_packet = client.recv(8)
    header = Header()
    header.unpack(binary_packet)

    # -- STEP 4: Send features_reply to the controller
    basedir = os.path.dirname(os.path.abspath(__file__))
    raw_dir = os.path.join(basedir, 'raw')
    message = None
    with open(os.path.join(raw_dir, 'features_reply.cap'), 'rb') as file:
        message = file.read()
    client.send(message)

    return client

def get_config():
    """Exclude unittest args from Config argparser."""
    argv_backup = None
    # If cli command was like "python -m unittest"
    if sys.argv[0].split()[-1] == 'unittest':
        argv_backup = sys.argv
        sys.argv = sys.argv[:1]
    config = KytosConfig()
    if argv_backup:
        # Recover original argv
        sys.argv = argv_backup
    return config

def new_controller(options=None):
    """Instantiate a Kytos Controller.

    Args:
        options (KytosConfig.options): options generated by KytosConfig

    Returns:
        controller: Running Controler

    """
    if options is None:
        options = get_config().options['daemon']
    controller = Controller(options)
    controller.start()
    time.sleep(0.1)
    return controller

def new_client(options=None):
    """Create and returns a socket client.

    Args:
        options (KytosConfig.options): options generated by KytosConfig

    Returns:
        client (socket): Client connected to the Kytos controller before
            handshake

    """
    if options is None:
        options = get_config().options['daemon']
    client = socket()
    client.connect((options.listen, options.port))
    return client

def new_handshaked_client(options=None):
    """Create and returns a socket client.

    Args:
        options (KytosConfig.options): options generated by KytosConfig

    Returns:
        client (socket): Client connected to the Kytos controller with
            handshake done

    """
    if options is None:
        options = get_config().options['daemon']
    client = new_client(options)
    return do_handshake(client)


text:
import assert from 'assert';
import Arc from '../index';

describe('document', () => {
    describe('plain string', () => {
        it('should return that string as the content', () => {
            const engine = new Arc();
            return engine.evaluateString('test').then(result => {
                assert.equal(result.content, 'test');
            });
        });
    });

    describe('html string', () => {
        it('should return full, unescaped text as the content', () => {
            const engine = new Arc();
            return engine.evaluateString('test').then(result => {
                assert.equal(result.content, 'test');
            });
        });
    });

    describe('quoted string', () => {
        it('should return full, unescaped text as the content', () => {
            const engine = new Arc();
            return engine.evaluateString('\"\'test\'\"').then(result => {
                assert.equal(result.content, '\"\'test\'\"');
            });
        });
    });

    describe('empty', () => {
        it('should return empty content', () => {
            const engine = new Arc();
            return engine.evaluateString('').then(result => {
                assert.equal(result.content, '');
            });
        });
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace AvalonDock
{
    internal class FloatingDocumentPane : DocumentPane
    {
        static FloatingDocumentPane()
        {
            Pane.ShowHeaderProperty.OverrideMetadata(typeof(FloatingDocumentPane), new FrameworkPropertyMetadata(false));
        }

        internal FloatingDocumentPane(DocumentFloatingWindow floatingWindow, DocumentContent documentToTransfer)
        {
            _floatingWindow = floatingWindow;
            _documentToTransfer = documentToTransfer;
        }

        DocumentContent _documentToTransfer = null;
        DocumentPane _previousPane = null;

        internal DocumentPane PreviousPane
        {
            get
            { return _previousPane; }
        }

        int _arrayIndexPreviousPane = -1;

        internal int ArrayIndexPreviousPane
        {
            get { return _arrayIndexPreviousPane; }
        }

        protected override void OnInitialized(EventArgs e)
        {
            _previousPane = _documentToTransfer.ContainerPane as DocumentPane;

            if (_documentToTransfer != null && _documentToTransfer.FloatingWindowSize.IsEmpty)
            {
                if (_previousPane != null)
                    _documentToTransfer.FloatingWindowSize = new Size(_previousPane.ActualWidth, _previousPane.ActualHeight);
                else
                    _documentToTransfer.FloatingWindowSize = new Size(400.0, 400.0);
            }

            if (_documentToTransfer != null && !_documentToTransfer.FloatingWindowSize.IsEmpty)
            {
                _floatingWindow.Width = _documentToTransfer.FloatingWindowSize.Width;
                _floatingWindow.Height = _documentToTransfer.FloatingWindowSize.Height;
            }

            if (_previousPane != null)
            {
                //setup window size
                _floatingWindow.Width = _documentToTransfer.ContainerPane.ActualWidth;
                _floatingWindow.Height = _documentToTransfer.ContainerPane.ActualHeight;

                //save current content position in container pane
                _arrayIndexPreviousPane = _previousPane.Items.IndexOf(_documentToTransfer);
                SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty));
                SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty));

                //Style = _previousPane.Style;
                AttachStyleFromPane(_previousPane);

                //remove content from container pane
                _previousPane.RemoveContent(_arrayIndexPreviousPane);
            }

            //add content to my temporary pane
            Items.Add(_documentToTransfer);

            _documentToTransfer.SetIsFloating(true);

            LayoutTransform = (MatrixTransform)_documentToTransfer.TansformToAncestor();

            base.OnInitialized(e);
        }

        void AttachStyleFromPane(DocumentPane copyFromPane)
        {
            if (copyFromPane == null)
                return;

            //Binding bnd = new Binding("Style");
            //bnd.Source = copyFromPane;
            //bnd.Mode = BindingMode.OneWay;

            //SetBinding(StyleProperty, bnd);
        }

        protected override void OnUnloaded(object sender, RoutedEventArgs e)
        {
            _documentToTransfer.SetIsFloating(false);
            base.OnUnloaded(sender, e);
        }

        DocumentFloatingWindow _floatingWindow = null;

        public DocumentFloatingWindow FloatingWindow
        {
            get { return _floatingWindow; }
        }

        public override DockingManager GetManager()
        {
            return _floatingWindow.Manager;
        }

        protected override bool IsSurfaceVisible
        {
            get
            {
                return false;
            }
        }

        protected override void CheckItems(System.Collections.IList newItems)
        {
            foreach (object newItem in newItems)
            {
                if (!(newItem is DocumentContent))
                    throw new InvalidOperationException("FloatingDocumentPane can contain only DocumentContents!");
            }

            if (Items.Count == 0 && FloatingWindow != null)
                FloatingWindow.Close(true);
        }

        public override void Dock()
        {
            var contentsToRedock = Items.Cast<DocumentContent>().ToArray();

            foreach (var cntToRedock in contentsToRedock)
                cntToRedock.Show();

            base.Dock();
        }
    }
}


text:
@implementation ZMHStatusTool

+ (void)newStatusWithSinceId:(NSString *)sinceId success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure
{
    // 创建参数模型
    ZMHStatusParam *param = [[ZMHStatusParam alloc] init];
    param.access_token = [ZMHAccountTool account].access_token;
    if (sinceId) { // 有微博数据,才需要下拉刷新
        param.since_id = sinceId;

    }

    [ZMHWeiboTool GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:param.keyValues success:^(NSURLSessionDataTask * task,id responseObject) { // HttpTool请求成功的回调
        // 请求成功代码先保存

        ZMHStatusResult *result = [ZMHStatusResult objectWithKeyValues:responseObject];

        if (success) {
            success(result.statuses);
        }

    } failure:^(NSURLSessionDataTask * task ,NSError *error) {
        if (failure) {
            NSLog(@"%@",error) ;
            failure(error);
        }
    }];

}

+ (void)moreStatusWithMaxId:(NSString *)maxId success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure
{
    // 创建参数模型
    ZMHStatusParam *param = [[ZMHStatusParam alloc] init];
    param.access_token = [ZMHAccountTool account].access_token;
    if (maxId) { // 有微博数据,才需要下拉刷新
        param.max_id = maxId;

    }

    [ZMHWeiboTool GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:param.keyValues success:^(NSURLSessionDataTask * task ,id responseObject) { // HttpTool请求成功的回调
        // 请求成功代码先保存

        // 把结果字典转换结果模型
        ZMHStatusResult *result = [ZMHStatusResult objectWithKeyValues:responseObject];

        if (success) {
            success(result.statuses);
        }

    } failure:^(NSURLSessionDataTask * task ,NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

@end


text:
layout: post
title: "One Year Post-transplant"
date: 2014-06-30 16:17:55 -0400
author: "kmbrlynn"
header-img: "img/projects.JPG"
tags:
- cancer
- Hodgkin
- lymphoma
- transplant
- autologous transplant
- autotransplant
- hdct-asct
- vaccines
- vaccination
- rock climbing
- First Descents
---

First things first, I never posted pictures of my Moab, Utah rock climbing trip with [First Descents](http://firstdescents.org/)! Here are a few good action shots of me climbing and rappelling:

![Climbing](../../../../img/kmbrlynnImages/climbing.JPG)

![Rappelling](../../../../img/kmbrlynnImages/rappelling.png)

![Rappelling](../../../../img/kmbrlynnImages/rappelling2.png)

This was such an incredible experience and deserves a much lengthier post, so more on that later! But for now, on to the scan...

I just met with Dr. Barnes, my head oncologist, and Dr. Winkfield, my radiation oncologist, to talk about the one-year CT scans that were taken last week.

**They are perfectly clean!!!**

There is still a large mass of scar tissue on the left side of my chest, as well as scarring in my spine and my pelvis. While these now-dead tumors are slowly but surely shrinking, they will always be there in some capacity. However, they show no signs of disease whatsoever. This is incredibly good news - even better than when I got clean scans six months ago. The first year after a transplant is the most precarious.

Treatment for cancers that are as advanced as mine have a much higher risk of failing than those for earlier-stage diagnoses. Dr. Chen, my transplant doctor, estimates a 50% chance of success for the type of [autologous stem cell transplant](http://kmbrlynn.github.io/blog/2013/06/19/on-to-the-transplant/) that I received - but gave me somewhere between 50% and 75% because I am otherwise young and strong. So that was good news, but still a little alarming. Usually failures occur within the first few years - so Dr. Barnes, who is not typically one to get hung up on statistics, was elated to report that the window is continuing to close.

Of course, Jeff Barnes wastes no time. He wouldn't let me leave without my vaccinations. When they wiped out my immune system with the stem cell transplant, they also wiped out all the immunities that I'd built up over 25 years. As logic would have it, my immune system is now one year old, so they are putting me on the same vaccination schedule that they use for infants - [Pediarix](http://www.cdc.gov/vaccines/vpd-vac/combo-vaccines/pediarix/faqs-hcp-pediarix.htm), which is a combination of several different vaccines, including hepatitis and polio. It's kind of a relief not to feel so vulnerable anymore (as you can see, this whole anti-vaccine nonsense has struck particularly close to home).

![Happy birthday to me!](../../../../img/kmbrlynnImages/oneYearCupcake.jpg)

The other milestone I've had recently is that they [removed my port](../../../../2013/03/01/ports/) on Friday! I have to say, I feel a little bit like they took my security blanket away. Needing blood drawn from my arm has been (literally) nauseating - when I watch them prep the butterfly needle and feel the rubber band tighten around my skin, it's hard not to be thrown back into the infusion unit, the Vinblastine curdling and scarring and blowing out all my veins.

But, today the blood draw went smoothly, and she didn't have to dig around to find a blood return. I guess some scars really do heal :)

My next appointment is a whole three months from now! So hopefully I can get some non-cancer posts in soon.

Kim


text:
<?php

declare (strict_types=1);
namespace Rector\Autodiscovery\Analyzer;

use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Type\ObjectType;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\Core\NodeAnalyzer\ClassAnalyzer;
use Rector\Core\ValueObject\MethodName;
use Rector\NodeCollector\NodeCollector\NodeRepository;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\NodeTypeResolver;
final class ValueObjectClassAnalyzer
{
    /**
     * @var array<string, bool>
     */
    private $valueObjectStatusByClassName = [];
    /**
     * @var \Rector\NodeNameResolver\NodeNameResolver
     */
    private $nodeNameResolver;
    /**
     * @var \Rector\NodeTypeResolver\NodeTypeResolver
     */
    private $nodeTypeResolver;
    /**
     * @var \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory
     */
    private $phpDocInfoFactory;
    /**
     * @var \Rector\NodeCollector\NodeCollector\NodeRepository
     */
    private $nodeRepository;
    /**
     * @var \Rector\Core\NodeAnalyzer\ClassAnalyzer
     */
    private $classAnalyzer;
    public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory $phpDocInfoFactory, \Rector\NodeCollector\NodeCollector\NodeRepository $nodeRepository, \Rector\Core\NodeAnalyzer\ClassAnalyzer $classAnalyzer)
    {
        $this->nodeNameResolver = $nodeNameResolver;
        $this->nodeTypeResolver = $nodeTypeResolver;
        $this->phpDocInfoFactory = $phpDocInfoFactory;
        $this->nodeRepository = $nodeRepository;
        $this->classAnalyzer = $classAnalyzer;
    }
    public function isValueObjectClass(\PhpParser\Node\Stmt\Class_ $class) : bool
    {
        if ($this->classAnalyzer->isAnonymousClass($class)) {
            return \false;
        }
        /** @var string $className */
        $className = $this->nodeNameResolver->getName($class);
        if (isset($this->valueObjectStatusByClassName[$className])) {
            return $this->valueObjectStatusByClassName[$className];
        }
        $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT);
        if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) {
            return $this->analyseWithoutConstructor($class, $className);
        }
        // resolve constructor types
        foreach ($constructClassMethod->params as $param) {
            $paramType = $this->nodeTypeResolver->resolve($param);
            if (!$paramType instanceof \PHPStan\Type\ObjectType) {
                continue;
            }
            // awesome!
            // is it services or value object?
            $paramTypeClass = $this->nodeRepository->findClass($paramType->getClassName());
            if (!$paramTypeClass instanceof \PhpParser\Node\Stmt\Class_) {
                // not sure :/
                continue;
            }
            if (!$this->isValueObjectClass($paramTypeClass)) {
                return \false;
            }
        }
        // if we didn't prove it's not a value object so far → fallback to true
        $this->valueObjectStatusByClassName[$className] = \true;
        return \true;
    }
    private function analyseWithoutConstructor(\PhpParser\Node\Stmt\Class_ $class, string $className) : bool
    {
        // A. has all properties with serialize?
        if ($this->hasAllPropertiesWithSerialize($class)) {
            $this->valueObjectStatusByClassName[$className] = \true;
            return \true;
        }
        // probably not a value object
        $this->valueObjectStatusByClassName[$className] = \false;
        return \false;
    }
    private function hasAllPropertiesWithSerialize(\PhpParser\Node\Stmt\Class_ $class) : bool
    {
        foreach ($class->getProperties() as $property) {
            $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property);
            if ($phpDocInfo->hasByAnnotationClass('JMS\\Serializer\\Annotation\\Type')) {
                continue;
            }
            return \false;
        }
        return \true;
    }
}


text:
'use strict';

let fs = require('fs-extra');
let request = require('request');
let path = require('path');
let ipcRenderer = require('electron').ipcRenderer;

import InstallableItem from './installable-item';
import Downloader from './helpers/downloader';
import Logger from '../services/logger';
import VagrantInstall from './vagrant';
import Installer from './helpers/installer';

class CDKInstall extends InstallableItem {
  constructor(installerDataSvc, $timeout, cdkUrl, cdkBoxUrl, ocUrl, pscpUrl, installFile, targetFolderName) {
    super('cdk',
          'Red Hat Container Development Kit',
          '2.0',
          'Developer Tools for Creating, Testing, and Distributing Red Hat Container-Based Applications',
          900,
          cdkUrl,
          installFile,
          targetFolderName,
          installerDataSvc);

    this.$timeout = $timeout;
    this.cdkBoxUrl = cdkBoxUrl;
    this.ocUrl = ocUrl;
    this.pscpUrl = pscpUrl;

    this.cdkFileName = 'cdk.zip';
    this.cdkDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.cdkFileName);
    this.version = '2.0';

    this.boxName = 'rhel-vagrant-virtualbox.box';
    this.cdkBoxDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.boxName);

    this.ocFileName = 'oc.zip';
    this.ocDownloadedFile = path.join(this.installerDataSvc.tempDir(),   this.ocFileName);

    this.pscpFileName = 'pscp.exe';
    this.pscpDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.pscpFileName);

    this.pscpPathScript = path.join(this.installerDataSvc.tempDir(), 'set-pscp-path.ps1');

    this.downloads = path.normalize(path.join(__dirname,"../../.."));

    this.addOption('install','2.0.0','',true);
  }

  static key() {
    return 'cdk';
  }

  checkForExistingInstall() {
  }

  downloadInstaller(progress, success, failure) {
    progress.setStatus('Downloading');

    let downloadSize = 869598013;

    let totalDownloads = 4;

    let downloader = new Downloader(progress, success, failure, downloadSize, totalDownloads);
    let username = this.installerDataSvc.getUsername(),
        password = this.installerDataSvc.getPassword();

    if(!fs.existsSync(path.join(this.downloads, this.boxName))) {
      let cdkBoxWriteStream = fs.createWriteStream(this.cdkBoxDownloadedFile);
      downloader.setWriteStream(cdkBoxWriteStream);
      downloader.download(this.cdkBoxUrl);
    } else {
      this.cdkBoxDownloadedFile = path.join(this.downloads, this.boxName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.cdkFileName))) {
      // TODO Switch back to auth download when CDK latest is in Customer Portal
      // downloader.downloadAuth
      //   ({
      //     url: this.cdkBoxUrl,
      //     rejectUnauthorized: false
      //   }, username, password);
      let cdkWriteStream = fs.createWriteStream(this.cdkDownloadedFile);
      downloader.setWriteStream(cdkWriteStream);
      downloader.downloadAuth
      ({
        url: this.getDownloadUrl(),
        rejectUnauthorized: false
      }, username, password);
    } else {
      this.cdkDownloadedFile = path.join(this.downloads, this.cdkFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.pscpFileName))) {
      let pscpWriteStream = fs.createWriteStream(this.pscpDownloadedFile);
      downloader.setWriteStream(pscpWriteStream);
      downloader.download(this.pscpUrl);
    } else {
      this.pscpDownloadedFile = path.join(this.downloads, this.pscpFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.ocFileName))) {
      let ocWriteStream = fs.createWriteStream(this.ocDownloadedFile);
      if(!this.ocUrl.endsWith('.zip')) {
        request(this.ocUrl,(err,rsp,body) => {
          var fname = body.match(/openshift-origin-client-tools-v\w(\.\w){1,2}-\w{1,3}-\w{8}-\w{7}-windows\.zip/)[0];
          downloader.setWriteStream(ocWriteStream);
          this.ocUrl=this.ocUrl.concat(fname);
          downloader.download(this.ocUrl);
        });
      } else {
        downloader.setWriteStream(ocWriteStream);
        downloader.download(this.ocUrl);
      }
    } else {
      this.ocDownloadedFile = path.join(this.downloads, this.ocFileName);
      downloader.closeHandler();
    }
  }

  install(progress, success, failure) {
    let vagrantInstall = this.installerDataSvc.getInstallable(VagrantInstall.key());
    if( vagrantInstall !== undefined && vagrantInstall.isInstalled() ) {
      this.postVagrantInstall(progress, success, failure);
    } else {
      progress.setStatus('Waiting for Vagrant to finish installation');
      ipcRenderer.on('installComplete', (event, arg) => {
        if (arg == 'vagrant') {
          this.postVagrantInstall(progress, success, failure);
        }
      });
    }
  }

  postVagrantInstall(progress, success, failure) {
    progress.setStatus('Installing');
    let installer = new Installer(CDKInstall.key(), progress, success, failure);

    let opts = [
      '-ExecutionPolicy',
      'ByPass',
      '-File',
      this.pscpPathScript
    ];
    let data = [
      '$newPath = "' + this.installerDataSvc.ocDir() + '";',
      '$oldPath = [Environment]::GetEnvironmentVariable("path", "User");',
      '[Environment]::SetEnvironmentVariable("Path", "$newPath;$oldPath", "User");',
      '[Environment]::Exit(0)'
    ].join('\r\n');
    let markerContent = [
      'openshift.auth.scheme=Basic',
      'openshift.auth.username=openshift-dev',
      'openshift.auth.password=devel',
      'vagrant.binary.path=' + path.join(this.installerDataSvc.vagrantDir(), 'bin'),
      'oc.binary.path=' + this.installerDataSvc.ocDir(),
      'rhel.subscription.username=' + this.installerDataSvc.getUsername()
    ].join('\r\n');

    installer.unzip(this.cdkDownloadedFile, this.installerDataSvc.installDir())
    .then((result) => { return installer.unzip(this.ocDownloadedFile, this.installerDataSvc.ocDir(), result); })
    .then((result) => { return installer.copyFile(this.cdkBoxDownloadedFile, path.join(this.installerDataSvc.cdkBoxDir(), this.boxName), result); })
    .then((result) => { return installer.copyFile(this.pscpDownloadedFile, path.join(this.installerDataSvc.ocDir(), 'pscp.exe'), result); })
    .then((result) => { return installer.writeFile(this.pscpPathScript, data, result); })
    .then((result) => { return installer.writeFile(this.installerDataSvc.cdkMarker(), markerContent, result); })
    .then((result) => { return installer.execFile('powershell', opts, result); })
    .then((result) => { return this.setupVagrant(installer, result); })
    .then((result) => { return installer.succeed(result); })
    .catch((error) => { return installer.fail(error); });
  }

  createEnvironment() {
    let env = {};

    //TODO Need to get this info from VagrantInstaller rather than hard code
    let vagrantInstall = this.installerDataSvc.getInstallable('vagrant');
    let vboxInstall = this.installerDataSvc.getInstallable('virtualbox');
    let vgrPath = vagrantInstall.getLocation();
    let vboxPath = vboxInstall.getLocation();
    env['path'] = path.join(vgrPath,'bin') + ';' + vboxPath + ';';
    return env;
  }

  setupVagrant(installer, result) {
    return new Promise((resolve, reject) => {
      let vagrantInstall = this.installerDataSvc.getInstallable(VagrantInstall.key());

      if (vagrantInstall !== undefined && vagrantInstall.isInstalled()) {
        return this.postVagrantSetup(installer, result)
        .then((res) => { return resolve(res); })
        .catch((err) => { return reject(err); });
      } else {
        Logger.info(CDKInstall.key() + ' - Vagrant has not finished installing, listener created to be called when it has.');
        ipcRenderer.on('installComplete', (event, arg) => {
          if (arg == 'vagrant') {
            return this.postVagrantSetup(installer, result)
            .then((res) => { return resolve(res); })
            .catch((err) => { return reject(err); });
          }
        });
      }
    });
  }

  postVagrantSetup(installer, promise) {
    Logger.info(CDKInstall.key() + ' - postVagrantSetup called');
    let vagrantInstall = this.installerDataSvc.getInstallable(VagrantInstall.key());
    if (vagrantInstall.isInstalled()) {
      // Vagrant is installed, add CDK bits
      let env = this.createEnvironment();
      let opts = {
        env: env
      };
      let res = installer.exec(
        'vagrant plugin install "' + path.join(this.installerDataSvc.cdkDir(), 'plugins', 'vagrant-registration-1.2.1.gem') + '"', opts, promise
      ).then((result) => {
        return new Promise((resolve,reject) => {
          installer.exec('vagrant box remove cdkv2 -f',opts, promise).then((result)=> {
            resolve(result);
          }).catch((result) => {
            resolve(result);
          });
        });
      }).then((result) => {
        return installer.exec('vagrant box add --name cdkv2 "' + path.join(this.installerDataSvc.cdkBoxDir(), this.boxName) + '"', opts, result);
      }).then((result) => {
        return installer.exec('vagrant plugin install "' + path.join(this.installerDataSvc.cdkDir(), 'plugins', 'vagrant-service-manager-1.0.1.gem') + '"', opts, result);
      });
      return res;
    }
  }
}

export default CDKInstall;


text:
package com.jivesoftware.example.github.service;

import com.jivesoftware.example.github.dao.Organization;
import com.jivesoftware.example.github.dao.Repository;
import com.jivesoftware.example.github.dao.Team;
import com.jivesoftware.example.github.dao.User;
import retrofit.Callback;
import retrofit.http.DELETE;
import retrofit.http.EncodedPath;
import retrofit.http.GET;
import retrofit.http.PUT;
import retrofit.http.Path;

/**
 * Created by mark.schisler on 9/3/14.
 */
public interface IGitHubRepoService {
    /**/

    @GET("/user/repos")
    Repository[] getUserRepositories();

    @GET("/user/repos")
    void getUserRepositories(Callback<Repository[]> callback);

    @GET("/{repo_url}")
    Repository[] getRepositories(@EncodedPath("repo_url") String repoUrl);

    @GET("/{repo_url}")
    void getRepositories(@EncodedPath("repo_url") String repoUrl, Callback<Repository[]> callback);

    /**/

    @GET("/user/orgs")
    Organization[] getOrganizations();

    @GET("/user/orgs")
    void getOrganizations(Callback<Organization[]> callback);

    @GET("/orgs/{org}/teams")
    Team[] getOrganizationTeams(@EncodedPath("org") String name);

    @GET("/orgs/{org}/teams")
    void getOrganizationTeams(@EncodedPath("org") String name, Callback<Team[]> callback);

    /**/

    @GET("/{repo_url}/teams")
    Team[] getRepoTeams(@EncodedPath("repo_url") String repoUrl);

    @GET("/{repo_url}/teams")
    void getRepoTeams(@EncodedPath("repo_url") String repoUrl, Callback<Team[]> callback);

    /**/

    @GET("/{repo_url}/collaborators")
    User[] getCollaborators(@EncodedPath("repo_url") String repoUrl);

    @GET("/{repo_url}/collaborators")
    void getCollaborators(@EncodedPath("repo_url") String repoUrl, Callback<User[]> callback);

    @PUT("/{repo_url}/collaborators/{collaborator}")
    Void putCollaborator(@EncodedPath("repo_url") String repoUrl, @Path("collaborator") String collaborator);

    @PUT("/{repo_url}/collaborators/{collaborator}")
    void putCollaborator(@EncodedPath("repo_url") String repoUrl, @Path("collaborator") String collaborator, Callback<Void> callback);

    @DELETE("/{repo_url}/collaborators/{collaborator}")
    Void deleteCollaborator(@EncodedPath("repo_url") String repoUrl, @Path("collaborator") String collaborator);

    @DELETE("/{repo_url}/collaborators/{collaborator}")
    void deleteCollaborator(@EncodedPath("repo_url") String repoUrl, @Path("collaborator") String collaborator, Callback<Void> callback);

    /**/

    @GET("/teams/{id}/members")
    User[] getTeamMembers(@Path("id") int id);

    @GET("/teams/{id}/members")
    void getTeamMembers(@Path("id") int id, Callback<User[]> callback);

    @PUT("/teams/{id}/memberships/{username}")
    Void putTeamMember(@Path("id") int id, @Path("username") String username);

    @PUT("/teams/{id}/memberships/{username}")
    void putTeamMember(@Path("id") int id, @Path("username") String username, Callback<Void> callback);

    @DELETE("/teams/{id}/members/{username}")
    Void deleteTeamMember(@Path("id") int id, @Path("username") String username);

    @DELETE("/teams/{id}/members/{username}")
    void deleteTeamMember(@Path("id") int id, @Path("username") String username, Callback<Void> callback);
}


text:
package powerapi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import powerapi.entity.AutoTest;
import powerapi.entity.UnitTest;
import powerapi.mapper.UnitTestMapper;
import powerapi.service.UnitTestService;

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

/**
 * Created by Melon on 17/3/14.
 */
@Service
public class UnitTestServiceImpl extends ServiceImpl<UnitTestMapper, UnitTest> implements UnitTestService {

    @Resource
    private UnitTestMapper unitTestMapper;

    @Override
    public List<UnitTest> findAutoTestList(Long aid) {

        return unitTestMapper.findAutoTestList(aid);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.toolresults.model;

/**
 * Additional details about encountered login screens.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Tool Results API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class EncounteredLoginScreen extends com.google.api.client.json.GenericJson {

  /**
   * Number of encountered distinct login screens.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer distinctScreens;

  /**
   * Subset of login screens.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> screenIds;

  /**
   * Number of encountered distinct login screens.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getDistinctScreens() {
    return distinctScreens;
  }

  /**
   * Number of encountered distinct login screens.
   * @param distinctScreens distinctScreens or {@code null} for none
   */
  public EncounteredLoginScreen setDistinctScreens(java.lang.Integer distinctScreens) {
    this.distinctScreens = distinctScreens;
    return this;
  }

  /**
   * Subset of login screens.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getScreenIds() {
    return screenIds;
  }

  /**
   * Subset of login screens.
   * @param screenIds screenIds or {@code null} for none
   */
  public EncounteredLoginScreen setScreenIds(java.util.List<java.lang.String> screenIds) {
    this.screenIds = screenIds;
    return this;
  }

  @Override
  public EncounteredLoginScreen set(String fieldName, Object value) {
    return (EncounteredLoginScreen) super.set(fieldName, value);
  }

  @Override
  public EncounteredLoginScreen clone() {
    return (EncounteredLoginScreen) super.clone();
  }

}


text:
<?php

namespace QueueSqsEbWorker\Queue;

use SlmQueue\Job\JobInterface;
use SlmQueue\Queue\AbstractQueue;

class EbWorkerQueue extends AbstractQueue
{
    /**
     * Push a new job into the queue
     *
     * @param  JobInterface $job
     * @param  array $options
     * @return void
     */
    public function push(JobInterface $job, array $options = array())
    {
        throw new \BadMethodCallException('Not Implemented.');
    }

    /**
     * Pop a job from the queue
     *
     * @param  array $options
     * @return JobInterface|null
     */
    public function pop(array $options = array())
    {
        throw new \BadMethodCallException('Not Implemented.');
    }

    /**
     * Delete a job from the queue
     *
     * @param  JobInterface $job
     * @return void
     */
    public function delete(JobInterface $job)
    {
        throw new \BadMethodCallException('Not Implemented.');
    }
}


text:
from numpy import outer, triu_indices
from scipy.sparse import csr_matrix, coo_matrix, triu
from code import interact

def second_deg_poly_features(X):
  D = X.shape[1]
  D2 = (D**2+D)/2+D
  print D2
  X2 = coo_matrix(X.tocsr(), shape=(X.shape[0], D2)).tocsr()
  for i, row in enumerate(X):
    interact(local=locals())
    nzrows, nzcols = triu(outer(row.T,row)[0][0]).flatten()
    print r.shape
    X2[i, D:] = r
  return X2


text:
<!DOCTYPE html>

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>class Validating - RDoc Documentation</title>

<link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet">

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Defined In

lib/roles/validating.rb

Parent

Dirt::Role

Methods

::new

#errors

#valid?

Pages

README

Class and Module Index

Dirt

Dirt::MemoryPersister

Dirt::MemoryRecord

Dirt::MissingRecordError

Dirt::Model

Dirt::NoPersisterError

Dirt::Relation

Dirt::Role

Dirt::TooManyRecordsError

Dirt::TransactionError

ClosureValidator

ExistenceValidator

Persister

Persisting

PresenceValidator

SelfExistenceValidator

Validating

class Validating

A Role for testing whether the wrapped object is valid, using the list of
validators provided in the constructor,

Validators

Each validator must respond to

valid?        to return whether that validator passes, and

error_message to return any errors found when
valid? is false.

Public Class Methods

          new(decorated, validators)
          click to toggle source

Takes the decorated object and then the list of validators. See Role for
more on decoration.

# File lib/roles/validating.rb, line 9
def initialize(decorated, validators)
  super(decorated)
  @validators = validators
end

Public Instance Methods

          errors()
          click to toggle source

Returns a list of the string messages returned from the validators that
have failed.

# File lib/roles/validating.rb, line 22
def errors
  @validators.collect do |v|
    v.error_message(@decorated) unless v.valid?(@decorated)
  end.reject { |m| m.nil? }
end

          valid?()
          click to toggle source

Returns true iff every validator passes.

# File lib/roles/validating.rb, line 15
def valid?
  @validators.all? do |v|
    v.valid?(@decorated)
  end
end

[Validate]

Generated by RDoc 3.12.2.

Generated with the Darkfish Rdoc Generator 3.


text:
using System;

namespace Engine.Xna.Network
{
    internal class SocketError : ISocketError
    {
        public Exception Exception { get; set; }
        public string Message { get; set; }

        public SocketError(Exception exception, string message)
        {
            Exception = exception;
            Message = message;
        }
    }
}


text:
export class PairSetupVerifyResponse {
    accessorySRPProof: Buffer;
}


text:
namespace crashpad {

ThreadContext::ThreadContext() {
  memset(this, 0, sizeof(*this));
}

ThreadContext::~ThreadContext() {}

FloatContext::FloatContext() {
  memset(this, 0, sizeof(*this));
}

FloatContext::~FloatContext() {}

ThreadInfo::ThreadInfo()
    : thread_context(), float_context(), thread_specific_data_address(0) {}

ThreadInfo::~ThreadInfo() {}

}  // namespace crashpad


text:
//
//  NSDictionary+ZCMerge.m
//  ZCKit
//
//  Created by t_zc on 16/1/24.
//  Copyright © 2016年 t_zc. All rights reserved.
//

#import "NSDictionary+ZCMerge.h"

@implementation NSDictionary(ZCMerge)
/**
 *  @brief  合并两个NSDictionary
 *
 *  @param dict1 NSDictionary
 *  @param dict2 NSDictionary
 *
 *  @return 合并后的NSDictionary
 */
+ (NSDictionary *)dictionaryByMerging:(NSDictionary *)dict1 with:(NSDictionary *)dict2 {
    NSMutableDictionary * result = [NSMutableDictionary dictionaryWithDictionary:dict1];
    NSMutableDictionary * resultTemp = [NSMutableDictionary dictionaryWithDictionary:dict1];
    [resultTemp addEntriesFromDictionary:dict2];
    [resultTemp enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
        if ([dict1 objectForKey:key]) {
            if ([obj isKindOfClass:[NSDictionary class]]) {
                NSDictionary * newVal = [[dict1 objectForKey: key] dictionaryByMergingWith: (NSDictionary *) obj];
                [result setObject: newVal forKey: key];
            } else {
                [result setObject: obj forKey: key];
            }
        }
        else if([dict2 objectForKey:key])
        {
            if ([obj isKindOfClass:[NSDictionary class]]) {
                NSDictionary * newVal = [[dict2 objectForKey: key] dictionaryByMergingWith: (NSDictionary *) obj];
                [result setObject: newVal forKey: key];
            } else {
                [result setObject: obj forKey: key];
            }
        }
    }];
    return (NSDictionary *) [result mutableCopy];

}
/**
 *  @brief  并入一个NSDictionary
 *
 *  @param dict NSDictionary
 *
 *  @return 增加后的NSDictionary
 */
- (NSDictionary *)dictionaryByMergingWith:(NSDictionary *)dict {
    return [[self class] dictionaryByMerging:self with: dict];
}
@end