text:
//=================================================================================================
// Copyright (c) 2012-2016, Institute of Flight Systems and Automatic Control,
// Technische Universität Darmstadt.
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of hector_quadrotor nor the names of its contributors
//       may be used to endorse or promote products derived from this software
//       without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//=================================================================================================

#include <hector_quadrotor_controller_gazebo/quadrotor_hardware_gazebo.h>

#include <geometry_msgs/WrenchStamped.h>
#include "tf/transform_datatypes.h"
#include "tf/LinearMath/Transform.h"
#include "tf/tf.h"

namespace hector_quadrotor_controller_gazebo
{

QuadrotorHardwareSim::QuadrotorHardwareSim()
{
  this->registerInterface(&interface_);
  interface_.registerAccel(&acceleration_);
  interface_.registerPose(&pose_);
  interface_.registerMotorStatus(&motor_status_);
  interface_.registerSensorImu(&imu_);
  interface_.registerTwist(&twist_);

  wrench_output_ = interface_.addInput<WrenchCommandHandle>("wrench");
  motor_output_ = interface_.addInput<MotorCommandHandle>("motor");
}

QuadrotorHardwareSim::~QuadrotorHardwareSim()
{

}

bool QuadrotorHardwareSim::initSim(
    const std::string &robot_namespace,
    ros::NodeHandle model_nh,
    gazebo::physics::ModelPtr parent_model,
    const urdf::Model *const urdf_model,
    std::vector<transmission_interface::TransmissionInfo> transmissions)
{
  // store parent model pointer
  model_ = parent_model;
  link_ = model_->GetLink();
  physics_ = model_->GetWorld()->GetPhysicsEngine();

  /*-------------------------------------------------------
  Start Hack - Janindu
  */

  linkMotor1_ = model_->GetLink("motor1");
  linkMotor2_ = model_->GetLink("motor2");
  linkMotor3_ = model_->GetLink("motor3");
  linkMotor4_ = model_->GetLink("motor4");

  std::cout << "Link vector size: " << linkList_.size() << std::endl;
  for (int i=0; i<linkList_.size(); i++) {
    std::cout << linkList_[i]->GetName() << " " << "" << std::endl;
  }

  std::cout << "------------\n\n----------------" << std::endl;
  std::cout <<linkMotor2_->GetName() << std::endl;
  std::cout << "------------\n\n----------------" << std::endl;

  motor1Sub = model_nh.subscribe("/wrench/pseudomotor1", 10, &QuadrotorHardwareSim::motor1Cb, this);
  motor2Sub = model_nh.subscribe("/wrench/pseudomotor2", 10, &QuadrotorHardwareSim::motor2Cb, this);
  motor3Sub = model_nh.subscribe("/wrench/pseudomotor3", 10, &QuadrotorHardwareSim::motor3Cb, this);
  motor4Sub = model_nh.subscribe("/wrench/pseudomotor4", 10, &QuadrotorHardwareSim::motor4Cb, this);
  motorAllSub = model_nh.subscribe("/wrench/pseudomotorsAll", 10, &QuadrotorHardwareSim::allMotorsCb, this);

  /*-------------------------------------------------------
  End Hack - Janindu
  */

  model_nh.param<std::string>("world_frame", world_frame_, "world");
  model_nh.param<std::string>("base_link_frame", base_link_frame_, "base_link");

  // subscribe state
  std::string state_topic;
  model_nh.getParam("state_topic", state_topic);
  if (!state_topic.empty())
  {
    odom_sub_helper_ = boost::make_shared<OdomSubscriberHelper>(model_nh, state_topic, boost::ref(pose_),
                                                                boost::ref(twist_), boost::ref(acceleration_),
                                                                boost::ref(header_));
    gzlog << "[hector_quadrotor_controller_gazebo] Using topic '" << state_topic << "' as state input for control" <<
    std::endl;
  }
  else
  {
    gzlog << "[hector_quadrotor_controller_gazebo] Using ground truth from Gazebo as state input for control" <<
    std::endl;
  }

  // subscribe imu
  std::string imu_topic;
  model_nh.getParam("imu_topic", imu_topic);
  if (!imu_topic.empty())
  {
    imu_sub_helper_ = boost::make_shared<ImuSubscriberHelper>(model_nh, imu_topic, boost::ref(imu_));
    gzlog << "[hector_quadrotor_controller_gazebo] Using topic '" << imu_topic << "' as imu input for control" <<
    std::endl;
  }
  else
  {
    gzlog << "[hector_quadrotor_controller_gazebo] Using ground truth from Gazebo as imu input for control" <<
    std::endl;
  }

  motor_status_.on = true;
  motor_status_.header.frame_id = base_link_frame_;

  enable_motors_server_ = model_nh.advertiseService("enable_motors", &QuadrotorHardwareSim::enableMotorsCallback, this);

  wrench_limiter_.init(model_nh, "wrench_limits");

  wrench_command_publisher_ = model_nh.advertise<geometry_msgs::WrenchStamped>("command/wrench", 1);
  motor_command_publisher_ = model_nh.advertise<geometry_msgs::WrenchStamped>("command/motor", 1);

  return true;
}

void QuadrotorHardwareSim::readSim(ros::Time time, ros::Duration period)
{
  // read state from Gazebo
  const double acceleration_time_constant = 0.1;
  gz_acceleration_ = ((link_->GetWorldLinearVel() - gz_velocity_) + acceleration_time_constant * gz_acceleration_) /
                     (period.toSec() + acceleration_time_constant);
  gz_angular_acceleration_ =
      ((link_->GetWorldLinearVel() - gz_angular_velocity_) + acceleration_time_constant * gz_angular_acceleration_) /
      (period.toSec() + acceleration_time_constant);

  gz_pose_ = link_->GetWorldPose();
  gz_velocity_ = link_->GetWorldLinearVel();
  gz_angular_velocity_ = link_->GetWorldAngularVel();

  // Use when Gazebo patches accel = 0 bug
//    gz_acceleration_ = link_->GetWorldLinearAccel();
//    gz_angular_acceleration_ = link_->GetWorldAngularAccel();

  if (!odom_sub_helper_)
  {
    header_.frame_id = world_frame_;
    header_.stamp = time;
    pose_.position.x = gz_pose_.pos.x;
    pose_.position.y = gz_pose_.pos.y;
    pose_.position.z = gz_pose_.pos.z;
    pose_.orientation.w = gz_pose_.rot.w;
    pose_.orientation.x = gz_pose_.rot.x;
    pose_.orientation.y = gz_pose_.rot.y;
    pose_.orientation.z = gz_pose_.rot.z;
    twist_.linear.x = gz_velocity_.x;
    twist_.linear.y = gz_velocity_.y;
    twist_.linear.z = gz_velocity_.z;
    twist_.angular.x = gz_angular_velocity_.x;
    twist_.angular.y = gz_angular_velocity_.y;
    twist_.angular.z = gz_angular_velocity_.z;
    acceleration_.linear.x = gz_acceleration_.x;
    acceleration_.linear.y = gz_acceleration_.y;
    acceleration_.linear.z = gz_acceleration_.z;
    acceleration_.angular.x = gz_angular_acceleration_.x;
    acceleration_.angular.y = gz_angular_acceleration_.y;
    acceleration_.angular.z = gz_angular_acceleration_.z;
  }

  if (!imu_sub_helper_)
  {
    imu_.orientation.w = gz_pose_.rot.w;
    imu_.orientation.x = gz_pose_.rot.x;
    imu_.orientation.y = gz_pose_.rot.y;
    imu_.orientation.z = gz_pose_.rot.z;

    gazebo::math::Vector3 gz_angular_velocity_body = gz_pose_.rot.RotateVectorReverse(gz_angular_velocity_);
    imu_.angular_velocity.x = gz_angular_velocity_body.x;
    imu_.angular_velocity.y = gz_angular_velocity_body.y;
    imu_.angular_velocity.z = gz_angular_velocity_body.z;

    gazebo::math::Vector3 gz_linear_acceleration_body = gz_pose_.rot.RotateVectorReverse(
        gz_acceleration_ - physics_->GetGravity());
    imu_.linear_acceleration.x = gz_linear_acceleration_body.x;
    imu_.linear_acceleration.y = gz_linear_acceleration_body.y;
    imu_.linear_acceleration.z = gz_linear_acceleration_body.z;
  }
}

void QuadrotorHardwareSim::writeSim(ros::Time time, ros::Duration period)
{
  bool result_written = false;

  if (motor_output_->connected() && motor_output_->enabled()) {
    motor_command_publisher_.publish(motor_output_->getCommand());
    result_written = true;
  }

  if (wrench_output_->connected() && wrench_output_->enabled()) {
    geometry_msgs::WrenchStamped wrench;
    wrench.header.stamp = time;
    wrench.header.frame_id = base_link_frame_;

    if (motor_status_.on && motor_status_.running) {
      wrench.wrench = wrench_limiter_(wrench_output_->getCommand());

      if (!result_written) {
        gazebo::math::Vector3 force(wrench.wrench.force.x, wrench.wrench.force.y, wrench.wrench.force.z);
        gazebo::math::Vector3 torque(wrench.wrench.torque.x, wrench.wrench.torque.y, wrench.wrench.torque.z);
        // link_->AddRelativeForce(force);
        // link_->AddRelativeTorque(torque - link_->GetInertial()->GetCoG().Cross(force));
        linkMotor2_->AddRelativeForce(force);
        linkMotor2_->AddRelativeTorque(torque - link_->GetInertial()->GetCoG().Cross(force));
      }

    } else {
      wrench.wrench = geometry_msgs::Wrench();
    }

    wrench_command_publisher_.publish(wrench);
  }
}

bool QuadrotorHardwareSim::enableMotorsCallback(hector_uav_msgs::EnableMotors::Request &req, hector_uav_msgs::EnableMotors::Response &res)
{
  res.success = enableMotors(req.enable);
  return true;
}

bool QuadrotorHardwareSim::enableMotors(bool enable)
{
  motor_status_.running = enable;
  return true;
}

void QuadrotorHardwareSim::motor1Cb(geometry_msgs::Wrench::ConstPtr msg) {
  this->applyWrench(linkMotor1_, msg);
}
void QuadrotorHardwareSim::motor2Cb(geometry_msgs::Wrench::ConstPtr msg) {
  this->applyWrench(linkMotor2_, msg);
}

void QuadrotorHardwareSim::motor3Cb(geometry_msgs::Wrench::ConstPtr msg) {
  this->applyWrench(linkMotor3_, msg);
}

void QuadrotorHardwareSim::motor4Cb(geometry_msgs::Wrench::ConstPtr msg) {
  this->applyWrench(linkMotor4_, msg);
}

void QuadrotorHardwareSim::allMotorsCb(geometry_msgs::Wrench::ConstPtr wrench) {
  gazebo::math::Vector3 force(wrench->force.x, wrench->force.y,wrench->force.z);
  gazebo::math::Vector3 torque(wrench->torque.x, wrench->torque.y, wrench->torque.z);

  tf::Quaternion q;
  tf::quaternionMsgToTF(pose_.orientation, q);
  double r,p,y;
  tf::Matrix3x3 rot(q);
  rot.getRPY(r,p,y);
  float k1 = 10;
  float k2 = 1.0;
  float f3 = k1*(1.309 - p) + 1;
  float t3 = k2*(-y);

  gazebo::math::Vector3 forceF3(wrench->force.x, wrench->force.y,f3);
  gazebo::math::Vector3 torqueF3(wrench->torque.x, wrench->torque.y, t3);

  linkMotor1_->AddRelativeForce(force);
  linkMotor2_->AddRelativeForce(force);
  // linkMotor3_->AddRelativeForce(force);
  linkMotor4_->AddRelativeForce(force);
  // link_->AddRelativeForce(force);
  linkMotor3_->AddRelativeForce(forceF3);
  linkMotor3_->AddRelativeTorque(torqueF3);

  std::cout << "pitch: " << p << " f3: " << f3 ;
  std::cout << ", velocity x,y,z: " << twist_.linear.x << "," << twist_.linear.y << "," << twist_.linear.z << std::endl;

}

void QuadrotorHardwareSim::applyWrench(gazebo::physics::LinkPtr motorLink, geometry_msgs::Wrench::ConstPtr wrench) {
  gazebo::math::Vector3 force(wrench->force.x, wrench->force.y,wrench->force.z);
  gazebo::math::Vector3 torque(wrench->torque.x, wrench->torque.y, wrench->torque.z);
  std::cout << pose_.position.x << " " << pose_.position.y << " " << pose_.position.z << std::endl;
  motorLink->AddRelativeForce(force);
}

} // namespace hector_quadrotor_controller_gazebo

