<commit_before>#ifndef REMOTE_LOGGING_HPP_
#define REMOTE_LOGGING_HPP_

#include <iostream>
#include <sstream>
#include <string>

namespace tmacam {

/** Make a UDP client socket connected to hostname:servname
 *
 * Errors returned by the syscalls used by this function are reported to
 * stderr.
 *
 * @return -1 in case of errors, a valid socket file descriptor otherwise.
 */
int MakeSocketFromAddr(const char* hostname, const char* servname);

/**Remote logging made easy with a std. stream-like interface.
 *
 * This class is to be used in place of std::cout for logging. But instead of
 * outputting (only) to the stdout, it will output to a remote
 * udp server. If no server is supplied or setup than it will just output
 * to std::cout.
 *
 * An optional prefix can be set and will be prepended to every message "logged"
 * using this class.
 *
 * Notice that, just as logging w/ printf's std::cout, this is a blocking
 * logging facility.
 *
 */
class RemoteLogging {

	int skt_; // the socket file descriptor
	std::string prefix_;
	std::ostringstream msg_buffer_;

public:
	//!Default constructor -- forces logging to stdout.
	RemoteLogging() : skt_(0), prefix_() {}

	/**Constructor
	 *
	 * @param host Hostname of the logging server.
	 * @param port Port or Serv. name of the logging server.
	 *
	 */
	RemoteLogging(const char* host, const char* port)
		: skt_(MakeSocketFromAddr(host, port)), prefix_() {}

	//!Destructor
	~RemoteLogging() {
		if (skt_) {
			close(skt_);
		}
	}

	std::string prefix() const;
	RemoteLogging& set_prefix(const std::string& prefix );

	RemoteLogging& set_loghost(const char* host, const char* port);

	/** Add msg to the log buffer.
	 *
	 * Output will be delayed untill Flush() is called. Applying a
	 * std::endl to us has the same effect of calling Flush().
	 *
	 */
	template <class T> RemoteLogging& operator<<(const T& msg) {
		msg_buffer_ << msg;
		return *this;
	}

	//! Force outputing the log buffer contents.
	RemoteLogging& Flush();

	// Deals with << endl in a sane manner.
	// http://bytes.com/topic/c/answers/128046-std-endl-type-unknown
	inline RemoteLogging& operator<<( std::ostream& (*f)(std::ostream&) ) {
		return this->Flush();
	}

private:
	// Disallow evil constructors
	RemoteLogging(const RemoteLogging&);
	RemoteLogging& operator=(const RemoteLogging&);
};

}; // namespace tmacam

#endif /* REMOTE_LOGGING_HPP_ */
<commit_msg>License added to .hpp<commit_after>#ifndef REMOTE_LOGGING_HPP_
#define REMOTE_LOGGING_HPP_

/* Copyright (c) 2009 Tiago Alves Macambira
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <sstream>
#include <string>

namespace tmacam {

/** Make a UDP client socket connected to hostname:servname
 *
 * Errors returned by the syscalls used by this function are reported to
 * stderr.
 *
 * @return -1 in case of errors, a valid socket file descriptor otherwise.
 */
int MakeSocketFromAddr(const char* hostname, const char* servname);

/**Remote logging made easy with a std. stream-like interface.
 *
 * This class is to be used in place of std::cout for logging. But instead of
 * outputting (only) to the stdout, it will output to a remote
 * udp server. If no server is supplied or setup than it will just output
 * to std::cout.
 *
 * An optional prefix can be set and will be prepended to every message "logged"
 * using this class.
 *
 * Notice that, just as logging w/ printf's std::cout, this is a blocking
 * logging facility.
 *
 */
class RemoteLogging {

	int skt_; // the socket file descriptor
	std::string prefix_;
	std::ostringstream msg_buffer_;

public:
	//!Default constructor -- forces logging to stdout.
	RemoteLogging() : skt_(0), prefix_() {}

	/**Constructor
	 *
	 * @param host Hostname of the logging server.
	 * @param port Port or Serv. name of the logging server.
	 *
	 */
	RemoteLogging(const char* host, const char* port)
		: skt_(MakeSocketFromAddr(host, port)), prefix_() {}

	//!Destructor
	~RemoteLogging() {
		if (skt_) {
			close(skt_);
		}
	}

	std::string prefix() const;
	RemoteLogging& set_prefix(const std::string& prefix );

	RemoteLogging& set_loghost(const char* host, const char* port);

	/** Add msg to the log buffer.
	 *
	 * Output will be delayed untill Flush() is called. Applying a
	 * std::endl to us has the same effect of calling Flush().
	 *
	 */
	template <class T> RemoteLogging& operator<<(const T& msg) {
		msg_buffer_ << msg;
		return *this;
	}

	//! Force outputing the log buffer contents.
	RemoteLogging& Flush();

	// Deals with << endl in a sane manner.
	// http://bytes.com/topic/c/answers/128046-std-endl-type-unknown
	inline RemoteLogging& operator<<( std::ostream& (*f)(std::ostream&) ) {
		return this->Flush();
	}

private:
	// Disallow evil constructors
	RemoteLogging(const RemoteLogging&);
	RemoteLogging& operator=(const RemoteLogging&);
};

}; // namespace tmacam

#endif /* REMOTE_LOGGING_HPP_ */
<|endoftext|>


<commit_before>#include <stdlib.h>
#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "braincloud/BrainCloudEntity.h"
#include "TestResult.h"
#include "json/json.h"
#include "braincloud/FriendPlatform.h"
#include "braincloud/AuthenticationType.h"
#include "TestBCFriend.h"
#include <vector>
#include <string>
#include "braincloud/reason_codes.h"
#include "braincloud/http_codes.h"

using namespace BrainCloud;

