<commit_before>
#include "simulation.h"

SimulatedRobotArm::SimulatedRobotArm() {

    arm_data.state = UNKNOWN;

    arm_info.version = 0.1;
    arm_info.name = string("Simulated Robot Arm");

    joint_info.push_back(createJointInfo(0, ROTATION, 0, 90, 65, 0, -180, 180));
    joint_data.push_back(createJointData(0, 0));

    joint_info.push_back(createJointInfo(1, ROTATION, 120, 0, 0, 90, 0, 170));
    joint_data.push_back(createJointData(1, 120));

    joint_info.push_back(createJointInfo(2, ROTATION, -90, 0, 0, 132, -110, 110));
    joint_data.push_back(createJointData(2, -90));

    joint_info.push_back(createJointInfo(3, ROTATION, 0, 0, 0, 70, -70, 70));
    joint_data.push_back(createJointData(3, -70));

    joint_info.push_back(createJointInfo(4, GRIPPER, 0, -90, 0, 60, 0, 1));
    joint_data.push_back(createJointData(4, 0));

    arm_info.joints = joint_info.size();
}

SimulatedRobotArm::~SimulatedRobotArm() {

}

bool SimulatedRobotArm::isConnected() {

    return arm_data.state == CONNECTED;

}

int SimulatedRobotArm::connect() {

    arm_data.state = CONNECTED;

	return 0;

}

int SimulatedRobotArm::disconnect() {

    arm_data.state = UNKNOWN;

	return 0;

}

#define MOVE_RESOLUTION_GRIP 0.1
#define MOVE_RESOLUTION_TRANSLATION 1
#define MOVE_RESOLUTION_ROTATION 5

int SimulatedRobotArm::poll() {

    for (int i = 0; i < joint_data.size(); i++) {
        float resolution = joint_info[i].type == ROTATION ?
            MOVE_RESOLUTION_ROTATION : (joint_info[i].type == TRANSLATION ? MOVE_RESOLUTION_TRANSLATION : MOVE_RESOLUTION_GRIP);

        if (joint_data[i].position - joint_data[i].position_goal >= resolution / 2)
            joint_data[i].position -= resolution;
        else if (joint_data[i].position - joint_data[i].position_goal < -resolution / 2)
            joint_data[i].position += resolution;
        else
            joint_data[i].position = joint_data[i].position_goal;
    }

    return 0;
}

int SimulatedRobotArm::calibrate(int joint) {
    return 0;
}

int SimulatedRobotArm::startControl() {
    return 0;
}

int SimulatedRobotArm::stopControl() {
	return 0;
}

int SimulatedRobotArm::lock(int joint) {
    return 0;
}

int SimulatedRobotArm::release(int joint) {
	return 0;
}

int SimulatedRobotArm::rest() {
	return 0;
}

int SimulatedRobotArm::size() {

    return joint_data.size();

}

int SimulatedRobotArm::moveTo(int joint, float speed, float position) {

    if (joint < 0 || joint >= joint_data.size())
        return false;

    if (joint_info[joint].position_min > position)
        position = joint_info[joint].position_min;

    if (joint_info[joint].position_max < position)
        position = joint_info[joint].position_max;

    joint_data[joint].position_goal = position;

	return 0;
}

int SimulatedRobotArm::move(int joint, float speed) {

    if (joint < 0 || joint >= joint_data.size())
        return false;

    float position = joint_data[joint].position_goal;

    if (speed < 0)
        position = joint_info[joint].position_min;

    if (speed > 0)
        position = joint_info[joint].position_max;

    joint_data[joint].position_goal = position;

	return 0;
}

int SimulatedRobotArm::getArmInfo(ArmInfo &data) {

    data = arm_info;

    return 0;

}

int SimulatedRobotArm::getArmData(ArmData &data) {

    data = arm_data;

	return 0;
}

int SimulatedRobotArm::getJointInfo(int joint, JointInfo &data) {

    if (joint < 0 || joint >= joint_info.size())
        return -1;

    data = joint_info[joint];

	return 0;
}

int SimulatedRobotArm::getJointData(int joint, JointData &data) {

    if (joint < 0 || joint >= joint_data.size())
        return -1;

    data = joint_data[joint];

	return true;
}

<commit_msg>Fixing simulated arm movement.<commit_after>
#include "simulation.h"

SimulatedRobotArm::SimulatedRobotArm() {

    arm_data.state = UNKNOWN;

    arm_info.version = 0.1;
    arm_info.name = string("Simulated Robot Arm");

    joint_info.push_back(createJointInfo(0, ROTATION, 0, 90, 65, 0, -180, 180));
    joint_data.push_back(createJointData(0, 0));

    joint_info.push_back(createJointInfo(1, ROTATION, 120, 0, 0, 90, 0, 170));
    joint_data.push_back(createJointData(1, 120));

    joint_info.push_back(createJointInfo(2, ROTATION, -90, 0, 0, 132, -110, 110));
    joint_data.push_back(createJointData(2, -90));

    joint_info.push_back(createJointInfo(3, ROTATION, 0, 0, 0, 70, -70, 70));
    joint_data.push_back(createJointData(3, -70));

    joint_info.push_back(createJointInfo(4, GRIPPER, 0, -90, 0, 60, 0, 1));
    joint_data.push_back(createJointData(4, 0));

    arm_info.joints = joint_info.size();
}

SimulatedRobotArm::~SimulatedRobotArm() {

}

bool SimulatedRobotArm::isConnected() {

    return arm_data.state == CONNECTED;

}

int SimulatedRobotArm::connect() {

    arm_data.state = CONNECTED;

	return 0;

}

int SimulatedRobotArm::disconnect() {

    arm_data.state = UNKNOWN;

	return 0;

}

#define MOVE_RESOLUTION_GRIP 0.001
#define MOVE_RESOLUTION_TRANSLATION 1
#define MOVE_RESOLUTION_ROTATION 5

int SimulatedRobotArm::poll() {

    for (int i = 0; i < joint_data.size(); i++) {
        float resolution = joint_info[i].type == ROTATION ?
            MOVE_RESOLUTION_ROTATION : (joint_info[i].type == TRANSLATION ? MOVE_RESOLUTION_TRANSLATION : MOVE_RESOLUTION_GRIP);

        if (joint_data[i].position - joint_data[i].position_goal >= resolution / 2)
            joint_data[i].position -= resolution;
        else if (joint_data[i].position - joint_data[i].position_goal < -resolution / 2)
            joint_data[i].position += resolution;
        else
            joint_data[i].position = joint_data[i].position_goal;

    }

    return 0;
}

int SimulatedRobotArm::calibrate(int joint) {
    return 0;
}

int SimulatedRobotArm::startControl() {
    return 0;
}

int SimulatedRobotArm::stopControl() {
	return 0;
}

int SimulatedRobotArm::lock(int joint) {
    return 0;
}

int SimulatedRobotArm::release(int joint) {
	return 0;
}

int SimulatedRobotArm::rest() {
	return 0;
}

int SimulatedRobotArm::size() {

    return joint_data.size();

}

int SimulatedRobotArm::moveTo(int joint, float speed, float position) {

    if (joint < 0 || joint >= joint_data.size())
        return -1;

    if (joint_info[joint].position_min > position)
        position = joint_info[joint].position_min;

    if (joint_info[joint].position_max < position)
        position = joint_info[joint].position_max;

    joint_data[joint].position_goal = position;

	return 0;
}

int SimulatedRobotArm::move(int joint, float speed) {

    if (joint < 0 || joint >= joint_data.size())
        return -1;

    float position = joint_data[joint].position_goal;

    if (speed < 0)
        position = joint_info[joint].position_min;

    if (speed > 0)
        position = joint_info[joint].position_max;

    joint_data[joint].position_goal = position;

	return 0;
}

int SimulatedRobotArm::getArmInfo(ArmInfo &data) {

    data = arm_info;

    return 0;

}

int SimulatedRobotArm::getArmData(ArmData &data) {

    data = arm_data;

	return 0;
}

int SimulatedRobotArm::getJointInfo(int joint, JointInfo &data) {

    if (joint < 0 || joint >= joint_info.size())
        return -1;

    data = joint_info[joint];

	return 0;
}

int SimulatedRobotArm::getJointData(int joint, JointData &data) {

    if (joint < 0 || joint >= joint_data.size())
        return -1;

    data = joint_data[joint];

    data.dh_position = (((data.position - joint_info[joint].position_min) / (joint_info[joint].position_max - joint_info[joint].position_min)) * (joint_info[joint].dh_max - joint_info[joint].dh_min)) + joint_info[joint].dh_min;
    data.dh_goal = (((data.position_goal - joint_info[joint].position_min) / (joint_info[joint].position_max - joint_info[joint].position_min)) * (joint_info[joint].dh_max - joint_info[joint].dh_min)) + joint_info[joint].dh_min;

	return true;
}

<|endoftext|>


<commit_before><commit_msg>24 TGraphs CFD vs timestamp added<commit_after><|endoftext|>


<commit_before>/*
Copyright 2016 Fixstars Corporation

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.
*/

#include <iostream>

#include <libsgm.h>

#include "internal.h"
#include "device_buffer.hpp"
#include "sgm.hpp"

namespace sgm {
	static bool is_cuda_input(EXECUTE_INOUT type) { return (type & 0x1) > 0; }
	static bool is_cuda_output(EXECUTE_INOUT type) { return (type & 0x2) > 0; }

	class SemiGlobalMatchingBase {
	public:
		using output_type = sgm::output_type;
		virtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
			int w, int h, int sp, int dp, StereoSGM::Parameters& param) = 0;