#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(hector_quadrotor_controller_gazebo::QuadrotorHardwareSim, gazebo_ros_control::RobotHWSim)


text:
<meta http-equiv="refresh" content="0; URL=disjoint_sets.html">

Automatic redirection failed, please go to
disjoint_sets.html.

© Copyright Beman Dawes, 2001

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy
at www.boost.org/LICENSE_1_0.txt)

redpajama_set_name: RedPajamaGithub


text:
require "chef/resource/apt_package"
require "chef/resource/apt_repository"
require "chef/resource/apt_update"
require "chef/resource/bash"
require "chef/resource/batch"
require "chef/resource/breakpoint"
require "chef/resource/cookbook_file"
require "chef/resource/chef_gem"
require "chef/resource/chocolatey_package"
require "chef/resource/cron"
require "chef/resource/csh"
require "chef/resource/deploy"
require "chef/resource/deploy_revision"
require "chef/resource/directory"
require "chef/resource/dpkg_package"
require "chef/resource/dsc_script"
require "chef/resource/dsc_resource"
require "chef/resource/easy_install_package"
require "chef/resource/env"
require "chef/resource/erl_call"
require "chef/resource/execute"
require "chef/resource/file"
require "chef/resource/freebsd_package"
require "chef/resource/ips_package"
require "chef/resource/gem_package"
require "chef/resource/git"
require "chef/resource/group"
require "chef/resource/http_request"
require "chef/resource/homebrew_package"
require "chef/resource/ifconfig"
require "chef/resource/ksh"
require "chef/resource/launchd"
require "chef/resource/link"
require "chef/resource/log"
require "chef/resource/macports_package"
require "chef/resource/mdadm"
require "chef/resource/mount"
require "chef/resource/ohai"
require "chef/resource/openbsd_package"
require "chef/resource/package"
require "chef/resource/pacman_package"
require "chef/resource/paludis_package"
require "chef/resource/perl"
require "chef/resource/portage_package"
require "chef/resource/powershell_script"
require "chef/resource/osx_profile"
require "chef/resource/python"
require "chef/resource/reboot"
require "chef/resource/registry_key"
require "chef/resource/remote_directory"
require "chef/resource/remote_file"
require "chef/resource/rpm_package"
require "chef/resource/solaris_package"
require "chef/resource/route"
require "chef/resource/ruby"
require "chef/resource/ruby_block"
require "chef/resource/scm"
require "chef/resource/script"
require "chef/resource/service"
require "chef/resource/systemd_unit"
require "chef/resource/windows_service"
require "chef/resource/subversion"
require "chef/resource/smartos_package"
require "chef/resource/template"
require "chef/resource/timestamped_deploy"
require "chef/resource/user"
require "chef/resource/user/aix_user"
require "chef/resource/user/dscl_user"
require "chef/resource/user/linux_user"
require "chef/resource/user/pw_user"
require "chef/resource/user/solaris_user"
require "chef/resource/user/windows_user"
require "chef/resource/whyrun_safe_ruby_block"
require "chef/resource/windows_package"
require "chef/resource/yum_package"
require "chef/resource/yum_repository"
require "chef/resource/lwrp_base"
require "chef/resource/bff_package"
require "chef/resource/zypper_package"
require "chef/resource/cab_package"
require "chef/resource/powershell_package"
require "chef/resource/msu_package"