TEST_F(TestBCFriend, GetProfileInfoForCredential)
{
	TestResult tr;
	m_bc->getFriendService()->getProfileInfoForCredential(GetUser(UserA)->m_id, AuthenticationType::Universal, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, GetProfileInfoForExternalAuthId)
{
	TestResult tr;
	m_bc->getFriendService()->getProfileInfoForExternalAuthId(GetUser(UserA)->m_id, "failType", &tr);
	tr.runExpectFail(m_bc, 400, INVALID_CREDENTIAL);
}

TEST_F(TestBCFriend, GetExternalIdForProfileId)
{
	TestResult tr;
	m_bc->getFriendService()->getExternalIdForProfileId(GetUser(UserA)->m_profileId, "Facebook", &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersByExactName)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersByExactName("test", 10, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUserByExactUniversalId)
{
	TestResult tr;
	m_bc->getFriendService()->findUserByExactUniversalId("test", &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersByUniversalIdStartingWith)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersByUniversalIdStartingWith("test", 30, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersByNameStartingWith)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersByExactName("test", 30, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersBySubstrName)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersBySubstrName("test", 10, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, GetSummaryDataForProfileId)
{
	TestResult tr;
	m_bc->getFriendService()->getSummaryDataForProfileId(GetUser(UserA)->m_profileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, AddFriendsFromPlatform)
{
	TestResult tr;
	m_bc->getFriendService()->addFriendsFromPlatform(FriendPlatform::Facebook, "ADD", {}, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, AddFriends)
{
	AddFriends();
}

TEST_F(TestBCFriend, ListFriends)
{
	TestResult tr;
	m_bc->getFriendService()->listFriends(FriendPlatform::All, true, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, RemoveFriends)
{
	AddFriends();

	TestResult tr;
	std::vector<std::string> profiles;
	profiles.push_back(GetUser(UserB)->m_profileId);

	m_bc->getFriendService()->removeFriends(profiles, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, GetUsersOnlineStatus)
{
	TestResult tr;
	std::vector<std::string> profiles;
	profiles.push_back(GetUser(UserB)->m_profileId);

	m_bc->getFriendService()->getUsersOnlineStatus(profiles, &tr);
	tr.run(m_bc);
}

void TestBCFriend::AddFriends()
{
	TestResult tr;
	std::vector<std::string> profiles;
	profiles.push_back(GetUser(UserB)->m_profileId);

	m_bc->getFriendService()->addFriends(profiles, &tr);
	tr.run(m_bc);
}

<commit_msg>Fixed wrong reason in  GetProfileInfoForExternalAuthId test<commit_after>#include <stdlib.h>
#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "braincloud/BrainCloudEntity.h"
#include "TestResult.h"
#include "json/json.h"
#include "braincloud/FriendPlatform.h"
#include "braincloud/AuthenticationType.h"
#include "TestBCFriend.h"
#include <vector>
#include <string>
#include "braincloud/reason_codes.h"
#include "braincloud/http_codes.h"

using namespace BrainCloud;

TEST_F(TestBCFriend, GetProfileInfoForCredential)
{
	TestResult tr;
	m_bc->getFriendService()->getProfileInfoForCredential(GetUser(UserA)->m_id, AuthenticationType::Universal, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, GetProfileInfoForExternalAuthId)
{
	TestResult tr;
	m_bc->getFriendService()->getProfileInfoForExternalAuthId(GetUser(UserA)->m_id, "failType", &tr);
	tr.runExpectFail(m_bc, 400, INVALID_EXT_AUTH_TYPE);
}

TEST_F(TestBCFriend, GetExternalIdForProfileId)
{
	TestResult tr;
	m_bc->getFriendService()->getExternalIdForProfileId(GetUser(UserA)->m_profileId, "Facebook", &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersByExactName)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersByExactName("test", 10, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUserByExactUniversalId)
{
	TestResult tr;
	m_bc->getFriendService()->findUserByExactUniversalId("test", &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersByUniversalIdStartingWith)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersByUniversalIdStartingWith("test", 30, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersByNameStartingWith)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersByExactName("test", 30, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, FindUsersBySubstrName)
{
	TestResult tr;
	m_bc->getFriendService()->findUsersBySubstrName("test", 10, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, GetSummaryDataForProfileId)
{
	TestResult tr;
	m_bc->getFriendService()->getSummaryDataForProfileId(GetUser(UserA)->m_profileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, AddFriendsFromPlatform)
{
	TestResult tr;
	m_bc->getFriendService()->addFriendsFromPlatform(FriendPlatform::Facebook, "ADD", {}, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, AddFriends)
{
	AddFriends();
}

TEST_F(TestBCFriend, ListFriends)
{
	TestResult tr;
	m_bc->getFriendService()->listFriends(FriendPlatform::All, true, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, RemoveFriends)
{
	AddFriends();

	TestResult tr;
	std::vector<std::string> profiles;
	profiles.push_back(GetUser(UserB)->m_profileId);

	m_bc->getFriendService()->removeFriends(profiles, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCFriend, GetUsersOnlineStatus)
{
	TestResult tr;
	std::vector<std::string> profiles;
	profiles.push_back(GetUser(UserB)->m_profileId);

	m_bc->getFriendService()->getUsersOnlineStatus(profiles, &tr);
	tr.run(m_bc);
}

void TestBCFriend::AddFriends()
{
	TestResult tr;
	std::vector<std::string> profiles;
	profiles.push_back(GetUser(UserB)->m_profileId);

	m_bc->getFriendService()->addFriends(profiles, &tr);
	tr.run(m_bc);
}

<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <wiringPi.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define MAXTIMINGS  85
#define DHTPIN      0

namespace {

int dht11_dat[5] = { 0, 0, 0, 0, 0 };

void read_data(){
    uint8_t laststate   = HIGH;
    uint8_t counter     = 0;
    uint8_t j       = 0, i;
    float   f; /* fahrenheit */

    dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;

    /* pull pin down for 18 milliseconds */
    pinMode( DHTPIN, OUTPUT );
    digitalWrite( DHTPIN, LOW );
    delay( 18 );
    /* then pull it up for 40 microseconds */
    digitalWrite( DHTPIN, HIGH );
    delayMicroseconds( 40 );
    /* prepare to read the pin */
    pinMode( DHTPIN, INPUT );

    /* detect change and read data */
    for ( i = 0; i < MAXTIMINGS; i++ ){
        counter = 0;
        while ( digitalRead( DHTPIN ) == laststate ){
            counter++;
            delayMicroseconds( 1 );
            if ( counter == 255 )
            {
                break;
            }
        }

        laststate = digitalRead( DHTPIN );

        if ( counter == 255 ){
            break;
        }

        /* ignore first 3 transitions */
        if ( (i >= 4) && (i % 2 == 0) ){
            /* shove each bit into the storage bytes */
            dht11_dat[j / 8] <<= 1;
            if ( counter > 16 ){
                dht11_dat[j / 8] |= 1;
            }
            j++;
        }
    }

    /*
     * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
     * print it out if data is good
     */
    if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ){
        f = dht11_dat[2] * 9. / 5. + 32;
        printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
            dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
    } else {
        printf( "Data not good, skip\n" );
    }
}

bool revoke_root(){
    if (getuid() == 0) {
        if (setgid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl;
            return false;
        }

        if (setuid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl;
            return false;
        }
    }

    if (setuid(0) != -1){
        std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl;
        return false;
    }

    return true;
}

} //end of namespace

int main(){
    //Run the wiringPi setup (as root)
    wiringPiSetup();

    //Drop root privileges and run as pi:pi again
    if(!revoke_root()){
       std::cout << "asgard:dht11: unable to revoke root privileges, exiting..." << std::endl;
       return 1;
    }

    while (1){
        read_data();
        delay(1000);
    }

    return(0);
}
<commit_msg>Fix pin<commit_after>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <wiringPi.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define MAXTIMINGS  85
#define DHTPIN      2

namespace {

int dht11_dat[5] = { 0, 0, 0, 0, 0 };

void read_data(){
    uint8_t laststate   = HIGH;
    uint8_t counter     = 0;
    uint8_t j       = 0, i;
    float   f; /* fahrenheit */

    dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;

    /* pull pin down for 18 milliseconds */
    pinMode( DHTPIN, OUTPUT );
    digitalWrite( DHTPIN, LOW );
    delay( 18 );
    /* then pull it up for 40 microseconds */
    digitalWrite( DHTPIN, HIGH );
    delayMicroseconds( 40 );
    /* prepare to read the pin */
    pinMode( DHTPIN, INPUT );

    /* detect change and read data */
    for ( i = 0; i < MAXTIMINGS; i++ ){
        counter = 0;
        while ( digitalRead( DHTPIN ) == laststate ){
            counter++;
            delayMicroseconds( 1 );
            if ( counter == 255 )
            {
                break;
            }
        }

        laststate = digitalRead( DHTPIN );

        if ( counter == 255 ){
            break;
        }

        /* ignore first 3 transitions */
        if ( (i >= 4) && (i % 2 == 0) ){
            /* shove each bit into the storage bytes */
            dht11_dat[j / 8] <<= 1;
            if ( counter > 16 ){
                dht11_dat[j / 8] |= 1;
            }
            j++;
        }
    }

    /*
     * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
     * print it out if data is good
     */
    if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ){
        f = dht11_dat[2] * 9. / 5. + 32;
        printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
            dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
    } else {
        printf( "Data not good, skip\n" );
    }
}

bool revoke_root(){
    if (getuid() == 0) {
        if (setgid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl;
            return false;
        }

        if (setuid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl;
            return false;
        }
    }

    if (setuid(0) != -1){
        std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl;
        return false;
    }

    return true;
}

} //end of namespace

int main(){
    //Run the wiringPi setup (as root)
    wiringPiSetup();

    //Drop root privileges and run as pi:pi again
    if(!revoke_root()){
       std::cout << "asgard:dht11: unable to revoke root privileges, exiting..." << std::endl;
       return 1;
    }

    while (1){
        read_data();
        delay(1000);
    }

    return(0);
}
<|endoftext|>


<commit_before>#include "element.h"

#define internal static
#define local_persist static

/* TODO(koekeishiya): Required for compatibility with current Kwm code */
bool AXLibGetFocusedWindow(AXUIElementRef *WindowRef)
{
    local_persist AXUIElementRef SystemWideElement = AXUIElementCreateSystemWide();
    AXUIElementRef Application = (AXUIElementRef) AXLibGetWindowProperty(SystemWideElement, kAXFocusedApplicationAttribute);

    if(Application)
    {
        AXUIElementRef AppWindowRef = (AXUIElementRef) AXLibGetWindowProperty(Application, kAXFocusedWindowAttribute);
        CFRelease(Application);

        if(AppWindowRef)
        {
            *WindowRef = AppWindowRef;
            return true;
        }
    }

    return false;
}
/* --- END --- */

CFTypeRef AXLibGetWindowProperty(AXUIElementRef WindowRef, CFStringRef Property)
{
    CFTypeRef TypeRef;
    AXError Error = AXUIElementCopyAttributeValue(WindowRef, Property, &TypeRef);
    return (Error == kAXErrorSuccess) ? TypeRef : NULL;
}

AXError AXLibSetWindowProperty(AXUIElementRef WindowRef, CFStringRef Property, CFTypeRef Value)
{
    return AXUIElementSetAttributeValue(WindowRef, Property, Value);
}

bool AXLibIsWindowMinimized(AXUIElementRef WindowRef)
{
    bool Result = true;

    CFBooleanRef Value = (CFBooleanRef) AXLibGetWindowProperty(WindowRef, kAXMinimizedAttribute);
    if(Value)
    {
        Result = CFBooleanGetValue(Value);
        CFRelease(Value);
    }

    return Result;
}

bool AXLibIsWindowMovable(AXUIElementRef WindowRef)
{
    bool Result;

    AXError Error = AXUIElementIsAttributeSettable(WindowRef, kAXPositionAttribute, (Boolean*)&Result);
    if(Error != kAXErrorSuccess)
        Result = false;

    return Result;
}

bool AXLibIsWindowResizable(AXUIElementRef WindowRef)
{
    bool Result;

    AXError Error = AXUIElementIsAttributeSettable(WindowRef, kAXSizeAttribute, (Boolean*)&Result);
    if(Error != kAXErrorSuccess)
        Result = false;

    return Result;
}

bool AXLibSetWindowPosition(AXUIElementRef WindowRef, int X, int Y)
{
    bool Result = false;

    CGPoint WindowPos = CGPointMake(X, Y);
    CFTypeRef WindowPosRef = (CFTypeRef)AXValueCreate(kAXValueCGPointType, (const void*)&WindowPos);
    if(WindowPosRef)
    {
        Result = AXLibSetWindowProperty(WindowRef, kAXPositionAttribute, WindowPosRef);
        CFRelease(WindowPosRef);
    }

    return Result;
}

bool AXLibSetWindowSize(AXUIElementRef WindowRef, int Width, int Height)
{
    bool Result = false;

    CGSize WindowSize = CGSizeMake(Width, Height);
    CFTypeRef WindowSizeRef = (CFTypeRef)AXValueCreate(kAXValueCGSizeType, (void*)&WindowSize);
    if(WindowSizeRef)
    {
        Result = AXLibSetWindowProperty(WindowRef, kAXSizeAttribute, WindowSizeRef);
        CFRelease(WindowSizeRef);
    }

    return Result;
}

uint32_t AXLibGetWindowID(AXUIElementRef WindowRef)
{
    uint32_t WindowID = kCGNullWindowID;
    _AXUIElementGetWindow(WindowRef, &WindowID);
    return WindowID;
}

std::string AXLibGetWindowTitle(AXUIElementRef WindowRef)
{
    CFStringRef WindowTitleRef = (CFStringRef) AXLibGetWindowProperty(WindowRef, kAXTitleAttribute);
    std::string WindowTitle;

    if(WindowTitleRef)
    {
        WindowTitle = GetUTF8String(WindowTitleRef);
        if(WindowTitle.empty())
            WindowTitle = CFStringGetCStringPtr(WindowTitleRef, kCFStringEncodingMacRoman);

        CFRelease(WindowTitleRef);
    }

    return WindowTitle;
}

CGPoint AXLibGetWindowPosition(AXUIElementRef WindowRef)
{
    CGPoint WindowPos = {};
    AXValueRef WindowPosRef = (AXValueRef) AXLibGetWindowProperty(WindowRef, kAXPositionAttribute);

    if(WindowPosRef)
    {
        AXValueGetValue(WindowPosRef, kAXValueCGPointType, &WindowPos);
        CFRelease(WindowPosRef);
    }

    return WindowPos;
}

CGSize AXLibGetWindowSize(AXUIElementRef WindowRef)
{
    CGSize WindowSize = {};
    AXValueRef WindowSizeRef = (AXValueRef) AXLibGetWindowProperty(WindowRef, kAXSizeAttribute);

    if(WindowSizeRef)
    {
        AXValueGetValue(WindowSizeRef, kAXValueCGSizeType, &WindowSize);
        CFRelease(WindowSizeRef);
    }

    return WindowSize;
}

bool AXLibGetWindowRole(AXUIElementRef WindowRef, CFTypeRef *Role)
{
    *Role = AXLibGetWindowProperty(WindowRef, kAXRoleAttribute);
    return *Role != NULL;
}

bool AXLibGetWindowSubrole(AXUIElementRef WindowRef, CFTypeRef *Subrole)
{
    *Subrole = AXLibGetWindowProperty(WindowRef, kAXSubroleAttribute);
    return *Subrole != NULL;
}

/*
void AXLibParseWindowInfo(const void *Key, const void *Value, void *Context)
{
    CFStringRef K = (CFStringRef)Key;
    std::string KeyStr = CFStringGetCStringPtr(K, kCFStringEncodingMacRoman);
    CFTypeID ID = CFGetTypeID(Value);
    if(ID == CFStringGetTypeID())
    {
        CFStringRef V = (CFStringRef)Value;
        std::string ValueStr = GetUTF8String(V);
        if(ValueStr.empty() && CFStringGetCStringPtr(V, kCFStringEncodingMacRoman))
            ValueStr = CFStringGetCStringPtr(V, kCFStringEncodingMacRoman);

        if(KeyStr == "kCGWindowName")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].Name = ValueStr;
        else if(KeyStr == "kCGWindowOwnerName")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].Owner = ValueStr;
    }
    else if(ID == CFNumberGetTypeID())
    {
        int MyInt;
        CFNumberRef V = (CFNumberRef)Value;
        CFNumberGetValue(V, kCFNumberSInt64Type, &MyInt);
        if(KeyStr == "kCGWindowNumber")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].WID = MyInt;
        else if(KeyStr == "kCGWindowOwnerPID")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].PID = MyInt;
        else if(KeyStr == "kCGWindowLayer")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].Layer = MyInt;
        else if(KeyStr == "X")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].X = MyInt;
        else if(KeyStr == "Y")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].Y = MyInt;
        else if(KeyStr == "Width")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].Width = MyInt;
        else if(KeyStr == "Height")
            KWMTiling.WindowLst[KWMTiling.WindowLst.size()-1].Height = MyInt;
    }
    else if(ID == CFDictionaryGetTypeID())
    {
        CFDictionaryRef Elem = (CFDictionaryRef)Value;
        CFDictionaryApplyFunction(Elem, GetWindowInfo, NULL);
    }
}
*/

std::string
GetUTF8String(CFStringRef Temp)
{
    std::string Result;

    if(!CFStringGetCStringPtr(Temp, kCFStringEncodingUTF8))
    {
        CFIndex Length = CFStringGetLength(Temp);
        CFIndex Bytes = 4 * Length + 1;
        char *TempUTF8StringPtr = (char*) malloc(Bytes);

        CFStringGetCString(Temp, TempUTF8StringPtr, Bytes, kCFStringEncodingUTF8);
        if(TempUTF8StringPtr)
        {
            Result = TempUTF8StringPtr;
            free(TempUTF8StringPtr);
        }
    }

    return Result;
}
<commit_msg>remove unnecessary function<commit_after>#include "element.h"

#define internal static
#define local_persist static

/* TODO(koekeishiya): Required for compatibility with current Kwm code */
bool AXLibGetFocusedWindow(AXUIElementRef *WindowRef)
{
    local_persist AXUIElementRef SystemWideElement = AXUIElementCreateSystemWide();
    AXUIElementRef Application = (AXUIElementRef) AXLibGetWindowProperty(SystemWideElement, kAXFocusedApplicationAttribute);

    if(Application)
    {
        AXUIElementRef AppWindowRef = (AXUIElementRef) AXLibGetWindowProperty(Application, kAXFocusedWindowAttribute);
        CFRelease(Application);

        if(AppWindowRef)
        {
            *WindowRef = AppWindowRef;
            return true;
        }
    }

    return false;
}
/* --- END --- */

CFTypeRef AXLibGetWindowProperty(AXUIElementRef WindowRef, CFStringRef Property)
{
    CFTypeRef TypeRef;
    AXError Error = AXUIElementCopyAttributeValue(WindowRef, Property, &TypeRef);
    return (Error == kAXErrorSuccess) ? TypeRef : NULL;
}

AXError AXLibSetWindowProperty(AXUIElementRef WindowRef, CFStringRef Property, CFTypeRef Value)
{
    return AXUIElementSetAttributeValue(WindowRef, Property, Value);
}

bool AXLibIsWindowMinimized(AXUIElementRef WindowRef)
{
    bool Result = true;

    CFBooleanRef Value = (CFBooleanRef) AXLibGetWindowProperty(WindowRef, kAXMinimizedAttribute);
    if(Value)
    {
        Result = CFBooleanGetValue(Value);
        CFRelease(Value);
    }

    return Result;
}

bool AXLibIsWindowMovable(AXUIElementRef WindowRef)
{
    bool Result;

    AXError Error = AXUIElementIsAttributeSettable(WindowRef, kAXPositionAttribute, (Boolean*)&Result);
    if(Error != kAXErrorSuccess)
        Result = false;

    return Result;
}

bool AXLibIsWindowResizable(AXUIElementRef WindowRef)
{
    bool Result;

    AXError Error = AXUIElementIsAttributeSettable(WindowRef, kAXSizeAttribute, (Boolean*)&Result);
    if(Error != kAXErrorSuccess)
        Result = false;

    return Result;
}

bool AXLibSetWindowPosition(AXUIElementRef WindowRef, int X, int Y)
{
    bool Result = false;

    CGPoint WindowPos = CGPointMake(X, Y);
    CFTypeRef WindowPosRef = (CFTypeRef)AXValueCreate(kAXValueCGPointType, (const void*)&WindowPos);
    if(WindowPosRef)
    {
        Result = AXLibSetWindowProperty(WindowRef, kAXPositionAttribute, WindowPosRef);
        CFRelease(WindowPosRef);
    }

    return Result;
}

bool AXLibSetWindowSize(AXUIElementRef WindowRef, int Width, int Height)
{
    bool Result = false;

    CGSize WindowSize = CGSizeMake(Width, Height);
    CFTypeRef WindowSizeRef = (CFTypeRef)AXValueCreate(kAXValueCGSizeType, (void*)&WindowSize);
    if(WindowSizeRef)
    {
        Result = AXLibSetWindowProperty(WindowRef, kAXSizeAttribute, WindowSizeRef);
        CFRelease(WindowSizeRef);
    }

    return Result;
}

uint32_t AXLibGetWindowID(AXUIElementRef WindowRef)
{
    uint32_t WindowID = kCGNullWindowID;
    _AXUIElementGetWindow(WindowRef, &WindowID);
    return WindowID;
}

std::string AXLibGetWindowTitle(AXUIElementRef WindowRef)
{
    CFStringRef WindowTitleRef = (CFStringRef) AXLibGetWindowProperty(WindowRef, kAXTitleAttribute);
    std::string WindowTitle;

    if(WindowTitleRef)
    {
        WindowTitle = GetUTF8String(WindowTitleRef);
        if(WindowTitle.empty())
            WindowTitle = CFStringGetCStringPtr(WindowTitleRef, kCFStringEncodingMacRoman);

        CFRelease(WindowTitleRef);
    }

    return WindowTitle;
}

CGPoint AXLibGetWindowPosition(AXUIElementRef WindowRef)
{
    CGPoint WindowPos = {};
    AXValueRef WindowPosRef = (AXValueRef) AXLibGetWindowProperty(WindowRef, kAXPositionAttribute);

    if(WindowPosRef)
    {
        AXValueGetValue(WindowPosRef, kAXValueCGPointType, &WindowPos);
        CFRelease(WindowPosRef);
    }

    return WindowPos;
}

CGSize AXLibGetWindowSize(AXUIElementRef WindowRef)
{
    CGSize WindowSize = {};
    AXValueRef WindowSizeRef = (AXValueRef) AXLibGetWindowProperty(WindowRef, kAXSizeAttribute);

    if(WindowSizeRef)
    {
        AXValueGetValue(WindowSizeRef, kAXValueCGSizeType, &WindowSize);
        CFRelease(WindowSizeRef);
    }

    return WindowSize;
}

bool AXLibGetWindowRole(AXUIElementRef WindowRef, CFTypeRef *Role)
{
    *Role = AXLibGetWindowProperty(WindowRef, kAXRoleAttribute);
    return *Role != NULL;
}

bool AXLibGetWindowSubrole(AXUIElementRef WindowRef, CFTypeRef *Subrole)
{
    *Subrole = AXLibGetWindowProperty(WindowRef, kAXSubroleAttribute);
    return *Subrole != NULL;
}

std::string
GetUTF8String(CFStringRef Temp)
{
    std::string Result;

    if(!CFStringGetCStringPtr(Temp, kCFStringEncodingUTF8))
    {
        CFIndex Length = CFStringGetLength(Temp);
        CFIndex Bytes = 4 * Length + 1;
        char *TempUTF8StringPtr = (char*) malloc(Bytes);

        CFStringGetCString(Temp, TempUTF8StringPtr, Bytes, kCFStringEncodingUTF8);
        if(TempUTF8StringPtr)
        {
            Result = TempUTF8StringPtr;
            free(TempUTF8StringPtr);
        }
    }

    return Result;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <SDL.h>
#include <SDL2_gfxPrimitives.h>
#include "demoloop.h"
#include "helpers.h"
#include "hsl.h"
using namespace std;

float t = 0;
const float PI = 3.1459;
const float CYCLE_LENGTH = 10;

class Loop5 : public Demoloop {
public:
  Loop5() : Demoloop(150, 150, 150) {}

  void Update(float dt) {
    t += dt;

    const float RADIUS = height / 3;

    float cycle = fmod(t, CYCLE_LENGTH);
    float cycle_ratio = cycle / CYCLE_LENGTH;
    int ox = width / 2, oy = height / 2;

    const int num_vertices = 5;
    const float interval = (PI * 2) / num_vertices;
    int16_t xCoords[num_vertices];
    int16_t yCoords[num_vertices];
    for (int i = 0; i < num_vertices; ++i) {
      float t = i;
      xCoords[i] = cos(interval * t - PI / 10) * RADIUS + ox;
      yCoords[i] = sin(interval * t - PI / 10) * RADIUS + oy;
    }

    auto color = hsl2rgb(cycle_ratio, 1, 0.5);
    filledPolygonColor(renderer, xCoords, yCoords, num_vertices, rgb2uint32(color));
    const int dot_count = 20;
    for (int v = 0; v < num_vertices; ++v) {
      const float angularOffset = interval * v;
      for (float i = 0; i < dot_count; ++i) {
        const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

        const float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
        const float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;

        filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255 * interval_cycle_ratio);

        if (i == 0) {
          const float x2 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float y2 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          lineRGBA(renderer, x2 + ox, y2 + oy, xCoords[v], yCoords[v], 0, 0, 0, 255);
        }
      }
    }

    for (float i = 0; i < dot_count; ++i) {
      const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

      const float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;
      const float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;

      filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255);
    }
  }

private:
};

int main(int, char**){
  Loop5 loop;
  loop.Run();

  return 0;
}
<commit_msg>loop5 final<commit_after>#include <iostream>
#include <SDL.h>
#include <SDL2_gfxPrimitives.h>
#include "demoloop.h"
#include "helpers.h"
#include "hsl.h"
using namespace std;

float t = 0;
const float PI = 3.1459;
const float CYCLE_LENGTH = 10;

class Loop5 : public Demoloop {
public:
  Loop5() : Demoloop(150, 150, 150) {}

  void Update(float dt) {
    t += dt;

    const float RADIUS = height / 3;

    float cycle = fmod(t, CYCLE_LENGTH);
    float cycle_ratio = cycle / CYCLE_LENGTH;
    int ox = width / 2, oy = height / 2;

    const int num_vertices = 5;
    const float interval = (PI * 2) / num_vertices;
    int16_t xCoords[num_vertices];
    int16_t yCoords[num_vertices];
    for (int i = 0; i < num_vertices; ++i) {
      float t = i;
      xCoords[i] = cos(interval * t - PI / 10) * RADIUS + ox;
      yCoords[i] = sin(interval * t - PI / 10) * RADIUS + oy;
    }

    auto color = hsl2rgb(cycle_ratio, 1, 0.5);
    filledPolygonColor(renderer, xCoords, yCoords, num_vertices, rgb2uint32(color));
    const int dot_count = 20;
    for (int v = 0; v < num_vertices; ++v) {
      const float angularOffset = interval * v;
      for (int t = 0; t < dot_count; ++t) {
        float i = t;
        const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

        const float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
        const float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;

        filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255 * interval_cycle_ratio);

        if (t == 0) {
          const int n = (v + 1) % num_vertices;
          const float x2 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float y2 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float x3 = cos(interval_cycle_ratio * PI * 2 - PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
          const float y3 = sin(interval_cycle_ratio * PI * 2 - PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
          lineRGBA(renderer, x2 + ox, y2 + oy, xCoords[v], yCoords[v], 0, 0, 0, 255);
          lineRGBA(renderer, x2 + ox, y2 + oy, x3 + ox, y3 + oy, 0, 0, 0, 255);
        }
      }
    }

    for (float i = 0; i < dot_count; ++i) {
      const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

      const float x1 = cos(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;
      const float y1 = sin(interval_cycle_ratio * PI * 2 - PI / 2) * RADIUS;

      filledCircleRGBA(renderer, x1 + ox, y1 + oy, 3, 0, 0, 0, 255);
    }
  }

private:
};

int main(int, char**){
  Loop5 loop;
  loop.Run();

  return 0;
}
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "RexUUID.h"

#include <iomanip>

using namespace std;

/// Converts a single char to a value of 0-15. (4 bits)
namespace
{

static uint8_t CharToNibble(char c)
{
    if (isdigit(c))
        return c - '0';
    if (c >= 'a' && c <= 'f')
        return 0xA + c - 'a';
    if (c >= 'A' && c <= 'F')
        return 0xA + c - 'A';

    // Invalid octet.
    return 0xFF;
}

/// @return The first two characters of the given string converted to a byte: "B9" -> 0xB9.
static uint8_t StringToByte(const char *str)
{
    return (CharToNibble(str[0]) << 4) | CharToNibble(str[1]);
}

}

namespace RexTypes
{

RexUUID::RexUUID()
{
    SetNull();
}

RexUUID::RexUUID(const char *str)
{
    if (str)
        FromString(str);
    else
        SetNull();
}

RexUUID::RexUUID(const std::string &str)
{
    FromString(str.c_str());
}

void RexUUID::SetNull()
{
    for(int i = 0; i < cSizeBytes; ++i)
        data[i] = 0;
}

bool RexUUID::IsNull() const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] != 0)
            return false;
    return true;
}

void RexUUID::Random()
{
    for (int i = 0; i < cSizeBytes; ++i)
        data[i] = rand() & 0xff;
}

bool RexUUID::IsValid(const char *str)
{
    if (!str) return false;

    int valid_nibbles = 0;

    while (*str)
    {
        if (CharToNibble(*str) <= 0xf)
            valid_nibbles++;
        str++;
    }

    return (valid_nibbles == cSizeBytes * 2);
}

/// Converts a C string representing a RexUUID to a uint8_t array.
/// Supports either the format "1c1bbda2-304b-4cbf-ba3f-75324b044c73" or "1c1bbda2304b4cbfba3f75324b044c73".
void RexUUID::FromString(const char *str)
{
    int curIndex = 0;
    for(int i = 0; i < cSizeBytes; ++i)
	{
        while(!(isalpha(str[curIndex]) || isdigit(str[curIndex]) || str[curIndex] == '\0'))
            ++curIndex;
            if (str[curIndex] == '\0')
                break;
        data[i] = StringToByte(str + curIndex);
        curIndex += 2;
    }
}

std::string RexUUID::ToString() const
{
    stringstream str;
    int i = 0;

    for(int j = 0; j < 4; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 6; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];

    return str.str();
}

/*    void RexUUID::operator =(const RexUUID &rhs)
{
    if (this != &rhs)
        for(int i = 0; i < cSizeBytes; ++i)
            data[i] = rhs.data[i];
}*/

bool RexUUID::operator ==(const RexUUID &rhs) const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] != rhs.data[i])
            return false;

    return true;
}

bool RexUUID::operator !=(const RexUUID &rhs) const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] != rhs.data[i])
            return true;

    return false;
}

bool RexUUID::operator <(const RexUUID &rhs) const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] < rhs.data[i])
            return true;
        else if (data[i] > rhs.data[i])
            return false;

    return false;
}

}<commit_msg>Fixed an UUID parsing error.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "RexUUID.h"

#include <iomanip>

using namespace std;

/// Converts a single char to a value of 0-15. (4 bits)
namespace
{

static uint8_t CharToNibble(char c)
{
    if (isdigit(c))
        return c - '0';
    if (c >= 'a' && c <= 'f')
        return 0xA + c - 'a';
    if (c >= 'A' && c <= 'F')
        return 0xA + c - 'A';

    // Invalid octet.
    return 0xFF;
}

/// @return The first two characters of the given string converted to a byte: "B9" -> 0xB9.
static uint8_t StringToByte(const char *str)
{
    return (CharToNibble(str[0]) << 4) | CharToNibble(str[1]);
}

}

namespace RexTypes
{

RexUUID::RexUUID()
{
    SetNull();
}

RexUUID::RexUUID(const char *str)
{
    if (str)
        FromString(str);
    else
        SetNull();
}

RexUUID::RexUUID(const std::string &str)
{
    FromString(str.c_str());
}

void RexUUID::SetNull()
{
    for(int i = 0; i < cSizeBytes; ++i)
        data[i] = 0;
}

bool RexUUID::IsNull() const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] != 0)
            return false;
    return true;
}