		virtual ~SemiGlobalMatchingBase() {}
	};

	template <typename input_type, int DISP_SIZE>
	class SemiGlobalMatchingImpl : public SemiGlobalMatchingBase {
	public:
		void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
			int w, int h, int sp, int dp, StereoSGM::Parameters& param) override
		{
			sgm_engine_.execute(dst_L, dst_R, (const input_type*)src_L, (const input_type*)src_R, w, h, sp, dp, param);
		}
	private:
		SemiGlobalMatching<input_type, DISP_SIZE> sgm_engine_;
	};

	struct CudaStereoSGMResources {
		DeviceBuffer<uint8_t> d_src_left;
		DeviceBuffer<uint8_t> d_src_right;
		DeviceBuffer<uint16_t> d_left_disp;
		DeviceBuffer<uint16_t> d_right_disp;
		DeviceBuffer<uint16_t> d_tmp_left_disp;
		DeviceBuffer<uint16_t> d_tmp_right_disp;

		SemiGlobalMatchingBase* sgm_engine;

		CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, int src_pitch_, int dst_pitch_, EXECUTE_INOUT inout_type_) {

			if (input_depth_bits_ == 8 && disparity_size_ == 64)
				sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 64>();
			else if (input_depth_bits_ == 8 && disparity_size_ == 128)
				sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 128>();
			else if (input_depth_bits_ == 8 && disparity_size_ == 256)
				sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 256>();
			else if (input_depth_bits_ == 16 && disparity_size_ == 64)
				sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 64>();
			else if (input_depth_bits_ == 16 && disparity_size_ == 128)
				sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 128>();
			else if (input_depth_bits_ == 16 && disparity_size_ == 256)
				sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 256>();
			else
				throw std::logic_error("depth bits must be 8 or 16, and disparity size must be 64 or 128");

			if (!is_cuda_input(inout_type_)) {
				this->d_src_left.allocate(input_depth_bits_ / 8 * src_pitch_ * height_);
				this->d_src_right.allocate(input_depth_bits_ / 8 * src_pitch_ * height_);
			}

			this->d_left_disp.allocate(dst_pitch_ * height_);
			this->d_right_disp.allocate(dst_pitch_ * height_);

			this->d_tmp_left_disp.allocate(dst_pitch_ * height_);
			this->d_tmp_right_disp.allocate(dst_pitch_ * height_);

			this->d_left_disp.fillZero();
			this->d_right_disp.fillZero();
			this->d_tmp_left_disp.fillZero();
			this->d_tmp_right_disp.fillZero();
		}

		~CudaStereoSGMResources() {
			delete sgm_engine;
		}
	};

	StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits,
		EXECUTE_INOUT inout_type, const Parameters& param) : StereoSGM(width, height, disparity_size, input_depth_bits, output_depth_bits, width, width, inout_type, param) {}

	StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, int src_pitch, int dst_pitch,
		EXECUTE_INOUT inout_type, const Parameters& param) :
		cu_res_(NULL),
		width_(width),
		height_(height),
		disparity_size_(disparity_size),
		input_depth_bits_(input_depth_bits),
		output_depth_bits_(output_depth_bits),
		src_pitch_(src_pitch),
		dst_pitch_(dst_pitch),
		inout_type_(inout_type),
		param_(param)
	{
		// check values
		if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {
			width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
			throw std::logic_error("depth bits must be 8 or 16");
		}
		if (disparity_size_ != 64 && disparity_size_ != 128 && disparity_size != 256) {
			width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
			throw std::logic_error("disparity size must be 64, 128 or 256");
		}
		{
			// simulate minimum/maximum value
			std::int64_t max = static_cast<int64_t>(disparity_size) + param.min_disp - 1;
			if (param.subpixel) {
				max *= SUBPIXEL_SCALE;
				max += SUBPIXEL_SCALE - 1;
			}
			bool enough = max < 1 << output_depth_bits;
			if (param.min_disp <= 0) {
				// whether or not output can be represented by signed
				std::int64_t min = static_cast<int64_t>(param.min_disp) - 1;
				if (param.subpixel) {
					min *= SUBPIXEL_SCALE;
				}
				enough = enough
						&& -(1 << (output_depth_bits - 1)) <= min
						&& max < 1 << (output_depth_bits - 1);
			}
			if (!enough) {
				width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
				throw std::logic_error("output depth bits must be sufficient for representing output value");
			}
		}
		if (param_.path_type != PathType::SCAN_4PATH && param_.path_type != PathType::SCAN_8PATH) {
			width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
			throw std::logic_error("Path type must be PathType::SCAN_4PATH or PathType::SCAN_8PATH");
		}

		cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, src_pitch, dst_pitch, inout_type_);
	}

	StereoSGM::~StereoSGM() {
		if (cu_res_) { delete cu_res_; }
	}

	void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void* dst) {

		const void *d_input_left, *d_input_right;

		if (is_cuda_input(inout_type_)) {
			d_input_left = left_pixels;
			d_input_right = right_pixels;
		}
		else {
			CudaSafeCall(cudaMemcpy(cu_res_->d_src_left.data(), left_pixels, cu_res_->d_src_left.size(), cudaMemcpyHostToDevice));
			CudaSafeCall(cudaMemcpy(cu_res_->d_src_right.data(), right_pixels, cu_res_->d_src_right.size(), cudaMemcpyHostToDevice));
			d_input_left = cu_res_->d_src_left.data();
			d_input_right = cu_res_->d_src_right.data();
		}

		void* d_tmp_left_disp = cu_res_->d_tmp_left_disp.data();
		void* d_tmp_right_disp = cu_res_->d_tmp_right_disp.data();
		void* d_left_disp = cu_res_->d_left_disp.data();
		void* d_right_disp = cu_res_->d_right_disp.data();

		if (is_cuda_output(inout_type_) && output_depth_bits_ == 16)
			d_left_disp = dst; // when threre is no device-host copy or type conversion, use passed buffer

		cu_res_->sgm_engine->execute((uint16_t*)d_tmp_left_disp, (uint16_t*)d_tmp_right_disp,
			d_input_left, d_input_right, width_, height_, src_pitch_, dst_pitch_, param_);

		sgm::details::median_filter((uint16_t*)d_tmp_left_disp, (uint16_t*)d_left_disp, width_, height_, dst_pitch_);
		sgm::details::median_filter((uint16_t*)d_tmp_right_disp, (uint16_t*)d_right_disp, width_, height_, dst_pitch_);
		sgm::details::check_consistency((uint16_t*)d_left_disp, (uint16_t*)d_right_disp, d_input_left, width_, height_, input_depth_bits_, src_pitch_, dst_pitch_, param_.subpixel, param_.min_disp);

		if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
			sgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)d_tmp_left_disp, dst_pitch_ * height_);
			CudaSafeCall(cudaMemcpy(dst, d_tmp_left_disp, sizeof(uint8_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));
		}
		else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
			sgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)dst, dst_pitch_ * height_);
		}
		else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
			CudaSafeCall(cudaMemcpy(dst, d_left_disp, sizeof(uint16_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));
		}
		else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
			// optimize! no-copy!
		}
		else {
			std::cerr << "not impl" << std::endl;
		}
	}
}
<commit_msg>Avoid warnings<commit_after>/*
Copyright 2016 Fixstars Corporation

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.
*/

#include <iostream>

#include <libsgm.h>

#include "internal.h"
#include "device_buffer.hpp"
#include "sgm.hpp"

namespace sgm {
	static bool is_cuda_input(EXECUTE_INOUT type) { return (type & 0x1) > 0; }
	static bool is_cuda_output(EXECUTE_INOUT type) { return (type & 0x2) > 0; }

	class SemiGlobalMatchingBase {
	public:
		using output_type = sgm::output_type;
		virtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
			int w, int h, int sp, int dp, StereoSGM::Parameters& param) = 0;

		virtual ~SemiGlobalMatchingBase() {}
	};

	template <typename input_type, int DISP_SIZE>
	class SemiGlobalMatchingImpl : public SemiGlobalMatchingBase {
	public:
		void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
			int w, int h, int sp, int dp, StereoSGM::Parameters& param) override
		{
			sgm_engine_.execute(dst_L, dst_R, (const input_type*)src_L, (const input_type*)src_R, w, h, sp, dp, param);
		}
	private:
		SemiGlobalMatching<input_type, DISP_SIZE> sgm_engine_;
	};

	struct CudaStereoSGMResources {
		DeviceBuffer<uint8_t> d_src_left;
		DeviceBuffer<uint8_t> d_src_right;
		DeviceBuffer<uint16_t> d_left_disp;
		DeviceBuffer<uint16_t> d_right_disp;
		DeviceBuffer<uint16_t> d_tmp_left_disp;
		DeviceBuffer<uint16_t> d_tmp_right_disp;

		SemiGlobalMatchingBase* sgm_engine;

		CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, int src_pitch_, int dst_pitch_, EXECUTE_INOUT inout_type_) {

			if (input_depth_bits_ == 8 && disparity_size_ == 64)
				sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 64>();
			else if (input_depth_bits_ == 8 && disparity_size_ == 128)
				sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 128>();
			else if (input_depth_bits_ == 8 && disparity_size_ == 256)
				sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 256>();
			else if (input_depth_bits_ == 16 && disparity_size_ == 64)
				sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 64>();
			else if (input_depth_bits_ == 16 && disparity_size_ == 128)
				sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 128>();
			else if (input_depth_bits_ == 16 && disparity_size_ == 256)
				sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 256>();
			else
				throw std::logic_error("depth bits must be 8 or 16, and disparity size must be 64 or 128");

			if (!is_cuda_input(inout_type_)) {
				this->d_src_left.allocate(input_depth_bits_ / 8 * src_pitch_ * height_);
				this->d_src_right.allocate(input_depth_bits_ / 8 * src_pitch_ * height_);
			}

			this->d_left_disp.allocate(dst_pitch_ * height_);
			this->d_right_disp.allocate(dst_pitch_ * height_);

			this->d_tmp_left_disp.allocate(dst_pitch_ * height_);
			this->d_tmp_right_disp.allocate(dst_pitch_ * height_);

			this->d_left_disp.fillZero();
			this->d_right_disp.fillZero();
			this->d_tmp_left_disp.fillZero();
			this->d_tmp_right_disp.fillZero();
		}

		~CudaStereoSGMResources() {
			delete sgm_engine;
		}
	};

	StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits,
		EXECUTE_INOUT inout_type, const Parameters& param) : StereoSGM(width, height, disparity_size, input_depth_bits, output_depth_bits, width, width, inout_type, param) {}

	StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, int src_pitch, int dst_pitch,
		EXECUTE_INOUT inout_type, const Parameters& param) :
		cu_res_(NULL),
		width_(width),
		height_(height),
		disparity_size_(disparity_size),
		input_depth_bits_(input_depth_bits),
		output_depth_bits_(output_depth_bits),
		src_pitch_(src_pitch),
		dst_pitch_(dst_pitch),
		inout_type_(inout_type),
		param_(param)
	{
		// check values
		if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {
			width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
			throw std::logic_error("depth bits must be 8 or 16");
		}
		if (disparity_size_ != 64 && disparity_size_ != 128 && disparity_size != 256) {
			width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
			throw std::logic_error("disparity size must be 64, 128 or 256");
		}
		{
			// simulate minimum/maximum value
			std::int64_t max = static_cast<int64_t>(disparity_size) + param.min_disp - 1;
			if (param.subpixel) {
				max *= SUBPIXEL_SCALE;
				max += SUBPIXEL_SCALE - 1;
			}
			bool enough = max < 1ll << output_depth_bits;
			if (param.min_disp <= 0) {
				// whether or not output can be represented by signed
				std::int64_t min = static_cast<int64_t>(param.min_disp) - 1;
				if (param.subpixel) {
					min *= SUBPIXEL_SCALE;
				}
				enough = enough
						&& -(1ll << (output_depth_bits - 1)) <= min
						&& max < 1ll << (output_depth_bits - 1);
			}
			if (!enough) {
				width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
				throw std::logic_error("output depth bits must be sufficient for representing output value");
			}
		}
		if (param_.path_type != PathType::SCAN_4PATH && param_.path_type != PathType::SCAN_8PATH) {
			width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
			throw std::logic_error("Path type must be PathType::SCAN_4PATH or PathType::SCAN_8PATH");
		}

		cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, src_pitch, dst_pitch, inout_type_);
	}

	StereoSGM::~StereoSGM() {
		if (cu_res_) { delete cu_res_; }
	}

	void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void* dst) {

		const void *d_input_left, *d_input_right;

		if (is_cuda_input(inout_type_)) {
			d_input_left = left_pixels;
			d_input_right = right_pixels;
		}
		else {
			CudaSafeCall(cudaMemcpy(cu_res_->d_src_left.data(), left_pixels, cu_res_->d_src_left.size(), cudaMemcpyHostToDevice));
			CudaSafeCall(cudaMemcpy(cu_res_->d_src_right.data(), right_pixels, cu_res_->d_src_right.size(), cudaMemcpyHostToDevice));
			d_input_left = cu_res_->d_src_left.data();
			d_input_right = cu_res_->d_src_right.data();
		}

		void* d_tmp_left_disp = cu_res_->d_tmp_left_disp.data();
		void* d_tmp_right_disp = cu_res_->d_tmp_right_disp.data();
		void* d_left_disp = cu_res_->d_left_disp.data();
		void* d_right_disp = cu_res_->d_right_disp.data();

		if (is_cuda_output(inout_type_) && output_depth_bits_ == 16)
			d_left_disp = dst; // when threre is no device-host copy or type conversion, use passed buffer

		cu_res_->sgm_engine->execute((uint16_t*)d_tmp_left_disp, (uint16_t*)d_tmp_right_disp,
			d_input_left, d_input_right, width_, height_, src_pitch_, dst_pitch_, param_);

		sgm::details::median_filter((uint16_t*)d_tmp_left_disp, (uint16_t*)d_left_disp, width_, height_, dst_pitch_);
		sgm::details::median_filter((uint16_t*)d_tmp_right_disp, (uint16_t*)d_right_disp, width_, height_, dst_pitch_);
		sgm::details::check_consistency((uint16_t*)d_left_disp, (uint16_t*)d_right_disp, d_input_left, width_, height_, input_depth_bits_, src_pitch_, dst_pitch_, param_.subpixel, param_.min_disp);

		if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
			sgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)d_tmp_left_disp, dst_pitch_ * height_);
			CudaSafeCall(cudaMemcpy(dst, d_tmp_left_disp, sizeof(uint8_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));
		}
		else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
			sgm::details::cast_16bit_8bit_array((const uint16_t*)d_left_disp, (uint8_t*)dst, dst_pitch_ * height_);
		}
		else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
			CudaSafeCall(cudaMemcpy(dst, d_left_disp, sizeof(uint16_t) * dst_pitch_ * height_, cudaMemcpyDeviceToHost));
		}
		else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
			// optimize! no-copy!
		}
		else {
			std::cerr << "not impl" << std::endl;
		}
	}
}
<|endoftext|>