text:
namespace content {

inline gfx::Point PP_ToGfxPoint(const PP_Point& p) {
  return gfx::Point(p.x, p.y);
}

inline PP_Point PP_FromGfxPoint(const gfx::Point& p) {
  return PP_MakePoint(p.x(), p.y());
}

inline gfx::Rect PP_ToGfxRect(const PP_Rect& r) {
  return gfx::Rect(r.point.x, r.point.y, r.size.width, r.size.height);
}

inline gfx::RectF PP_ToGfxRectF(const PP_FloatRect& r) {
  return gfx::RectF(r.point.x, r.point.y, r.size.width, r.size.height);
}

inline PP_Rect PP_FromGfxRect(const gfx::Rect& r) {
  return PP_MakeRectFromXYWH(r.x(), r.y(), r.width(), r.height());
}

inline gfx::Size PP_ToGfxSize(const PP_Size& s) {
  return gfx::Size(s.width, s.height);
}

inline PP_Size PP_FromGfxSize(const gfx::Size& s) {
  return PP_MakeSize(s.width(), s.height());
}

}  // namespace content

#endif  // CONTENT_RENDERER_PEPPER_GFX_CONVERSION_H_


text:
EXTERN_C_BEGIN

extern const char * lookup_wchan(unsigned KLONG address, unsigned pid);
extern int   open_psdb(const char *__restrict override);
extern int   open_psdb_message(const char *__restrict override, message_fn message);