void RexUUID::Random()
{
    for (int i = 0; i < cSizeBytes; ++i)
        data[i] = rand() & 0xff;
}

bool RexUUID::IsValid(const char *str)
{
    if (!str) return false;

    int valid_nibbles = 0;

    while (*str)
    {
        if (CharToNibble(*str) <= 0xf)
            valid_nibbles++;
        str++;
    }

    return (valid_nibbles == cSizeBytes * 2);
}

/// Converts a C string representing a RexUUID to a uint8_t array.
/// Supports either the format "1c1bbda2-304b-4cbf-ba3f-75324b044c73" or "1c1bbda2304b4cbfba3f75324b044c73".
/// If the inputted string is zero, or if the length is zero, or if a parsing error occurs, the UUID will be
/// set to null.
void RexUUID::FromString(const char *str)
{
    const int strLen = (str == 0) ? 0 : strlen(str);
    if (strLen == 0)
    {
        SetNull();
        return;
    }
    int curIndex = 0;
    for(int i = 0; i < cSizeBytes; ++i)
	{
        if (curIndex >= strLen)
        {
            SetNull();
            return;
        }

        while(!(isalpha(str[curIndex]) || isdigit(str[curIndex]) || str[curIndex] == '\0'))
            ++curIndex;

        if (curIndex >= strLen)
        {
            SetNull();
            return;
        }

        data[i] = StringToByte(str + curIndex);
        curIndex += 2;
    }
}