<commit_before>#include "html.h"
#include "stylesheet.h"
#include <algorithm>
#include "document.h"

void litehtml::css::parse_stylesheet( const tchar_t* str, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )
{
	tstring text = str;

	// remove comments
	tstring::size_type c_start = text.find(_t("/*"));
	while(c_start != tstring::npos)
	{
		tstring::size_type c_end = text.find(_t("*/"), c_start + 2);
		text.erase(c_start, c_end - c_start + 2);
		c_start = text.find(_t("/*"));
	}

	tstring::size_type pos = text.find_first_not_of(_t(" \n\r\t"));
	while(pos != tstring::npos)
	{
		while(pos != tstring::npos && text[pos] == _t('@'))
		{
			tstring::size_type sPos = pos;
			pos = text.find_first_of(_t("{"), pos);
			if(pos != tstring::npos && text[pos] == _t('{'))
			{
				pos = find_close_bracket(text, pos, _t('{'), _t('}'));
			}
			if(pos != tstring::npos)
			{
				parse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media);
			} else
			{
				parse_atrule(text.substr(sPos), baseurl, doc, media);
			}

			if(pos != tstring::npos)
			{
				pos = text.find_first_not_of(_t(" \n\r\t"), pos + 1);
			}
		}

		if(pos == tstring::npos)
		{
			break;
		}

		tstring::size_type style_start = text.find(_t("{"), pos);
		tstring::size_type style_end	= text.find(_t("}"), pos);
		if(style_start != tstring::npos && style_end != tstring::npos)
		{
			style::ptr st = new style;
			st->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl);

			parse_selectors(text.substr(pos, style_start - pos), st, media);

			if(media && doc)
			{
				doc->add_media_list(media);
			}

			pos = style_end + 1;
		} else
		{
			pos = tstring::npos;
		}

		if(pos != tstring::npos)
		{
			pos = text.find_first_not_of(_t(" \n\r\t"), pos);
		}
	}
}

void litehtml::css::parse_css_url( const tstring& str, tstring& url )
{
	url = _t("");
	size_t pos1 = str.find(_t('('));
	size_t pos2 = str.find(_t(')'));
	if(pos1 != tstring::npos && pos2 != tstring::npos)
	{
		url = str.substr(pos1 + 1, pos2 - pos1 - 1);
		if(url.length())
		{
			if(url[0] == _t('\'') || url[0] == _t('"'))
			{
				url.erase(0, 1);
			}
		}
		if(url.length())
		{
			if(url[url.length() - 1] == _t('\'') || url[url.length() - 1] == _t('"'))
			{
				url.erase(url.length() - 1, 1);
			}
		}
	}
}

bool litehtml::css::parse_selectors( const tstring& txt, litehtml::style::ptr styles, media_query_list::ptr& media )
{
	tstring selector = txt;
	trim(selector);
	string_vector tokens;
	split_string(selector, tokens, _t(","));

	bool added_something = false;

	for(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++)
	{
		css_selector::ptr selector = new css_selector(media);
		selector->m_style = styles;
		trim(*tok);
		if(selector->parse(*tok))
		{
			selector->calc_specificity();
			add_selector(selector);
			added_something = true;
		}
	}

	return added_something;
}

void litehtml::css::sort_selectors()
{
	sort(m_selectors.begin(), m_selectors.end(), std::less<css_selector::ptr>( ));
}

void litehtml::css::parse_atrule( const tstring& text, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )
{
	if(text.substr(0, 7) == _t("@import"))
	{
		int sPos = 7;
		tstring iStr;
		iStr = text.substr(sPos);
		if(iStr[iStr.length() - 1] == _t(';'))
		{
			iStr.erase(iStr.length() - 1);
		}
		trim(iStr);
		string_vector tokens;
		split_string(iStr, tokens, _t(" "), _t(""), _t("(\""));
		if(!tokens.empty())
		{
			tstring url;
			parse_css_url(tokens.front(), url);
			if(url.empty())
			{
				url = tokens.front();
			}
			tokens.erase(tokens.begin());
			if(doc)
			{
				document_container* doc_cont = doc->container();
				if(doc_cont)
				{
					tstring css_text;
					tstring css_baseurl;
					if(baseurl)
					{
						css_baseurl = baseurl;
					}
					doc_cont->import_css(css_text, url, css_baseurl);
					if(!css_text.empty())
					{
						media_query_list::ptr new_media = media;
						if(!tokens.empty())
						{
							tstring media_str;
							for(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++)
							{
								if(iter != tokens.begin())
								{
									media_str += _t(" ");
								}
								media_str += (*iter);
							}
							new_media = media_query_list::create_from_string(media_str, doc);
							if(!new_media)
							{
								new_media = media;
							}
						}
						parse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media);
					}
				}
			}
		}
	} else if(text.substr(0, 6) == _t("@media"))
	{
		tstring::size_type b1 = text.find_first_of(_t('{'));
		tstring::size_type b2 = text.find_last_of(_t('}'));
		if(b1 != tstring::npos)
		{
			tstring media_type = text.substr(6, b1 - 6);
			trim(media_type);
			media_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc);

			tstring media_style;
			if(b2 != tstring::npos)
			{
				media_style = text.substr(b1 + 1, b2 - b1 - 1);
			} else
			{
				media_style = text.substr(b1 + 1);
			}

			parse_stylesheet(media_style.c_str(), baseurl, doc, new_media);
		}
	}
}
<commit_msg>fixed case where ; was not removed when it was followed by a whitepace.<commit_after>#include "html.h"
#include "stylesheet.h"
#include <algorithm>
#include "document.h"

void litehtml::css::parse_stylesheet( const tchar_t* str, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )
{
	tstring text = str;

	// remove comments
	tstring::size_type c_start = text.find(_t("/*"));
	while(c_start != tstring::npos)
	{
		tstring::size_type c_end = text.find(_t("*/"), c_start + 2);
		text.erase(c_start, c_end - c_start + 2);
		c_start = text.find(_t("/*"));
	}

	tstring::size_type pos = text.find_first_not_of(_t(" \n\r\t"));
	while(pos != tstring::npos)
	{
		while(pos != tstring::npos && text[pos] == _t('@'))
		{
			tstring::size_type sPos = pos;
			pos = text.find_first_of(_t("{"), pos);
			if(pos != tstring::npos && text[pos] == _t('{'))
			{
				pos = find_close_bracket(text, pos, _t('{'), _t('}'));
			}
			if(pos != tstring::npos)
			{
				parse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media);
			} else
			{
				parse_atrule(text.substr(sPos), baseurl, doc, media);
			}

			if(pos != tstring::npos)
			{
				pos = text.find_first_not_of(_t(" \n\r\t"), pos + 1);
			}
		}

		if(pos == tstring::npos)
		{
			break;
		}

		tstring::size_type style_start = text.find(_t("{"), pos);
		tstring::size_type style_end	= text.find(_t("}"), pos);
		if(style_start != tstring::npos && style_end != tstring::npos)
		{
			style::ptr st = new style;
			st->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl);

			parse_selectors(text.substr(pos, style_start - pos), st, media);

			if(media && doc)
			{
				doc->add_media_list(media);
			}

			pos = style_end + 1;
		} else
		{
			pos = tstring::npos;
		}

		if(pos != tstring::npos)
		{
			pos = text.find_first_not_of(_t(" \n\r\t"), pos);
		}
	}
}

void litehtml::css::parse_css_url( const tstring& str, tstring& url )
{
	url = _t("");
	size_t pos1 = str.find(_t('('));
	size_t pos2 = str.find(_t(')'));
	if(pos1 != tstring::npos && pos2 != tstring::npos)
	{
		url = str.substr(pos1 + 1, pos2 - pos1 - 1);
		if(url.length())
		{
			if(url[0] == _t('\'') || url[0] == _t('"'))
			{
				url.erase(0, 1);
			}
		}
		if(url.length())
		{
			if(url[url.length() - 1] == _t('\'') || url[url.length() - 1] == _t('"'))
			{
				url.erase(url.length() - 1, 1);
			}
		}
	}
}

bool litehtml::css::parse_selectors( const tstring& txt, litehtml::style::ptr styles, media_query_list::ptr& media )
{
	tstring selector = txt;
	trim(selector);
	string_vector tokens;
	split_string(selector, tokens, _t(","));

	bool added_something = false;

	for(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++)
	{
		css_selector::ptr selector = new css_selector(media);
		selector->m_style = styles;
		trim(*tok);
		if(selector->parse(*tok))
		{
			selector->calc_specificity();
			add_selector(selector);
			added_something = true;
		}
	}

	return added_something;
}

void litehtml::css::sort_selectors()
{
	sort(m_selectors.begin(), m_selectors.end(), std::less<css_selector::ptr>( ));
}