EXTERN_C_END

#endif


text:
/**
 *
 * @file sg_wc_tx__rename.c
 *
 * @details Handle a plain RENAME (without MOVE).
 *
 */

//////////////////////////////////////////////////////////////////

#include <sg.h>

#include "sg_wc__public_typedefs.h"
#include "sg_wc__public_prototypes.h"
#include "sg_wc__private.h"

//////////////////////////////////////////////////////////////////

/**
 * The classic interface for a RENAME.
 *
 * The inputs are:
 * [] the repo-path of the item to be renamed.
 * [] the ENTRYNAME of the new name.
 *
 * This API corresponds to the usual command line usage
 * where you don't repeat the path of the destination,
 * just the entryname.  It is a simple RENAME not a
 * MOVE+RENAME.  This is an arbitrary choice because
 * the underlying layers allow both to be done in one
 * step.  This division is primarily for user convenience.
 *
 * We optionally allow/disallow after-the-fact renames.
 *
 */
void SG_wc_tx__rename(SG_context * pCtx,
					  SG_wc_tx * pWcTx,
					  const char * pszInput_Src,
					  const char * pszNewEntryname,
					  SG_bool bNoAllowAfterTheFact)
{
	SG_string * pStringRepoPath_Src = NULL;
	sg_wc_liveview_item * pLVI_Src;			// we do not own this
	sg_wc_liveview_item * pLVI_DestDir;		// we do not own this
	char chDomain_Src;
	SG_bool bKnown_Src;
	SG_bool bKnown_DestDir;
	SG_wc_status_flags xu_mask = SG_WC_STATUS_FLAGS__ZERO;

	SG_NULLARGCHECK_RETURN( pWcTx );
	SG_NONEMPTYCHECK_RETURN( pszNewEntryname );

	SG_ERR_CHECK(  sg_wc_db__path__anything_to_repopath(pCtx, pWcTx->pDb, pszInput_Src,
														SG_WC_DB__PATH__IMPORT_FLAGS__TREAT_NULL_AS_ERROR,
														&pStringRepoPath_Src, &chDomain_Src)  );

#if TRACE_WC_TX_MOVE_RENAME
	SG_ERR_IGNORE(  SG_console(pCtx, SG_CS_STDERR,
							   "SG_wc_tx__rename: source '%s' normalized to [domain %c] '%s'\n",
							   pszInput_Src, chDomain_Src, SG_string__sz(pStringRepoPath_Src))  );
	SG_ERR_IGNORE(  SG_console(pCtx, SG_CS_STDERR,
							   "SG_wc_tx__rename: new name '%s'\n",
							   pszNewEntryname)  );
#endif

	if ((strchr(pszNewEntryname, '/')  != NULL)
		|| (strchr(pszNewEntryname, '\\')  != NULL)
		|| (pszNewEntryname[0] == '@'))
		SG_ERR_THROW2(  SG_ERR_INVALIDARG,
						(pCtx,
						 "The destination of a RENAME must be a simple entryname, not a pathname: '%s'",
						 pszNewEntryname)  );

	// do minimal validation here (just enough to print
	// better error messages while we still have access
	// to the user-input and the normalized domain-aware
	// repo-paths.  save the serious validation for the
	// "move-rename" code.

	SG_ERR_CHECK(  sg_wc_tx__liveview__fetch_item__domain(pCtx, pWcTx, pStringRepoPath_Src,
														  &bKnown_Src, &pLVI_Src)  );
	if (!bKnown_Src || (SG_WC_PRESCAN_FLAGS__IS_UNCONTROLLED_UNQUALIFIED(pLVI_Src->scan_flags_Live)))
		SG_ERR_THROW2(  SG_ERR_ITEM_NOT_UNDER_VERSION_CONTROL,
						(pCtx, "Source '%s' (%s)",
						 pszInput_Src, SG_string__sz(pStringRepoPath_Src))  );
	if (pLVI_Src == pWcTx->pLiveViewItem_Root)
		SG_ERR_THROW2(  SG_ERR_INVALIDARG,
						(pCtx, "Cannot MOVE/RENAME the root directory '%s' (%s)",
						 pszInput_Src, SG_string__sz(pStringRepoPath_Src))  );

	// since the source input/repo-path
	// could be a GID- or baseline- domain string, we can't
	// use the actual text in it.  we have to use the LVI.
	//
	// get LVI of the parent directory of the source item.

	SG_ERR_CHECK(  sg_wc_tx__liveview__fetch_random_item(pCtx, pWcTx,
														 pLVI_Src->pLiveViewDir->uiAliasGidDir,
														 &bKnown_DestDir, &pLVI_DestDir)  );
	SG_ASSERT_RELEASE_FAIL( (bKnown_DestDir) );

	if (pLVI_Src->pvhIssue && (pLVI_Src->statusFlags_x_xr_xu & SG_WC_STATUS_FLAGS__X__UNRESOLVED))
	{
		xu_mask |= (pLVI_Src->statusFlags_x_xr_xu & SG_WC_STATUS_FLAGS__XU__EXISTENCE);
		xu_mask |= (pLVI_Src->statusFlags_x_xr_xu & SG_WC_STATUS_FLAGS__XU__NAME);
	}

	SG_ERR_CHECK(  sg_wc_tx__rp__move_rename__lvi_lvi_sz(pCtx, pWcTx,
														 pLVI_Src,
														 pLVI_DestDir,
														 pszNewEntryname,
														 bNoAllowAfterTheFact,
														 xu_mask)  );

fail:
	SG_STRING_NULLFREE(pCtx, pStringRepoPath_Src);
}