std::string RexUUID::ToString() const
{
    stringstream str;
    int i = 0;

    for(int j = 0; j < 4; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
    str << "-";

    for(int j = 0; j < 6; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];

    return str.str();
}

/*    void RexUUID::operator =(const RexUUID &rhs)
{
    if (this != &rhs)
        for(int i = 0; i < cSizeBytes; ++i)
            data[i] = rhs.data[i];
}*/

bool RexUUID::operator ==(const RexUUID &rhs) const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] != rhs.data[i])
            return false;

    return true;
}

bool RexUUID::operator !=(const RexUUID &rhs) const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] != rhs.data[i])
            return true;

    return false;
}

bool RexUUID::operator <(const RexUUID &rhs) const
{
    for(int i = 0; i < cSizeBytes; ++i)
        if (data[i] < rhs.data[i])
            return true;
        else if (data[i] > rhs.data[i])
            return false;

    return false;
}

}<|endoftext|>


<commit_before>#include "SlidingHyperService.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>
#include <syslog.h>

#include "config.h"
#include "set_manager.h"
#include "thrift_server.h"

using namespace apache::thrift::concurrency;
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

class SlidingHyperServiceHandler : virtual public SlidingHyperServiceIf {
 private:
  hlld_setmgr *mgr;
 public:
  SlidingHyperServiceHandler(hlld_setmgr *mgr) {
      assert(mgr != NULL);
      this->mgr = mgr;
  }