void litehtml::css::parse_atrule( const tstring& text, const tchar_t* baseurl, document* doc, media_query_list::ptr& media )
{
	if(text.substr(0, 7) == _t("@import"))
	{
		int sPos = 7;
		tstring iStr;
		iStr = text.substr(sPos);
		trim(iStr);
		if(iStr[iStr.length() - 1] == _t(';'))
		{
			iStr.erase(iStr.length() - 1);
		}
		trim(iStr);
		string_vector tokens;
		split_string(iStr, tokens, _t(" "), _t(""), _t("(\""));
		if(!tokens.empty())
		{
			tstring url;
			parse_css_url(tokens.front(), url);
			if(url.empty())
			{
				url = tokens.front();
			}
			tokens.erase(tokens.begin());
			if(doc)
			{
				document_container* doc_cont = doc->container();
				if(doc_cont)
				{
					tstring css_text;
					tstring css_baseurl;
					if(baseurl)
					{
						css_baseurl = baseurl;
					}
					doc_cont->import_css(css_text, url, css_baseurl);
					if(!css_text.empty())
					{
						media_query_list::ptr new_media = media;
						if(!tokens.empty())
						{
							tstring media_str;
							for(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++)
							{
								if(iter != tokens.begin())
								{
									media_str += _t(" ");
								}
								media_str += (*iter);
							}
							new_media = media_query_list::create_from_string(media_str, doc);
							if(!new_media)
							{
								new_media = media;
							}
						}
						parse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media);
					}
				}
			}
		}
	} else if(text.substr(0, 6) == _t("@media"))
	{
		tstring::size_type b1 = text.find_first_of(_t('{'));
		tstring::size_type b2 = text.find_last_of(_t('}'));
		if(b1 != tstring::npos)
		{
			tstring media_type = text.substr(6, b1 - 6);
			trim(media_type);
			media_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc);

			tstring media_style;
			if(b2 != tstring::npos)
			{
				media_style = text.substr(b1 + 1, b2 - b1 - 1);
			} else
			{
				media_style = text.substr(b1 + 1);
			}

			parse_stylesheet(media_style.c_str(), baseurl, doc, new_media);
		}
	}
}
<|endoftext|>


<commit_before>#include "midi.h"
#include <algorithm>
#include <iostream>

MIDI::MIDI() {}

RtMidiIn *MIDI::createMidiIn(const std::string clientName) {
  // RtMidiIn constructor
  RtMidiIn *midiin = 0;
  try {
    midiin = new RtMidiIn(RtMidi::LINUX_ALSA, clientName);
  } catch (RtMidiError &error) {
    // Handle the exception here
    error.printMessage();
  }
  midiin->ignoreTypes(false, true, true);
  return midiin;
}

RtMidiOut *
MIDI::createMidiOut(const std::string clientName) { // RtMidiOut constructor
  RtMidiOut *midiout = 0;
  try {
    midiout = new RtMidiOut(RtMidi::LINUX_ALSA, clientName);
  } catch (RtMidiError &error) {
    // Handle the exception here
    error.printMessage();
  }
  return midiout;
}

unsigned char MIDI::RolandChecksum(std::vector<unsigned char> *message) {
  unsigned int nBytes = message->size();
  unsigned int sum = 0;
  for (unsigned int i = 0; i < nBytes; i++) {
    sum += (int)message->at(i);
    if (sum > 127)
      sum -= 128;
  }
  return 128 - sum;
}

std::vector<unsigned char> *MIDI::byteSplit(long val) {
  return MIDI::byteSplit(val, 0);
}

std::vector<unsigned char> *MIDI::byteSplit(long val, int size) {
  std::vector<unsigned char> *bytes = new std::vector<unsigned char>();
  while (val > 0) {
    unsigned char c = val & 0x7f;
    val >>= 7;
    bytes->push_back(c);
  }
  if (size > 0) {
    int nLength = bytes->size();
    if (nLength < size) {
      for (int i = nLength; i < size; i++)
        bytes->push_back(0x00);
    }
  }
  std::reverse(bytes->begin(), bytes->end());
  return bytes;
}

long MIDI::byteJoin(std::vector<unsigned char> *message) {
  return byteJoin(message, 0, message->size());
}

long MIDI::byteJoin(std::vector<unsigned char> *message, unsigned int start,
                    unsigned int length) {
  unsigned int cnt;
  int current = 0;

  if (start + length >= message->size())
    return -1;

  for (cnt = start; cnt < start + length; cnt++) {
    current <<= 7;
    current += message->at(cnt);
  }
  return current;
}

void MIDI::printMessage(BYTE_VECTOR *message) {
  unsigned int nMessageSize = message->size();
  for (unsigned int i = 0; i < nMessageSize; i++)
    std::cout << std::hex << (int)message->at(i) << " ";
  std::cout << "\n" << std::flush;
}
<commit_msg>reserve vector size<commit_after>#include "midi.h"
#include <algorithm>
#include <iostream>

MIDI::MIDI() {}

RtMidiIn *MIDI::createMidiIn(const std::string clientName) {
  // RtMidiIn constructor
  RtMidiIn *midiin = 0;
  try {
    midiin = new RtMidiIn(RtMidi::LINUX_ALSA, clientName);
  } catch (RtMidiError &error) {
    // Handle the exception here
    error.printMessage();
  }
  midiin->ignoreTypes(false, true, true);
  return midiin;
}

RtMidiOut *
MIDI::createMidiOut(const std::string clientName) { // RtMidiOut constructor
  RtMidiOut *midiout = 0;
  try {
    midiout = new RtMidiOut(RtMidi::LINUX_ALSA, clientName);
  } catch (RtMidiError &error) {
    // Handle the exception here
    error.printMessage();
  }
  return midiout;
}

unsigned char MIDI::RolandChecksum(std::vector<unsigned char> *message) {
  unsigned int nBytes = message->size();
  unsigned int sum = 0;
  for (unsigned int i = 0; i < nBytes; i++) {
    sum += (int)message->at(i);
    if (sum > 127)
      sum -= 128;
  }
  return 128 - sum;
}

std::vector<unsigned char> *MIDI::byteSplit(long val) {
  return MIDI::byteSplit(val, 0);
}

std::vector<unsigned char> *MIDI::byteSplit(long val, int size) {
  std::vector<unsigned char> *bytes = new std::vector<unsigned char>();
  bytes->reserve(size);
  while (val > 0) {
    unsigned char c = val & 0x7f;
    val >>= 7;
    bytes->push_back(c);
  }
  if (size > 0) {
    int nLength = bytes->size();
    if (nLength < size) {
      for (int i = nLength; i < size; i++)
        bytes->push_back(0x00);
    }
  }
  std::reverse(bytes->begin(), bytes->end());
  return bytes;
}

long MIDI::byteJoin(std::vector<unsigned char> *message) {
  return byteJoin(message, 0, message->size());
}

long MIDI::byteJoin(std::vector<unsigned char> *message, unsigned int start,
                    unsigned int length) {
  unsigned int cnt;
  int current = 0;

  if (start + length >= message->size())
    return -1;

  for (cnt = start; cnt < start + length; cnt++) {
    current <<= 7;
    current += message->at(cnt);
  }
  return current;
}

void MIDI::printMessage(BYTE_VECTOR *message) {
  unsigned int nMessageSize = message->size();
  for (unsigned int i = 0; i < nMessageSize; i++)
    std::cout << std::hex << (int)message->at(i) << " ";
  std::cout << "\n" << std::flush;
}
<|endoftext|>


<commit_before>//
// Created by H�vard on 13.06.2015.
//

#include <stdio.h>
#include <string.h>
#include "WebSocketServer.h"
#include "Base64.h"
#include "sha1.h"

using namespace libwebsockets;

WebSocketServer WebSocketServer::instance;
bool WebSocketServer::init = false;

int WebSocketServer::WaitForSockets(int Milliseconds)
{
	struct pollfd pfds[Sockets.size()];
	int i = 0;
	for(auto& socket : Sockets)
	{
		pfds[i].fd = socket.GetFileDescriptor();
		pfds[i].events = POLLIN;
		i++;
	}

	int ret = poll(&pfds[0], (int)Sockets.size(), Milliseconds);

	for(int i = 0; i < Sockets.size(); i++)
	{
		if((pfds[i].revents & POLLIN) != 0)
			Sockets[i].HandleEvent();
	}

	return ret;
}