text:
require 'spec_helper'

describe GraphQL::Schema::TypeReducer do
  it 'finds types from a single type and its fields' do
    reducer = GraphQL::Schema::TypeReducer.new(CheeseType, {})
    expected = {
      "Cheese" => CheeseType,
      "Int" => GraphQL::INT_TYPE,
      "String" => GraphQL::STRING_TYPE,
      "DairyAnimal" => DairyAnimalEnum,
      "Float" => GraphQL::FLOAT_TYPE,
      "Edible" => EdibleInterface,
      "Milk" => MilkType,
      "ID" => GraphQL::ID_TYPE,
      "AnimalProduct" => AnimalProductInterface,
    }
    assert_equal(expected.keys, reducer.result.keys)
    assert_equal(expected, reducer.result)
  end

  it 'finds type from arguments' do
    reducer = GraphQL::Schema::TypeReducer.new(QueryType, {})
    assert_equal(DairyProductInputType, reducer.result["DairyProductInput"])
  end

  describe 'when a type is invalid' do
    let(:invalid_type) {
      GraphQL::ObjectType.define do
        name "InvalidType"
        field :someField
      end
    }

    it 'raises an InvalidTypeError' do
      reducer = GraphQL::Schema::TypeReducer.new(invalid_type, {})
      assert_raises(GraphQL::Schema::InvalidTypeError) { reducer.result }
    end
  end