  void ping(std::string& _return) {
      _return = "PONG";
  }

  void add_many(const int32_t timestamp, const std::string& key, const std::vector<std::string> & values) {
      setmgr_client_checkpoint(mgr);

      char **char_v = (char**)malloc(sizeof(char*)*values.size());
      for(size_t i=0; i<values.size(); i++) {
          char_v[i] = (char*)&values[i][0];
      }

      int res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }
      free(char_v);
  }

  int32_t card(const int32_t timestamp, const int32_t window, const std::vector<std::string> & keys, const std::vector<std::string> & values) {
      //add(timestamp,
      //return get_union(timestamp, window, keys);
  }

  void flush() {
    // Your implementation goes here
    printf("flush\n");
  }

  void add(const int32_t timestamp, const std::string& key, const std::string& value) {
      char *values[] = {(char*)&value[0]};
      int res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }

  }

  int32_t get(const int32_t timestamp, const int16_t window, const std::string& key) {
      uint64_t estimate = 0;
      int res = setmgr_set_size(mgr, (char*)&key[0], &estimate, window);
      if (res == -1) {
          res = setmgr_create_set(mgr, (char*)&key[0], NULL);
          return 0;
      } else if (res < -1) {
          syslog(LOG_ERR, "Failed to get set cardinality %s res %d", (char*)&key[0], res);
      }
      return estimate;
  }

  int32_t get_union(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys) {
      char **set_names = (char**)malloc(keys.size()*sizeof(char**));
      for(size_t i=0; i<keys.size(); i++) {
          set_names[i] = (char*)&keys[i];
      }
      uint64_t estimate;
      setmgr_set_union_size(mgr, keys.size(), set_names, &estimate, window);
      free(set_names);

      return (int32_t)estimate;

  }

  int32_t get_with_element(const int32_t timestamp, const int16_t window, const std::string& key, const std::string& value) {
    // Your implementation goes here
    printf("get_withelement\n");
  }

  int32_t get_union_with_element(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys, const std::string& value) {
    // Your implementation goes here
    printf("get_union_with_element\n");
  }

};

TThreadPoolServer *thrift_server;

void start_thrift_server(hlld_setmgr *mgr) {
  setmgr_client_checkpoint(mgr);
  int port = 9090;
  shared_ptr<SlidingHyperServiceHandler> handler(new SlidingHyperServiceHandler(mgr));
  shared_ptr<TProcessor> processor(new SlidingHyperServiceProcessor(handler));
  shared_ptr<TServerSocket> serverTransport(new TServerSocket(port));
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

 shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(4);

 shared_ptr<PosixThreadFactory> threadFactory
     = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());

 threadManager->threadFactory(threadFactory);

 threadManager->start();
printf("thread manager state %d\n", threadManager->state());

  thrift_server = new TThreadPoolServer(processor, serverTransport, transportFactory, protocolFactory, threadManager);
  syslog(LOG_INFO, "Starting thrift server");
  thrift_server->serve();
  syslog(LOG_INFO, "Stopping thrift server");
}

void stop_thrift_server() {
    thrift_server->stop();
}
<commit_msg>do not checkpoint on main thread with threaded thrift server. Causes huge perf issues<commit_after>#include "SlidingHyperService.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>
#include <syslog.h>

#include "config.h"
#include "set_manager.h"
#include "thrift_server.h"

using namespace apache::thrift::concurrency;
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

class SlidingHyperServiceHandler : virtual public SlidingHyperServiceIf {
 private:
  hlld_setmgr *mgr;
 public:
  SlidingHyperServiceHandler(hlld_setmgr *mgr) {
      assert(mgr != NULL);
      this->mgr = mgr;
  }

  void ping(std::string& _return) {
      _return = "PONG";
  }

  void add_many(const int32_t timestamp, const std::string& key, const std::vector<std::string> & values) {
      setmgr_client_checkpoint(mgr);

      char **char_v = (char**)malloc(sizeof(char*)*values.size());
      for(size_t i=0; i<values.size(); i++) {
          char_v[i] = (char*)&values[i][0];
      }

      int res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }
      free(char_v);
  }

  int32_t card(const int32_t timestamp, const int32_t window, const std::vector<std::string> & keys, const std::vector<std::string> & values) {
      //add(timestamp,
      //return get_union(timestamp, window, keys);
  }

  void flush() {
    // Your implementation goes here
    printf("flush\n");
  }

  void add(const int32_t timestamp, const std::string& key, const std::string& value) {
      char *values[] = {(char*)&value[0]};
      int res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }

  }

  int32_t get(const int32_t timestamp, const int16_t window, const std::string& key) {
      uint64_t estimate = 0;
      int res = setmgr_set_size(mgr, (char*)&key[0], &estimate, window);
      if (res == -1) {
          res = setmgr_create_set(mgr, (char*)&key[0], NULL);
          return 0;
      } else if (res < -1) {
          syslog(LOG_ERR, "Failed to get set cardinality %s res %d", (char*)&key[0], res);
      }
      return estimate;
  }

  int32_t get_union(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys) {
      char **set_names = (char**)malloc(keys.size()*sizeof(char**));
      for(size_t i=0; i<keys.size(); i++) {
          set_names[i] = (char*)&keys[i];
      }
      uint64_t estimate;
      setmgr_set_union_size(mgr, keys.size(), set_names, &estimate, window);
      free(set_names);

      return (int32_t)estimate;

  }

  int32_t get_with_element(const int32_t timestamp, const int16_t window, const std::string& key, const std::string& value) {
    // Your implementation goes here
    printf("get_withelement\n");
  }

  int32_t get_union_with_element(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys, const std::string& value) {
    // Your implementation goes here
    printf("get_union_with_element\n");
  }

};

TThreadPoolServer *thrift_server;

void start_thrift_server(hlld_setmgr *mgr) {
  int port = 9090;
  shared_ptr<SlidingHyperServiceHandler> handler(new SlidingHyperServiceHandler(mgr));
  shared_ptr<TProcessor> processor(new SlidingHyperServiceProcessor(handler));
  shared_ptr<TServerSocket> serverTransport(new TServerSocket(port));
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

 shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(4);

 shared_ptr<PosixThreadFactory> threadFactory
     = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());

 threadManager->threadFactory(threadFactory);

 threadManager->start();

  thrift_server = new TThreadPoolServer(processor, serverTransport, transportFactory, protocolFactory, threadManager);
  syslog(LOG_INFO, "Starting thrift server");
  thrift_server->serve();
  syslog(LOG_INFO, "Stopping thrift server");
}

void stop_thrift_server() {
    thrift_server->stop();
}
<|endoftext|>