int WebSocketServer::HandleConnectionEvent(Socket & socket)
{
	auto& ws = WebSocketServer::Instance();
	struct sockaddr_in client_addr;
	socklen_t client_length = sizeof(client_addr);
	int client = accept(socket.GetFileDescriptor(), (struct sockaddr *)&client_addr, &client_length);
	size_t BufferSize = 1500;
	uint8 Buffer[BufferSize]; //Buffer for current packet
	size_t ReadBytes;
	Socket ClientSocket = Socket(SocketType::STREAM, client, &HandleClientEvent);

	try
	{
		ReadBytes = ClientSocket.Read(Buffer, BufferSize);
		Buffer[ReadBytes] = '\0';

		map<string, string> header = ParseHTTPHeader(string((const char*)Buffer));

		string appended = header["Sec-WebSocket-Key"] + GID;
		uint8 hash[20];
		sha1::calc(appended.c_str(), appended.length(), hash);

		string HashedKey = Base64Encode(hash, 20);

		char handshake[BufferSize];

		sprintf(handshake, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n", HashedKey.c_str());

		send(ClientSocket.GetFileDescriptor(), handshake, strlen(handshake), 0);

		ws.AddToPoll(ClientSocket);

		if(ws.OnOpen != nullptr) ws.OnOpen(ClientSocket);

	}
	catch(const exception& ex)
	{
		cout << "Could not read from socket" << endl;
	}

}

int WebSocketServer::HandleClientEvent(Socket &socket)
{
	auto& ws = WebSocketServer::Instance();
	size_t BufferSize = 1500;
	uint8 Buffer[BufferSize]; //Buffer for current packet

	size_t ReadBytes;
	try
	{
		ReadBytes = socket.Read(Buffer, BufferSize);
		Buffer[ReadBytes] = '\0';
		size_t MessageOffset = 2;
		struct WebSocketHeader header;

		if(Buffer[0] & 0x80) header.IsFinal = true;
		else header.IsFinal = false;
		if(Buffer[1] & 0x80) header.IsMasked = true;
		else header.IsMasked = false;

		header.Opcode = static_cast<WebSocketOpcode >(Buffer[0] & 0x0F);

		if(Buffer[1] == 0x7E)
		{
			uint16* tempSize = (uint16*) &Buffer[2];
			header.Length = ntohs(*tempSize);
			MessageOffset += 2;
		}
		else if(Buffer[1] == 0x7F)
		{
			uint64* tempSize = (uint64*) &Buffer[2];
			header.Length = ntohll(*tempSize);
			MessageOffset += 8;
		}
		else header.Length = Buffer[1] & 0x7F;

		if(header.IsMasked)
		{
			uint32* tempMask = (uint32*) &Buffer[MessageOffset];
			header.MaskingKey = *tempMask;
			MessageOffset += 4;
		}

		socket.AddToMessage(&Buffer[MessageOffset], ReadBytes - MessageOffset, header);

		if(header.IsFinal)
		{
			if(header.Opcode == WebSocketOpcode::CLOSE)
			{
				uint8 buffer[4];

				bool payload = socket.GetMessageSize() > 0;

				buffer[0] = 0x88;
				if(payload)
				{
					buffer[1] = 2;
					buffer[2] = socket.GetMessage()[0];
					buffer[3] = socket.GetMessage()[1];
				}
				else
					buffer[1] = 0;

				send(socket.GetFileDescriptor(), buffer, payload?4:2, 0);

				if(ws.OnClose != nullptr) ws.OnClose(socket);
				ws.RemoveFromPoll(socket);
			}
			else if(header.Opcode == WebSocketOpcode::PING)
			{
				uint8 buffer[0xFFFF];
				buffer[0] = 0x89;

				size_t size = socket.GetMessageSize();
				int offset = 2;
				if(size < 0x7E)
					buffer[0] = size;
				else if(size < 0x7F)
				{
					buffer[0] = 0x7E;
					offset += 2;
					*((uint16*) &buffer[2]) = (uint16) size;
				}
				else
				{
					buffer[0] = 0x7F;
					offset += 8;
					*((uint64*) &buffer[2]) = (uint64) size;
				}

				memcpy(buffer + offset, socket.GetMessage(), socket.GetMessageSize());

				int sent = send(socket.GetFileDescriptor(), buffer, offset + socket.GetMessageSize(), 0x0);

				if(sent != sizeof(buffer))
				{
					cout << "ERROR: Could not send ping" << endl;
				}

				if(ws.OnPing != nullptr) ws.OnPing(socket);
			}
			else if(header.Opcode == WebSocketOpcode::PONG)
			{
				if(ws.OnPong != nullptr) ws.OnPong(socket);
			}
			else
			{
				if(header.Opcode == WebSocketOpcode::TEXT && socket.GetMessageSize() < MAX_MESSAGE_SIZE)
					socket.GetMessage()[socket.GetMessageSize()] = 0;
				//Call some function
				if(ws.OnMessage != nullptr) ws.OnMessage(socket);

			}
			socket.ResetMessage();
		}

		return 0;
	}
	catch(const exception& ex)
	{
		cout << "Could not read from socket" << endl;
	}

}

map<string, string> WebSocketServer::ParseHTTPHeader(string header)
{
	std::string delimiter = "\r\n";
	map<string, string> m;
	size_t pos = 0;
	std::string token;
	while ((pos = header.find(delimiter)) != std::string::npos) {
		token = header.substr(0, pos);

		size_t colon = token.find(':');

		if(colon != string::npos)
		{
			int skip = 1;
			if(token.at(colon+skip) == ' ') skip++;
			string key = token.substr(0, colon);
			string value = token.substr(colon+skip);
			m.insert(make_pair(key, value));
		}
		else
		{
			if(token.find("GET ") == 0)
			{
				m.insert(make_pair("Request", token));
			}
		}

		header.erase(0, pos + delimiter.length());
	}

	return m;
}

int WebSocketServer::RemoveFromPoll(Socket &Socket)
{
	for(int i = 0; i < Sockets.size(); i++)
	{
		if(&Sockets[i] == &Socket)
		{
			Sockets[i].Close();
			Sockets.erase(Sockets.begin() + i);

			return 0;
		}
	}
}
<commit_msg>static derp<commit_after>//
// Created by H�vard on 13.06.2015.
//

#include <stdio.h>
#include <string.h>
#include "WebSocketServer.h"
#include "Base64.h"
#include "sha1.h"

using namespace libwebsockets;

WebSocketServer WebSocketServer::instance;
bool WebSocketServer::init = false;
Socket WebSocketServer::ServerSocket;

int WebSocketServer::WaitForSockets(int Milliseconds)
{
	struct pollfd pfds[Sockets.size()];
	int i = 0;
	for(auto& socket : Sockets)
	{
		pfds[i].fd = socket.GetFileDescriptor();
		pfds[i].events = POLLIN;
		i++;
	}

	int ret = poll(&pfds[0], (int)Sockets.size(), Milliseconds);

	for(int i = 0; i < Sockets.size(); i++)
	{
		if((pfds[i].revents & POLLIN) != 0)
			Sockets[i].HandleEvent();
	}

	return ret;
}

int WebSocketServer::HandleConnectionEvent(Socket & socket)
{
	auto& ws = WebSocketServer::Instance();
	struct sockaddr_in client_addr;
	socklen_t client_length = sizeof(client_addr);
	int client = accept(socket.GetFileDescriptor(), (struct sockaddr *)&client_addr, &client_length);
	size_t BufferSize = 1500;
	uint8 Buffer[BufferSize]; //Buffer for current packet
	size_t ReadBytes;
	Socket ClientSocket = Socket(SocketType::STREAM, client, &HandleClientEvent);

	try
	{
		ReadBytes = ClientSocket.Read(Buffer, BufferSize);
		Buffer[ReadBytes] = '\0';

		map<string, string> header = ParseHTTPHeader(string((const char*)Buffer));

		string appended = header["Sec-WebSocket-Key"] + GID;
		uint8 hash[20];
		sha1::calc(appended.c_str(), appended.length(), hash);

		string HashedKey = Base64Encode(hash, 20);

		char handshake[BufferSize];

		sprintf(handshake, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n", HashedKey.c_str());

		send(ClientSocket.GetFileDescriptor(), handshake, strlen(handshake), 0);

		ws.AddToPoll(ClientSocket);

		if(ws.OnOpen != nullptr) ws.OnOpen(ClientSocket);

	}
	catch(const exception& ex)
	{
		cout << "Could not read from socket" << endl;
	}

}

int WebSocketServer::HandleClientEvent(Socket &socket)
{
	auto& ws = WebSocketServer::Instance();
	size_t BufferSize = 1500;
	uint8 Buffer[BufferSize]; //Buffer for current packet

	size_t ReadBytes;
	try
	{
		ReadBytes = socket.Read(Buffer, BufferSize);
		Buffer[ReadBytes] = '\0';
		size_t MessageOffset = 2;
		struct WebSocketHeader header;

		if(Buffer[0] & 0x80) header.IsFinal = true;
		else header.IsFinal = false;
		if(Buffer[1] & 0x80) header.IsMasked = true;
		else header.IsMasked = false;

		header.Opcode = static_cast<WebSocketOpcode >(Buffer[0] & 0x0F);

		if(Buffer[1] == 0x7E)
		{
			uint16* tempSize = (uint16*) &Buffer[2];
			header.Length = ntohs(*tempSize);
			MessageOffset += 2;
		}
		else if(Buffer[1] == 0x7F)
		{
			uint64* tempSize = (uint64*) &Buffer[2];
			header.Length = ntohll(*tempSize);
			MessageOffset += 8;
		}
		else header.Length = Buffer[1] & 0x7F;

		if(header.IsMasked)
		{
			uint32* tempMask = (uint32*) &Buffer[MessageOffset];
			header.MaskingKey = *tempMask;
			MessageOffset += 4;
		}

		socket.AddToMessage(&Buffer[MessageOffset], ReadBytes - MessageOffset, header);

		if(header.IsFinal)
		{
			if(header.Opcode == WebSocketOpcode::CLOSE)
			{
				uint8 buffer[4];

				bool payload = socket.GetMessageSize() > 0;

				buffer[0] = 0x88;
				if(payload)
				{
					buffer[1] = 2;
					buffer[2] = socket.GetMessage()[0];
					buffer[3] = socket.GetMessage()[1];
				}
				else
					buffer[1] = 0;

				send(socket.GetFileDescriptor(), buffer, payload?4:2, 0);

				if(ws.OnClose != nullptr) ws.OnClose(socket);
				ws.RemoveFromPoll(socket);
			}
			else if(header.Opcode == WebSocketOpcode::PING)
			{
				uint8 buffer[0xFFFF];
				buffer[0] = 0x89;

				size_t size = socket.GetMessageSize();
				int offset = 2;
				if(size < 0x7E)
					buffer[0] = size;
				else if(size < 0x7F)
				{
					buffer[0] = 0x7E;
					offset += 2;
					*((uint16*) &buffer[2]) = (uint16) size;
				}
				else
				{
					buffer[0] = 0x7F;
					offset += 8;
					*((uint64*) &buffer[2]) = (uint64) size;
				}

				memcpy(buffer + offset, socket.GetMessage(), socket.GetMessageSize());

				int sent = send(socket.GetFileDescriptor(), buffer, offset + socket.GetMessageSize(), 0x0);

				if(sent != sizeof(buffer))
				{
					cout << "ERROR: Could not send ping" << endl;
				}

				if(ws.OnPing != nullptr) ws.OnPing(socket);
			}
			else if(header.Opcode == WebSocketOpcode::PONG)
			{
				if(ws.OnPong != nullptr) ws.OnPong(socket);
			}
			else
			{
				if(header.Opcode == WebSocketOpcode::TEXT && socket.GetMessageSize() < MAX_MESSAGE_SIZE)
					socket.GetMessage()[socket.GetMessageSize()] = 0;
				//Call some function
				if(ws.OnMessage != nullptr) ws.OnMessage(socket);

			}
			socket.ResetMessage();
		}

		return 0;
	}
	catch(const exception& ex)
	{
		cout << "Could not read from socket" << endl;
	}

}

map<string, string> WebSocketServer::ParseHTTPHeader(string header)
{
	std::string delimiter = "\r\n";
	map<string, string> m;
	size_t pos = 0;
	std::string token;
	while ((pos = header.find(delimiter)) != std::string::npos) {
		token = header.substr(0, pos);

		size_t colon = token.find(':');

		if(colon != string::npos)
		{
			int skip = 1;
			if(token.at(colon+skip) == ' ') skip++;
			string key = token.substr(0, colon);
			string value = token.substr(colon+skip);
			m.insert(make_pair(key, value));
		}
		else
		{
			if(token.find("GET ") == 0)
			{
				m.insert(make_pair("Request", token));
			}
		}

		header.erase(0, pos + delimiter.length());
	}

	return m;
}

int WebSocketServer::RemoveFromPoll(Socket &Socket)
{
	for(int i = 0; i < Sockets.size(); i++)
	{
		if(&Sockets[i] == &Socket)
		{
			Sockets[i].Close();
			Sockets.erase(Sockets.begin() + i);

			return 0;
		}
	}
}
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "Vote.h"
#include "ETypes.h"
#include <ATF/global.hpp>
#include <ATF/PatriarchElectProcessor.hpp>
#include <ATF/CandidateMgr.hpp>
#include <ATF/_pt_notify_vote_score_zocl.hpp>

namespace GameServer
{
    namespace Fixes
    {
        void CVote::load()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.set_hook(&ATF::Voter::_Vote, &CVote::_Vote);
            core.set_hook(&ATF::Voter::_SendVotePaper, &CVote::_SendVotePaper);
            core.set_hook(&ATF::Voter::_SendVotePaperAll, &CVote::_SendVotePaperAll);
            core.set_hook(&ATF::Voter::_SendVoteScore, &CVote::_SendVoteScore);
            core.set_hook(&ATF::Voter::_SendVoteScoreAll, &CVote::_SendVoteScoreAll);
        }

        void CVote::unload()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.unset_hook(&ATF::Voter::_Vote);
            core.unset_hook(&ATF::Voter::_SendVotePaper);
            core.unset_hook(&ATF::Voter::_SendVotePaperAll);
            core.unset_hook(&ATF::Voter::_SendVoteScore);
            core.unset_hook(&ATF::Voter::_SendVoteScoreAll);
        }

        void CVote::loop()
        {
        }

        ModuleVersion_t CVote::get_version()
        {
            return ATF::usVersion;
        }

        ModuleName_t CVote::get_name()
        {
            static const ModuleName_t name = "fix_Vote";
            return name;
        }

        void CVote::configure(
            const rapidjson::Value & nodeConfig)
        {
            m_nLv = nodeConfig["level"].GetInt();
            m_nPlayTime = nodeConfig["play_time"].GetInt();
            m_dPvpPoint = nodeConfig["pvp_point"].GetDouble();
            m_dPvpCashBag = nodeConfig["pvp_cash_bag"].GetDouble();
            m_nClassGrade = nodeConfig["class_grade"].GetInt();
            m_bScoreListShow = nodeConfig["score_list_show"].GetBool();
            m_bScoreHide = nodeConfig["score_hide"].GetBool();
        }

        bool CVote::check_conditions(
            ATF::CPlayer * pOne)
        {
            bool result = false;

            do
            {
                if (!pOne || !pOne->m_bOper)
                    break;

                if (!pOne->m_pUserDB->m_AvatorData.dbSupplement.VoteEnable)
                    break;

                if (get_class_grade() > pOne->m_pUserDB->m_AvatorData.dbAvator.m_byLastClassGrade)
                    break;

                if (get_level() > pOne->GetLevel())
                    break;

                if (get_pvp_cash_bag() > pOne->GetPvpOrderView()->GetPvpCash())
                    break;

                if (get_pvp_point() > pOne->m_Param.GetPvPPoint())
                    break;

                if (get_play_time() > pOne->m_pUserDB->m_AvatorData.dbSupplement.dwAccumPlayTime)
                    break;

                result = true;
            } while (false);

            return result;
        }

        int WINAPIV CVote::_SendVotePaper(
            ATF::Voter * pObj,
            ATF::CPlayer * pOne,
            ATF::Info::Voter_SendVotePaper12_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto spModule = GetModule<CVote>();
            int result = 0;

            do
            {
                if (!pOne)
                    break;

                if (!pOne->m_bOper)
                    break;

                if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)
                {
                    auto instance = ATF::PatriarchElectProcessor::Instance();
                    instance->SendMsg_ResultCode(pOne->m_id.wIndex, 8);
                    result = 9;
                    break;
                }

                if (pOne->m_pUserDB->m_AvatorData.dbAvator.m_bOverlapVote)
                {
                    result = 10;
                    break;
                }

                if (!spModule->check_conditions(pOne))
                {
                    result = 11;
                    break;
                }

                auto instance = ATF::CandidateMgr::Instance();
                if (instance->IsRegistedAvator_2(pOne->m_Param.GetRaceCode(), pOne->m_Param.GetCharSerial()))
                {
                    result = 11;
                    break;
                }

                char pbyType[2]{ 56, 5 };
                auto msg = &pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()];
                ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)msg, msg->size());
            } while (false);

            return result;
        }

        void WINAPIV CVote::_SendVotePaperAll(
            ATF::Voter * pObj,
            ATF::Info::Voter_SendVotePaperAll14_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            for (auto& player : ATF::Global::g_Player)
            {
                _SendVotePaper(pObj, &player, nullptr);
            }
        }

        void WINAPIV CVote::_SendVoteScore(
            ATF::Voter * pObj,
            ATF::CPlayer * pOne,
            ATF::Info::Voter_SendVoteScore16_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto instance = GetModule<CVote>();
            if (!instance->score_list_show())
                return;

            if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)
                return;

            char pbyType[2]{ 56, 6 };
            ATF::_pt_notify_vote_score_zocl info;
            memcpy_s(
                &info, sizeof(info),
                &pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()],
                sizeof(pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()]));

            if (!instance->score_hide())
            {
                info.byVoteRate = 0;
                info.byNonvoteRate = 0;
                for (auto& b : info.body)
                    b.byScoreRate = 0;
            }

            ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)&info, info.size());
        }

        void WINAPIV CVote::_SendVoteScoreAll(
            ATF::Voter * pObj,
            char byRace,
            ATF::Info::Voter_SendVoteScoreAll18_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto instance = GetModule<CVote>();
            if (!instance->score_list_show())
                return;

            if (pObj->_kCandidateInfo[byRace].byCnt < 2)
                return;

            char pbyType[2]{ 56, 6 };
            ATF::_pt_notify_vote_score_zocl info;
            memcpy_s(
                &info, sizeof(info),
                &pObj->_kVoteScoreInfo[byRace],
                sizeof(pObj->_kVoteScoreInfo[byRace]));

            if (!instance->score_hide())
            {
                info.byVoteRate = 0;
                info.byNonvoteRate = 0;
                for (auto& b : info.body)
                    b.byScoreRate = 0;
            }

            for (int i = 0; i < MAX_PLAYER; ++i)
            {
                auto& player = ATF::Global::g_Player[i];
                if (!player.m_bOper)
                    continue;

                if (player.m_Param.GetRaceCode() != byRace)
                    continue;

                ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(i, pbyType, (char *)&info, info.size());
            }
        }

        int WINAPIV CVote::_Vote(
            ATF::Voter * pObj,
            ATF::CPlayer * pOne,
            char * pdata,
            ATF::Info::Voter_Vote22_ptr next)
        {
            auto instance = GetModule<CVote>();
            if (instance->check_conditions(pOne))
                return next(pObj, pOne, pdata);
            else
                return 10;
        }
    }
}<commit_msg>[Vote] Fixed bug in config<commit_after>#include "stdafx.h"