end


text:
``` diff
 namespace System.Threading.Tasks {
     public class Task : IAsyncResult, IDisposable {
+        public bool IsCompletedSuccessfully { get; }
     }
+    [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size=1)]
+    public struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> {
+        public ValueTask(Task<TResult> task);
+        public ValueTask(TResult result);
+        public bool IsCanceled { get; }
+        public bool IsCompleted { get; }
+        public bool IsCompletedSuccessfully { get; }
+        public bool IsFaulted { get; }
+        public TResult Result { get; }
+        public Task<TResult> AsTask();
+        public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext);
+        public static AsyncValueTaskMethodBuilder<TResult> CreateAsyncMethodBuilder();
+        public override bool Equals(object obj);
+        public bool Equals(ValueTask<TResult> other);
+        public ValueTaskAwaiter<TResult> GetAwaiter();
+        public override int GetHashCode();
+        public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right);
+        public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right);
+        public override string ToString();
+    }
 }
```


text:
<?xml version="1.0" encoding="utf-8" ?>
<language xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
    xs:noNamespaceSchemaLocation="http://www.csphere.eu/xml/schemas/language.xsd">
    <translation type="plugin" name="cache" version_min="0.1" short="de" />
    <vendor>csphere</vendor>
    <version>0.1</version>
    <published>2012-03-01</published>
    <copyright>cSphere Team</copyright>
    <license>Simplified BSD License</license>
    <name>Cache</name>
    <info>Speichert vorbereitete Daten zwischen</info>
    <engine name="csphere" version_min="2013.0" />
    <icon type="famfamfam">de</icon>
    <authors>
        <current>cSphere Team</current>
        <past>cSphere Team</past>
    </authors>
    <contact>
        <email adress="contact@csphere.eu" />
        <web url="http://www.csphere.eu" />
    </contact>
    <definitions>
        <define name="cache">Cache</define>
        <define name="clear">Cache leeren</define>
        <define name="clear_ok">Cache mit Erfolg geleert</define>
        <define name="key">Schlüssel</define>
        <define name="keys">Keys</define>
        <define name="no_entry">Kein Eintrag gefunden</define>
        <define name="op_enable">Aktiv</define>
        <define name="op_enable_cli">Aktiv beim CLI Modus</define>
        <define name="op_load_com">Lade Kommentarblöcke</define>
        <define name="op_loaded">OPcache PHP-Erweiterung geladen</define>
        <define name="op_memory_con">Zugeteilter Speicher in Megabytes</define>
        <define name="op_save_com">Speichere Kommentarblöcke</define>
        <define name="op_revalid_freq">Sekunden zwischen diesen Prüfungen</define>
        <define name="op_valid_time">Prüfe Dateien auf Änderungen</define>
        <define name="opcache">OPcache</define>
    </definitions>
</language>


text:
<!--
 ~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ WSO2 Inc. licenses this file to you 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.
 -->

<api xmlns="http://ws.apache.org/ns/synapse" name="MockResponseTestAPI" context="/mockresponse">
    <resource methods="POST">
        <inSequence>
            <payloadFactory media-type="xml">
                <format>
                    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
                        <soapenv:Body/>
                    </soapenv:Envelope>
                </format>
                <args/>
            </payloadFactory>
            <property name="messageType" value="text/xml" scope="axis2"/>
            <property name="DISABLE_CHUNKING" value="true" scope="axis2"/>
            <property name="HTTP_SC" value="200" scope="axis2"/>
            <property name="Content-Length" value="0" scope="transport"/>
            <respond/>
        </inSequence>
    </resource>