<commit_before>/* The MIT License

   Copyright (c) 2014 Adrian Tan <atks@umich.edu>

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

#include "remove_overlap.h"

KHASH_MAP_INIT_STR(xdict, bcf1_t*);

namespace
{

class Igor : Program
{
    public:

    ///////////
    //options//
    ///////////
    std::string input_vcf_file;
    std::string output_vcf_file;
    std::vector<GenomeInterval> intervals;
    bool merge_by_pos;

    ///////
    //i/o//
    ///////
    BCFOrderedReader *odr;
    BCFOrderedWriter *odw;
    std::vector<bcf1_t*> pool;

    /////////
    //stats//
    /////////
    int32_t no_total_variants;
    int32_t no_nonoverlap_variants;
    int32_t no_overlap_variants;

    /////////
    //tools//
    /////////
    VariantManip *var_manip;

    Igor(int argc, char **argv)
    {
        version = "0.57";

        //////////////////////////
        //options initialization//
        //////////////////////////
        try
        {
            std::string desc = "Removes overlapping variants in a VCF file.";

            TCLAP::CmdLine cmd(desc, ' ', version);
            VTOutput my;
            cmd.setOutput(&my);
            TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd);
            TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "str", cmd);
            TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);

            cmd.parse(argc, argv);

            input_vcf_file = arg_input_vcf_file.getValue();
            output_vcf_file = arg_output_vcf_file.getValue();
            parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
        }
        catch (TCLAP::ArgException &e)
        {
            std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
            abort();
        }
    };

    void initialize()
    {
        //////////////////////
        //i/o initialization//
        //////////////////////
        odr = new BCFOrderedReader(input_vcf_file, intervals);
        odw = new BCFOrderedWriter(output_vcf_file, 0);
        odw->link_hdr(odr->hdr);

        bcf_hdr_append(odw->hdr, "##FILTER=<ID=PASS,Description=\"Passed variant\">");
        bcf_hdr_append(odw->hdr, "##FILTER=<ID=overlap,Description=\"Overlapping variant\">");

        odw->write_hdr();

        ////////////////////////
        //stats initialization//
        ////////////////////////
        no_total_variants = 0;
        no_nonoverlap_variants = 0;
        no_overlap_variants = 0;

        ////////////////////////
        //tools initialization//
        ////////////////////////
    }

    void remove_overlap()
    {
        kstring_t variant = {0, 0, 0};

        int32_t crid = -1;
        int32_t cpos1 = -1;
        int32_t cepos1 = -1;
        bcf1_t* cv = NULL;

        bcf1_t *v = odw->get_bcf1_from_pool();

        int32_t tpass_id = bcf_hdr_id2int(odw->hdr, BCF_DT_ID, "PASS");
        int32_t overlap_id = bcf_hdr_id2int(odw->hdr, BCF_DT_ID, "overlap");

        while (odr->read(v))
        {
            bcf_unpack(v, BCF_UN_STR);
            int32_t rid = bcf_get_rid(v);
            int32_t pos1 = bcf_get_pos1(v);
            int32_t epos1 = bcf_get_end_pos1(v);

            //does this overlap
            if (crid==rid && cepos1>=pos1 && cpos1<=epos1)
            {
                //update overlap range
                cpos1 = std::min(cpos1, pos1);
                cepos1 = std::max(cepos1, epos1);

                if (cv)
                {
                    ++no_overlap_variants;
                    bcf_add_filter(odw->hdr, cv, overlap_id);
                    odw->write(cv);
                    cv = NULL;
                }

                ++no_overlap_variants;
            }
            else
            {
                crid = rid;
                cpos1 = pos1;
                cepos1 = epos1;

                if (cv)
                {
                    bcf_add_filter(odw->hdr, cv, tpass_id);
                    odw->write(cv);
                    ++no_nonoverlap_variants;
                }
                cv = v;
                v = odw->get_bcf1_from_pool();
            }

            ++no_total_variants;
        }

        //the last non overlapping variant
        if (cv)
        {
            bcf_add_filter(odw->hdr, cv, tpass_id);
            odw->write(cv);
            ++no_nonoverlap_variants;
        }

        odr->close();
        odw->close();
    };

    void print_options()
    {
        std::clog << "remove_overlap v" << version << "\n\n";

        std::clog << "options:     input VCF file        " << input_vcf_file << "\n";
        std::clog << "         [o] output VCF file       " << output_vcf_file << "\n";
        if (intervals.size()!=0)
        {
            std::clog << "         [i] intervals             " << intervals.size() <<  " intervals\n";
        }
        std::clog << "\n";
    }

    void print_stats()
    {
        std::clog << "\n";
        std::clog << "stats: Total number of observed variants    " << no_total_variants << "\n";
        std::clog << "       Total number of nonoverlap variants  " << no_nonoverlap_variants << "\n";
        std::clog << "       Total number of overlap variants     " << no_overlap_variants << "\n";
        std::clog << "\n";
    };

    ~Igor() {};

    private:
};

}

void remove_overlap(int argc, char ** argv)
{
    Igor igor(argc, argv);
    igor.print_options();
    igor.initialize();
    igor.remove_overlap();
    igor.print_stats();
};
<commit_msg>modified documentation<commit_after>/* The MIT License

   Copyright (c) 2014 Adrian Tan <atks@umich.edu>

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

#include "remove_overlap.h"

KHASH_MAP_INIT_STR(xdict, bcf1_t*);

namespace
{

class Igor : Program
{
    public:

    ///////////
    //options//
    ///////////
    std::string input_vcf_file;
    std::string output_vcf_file;
    std::vector<GenomeInterval> intervals;
    bool merge_by_pos;

    ///////
    //i/o//
    ///////
    BCFOrderedReader *odr;
    BCFOrderedWriter *odw;
    std::vector<bcf1_t*> pool;

    /////////
    //stats//
    /////////
    int32_t no_total_variants;
    int32_t no_nonoverlap_variants;
    int32_t no_overlap_variants;

    /////////
    //tools//
    /////////
    VariantManip *var_manip;

    Igor(int argc, char **argv)
    {
        version = "0.57";

        //////////////////////////
        //options initialization//
        //////////////////////////
        try
        {
            std::string desc = "Removes overlapping variants in a VCF file by tagging such variants with the FILTER flag overlap.";

            TCLAP::CmdLine cmd(desc, ' ', version);
            VTOutput my;
            cmd.setOutput(&my);
            TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd);
            TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "str", cmd);
            TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);

            cmd.parse(argc, argv);

            input_vcf_file = arg_input_vcf_file.getValue();
            output_vcf_file = arg_output_vcf_file.getValue();
            parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
        }
        catch (TCLAP::ArgException &e)
        {
            std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
            abort();
        }
    };

    void initialize()
    {
        //////////////////////
        //i/o initialization//
        //////////////////////
        odr = new BCFOrderedReader(input_vcf_file, intervals);
        odw = new BCFOrderedWriter(output_vcf_file, 0);
        odw->link_hdr(odr->hdr);

        bcf_hdr_append(odw->hdr, "##FILTER=<ID=PASS,Description=\"Passed variant\">");
        bcf_hdr_append(odw->hdr, "##FILTER=<ID=overlap,Description=\"Overlapping variant\">");

        odw->write_hdr();

        ////////////////////////
        //stats initialization//
        ////////////////////////
        no_total_variants = 0;
        no_nonoverlap_variants = 0;
        no_overlap_variants = 0;

        ////////////////////////
        //tools initialization//
        ////////////////////////
    }

    void remove_overlap()
    {
        kstring_t variant = {0, 0, 0};

        int32_t crid = -1;
        int32_t cpos1 = -1;
        int32_t cepos1 = -1;
        bcf1_t* cv = NULL;

        bcf1_t *v = odw->get_bcf1_from_pool();

        int32_t tpass_id = bcf_hdr_id2int(odw->hdr, BCF_DT_ID, "PASS");
        int32_t overlap_id = bcf_hdr_id2int(odw->hdr, BCF_DT_ID, "overlap");

        while (odr->read(v))
        {
            bcf_unpack(v, BCF_UN_STR);
            int32_t rid = bcf_get_rid(v);
            int32_t pos1 = bcf_get_pos1(v);
            int32_t epos1 = bcf_get_end_pos1(v);

            //does this overlap
            if (crid==rid && cepos1>=pos1 && cpos1<=epos1)
            {
                //update overlap range
                cpos1 = std::min(cpos1, pos1);
                cepos1 = std::max(cepos1, epos1);

                if (cv)
                {
                    ++no_overlap_variants;
                    bcf_add_filter(odw->hdr, cv, overlap_id);
                    odw->write(cv);
                    cv = NULL;
                }

                ++no_overlap_variants;
            }
            else
            {
                crid = rid;
                cpos1 = pos1;
                cepos1 = epos1;

                if (cv)
                {
                    bcf_add_filter(odw->hdr, cv, tpass_id);
                    odw->write(cv);
                    ++no_nonoverlap_variants;
                }
                cv = v;
                v = odw->get_bcf1_from_pool();
            }

            ++no_total_variants;
        }

        //the last non overlapping variant
        if (cv)
        {
            bcf_add_filter(odw->hdr, cv, tpass_id);
            odw->write(cv);
            ++no_nonoverlap_variants;
        }

        odr->close();
        odw->close();
    };

    void print_options()
    {
        std::clog << "remove_overlap v" << version << "\n\n";

        std::clog << "options:     input VCF file        " << input_vcf_file << "\n";
        std::clog << "         [o] output VCF file       " << output_vcf_file << "\n";
        if (intervals.size()!=0)
        {
            std::clog << "         [i] intervals             " << intervals.size() <<  " intervals\n";
        }
        std::clog << "\n";
    }

    void print_stats()
    {
        std::clog << "\n";
        std::clog << "stats: Total number of observed variants    " << no_total_variants << "\n";
        std::clog << "       Total number of nonoverlap variants  " << no_nonoverlap_variants << "\n";
        std::clog << "       Total number of overlap variants     " << no_overlap_variants << "\n";
        std::clog << "\n";
    };

    ~Igor() {};

    private:
};

}

void remove_overlap(int argc, char ** argv)
{
    Igor igor(argc, argv);
    igor.print_options();
    igor.initialize();
    igor.remove_overlap();
    igor.print_stats();
};
<|endoftext|>


<commit_before>#include "circuit.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace qflex {
namespace {

// Passing in an invalid filename to circuit.load().
TEST(CircuitExceptionTest, InvalidFilenameInput) {
  QflexCircuit circuit;
  std::string invalid_filename = "invalid.txt";
  try {
    circuit.load(invalid_filename);
  } catch (std::string msg) {
    EXPECT_THAT(msg,
                testing::HasSubstr("Cannot open circuit file invalid.txt."));
  }
}

TEST(CircuitExceptionTest, PrintGate) {
  QflexGate gate;
  gate.name = "cx";
  gate.cycle = 1;
  gate.qubits = {2, 4};
  gate.params = {3, 5};
  // std::cout << gate << std::endl;
}

constexpr char kBadCircuit1[] = R"(
0 h 0
0 h 1
0 h 2)";

TEST(CircuitExceptionTest, BadCircuits) {
  QflexCircuit circuit;
  // try {
  circuit.load(std::stringstream(kBadCircuit1));
  // shouldn't this throw an error??
  // } catch (std::string msg) {
  //     std::cout << msg << std::endl;
  //     EXPECT_THAT(msg, testing::HasSubstr("asdf"));
  // }
}

constexpr char kSimpleCircuit[] = R"(5
0 h 0
0 h 1
0 h 2
0 h 3
0 h 5
1 t 0
1 t 1
1 t 2
1 t 3
1 t 5
2 cz 0 1
3 cx 0 2
4 cx 1 3
5 cz 2 3
6 cz 3 5
11 cz 0 1
12 cx 0 2
14 h 0
14 h 1
14 h 2
14 h 3
14 h 5)";

// Testing loading a simple circuit.
TEST(CircuitTest, SimpleLoadTest) {
  QflexCircuit circuit;
  circuit.load(std::stringstream(kSimpleCircuit));

  EXPECT_EQ(circuit.num_active_qubits, 5);
  EXPECT_EQ(circuit.gates.size(), 22);
}

// Testing circuit.clear()
constexpr char kClearCircuit[] = R"(2
0 h 0
0 h 1
9 h 0
9 h 1)";

TEST(CircuitTest, ClearCircuitTest) {
  QflexCircuit circuit;
  circuit.load(std::stringstream(kClearCircuit));
  circuit.clear();
  EXPECT_EQ(circuit.gates.size(), 0);
  EXPECT_EQ(circuit.num_active_qubits, 0);
}

}  // namespace
}  // namespace qflex

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<commit_msg>still broken<commit_after>#include "circuit.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace qflex {
namespace {

// Passing in an invalid filename to circuit.load().
TEST(CircuitExceptionTest, InvalidFilenameInput) {
  QflexCircuit circuit;
  std::string invalid_filename = "invalid.txt";
  try {
    circuit.load(invalid_filename);
  } catch (std::string msg) {
    EXPECT_THAT(msg,
                testing::HasSubstr("Cannot open circuit file invalid.txt."));
  }
}

TEST(CircuitExceptionTest, PrintGate) {
  QflexGate gate;
  gate.name = "cx";
  gate.cycle = 1;
  gate.qubits = {2, 4};
  gate.params = {3, 5};
  // std::cout << gate << std::endl;
}

constexpr char kBadCircuit1[] = R"(
0 h 0
0 h 1
0 h 2)";

TEST(CircuitExceptionTest, BadCircuits) {
  QflexCircuit circuit;
  try {
    circuit.load(std::stringstream(kBadCircuit1));
  // shouldn't this throw an error??
  } catch (std::string msg) {
      std::cout << msg << std::endl;
      EXPECT_THAT(msg, testing::HasSubstr("asdf"));
  }
}

constexpr char kSimpleCircuit[] = R"(5
0 h 0
0 h 1
0 h 2
0 h 3
0 h 5
1 t 0
1 t 1
1 t 2
1 t 3
1 t 5
2 cz 0 1
3 cx 0 2
4 cx 1 3
5 cz 2 3
6 cz 3 5
11 cz 0 1
12 cx 0 2
14 h 0
14 h 1
14 h 2
14 h 3
14 h 5)";

// Testing loading a simple circuit.
TEST(CircuitTest, SimpleLoadTest) {
  QflexCircuit circuit;
  circuit.load(std::stringstream(kSimpleCircuit));

  EXPECT_EQ(circuit.num_active_qubits, 5);
  EXPECT_EQ(circuit.gates.size(), 22);
}

// Testing circuit.clear()
constexpr char kClearCircuit[] = R"(2
0 h 0
0 h 1
9 h 0
9 h 1)";

TEST(CircuitTest, ClearCircuitTest) {
  QflexCircuit circuit;
  circuit.load(std::stringstream(kClearCircuit));
  circuit.clear();
  EXPECT_EQ(circuit.gates.size(), 0);
  EXPECT_EQ(circuit.num_active_qubits, 0);
}

}  // namespace
}  // namespace qflex

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<|endoftext|>


<commit_before>#include <iostream>

extern "C" {
#include <lirc/lirc_client.h>
};

void ir_received(char* code){
    std::cout << "Received code:" << code << std::endl;
}

int main(){
    //Initiate LIRC. Exit on failure
    if(lirc_init("lirc",1)==-1){
        return EXIT_FAILURE;
    }

    struct lirc_config* config;

    //Read the default LIRC config at /etc/lirc/lircd.conf  This is the config for your remote.
    if(lirc_readconfig(NULL,&config,NULL)==0){
        char* code;

        //Do stuff while LIRC socket is open  0=open  -1=closed.
        while(lirc_nextcode(&code)==0){
            //If code = NULL, nothing was returned from LIRC socket
            if(code){
                //Send code further
                ir_received(code);

                //Need to free up code before the next loop
                free(code);
            }
        }

        //Frees the data structures associated with config.
        lirc_freeconfig(config);
    }

    //Closes LIRC
    lirc_deinit();

    return 0;
}
<commit_msg>Update<commit_after>#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>

extern "C" {
#include <lirc/lirc_client.h>
};

void ir_received(char* code){
    std::cout << "Received code:" << code << std::endl;
}

int main(){
    //Initiate LIRC. Exit on failure
    char lirc_name[] = "lirc";
    if(lirc_init(lirc_name, 1) == -1){
        return 1;
    }

    struct lirc_config* config;

    //Read the default LIRC config at /etc/lirc/lircd.conf  This is the config for your remote.
    if(lirc_readconfig(NULL,&config,NULL)==0){
        char* code;

        //Do stuff while LIRC socket is open  0=open  -1=closed.
        while(lirc_nextcode(&code)==0){
            //If code = NULL, nothing was returned from LIRC socket
            if(code){
                //Send code further
                ir_received(code);

                //Need to free up code before the next loop
                free(code);
            }
        }

        //Frees the data structures associated with config.
        lirc_freeconfig(config);
    }

    //Closes LIRC
    lirc_deinit();

    return 0;
}
<|endoftext|>


<commit_before>#include "notifications.h"
#include "display.h"
#include "space.h"
#include "window.h"
#include "border.h"

extern kwm_screen KWMScreen;
extern kwm_toggles KWMToggles;
extern kwm_tiling KWMTiling;
extern kwm_focus KWMFocus;
extern kwm_thread KWMThread;
extern kwm_mode KWMMode;

void FocusedAXObserverCallback(AXObserverRef Observer, AXUIElementRef Element, CFStringRef Notification, void *ContextData)
{
    pthread_mutex_lock(&KWMThread.Lock);

    window_info *Window = KWMFocus.Window;
    if(Window && CFEqual(Notification, kAXTitleChangedNotification))
        Window->Name = GetWindowTitle(Element);
    else if(CFEqual(Notification, kAXFocusedWindowChangedNotification))
    {
        if(!Window || Window->WID != GetWindowIDFromRef(Element))
        {
            DEBUG("Element: " << GetWindowTitle(Element))
            window_info *OSXWindow = GetWindowByID(GetWindowIDFromRef(Element));
            screen_info *Screen = GetDisplayOfWindow(OSXWindow);
            if(OSXWindow && Screen)
            {
                screen_info *ScreenOfWindow = GetDisplayOfWindow(Window);
                if(ScreenOfWindow && Window && ScreenOfWindow != Screen)
                {
                    space_info *SpaceOfWindow = GetActiveSpaceOfScreen(ScreenOfWindow);
                    if(SpaceOfWindow->Mode == SpaceModeBSP)
                        RemoveWindowFromBSPTree(ScreenOfWindow, Window->WID, false, false);
                    else if(SpaceOfWindow->Mode == SpaceModeMonocle)
                        RemoveWindowFromMonocleTree(ScreenOfWindow, Window->WID, false);

                    SpaceOfWindow->FocusedWindowID = 0;
                    GiveFocusToScreen(Screen->ID, NULL, false, false);
                }

                SetKwmFocus(Element);
                if(Screen == ScreenOfWindow)
                    KWMFocus.InsertionPoint = KWMFocus.Cache;
            }
        }
    }
    else if(CFEqual(Notification, kAXWindowResizedNotification) ||
            CFEqual(Notification, kAXWindowMovedNotification) ||
            CFEqual(Notification, kAXWindowMiniaturizedNotification))
    {
        UpdateBorder("focused");
        if (Window && Window->WID == KWMScreen.MarkedWindow)
            UpdateBorder("marked");
    }

    pthread_mutex_unlock(&KWMThread.Lock);
}

void DestroyApplicationNotifications()
{
    if(!KWMFocus.Observer)
        return;

    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMiniaturizedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMovedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowResizedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXTitleChangedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXFocusedWindowChangedNotification);
    CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(KWMFocus.Observer), kCFRunLoopDefaultMode);

    CFRelease(KWMFocus.Observer);
    KWMFocus.Observer = NULL;
    CFRelease(KWMFocus.Application);
    KWMFocus.Application = NULL;
}

void CreateApplicationNotifications()
{
    DestroyApplicationNotifications();

    if(KWMFocus.Window)
    {
        KWMFocus.Application = AXUIElementCreateApplication(KWMFocus.Window->PID);
        if(!KWMFocus.Application)
            return;

        AXError Error = AXObserverCreate(KWMFocus.Window->PID, FocusedAXObserverCallback, &KWMFocus.Observer);
        if(Error == kAXErrorSuccess)
        {
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMiniaturizedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMovedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowResizedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXTitleChangedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXFocusedWindowChangedNotification, NULL);
            CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(KWMFocus.Observer), kCFRunLoopDefaultMode);
        }
    }
}
<commit_msg>properly rebalance tree before switching to OSX focus<commit_after>#include "notifications.h"
#include "display.h"
#include "space.h"
#include "window.h"
#include "border.h"

extern kwm_screen KWMScreen;
extern kwm_toggles KWMToggles;
extern kwm_tiling KWMTiling;
extern kwm_focus KWMFocus;
extern kwm_thread KWMThread;
extern kwm_mode KWMMode;

void FocusedAXObserverCallback(AXObserverRef Observer, AXUIElementRef Element, CFStringRef Notification, void *ContextData)
{
    pthread_mutex_lock(&KWMThread.Lock);

    window_info *Window = KWMFocus.Window;
    if(Window && CFEqual(Notification, kAXTitleChangedNotification))
        Window->Name = GetWindowTitle(Element);
    else if(CFEqual(Notification, kAXFocusedWindowChangedNotification))
    {
        if(!Window || Window->WID != GetWindowIDFromRef(Element))
        {
            DEBUG("Element: " << GetWindowTitle(Element))
            window_info *OSXWindow = GetWindowByID(GetWindowIDFromRef(Element));
            screen_info *OSXScreen = GetDisplayOfWindow(OSXWindow);
            if(OSXWindow && OSXScreen)
            {
                screen_info *ScreenOfWindow = GetDisplayOfWindow(Window);
                UpdateActiveWindowList(ScreenOfWindow);

                if(ScreenOfWindow && Window &&
                   GetWindowByID(Window->WID) == NULL &&
                   OSXScreen != ScreenOfWindow)
                {
                    space_info *SpaceOfWindow = GetActiveSpaceOfScreen(ScreenOfWindow);
                    if(SpaceOfWindow->Mode == SpaceModeBSP)
                        RemoveWindowFromBSPTree(ScreenOfWindow, Window->WID, false, false);
                    else if(SpaceOfWindow->Mode == SpaceModeMonocle)
                        RemoveWindowFromMonocleTree(ScreenOfWindow, Window->WID, false);

                    SpaceOfWindow->FocusedWindowID = 0;
                }

                GiveFocusToScreen(OSXScreen->ID, NULL, false, false);
                SetKwmFocus(Element);
                if(OSXScreen == ScreenOfWindow)
                    KWMFocus.InsertionPoint = KWMFocus.Cache;
            }
        }
    }
    else if(CFEqual(Notification, kAXWindowResizedNotification) ||
            CFEqual(Notification, kAXWindowMovedNotification) ||
            CFEqual(Notification, kAXWindowMiniaturizedNotification))
    {
        UpdateBorder("focused");
        if (Window && Window->WID == KWMScreen.MarkedWindow)
            UpdateBorder("marked");
    }

    pthread_mutex_unlock(&KWMThread.Lock);
}

void DestroyApplicationNotifications()
{
    if(!KWMFocus.Observer)
        return;

    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMiniaturizedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMovedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowResizedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXTitleChangedNotification);
    AXObserverRemoveNotification(KWMFocus.Observer, KWMFocus.Application, kAXFocusedWindowChangedNotification);
    CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(KWMFocus.Observer), kCFRunLoopDefaultMode);

    CFRelease(KWMFocus.Observer);
    KWMFocus.Observer = NULL;
    CFRelease(KWMFocus.Application);
    KWMFocus.Application = NULL;
}

void CreateApplicationNotifications()
{
    DestroyApplicationNotifications();

    if(KWMFocus.Window)
    {
        KWMFocus.Application = AXUIElementCreateApplication(KWMFocus.Window->PID);
        if(!KWMFocus.Application)
            return;

        AXError Error = AXObserverCreate(KWMFocus.Window->PID, FocusedAXObserverCallback, &KWMFocus.Observer);
        if(Error == kAXErrorSuccess)
        {
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMiniaturizedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowMovedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXWindowResizedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXTitleChangedNotification, NULL);
            AXObserverAddNotification(KWMFocus.Observer, KWMFocus.Application, kAXFocusedWindowChangedNotification, NULL);
            CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(KWMFocus.Observer), kCFRunLoopDefaultMode);
        }
    }
}
<|endoftext|>


<commit_before>#include <SimFieldView.hpp>

#include <Constants.hpp>
#include <Network.hpp>

#include <QPainter>
#include <QMouseEvent>

using namespace boost;
using namespace Packet;

// Converts from meters to m/s for manually shooting the ball
static const float ShootScale = 5;

SimFieldView::SimFieldView(QWidget* parent): FieldView(parent)
{
	_dragMode = DRAG_NONE;
	_dragRobot = -1;
	_dragRobotBlue = false;
}

void SimFieldView::mousePressEvent(QMouseEvent* me)
{
	Geometry2d::Point pos = _worldToTeam * _screenToWorld * me->pos();

	std::shared_ptr<LogFrame> frame = currentFrame();
	if (me->button() == Qt::LeftButton && frame)
	{
		_dragRobot = -1;
		for (const LogFrame::Robot &r :  frame->self())
		{
			if (pos.nearPoint(r.pos(), Robot_Radius))
			{
				_dragRobot = r.shell();
				_dragRobotBlue = frame->blue_team();
				break;
			}
		}
		for (const LogFrame::Robot &r :  frame->opp())
		{
			if (pos.nearPoint(r.pos(), Robot_Radius))
			{
				_dragRobot = r.shell();
				_dragRobotBlue = !frame->blue_team();
				break;
			}
		}

		if (_dragRobot < 0)
		{
			placeBall(me->pos());
		}

		_dragMode = DRAG_PLACE;
	} else if (me->button() == Qt::RightButton && frame)
	{
		if (frame->has_ball() && pos.nearPoint(frame->ball().pos(), Ball_Radius))
		{
			// Drag to shoot the ball
			_dragMode = DRAG_SHOOT;
			_dragTo = pos;
		} else {
			// Look for a robot selection
			int newID = -1;
			for (int i = 0; i < frame->self_size(); ++i)
			{
				if (pos.distTo(frame->self(i).pos()) < Robot_Radius)
				{
					newID = frame->self(i).shell();
					break;
				}
			}

			if (newID != frame->manual_id())
			{
				robotSelected(newID);
			}
		}
	}
}

void SimFieldView::mouseMoveEvent(QMouseEvent* me)
{
	switch (_dragMode)
	{
		case DRAG_SHOOT:
			_dragTo = _worldToTeam * _screenToWorld * me->pos();
			break;

		case DRAG_PLACE:
			if (_dragRobot >= 0)
			{
				SimCommand cmd;
				SimCommand::Robot *r = cmd.add_robots();
				r->set_shell(_dragRobot);
				r->set_blue_team(_dragRobotBlue);
				r->mutable_pos()->CopyFrom(_screenToWorld * me->pos());
				r->mutable_vel()->set_x(0);
				r->mutable_vel()->set_y(0);
				sendSimCommand(cmd);
			} else {
				placeBall(me->pos());
			}
			break;

		default:
			break;
	}
	update();
}

void SimFieldView::mouseReleaseEvent(QMouseEvent* me)
{
	if (_dragMode == DRAG_SHOOT)
	{
		SimCommand cmd;
		*cmd.mutable_ball_vel() = _teamToWorld.transformDirection(_shot);
		sendSimCommand(cmd);

		update();
	}

	_dragMode = DRAG_NONE;
}

void SimFieldView::placeBall(QPointF pos)
{
	SimCommand cmd;
	cmd.mutable_ball_pos()->CopyFrom(_screenToWorld * pos);
	cmd.mutable_ball_vel()->set_x(0);
	cmd.mutable_ball_vel()->set_y(0);
	sendSimCommand(cmd);
}

void SimFieldView::sendSimCommand(const Packet::SimCommand& cmd)
{
	std::string out;
	cmd.SerializeToString(&out);
	_simCommandSocket.writeDatagram(&out[0], out.size(), QHostAddress(QHostAddress::LocalHost), SimCommandPort);
}

void SimFieldView::drawTeamSpace(QPainter& p)
{
	FieldView::drawTeamSpace(p);

	// Simulator drag-to-shoot
	std::shared_ptr<LogFrame> frame = currentFrame();
	if (_dragMode == DRAG_SHOOT && frame)
	{
		p.setPen(Qt::white);
		Geometry2d::Point ball = frame->ball().pos();
		p.drawLine(ball.toQPointF(), _dragTo.toQPointF());

		if (ball != _dragTo)
		{
			p.setPen(Qt::gray);

			_shot = (ball - _dragTo) * ShootScale;
			float speed = _shot.mag();
			Geometry2d::Point shotExtension = ball + _shot / speed * 8;

			p.drawLine(ball.toQPointF(), shotExtension.toQPointF());
			drawText(p, _dragTo.toQPointF(), QString("%1 m/s").arg(speed, 0, 'f', 1));
		}
	}
}
<commit_msg>Fixed the fat aiming bar.<commit_after>#include <SimFieldView.hpp>

#include <Constants.hpp>
#include <Network.hpp>

#include <QPainter>
#include <QMouseEvent>

using namespace boost;
using namespace Packet;

// Converts from meters to m/s for manually shooting the ball
static const float ShootScale = 5;

SimFieldView::SimFieldView(QWidget* parent): FieldView(parent)
{
	_dragMode = DRAG_NONE;
	_dragRobot = -1;
	_dragRobotBlue = false;
}

void SimFieldView::mousePressEvent(QMouseEvent* me)
{
	Geometry2d::Point pos = _worldToTeam * _screenToWorld * me->pos();

	std::shared_ptr<LogFrame> frame = currentFrame();
	if (me->button() == Qt::LeftButton && frame)
	{
		_dragRobot = -1;
		for (const LogFrame::Robot &r :  frame->self())
		{
			if (pos.nearPoint(r.pos(), Robot_Radius))
			{
				_dragRobot = r.shell();
				_dragRobotBlue = frame->blue_team();
				break;
			}
		}
		for (const LogFrame::Robot &r :  frame->opp())
		{
			if (pos.nearPoint(r.pos(), Robot_Radius))
			{
				_dragRobot = r.shell();
				_dragRobotBlue = !frame->blue_team();
				break;
			}
		}

		if (_dragRobot < 0)
		{
			placeBall(me->pos());
		}

		_dragMode = DRAG_PLACE;
	} else if (me->button() == Qt::RightButton && frame)
	{
		if (frame->has_ball() && pos.nearPoint(frame->ball().pos(), Ball_Radius))
		{
			// Drag to shoot the ball
			_dragMode = DRAG_SHOOT;
			_dragTo = pos;
		} else {
			// Look for a robot selection
			int newID = -1;
			for (int i = 0; i < frame->self_size(); ++i)
			{
				if (pos.distTo(frame->self(i).pos()) < Robot_Radius)
				{
					newID = frame->self(i).shell();
					break;
				}
			}

			if (newID != frame->manual_id())
			{
				robotSelected(newID);
			}
		}
	}
}

void SimFieldView::mouseMoveEvent(QMouseEvent* me)
{
	switch (_dragMode)
	{
		case DRAG_SHOOT:
			_dragTo = _worldToTeam * _screenToWorld * me->pos();
			break;

		case DRAG_PLACE:
			if (_dragRobot >= 0)
			{
				SimCommand cmd;
				SimCommand::Robot *r = cmd.add_robots();
				r->set_shell(_dragRobot);
				r->set_blue_team(_dragRobotBlue);
				r->mutable_pos()->CopyFrom(_screenToWorld * me->pos());
				r->mutable_vel()->set_x(0);
				r->mutable_vel()->set_y(0);
				sendSimCommand(cmd);
			} else {
				placeBall(me->pos());
			}
			break;

		default:
			break;
	}
	update();
}

void SimFieldView::mouseReleaseEvent(QMouseEvent* me)
{
	if (_dragMode == DRAG_SHOOT)
	{
		SimCommand cmd;
		*cmd.mutable_ball_vel() = _teamToWorld.transformDirection(_shot);
		sendSimCommand(cmd);

		update();
	}

	_dragMode = DRAG_NONE;
}

void SimFieldView::placeBall(QPointF pos)
{
	SimCommand cmd;
	cmd.mutable_ball_pos()->CopyFrom(_screenToWorld * pos);
	cmd.mutable_ball_vel()->set_x(0);
	cmd.mutable_ball_vel()->set_y(0);
	sendSimCommand(cmd);
}

void SimFieldView::sendSimCommand(const Packet::SimCommand& cmd)
{
	std::string out;
	cmd.SerializeToString(&out);
	_simCommandSocket.writeDatagram(&out[0], out.size(), QHostAddress(QHostAddress::LocalHost), SimCommandPort);
}

void SimFieldView::drawTeamSpace(QPainter& p)
{
	FieldView::drawTeamSpace(p);

	// Simulator drag-to-shoot
	std::shared_ptr<LogFrame> frame = currentFrame();
	if (_dragMode == DRAG_SHOOT && frame)
	{
		p.setPen(QPen(Qt::white, 0.1f));
		Geometry2d::Point ball = frame->ball().pos();
		p.drawLine(ball.toQPointF(), _dragTo.toQPointF());

		if (ball != _dragTo)
		{
			p.setPen(QPen(Qt::gray, 0.1f));

			_shot = (ball - _dragTo) * ShootScale;
			float speed = _shot.mag();
			Geometry2d::Point shotExtension = ball + _shot / speed * 8;

			p.drawLine(ball.toQPointF(), shotExtension.toQPointF());

			p.setPen(Qt::black);
			drawText(p, _dragTo.toQPointF(), QString("%1 m/s").arg(speed, 0, 'f', 1));
		}
	}
}
<|endoftext|>