#include "Vote.h"
#include "ETypes.h"
#include <ATF/global.hpp>
#include <ATF/PatriarchElectProcessor.hpp>
#include <ATF/CandidateMgr.hpp>
#include <ATF/_pt_notify_vote_score_zocl.hpp>

namespace GameServer
{
    namespace Fixes
    {
        void CVote::load()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.set_hook(&ATF::Voter::_Vote, &CVote::_Vote);
            core.set_hook(&ATF::Voter::_SendVotePaper, &CVote::_SendVotePaper);
            core.set_hook(&ATF::Voter::_SendVotePaperAll, &CVote::_SendVotePaperAll);
            core.set_hook(&ATF::Voter::_SendVoteScore, &CVote::_SendVoteScore);
            core.set_hook(&ATF::Voter::_SendVoteScoreAll, &CVote::_SendVoteScoreAll);
        }

        void CVote::unload()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.unset_hook(&ATF::Voter::_Vote);
            core.unset_hook(&ATF::Voter::_SendVotePaper);
            core.unset_hook(&ATF::Voter::_SendVotePaperAll);
            core.unset_hook(&ATF::Voter::_SendVoteScore);
            core.unset_hook(&ATF::Voter::_SendVoteScoreAll);
        }

        void CVote::loop()
        {
        }

        ModuleVersion_t CVote::get_version()
        {
            return ATF::usVersion;
        }

        ModuleName_t CVote::get_name()
        {
            static const ModuleName_t name = "fix_Vote";
            return name;
        }

        void CVote::configure(
            const rapidjson::Value & nodeConfig)
        {
            m_nLv = nodeConfig["level"].GetInt();
            m_nPlayTime = nodeConfig["play_time"].GetInt();
            m_dPvpPoint = nodeConfig["pvp_point"].GetDouble();
            m_dPvpCashBag = nodeConfig["pvp_cash_bag"].GetDouble();
            m_nClassGrade = nodeConfig["class_grade"].GetInt();
            m_bScoreListShow = nodeConfig["score_list_show"].GetBool();
            m_bScoreHide = nodeConfig["score_hide"].GetBool();
        }

        bool CVote::check_conditions(
            ATF::CPlayer * pOne)
        {
            bool result = false;

            do
            {
                if (!pOne || !pOne->m_bOper)
                    break;

                if (!pOne->m_pUserDB->m_AvatorData.dbSupplement.VoteEnable)
                    break;

                if (get_class_grade() > pOne->m_pUserDB->m_AvatorData.dbAvator.m_byLastClassGrade)
                    break;

                if (get_level() > pOne->GetLevel())
                    break;

                if (get_pvp_cash_bag() > pOne->GetPvpOrderView()->GetPvpCash())
                    break;

                if (get_pvp_point() > pOne->m_Param.GetPvPPoint())
                    break;

                if (get_play_time() > pOne->m_pUserDB->m_AvatorData.dbSupplement.dwAccumPlayTime)
                    break;

                result = true;
            } while (false);

            return result;
        }

        int WINAPIV CVote::_SendVotePaper(
            ATF::Voter * pObj,
            ATF::CPlayer * pOne,
            ATF::Info::Voter_SendVotePaper12_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto spModule = GetModule<CVote>();
            int result = 0;

            do
            {
                if (!pOne)
                    break;

                if (!pOne->m_bOper)
                    break;

                if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)
                {
                    auto instance = ATF::PatriarchElectProcessor::Instance();
                    instance->SendMsg_ResultCode(pOne->m_id.wIndex, 8);
                    result = 9;
                    break;
                }

                if (pOne->m_pUserDB->m_AvatorData.dbAvator.m_bOverlapVote)
                {
                    result = 10;
                    break;
                }

                if (!spModule->check_conditions(pOne))
                {
                    result = 11;
                    break;
                }

                auto instance = ATF::CandidateMgr::Instance();
                if (instance->IsRegistedAvator_2(pOne->m_Param.GetRaceCode(), pOne->m_Param.GetCharSerial()))
                {
                    result = 11;
                    break;
                }

                char pbyType[2]{ 56, 5 };
                auto msg = &pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()];
                ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)msg, msg->size());
            } while (false);

            return result;
        }

        void WINAPIV CVote::_SendVotePaperAll(
            ATF::Voter * pObj,
            ATF::Info::Voter_SendVotePaperAll14_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            for (auto& player : ATF::Global::g_Player)
            {
                _SendVotePaper(pObj, &player, nullptr);
            }
        }

        void WINAPIV CVote::_SendVoteScore(
            ATF::Voter * pObj,
            ATF::CPlayer * pOne,
            ATF::Info::Voter_SendVoteScore16_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto instance = GetModule<CVote>();
            if (!instance->score_list_show())
                return;

            if (pObj->_kCandidateInfo[pOne->m_Param.GetRaceCode()].byCnt < 2)
                return;

            char pbyType[2]{ 56, 6 };
            ATF::_pt_notify_vote_score_zocl info;
            memcpy_s(
                &info, sizeof(info),
                &pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()],
                sizeof(pObj->_kVoteScoreInfo[pOne->m_Param.GetRaceCode()]));

            if (instance->score_hide())
            {
                info.byVoteRate = 0;
                info.byNonvoteRate = 0;
                for (auto& b : info.body)
                    b.byScoreRate = 0;
            }

            ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(pOne->m_ObjID.m_wIndex, pbyType, (char *)&info, info.size());
        }

        void WINAPIV CVote::_SendVoteScoreAll(
            ATF::Voter * pObj,
            char byRace,
            ATF::Info::Voter_SendVoteScoreAll18_ptr next)
        {
            UNREFERENCED_PARAMETER(next);

            auto instance = GetModule<CVote>();
            if (!instance->score_list_show())
                return;

            if (pObj->_kCandidateInfo[byRace].byCnt < 2)
                return;

            char pbyType[2]{ 56, 6 };
            ATF::_pt_notify_vote_score_zocl info;
            memcpy_s(
                &info, sizeof(info),
                &pObj->_kVoteScoreInfo[byRace],
                sizeof(pObj->_kVoteScoreInfo[byRace]));

            if (instance->score_hide())
            {
                info.byVoteRate = 0;
                info.byNonvoteRate = 0;
                for (auto& b : info.body)
                    b.byScoreRate = 0;
            }

            for (int i = 0; i < MAX_PLAYER; ++i)
            {
                auto& player = ATF::Global::g_Player[i];
                if (!player.m_bOper)
                    continue;

                if (player.m_Param.GetRaceCode() != byRace)
                    continue;

                ATF::Global::g_NetProcess[(uint8_t)e_type_line::client]->LoadSendMsg(i, pbyType, (char *)&info, info.size());
            }
        }

        int WINAPIV CVote::_Vote(
            ATF::Voter * pObj,
            ATF::CPlayer * pOne,
            char * pdata,
            ATF::Info::Voter_Vote22_ptr next)
        {
            auto instance = GetModule<CVote>();
            if (instance->check_conditions(pOne))
                return next(pObj, pOne, pdata);
            else
                return 10;
        }
    }
}<|endoftext|>