</api>


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Executes a low-down and dirty SSH command, not going through the module subsystem. This is useful and should only be done in a few cases. A common case is installing C(python) on a system without python installed by default. Another is speaking to any devices such as routers that do not have any Python installed. In any other case, using the M(shell) or M(command) module is much more appropriate. Arguments given to C(raw) are run directly through the configured remote shell. Standard output, error output and return code are returned when available. There is no change handler support for this module.
      # This module does not require python on the remote system, much like the M(script) module.
      # This module is also supported for Windows targets.
      class Raw < Base
        # @return [Object] the raw module takes a free form command to run. There is no parameter actually named 'free form'; see the examples!
        attribute :free_form
        validates :free_form, presence: true

        # @return [String, nil] change the shell used to execute the command. Should be an absolute path to the executable.,when using privilege escalation (C(become)), a default shell will be assigned if one is not provided as privilege escalation requires a shell.
        attribute :executable
        validates :executable, type: String
      end
    end
  end
end


text:
using System;
using Microsoft.Practices.Unity;

namespace KickStart.Unity
{
    public class UnityBuilder : IUnityBuilder
    {
        private readonly UnityOptions _options;

        public UnityBuilder(UnityOptions options)
        {
            _options = options;
        }

        public IUnityBuilder Container(Action<IUnityContainer> initializer)
        {
            _options.InitializeContainer = initializer;
            return this;
        }
    }
}


text:
<template name="Aukahi">

The Aukahi: Tahitian V1 design with Hawaiian attitude.

</template>


text:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_mode_edit_black"
    android:tint="@color/colorTextPrimary"/>


text:
<?php

use yii\db\Migration;

class m170322_183916_some_fixs extends Migration
{
    public function up()
    {
        $this->addColumn('events', 'created_by', $this->integer(11));
        $this->addColumn('services', 'status', $this->integer(1) . " default 1");
    }