<commit_before>/*!
 *  Copyright (c) 2015 by Contributors
 * \file iter_csv.cc
 * \brief define a CSV Reader to read in arrays
 */
#include <mxnet/io.h>
#include <dmlc/base.h>
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <dmlc/data.h>
#include "./iter_prefetcher.h"
#include "./iter_batchloader.h"

namespace mxnet {
namespace io {
// CSV parameters
struct CSVIterParam : public dmlc::Parameter<CSVIterParam> {
  /*! \brief path to data csv file */
  std::string data_csv;
  /*! \brief data shape */
  TShape data_shape;
  /*! \brief path to label csv file */
  std::string label_csv;
  /*! \brief label shape */
  TShape label_shape;
  // declare parameters
  DMLC_DECLARE_PARAMETER(CSVIterParam) {
    DMLC_DECLARE_FIELD(data_csv)
        .describe("The input CSV file or a directory path.");
    DMLC_DECLARE_FIELD(data_shape)
        .describe("The shape of one example.");
    DMLC_DECLARE_FIELD(label_csv).set_default("NULL")
        .describe("The input CSV file or a directory path. "
                  "If NULL, all labels will be returned as 0.");
    index_t shape1[] = {1};
    DMLC_DECLARE_FIELD(label_shape).set_default(TShape(shape1, shape1 + 1))
        .describe("The shape of one label.");
  }
};

class CSVIter: public IIterator<DataInst> {
 public:
  CSVIter() {
    out_.data.resize(2);
  }
  virtual ~CSVIter() {}

  // intialize iterator loads data in
  virtual void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) {
    param_.InitAllowUnknown(kwargs);
    data_parser_.reset(dmlc::Parser<uint32_t>::Create(param_.data_csv.c_str(), 0, 1, "csv"));
    if (param_.label_csv != "NULL") {
      label_parser_.reset(dmlc::Parser<uint32_t>::Create(param_.label_csv.c_str(), 0, 1, "csv"));
    } else {
      dummy_label.set_pad(false);
      dummy_label.Resize(mshadow::Shape1(1));
      dummy_label = 0.0f;
    }
  }

  virtual void BeforeFirst() {
    data_parser_->BeforeFirst();
    if (label_parser_.get() != nullptr) {
      label_parser_->BeforeFirst();
    }
    data_ptr_ = label_ptr_ = 0;
    data_size_ = label_size_ = 0;
    inst_counter_ = 0;
    end_ = false;
  }

  virtual bool Next() {
    if (end_) return false;
    while (data_ptr_ >= data_size_) {
      if (!data_parser_->Next()) {
        end_ = true; return false;
      }
      data_ptr_ = 0;
      data_size_ = data_parser_->Value().size;
    }
    out_.index = inst_counter_++;
    CHECK_LT(data_ptr_, data_size_);
    out_.data[0] = AsTBlob(data_parser_->Value()[data_ptr_++], param_.data_shape);

    if (label_parser_.get() != nullptr) {
      while (label_ptr_ >= label_size_) {
        CHECK(label_parser_->Next())
            << "Data CSV's row is smaller than the number of rows in label_csv";
        label_ptr_ = 0;
        label_size_ = label_parser_->Value().size;
      }
      CHECK_LT(label_ptr_, label_size_);
      out_.data[1] = AsTBlob(label_parser_->Value()[label_ptr_++], param_.label_shape);
    } else {
      out_.data[1] = dummy_label;
    }
    return true;
  }

  virtual const DataInst &Value(void) const {
    return out_;
  }

 private:
  inline TBlob AsTBlob(const dmlc::Row<uint32_t>& row, const TShape& shape) {
    CHECK_EQ(row.length, shape.Size())
        << "The data size in CSV do not match size of shape: "
        << "specified shape=" << shape << ", the csv row-length=" << row.length;
    const real_t* ptr = row.value;
    return TBlob((real_t*)ptr, shape, cpu::kDevMask);  // NOLINT(*)
  }

  CSVIterParam param_;
  // output instance
  DataInst out_;
  // internal instance counter
  unsigned inst_counter_{0};
  // at end
  bool end_{false};
  // dummy label
  mshadow::TensorContainer<cpu, 1, real_t> dummy_label;
  // label parser
  size_t label_ptr_{0}, label_size_{0};
  size_t data_ptr_{0}, data_size_{0};
  std::unique_ptr<dmlc::Parser<uint32_t> > label_parser_;
  std::unique_ptr<dmlc::Parser<uint32_t> > data_parser_;
};

DMLC_REGISTER_PARAMETER(CSVIterParam);

MXNET_REGISTER_IO_ITER(CSVIter)
.describe(R"code(Returns the CSV file iterator.

In this function, the `data_shape` parameter is used to set the shape of each line of the input data.
If a row in an input file is `1,2,3,4,5,6`` and `data_shape` is (3,2), that row
will be reshaped, yielding the array [[1,2],[3,4],[5,6]] of shape (3,2).

By default, the `CSVIter` has `round_batch` parameter set to ``True``. So, if `batch_size`
is 3 and there are 4 total rows in CSV file, 2 more examples
are consumed at the first round. If `reset` function is called after first round,
the call is ignored and remaining examples are returned in the second round.

If one wants all the instances in the second round after calling `reset`, make sure
to set `round_batch` to False.

If ``data_csv = 'data/'`` is set, then all the files in this directory will be read.

Examples::

  // Contents of CSV file ``data/data.csv``.
  1,2,3
  2,3,4
  3,4,5
  4,5,6

  // Creates a `CSVIter` with `batch_size`=2 and default `round_batch`=True.
  CSVIter = mx.io.CSVIter(data_csv = 'data/data.csv', data_shape = (3,),
  batch_size = 2)

  // Two batches read from the above iterator are as follows:
  [[ 1.  2.  3.]
  [ 2.  3.  4.]]
  [[ 3.  4.  5.]
  [ 4.  5.  6.]]

  // Creates a `CSVIter` with `round_batch` set to False.
  CSVIter = mx.io.CSVIter(data_csv = 'data/data.csv', data_shape = (3,),
  batch_size = 3)

  // Two batches read from the above iterator in the first pass are as follows:
  [[1.  2.  3.]
  [2.  3.  4.]
  [3.  4.  5.]]

  [[4.  5.  6.]
  [2.  3.  4.]
  [3.  4.  5.]]

  // Now, `reset` method is called.
  CSVIter.reset()

  // Batch read from the above iterator in the second pass is as follows:
  [[ 3.  4.  5.]
  [ 4.  5.  6.]
  [ 1.  2.  3.]]

  // Creates a `CSVIter` with `round_batch`=False.
  CSVIter = mx.io.CSVIter(data_csv = 'data/data.csv', data_shape = (3,),
  batch_size = 3, round_batch=True)

  // Contents of two batches read from the above iterator in both passes after calling
  // `reset` method before second pass is as follows:
  [[1.  2.  3.]
  [2.  3.  4.]
  [3.  4.  5.]]

  [[4.  5.  6.]
  [2.  3.  4.]
  [3.  4.  5.]]

)code" ADD_FILELINE)
.add_arguments(CSVIterParam::__FIELDS__())
.add_arguments(BatchParam::__FIELDS__())
.add_arguments(PrefetcherParam::__FIELDS__())
.set_body([]() {
    return new PrefetcherIter(
        new BatchLoader(
            new CSVIter()));
  });

}  // namespace io
}  // namespace mxnet
<commit_msg>Correction (#6444)<commit_after>/*!
 *  Copyright (c) 2015 by Contributors
 * \file iter_csv.cc
 * \brief define a CSV Reader to read in arrays
 */
#include <mxnet/io.h>
#include <dmlc/base.h>
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <dmlc/data.h>
#include "./iter_prefetcher.h"
#include "./iter_batchloader.h"

namespace mxnet {
namespace io {
// CSV parameters
struct CSVIterParam : public dmlc::Parameter<CSVIterParam> {
  /*! \brief path to data csv file */
  std::string data_csv;
  /*! \brief data shape */
  TShape data_shape;
  /*! \brief path to label csv file */
  std::string label_csv;
  /*! \brief label shape */
  TShape label_shape;
  // declare parameters
  DMLC_DECLARE_PARAMETER(CSVIterParam) {
    DMLC_DECLARE_FIELD(data_csv)
        .describe("The input CSV file or a directory path.");
    DMLC_DECLARE_FIELD(data_shape)
        .describe("The shape of one example.");
    DMLC_DECLARE_FIELD(label_csv).set_default("NULL")
        .describe("The input CSV file or a directory path. "
                  "If NULL, all labels will be returned as 0.");
    index_t shape1[] = {1};
    DMLC_DECLARE_FIELD(label_shape).set_default(TShape(shape1, shape1 + 1))
        .describe("The shape of one label.");
  }
};

class CSVIter: public IIterator<DataInst> {
 public:
  CSVIter() {
    out_.data.resize(2);
  }
  virtual ~CSVIter() {}

  // intialize iterator loads data in
  virtual void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) {
    param_.InitAllowUnknown(kwargs);
    data_parser_.reset(dmlc::Parser<uint32_t>::Create(param_.data_csv.c_str(), 0, 1, "csv"));
    if (param_.label_csv != "NULL") {
      label_parser_.reset(dmlc::Parser<uint32_t>::Create(param_.label_csv.c_str(), 0, 1, "csv"));
    } else {
      dummy_label.set_pad(false);
      dummy_label.Resize(mshadow::Shape1(1));
      dummy_label = 0.0f;
    }
  }

  virtual void BeforeFirst() {
    data_parser_->BeforeFirst();
    if (label_parser_.get() != nullptr) {
      label_parser_->BeforeFirst();
    }
    data_ptr_ = label_ptr_ = 0;
    data_size_ = label_size_ = 0;
    inst_counter_ = 0;
    end_ = false;
  }

  virtual bool Next() {
    if (end_) return false;
    while (data_ptr_ >= data_size_) {
      if (!data_parser_->Next()) {
        end_ = true; return false;
      }
      data_ptr_ = 0;
      data_size_ = data_parser_->Value().size;
    }
    out_.index = inst_counter_++;
    CHECK_LT(data_ptr_, data_size_);
    out_.data[0] = AsTBlob(data_parser_->Value()[data_ptr_++], param_.data_shape);

    if (label_parser_.get() != nullptr) {
      while (label_ptr_ >= label_size_) {
        CHECK(label_parser_->Next())
            << "Data CSV's row is smaller than the number of rows in label_csv";
        label_ptr_ = 0;
        label_size_ = label_parser_->Value().size;
      }
      CHECK_LT(label_ptr_, label_size_);
      out_.data[1] = AsTBlob(label_parser_->Value()[label_ptr_++], param_.label_shape);
    } else {
      out_.data[1] = dummy_label;
    }
    return true;
  }

  virtual const DataInst &Value(void) const {
    return out_;
  }

 private:
  inline TBlob AsTBlob(const dmlc::Row<uint32_t>& row, const TShape& shape) {
    CHECK_EQ(row.length, shape.Size())
        << "The data size in CSV do not match size of shape: "
        << "specified shape=" << shape << ", the csv row-length=" << row.length;
    const real_t* ptr = row.value;
    return TBlob((real_t*)ptr, shape, cpu::kDevMask);  // NOLINT(*)
  }

  CSVIterParam param_;
  // output instance
  DataInst out_;
  // internal instance counter
  unsigned inst_counter_{0};
  // at end
  bool end_{false};
  // dummy label
  mshadow::TensorContainer<cpu, 1, real_t> dummy_label;
  // label parser
  size_t label_ptr_{0}, label_size_{0};
  size_t data_ptr_{0}, data_size_{0};
  std::unique_ptr<dmlc::Parser<uint32_t> > label_parser_;
  std::unique_ptr<dmlc::Parser<uint32_t> > data_parser_;
};

DMLC_REGISTER_PARAMETER(CSVIterParam);

MXNET_REGISTER_IO_ITER(CSVIter)
.describe(R"code(Returns the CSV file iterator.

In this function, the `data_shape` parameter is used to set the shape of each line of the input data.
If a row in an input file is `1,2,3,4,5,6`` and `data_shape` is (3,2), that row
will be reshaped, yielding the array [[1,2],[3,4],[5,6]] of shape (3,2).

By default, the `CSVIter` has `round_batch` parameter set to ``True``. So, if `batch_size`
is 3 and there are 4 total rows in CSV file, 2 more examples
are consumed at the first round. If `reset` function is called after first round,
the call is ignored and remaining examples are returned in the second round.

If one wants all the instances in the second round after calling `reset`, make sure
to set `round_batch` to False.

If ``data_csv = 'data/'`` is set, then all the files in this directory will be read.

Examples::

  // Contents of CSV file ``data/data.csv``.
  1,2,3
  2,3,4
  3,4,5
  4,5,6

  // Creates a `CSVIter` with `batch_size`=2 and default `round_batch`=True.
  CSVIter = mx.io.CSVIter(data_csv = 'data/data.csv', data_shape = (3,),
  batch_size = 2)

  // Two batches read from the above iterator are as follows:
  [[ 1.  2.  3.]
  [ 2.  3.  4.]]
  [[ 3.  4.  5.]
  [ 4.  5.  6.]]

  // Creates a `CSVIter` with default `round_batch` set to True.
  CSVIter = mx.io.CSVIter(data_csv = 'data/data.csv', data_shape = (3,),
  batch_size = 3)

  // Two batches read from the above iterator in the first pass are as follows:
  [[1.  2.  3.]
  [2.  3.  4.]
  [3.  4.  5.]]

  [[4.  5.  6.]
  [2.  3.  4.]
  [3.  4.  5.]]

  // Now, `reset` method is called.
  CSVIter.reset()

  // Batch read from the above iterator in the second pass is as follows:
  [[ 3.  4.  5.]
  [ 4.  5.  6.]
  [ 1.  2.  3.]]

  // Creates a `CSVIter` with `round_batch`=False.
  CSVIter = mx.io.CSVIter(data_csv = 'data/data.csv', data_shape = (3,),
  batch_size = 3, round_batch=False)

  // Contents of two batches read from the above iterator in both passes, after calling
  // `reset` method before second pass, is as follows:
  [[1.  2.  3.]
  [2.  3.  4.]
  [3.  4.  5.]]

  [[4.  5.  6.]
  [2.  3.  4.]
  [3.  4.  5.]]

)code" ADD_FILELINE)
.add_arguments(CSVIterParam::__FIELDS__())
.add_arguments(BatchParam::__FIELDS__())
.add_arguments(PrefetcherParam::__FIELDS__())
.set_body([]() {
    return new PrefetcherIter(
        new BatchLoader(
            new CSVIter()));
  });

}  // namespace io
}  // namespace mxnet
<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include "ircencoder_p.h"
#include <QTextCodec>

#ifdef HAVE_ICU
#include <unicode/ucsdet.h>
#endif // HAVE_ICU

IrcEncoder::IrcEncoder()
{
    d.detector = 0;
#ifdef HAVE_ICU
    UErrorCode status = U_ZERO_ERROR;
    d.detector = ucsdet_open(&status);
    if (U_FAILURE(status))
        qWarning("IrcEncoder: ICU initialization failed: %s", u_errorName(status));
#endif // HAVE_ICU
}

IrcEncoder::~IrcEncoder()
{
#ifdef HAVE_ICU
    ucsdet_close(d.detector);
#endif // HAVE_ICU
}

QString IrcEncoder::encode(const QByteArray& data) const
{
    QByteArray enc = d.encoding;
    if (enc.isNull())
        enc = detectEncoding(data);
    QTextCodec *codec = QTextCodec::codecForName(d.encoding);
    if (!codec)
        codec = QTextCodec::codecForLocale();
    return codec->toUnicode(data);
}

QByteArray IrcEncoder::detectEncoding(const QByteArray& data) const
{
    Q_UNUSED(data);
    QByteArray encoding;
#ifdef HAVE_ICU
    UErrorCode status = U_ZERO_ERROR;
    if (d.detector)
    {
        ucsdet_setText(d.detector, data.constData(), data.length(), &status);
        if (!U_FAILURE(status))
        {
            const UCharsetMatch* match = ucsdet_detect(d.detector, &status);
            if (match && !U_FAILURE(status))
                encoding = ucsdet_getName(match, &status);
        }
    }
    if (U_FAILURE(status))
        qWarning("IrcEncoder::detectEncoding() failed: %s", u_errorName(status));
#endif // HAVE_ICU
    return encoding;
}
<commit_msg>IrcEncoder: revised encoding auto-detection<commit_after>/*
* Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include "ircencoder_p.h"
#include <QTextCodec>

#ifdef HAVE_ICU
#include <unicode/ucsdet.h>
#endif // HAVE_ICU

static bool isUtf8(const QByteArray& utf8);

IrcEncoder::IrcEncoder()
{
    d.detector = 0;
#ifdef HAVE_ICU
    UErrorCode status = U_ZERO_ERROR;
    d.detector = ucsdet_open(&status);
    if (U_FAILURE(status))
        qWarning("IrcEncoder: ICU initialization failed: %s", u_errorName(status));
#endif // HAVE_ICU
}

IrcEncoder::~IrcEncoder()
{
#ifdef HAVE_ICU
    ucsdet_close(d.detector);
#endif // HAVE_ICU
}

QString IrcEncoder::encode(const QByteArray& data) const
{
    QByteArray enc = d.encoding;
    if (enc.isNull())
        enc = detectEncoding(data);
    QTextCodec *codec = QTextCodec::codecForName(enc);
    if (!codec)
        codec = QTextCodec::codecForLocale();
    return codec->toUnicode(data);
}

QByteArray IrcEncoder::detectEncoding(const QByteArray& data) const
{
    QByteArray encoding("ISO 8859-1");
    if (isUtf8(data))
        return "UTF-8";
#ifdef HAVE_ICU
    UErrorCode status = U_ZERO_ERROR;
    if (d.detector)
    {
        ucsdet_setText(d.detector, data.constData(), data.length(), &status);
        if (!U_FAILURE(status))
        {
            const UCharsetMatch* match = ucsdet_detect(d.detector, &status);
            if (match && !U_FAILURE(status))
                encoding = ucsdet_getName(match, &status);
        }
    }
    if (U_FAILURE(status))
        qWarning("IrcEncoder::detectEncoding() failed: %s", u_errorName(status));
#endif // HAVE_ICU
    return encoding;
}

/*
  The Original Code is mozilla.org code.
  See http://lxr.mozilla.org/mozilla/source/modules/rdf/src/utils.c

  Copyright (C) 1998 Netscape Communications Corporation
*/

#define kLeft1BitMask  0x80
#define kLeft2BitsMask 0xC0
#define kLeft3BitsMask 0xE0
#define kLeft4BitsMask 0xF0
#define kLeft5BitsMask 0xF8
#define kLeft6BitsMask 0xFC
#define kLeft7BitsMask 0xFE

#define k2BytesLeadByte kLeft2BitsMask
#define k3BytesLeadByte kLeft3BitsMask
#define k4BytesLeadByte kLeft4BitsMask
#define k5BytesLeadByte kLeft5BitsMask
#define k6BytesLeadByte kLeft6BitsMask
#define kTrialByte      kLeft1BitMask

#define UTF8_1Byte(c) ( 0 == ((c) & kLeft1BitMask))
#define UTF8_2Bytes(c) ( k2BytesLeadByte == ((c) & kLeft3BitsMask))
#define UTF8_3Bytes(c) ( k3BytesLeadByte == ((c) & kLeft4BitsMask))
#define UTF8_4Bytes(c) ( k4BytesLeadByte == ((c) & kLeft5BitsMask))
#define UTF8_5Bytes(c) ( k5BytesLeadByte == ((c) & kLeft6BitsMask))
#define UTF8_6Bytes(c) ( k6BytesLeadByte == ((c) & kLeft7BitsMask))
#define UTF8_ValidTrialByte(c) ( kTrialByte == ((c) & kLeft2BitsMask))

bool isUtf8(const QByteArray& utf8)
{
    int clen = 0;
    for (int i = 0; i < utf8.length(); i += clen)
    {
        if (UTF8_1Byte(utf8[i]))
        {
            clen = 1;
        }
        else if (UTF8_2Bytes(utf8[i]))
        {
            clen = 2;
            // No enough trail bytes
            if ((i + clen) > utf8.length())
                return false;
            // 0000 0000 - 0000 007F : should encode in less bytes
            if (0 ==  (utf8[i] & 0x1E))
                return false;
        }
        else if (UTF8_3Bytes(utf8[i]))
        {
            clen = 3;
            // No enough trail bytes
            if ((i + clen) > utf8.length())
                return false;
            // a single Surrogate should not show in 3 bytes UTF8, instead,
            // the pair should be intepreted as one single UCS4 char and
            // encoded UTF8 in 4 bytes
            if ((0xED == utf8[i]) && (0xA0 == (utf8[i+1] & 0xA0)))
                return false;
            // 0000 0000 - 0000 07FF : should encode in less bytes
            if ((0 == (utf8[i] & 0x0F)) && (0 == (utf8[i+1] & 0x20)))
                return false;
        }
        else if (UTF8_4Bytes(utf8[i]))
        {
            clen = 4;
            // No enough trail bytes
            if ((i + clen) > utf8.length())
                return false;
            // 0000 0000 - 0000 FFFF : should encode in less bytes
            if ((0 == (utf8[i] & 0x07 )) && (0 == (utf8[i+1] & 0x30)))
                return false;
        }
        else if (UTF8_5Bytes(utf8[i]))
        {
            clen = 5;
            // No enough trail bytes
            if ((i + clen) > utf8.length())
                return false;
            // 0000 0000 - 001F FFFF : should encode in less bytes
            if ((0 == (utf8[i] & 0x03 )) && (0 == (utf8[i+1] & 0x38)))
                return false;
        }
        else if (UTF8_6Bytes(utf8[i]))
        {
            clen = 6;
            // No enough trail bytes
            if ((i + clen) > utf8.length())
                return false;
            // 0000 0000 - 03FF FFFF : should encode in less bytes
            if ((0 == (utf8[i] & 0x01)) && (0 == (utf8[i+1] & 0x3E)))
                return false;
        }
        else
        {
            return false;
        }
        for (int j = 1; j < clen; ++j)
        {
            if (!UTF8_ValidTrialByte(utf8[i+j])) // Trail bytes invalid
                return false;
        }
    }
    return true;
}
<|endoftext|>