    public function down()
    {
        echo "m170322_183916_some_fixs cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
namespace Nop.Core.Plugins
{
    public abstract class BasePlugin : IPlugin
    {
        protected BasePlugin()
        {
        }

        /// <summary>
        /// Gets or sets the plugin descriptor
        /// </summary>
        public virtual PluginDescriptor PluginDescriptor { get; set; }

        /// <summary>
        /// Install plugin
        /// </summary>
        public virtual void Install()
        {
            PluginManager.MarkPluginAsInstalled(this.PluginDescriptor.SystemName);
        }

        /// <summary>
        /// Uninstall plugin
        /// </summary>
        public virtual void Uninstall()
        {
            PluginManager.MarkPluginAsUninstalled(this.PluginDescriptor.SystemName);
        }

    }
}


text:
$TenantId = "YOUR_TENANT_ID"
$ApplicationId = "YOUR_APPLICATION_ID"
$ApplicationPassword = "YOUR_APPLICATION_PASSWORD"
$AzureSubscriptionId = "YOU_SUBSCRIPTION_ID"
$secpasswd = ConvertTo-SecureString $ApplicationPassword -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($ApplicationId, $secpasswd)
Login-AzureRmAccount -ServicePrincipal -Tenant $TenantId -Credential $mycreds
Set-AzureRmContext -SubscriptionID $AzureSubscriptionId -TenantId $TenantId


text:
var toolActInd = Ti.UI.createActivityIndicator();
Ti.UI.currentWindow.setRightNavButton(toolActInd);
toolActInd.show();

// create table view data object
var data = [];
var newXMLlink = "";

var xhr = Ti.Network.createHTTPClient();
xhr.open("GET","http://journeyon.net/media/api/churchapp/all-series.xml");
xhr.onload = function() {
	try {
		Ti.API.info('[sermons.js] got rss feed!');
		var doc = this.responseXML.documentElement;
		var items = doc.getElementsByTagName("row");
		var x = 0;
		Ti.API.info('[sermons.js] number of items = \'' + items.length + '\'');
		for (var c = 0; c < items.length; c++) {
			// Grab data from XML
			var item = items.item(c);
			var media = item.getElementsByTagName("icon").item(0).text;
			var title = item.getElementsByTagName("name").item(0).text;
			title = title.replace(/'/g, "'").replace("/&/g", "&");
			Ti.API.info('[sermons.js]   Processing #' + c + " - " + title);

			// Set up display of row
			var row = Ti.UI.createTableViewRow({height:60});
			var label = Ti.UI.createLabel( {
				text:title,
				left:72,
				top:5,
				font:{fontWeight:'bold',fontSize:18},
				bottom:5,
				right:5
			});
			row.add(label);
			var img = Ti.UI.createImageView({
				url:media,
				left:5,
				height:60,
				width:60
			});
			row.add(img);
			row.url = item.getElementsByTagName("link").item(0).text;
			row.titleStr = title;
			data[x++] = row;
		}

		// Create and add the tableview to the window
		var tableview = Ti.UI.createTableView({data:data});
		Ti.UI.currentWindow.add(tableview);

		toolActInd.hide();
		Ti.UI.currentWindow.setRightNavButton(null);

		// Add event listener for selection
		tableview.addEventListener('click',function(e) {
			if (e.rowData.url) {
				var win = Ti.UI.createWindow({
					barColor:'#111',
					title:e.rowData.titleStr,
					url:'../sermonviews/series.js'
				});
				newXMLlink = e.rowData.url;
				win.newXMLlink = newXMLlink;

				Ti.UI.currentTab.open(win, {animated:true});
			}
		});
	} catch(E) {
		alert(E);
	}
};
xhr.send();


text:
package routing

import (
	"encoding/json"
	"net/http"

	"github.com/matrix-org/dendrite/clientapi/httputil"
	"github.com/matrix-org/dendrite/clientapi/jsonerror"
	"github.com/matrix-org/dendrite/syncapi/storage"
	"github.com/matrix-org/dendrite/syncapi/types"
	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/util"
	log "github.com/sirupsen/logrus"
)

type stateEventInStateResp struct {
	gomatrixserverlib.ClientEvent
	PrevContent   json.RawMessage `json:"prev_content,omitempty"`
	ReplacesState string          `json:"replaces_state,omitempty"`
}

// OnIncomingStateRequest is called when a client makes a /rooms/{roomID}/state
// request. It will fetch all the state events from the specified room and will
// append the necessary keys to them if applicable before returning them.
// Returns an error if something went wrong in the process.
// TODO: Check if the user is in the room. If not, check if the room's history
// is publicly visible. Current behaviour is returning an empty array if the
// user cannot see the room's history.
func OnIncomingStateRequest(req *http.Request, db *storage.SyncServerDatabase, roomID string) util.JSONResponse {
	// TODO(#287): Auth request and handle the case where the user has left (where
	// we should return the state at the poin they left)

	stateEvents, err := db.GetStateEventsForRoom(req.Context(), roomID)
	if err != nil {
		return httputil.LogThenError(req, err)
	}

	resp := []stateEventInStateResp{}
	// Fill the prev_content and replaces_state keys if necessary
	for _, event := range stateEvents {
		stateEvent := stateEventInStateResp{
			ClientEvent: gomatrixserverlib.ToClientEvent(event, gomatrixserverlib.FormatAll),
		}
		var prevEventRef types.PrevEventRef
		if len(event.Unsigned()) > 0 {
			if err := json.Unmarshal(event.Unsigned(), &prevEventRef); err != nil {
				return httputil.LogThenError(req, err)
			}
			// Fills the previous state event ID if the state event replaces another
			// state event
			if len(prevEventRef.ReplacesState) > 0 {
				stateEvent.ReplacesState = prevEventRef.ReplacesState
			}
			// Fill the previous event if the state event references a previous event
			if prevEventRef.PrevContent != nil {
				stateEvent.PrevContent = prevEventRef.PrevContent
			}
		}

		resp = append(resp, stateEvent)
	}

	return util.JSONResponse{
		Code: http.StatusOK,
		JSON: resp,
	}
}

// OnIncomingStateTypeRequest is called when a client makes a
// /rooms/{roomID}/state/{type}/{statekey} request. It will look in current
// state to see if there is an event with that type and state key, if there
// is then (by default) we return the content, otherwise a 404.
func OnIncomingStateTypeRequest(req *http.Request, db *storage.SyncServerDatabase, roomID string, evType, stateKey string) util.JSONResponse {
	// TODO(#287): Auth request and handle the case where the user has left (where
	// we should return the state at the poin they left)

	logger := util.GetLogger(req.Context())
	logger.WithFields(log.Fields{
		"roomID":   roomID,
		"evType":   evType,
		"stateKey": stateKey,
	}).Info("Fetching state")

	event, err := db.GetStateEvent(req.Context(), roomID, evType, stateKey)
	if err != nil {
		return httputil.LogThenError(req, err)
	}

	if event == nil {
		return util.JSONResponse{
			Code: http.StatusNotFound,
			JSON: jsonerror.NotFound("cannot find state"),
		}
	}

	stateEvent := stateEventInStateResp{
		ClientEvent: gomatrixserverlib.ToClientEvent(*event, gomatrixserverlib.FormatAll),
	}

	return util.JSONResponse{
		Code: http.StatusOK,
		JSON: stateEvent.Content,
	}
}