<commit_before>
#ifndef __FRAMEWORK_CLASSES_STATUSBARCONFIGURATION_HXX_
#include <xml/statusbarconfiguration.hxx>
#endif

#ifndef __FRAMEWORK_CLASSES_STATUSBARDOCUMENTHANDLER_HXX_
#include <xml/statusbardocumenthandler.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_SAXNAMESPACEFILTER_HXX_
#include <xml/saxnamespacefilter.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::container;

namespace framework
{

SV_IMPL_PTRARR( StatusBarDescriptor, StatusBarItemDescriptorPtr);

static Reference< XParser > GetSaxParser(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    return Reference< XParser >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" )), UNO_QUERY);
}

static Reference< XDocumentHandler > GetSaxWriter(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    return Reference< XDocumentHandler >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" )), UNO_QUERY) ;
}

sal_Bool StatusBarConfiguration::LoadStatusBar(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
    SvStream& rInStream, StatusBarDescriptor& aItems )
{
    // obsolete - only support linkage of binary filters!
    return sal_True;
}

sal_Bool StatusBarConfiguration::StoreStatusBar(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
    SvStream& rOutStream, const StatusBarDescriptor& aItems )
{
    // obsolete - only support linkage of binary filters!
    return sal_True;
}

sal_Bool StatusBarConfiguration::LoadStatusBar(
    const Reference< XMultiServiceFactory >& xServiceFactory,
    const Reference< XInputStream >& xInputStream,
    const Reference< XIndexContainer >& rStatusbarConfiguration )
{
    Reference< XParser > xParser( GetSaxParser( xServiceFactory ) );

    // connect stream to input stream to the parser
    InputSource aInputSource;
    aInputSource.aInputStream = xInputStream;

    // create namespace filter and set menudocument handler inside to support xml namespaces
    Reference< XDocumentHandler > xDocHandler( new OReadStatusBarDocumentHandler( rStatusbarConfiguration ));
    Reference< XDocumentHandler > xFilter( new SaxNamespaceFilter( xDocHandler ));

    // connect parser and filter
    xParser->setDocumentHandler( xFilter );

    try
    {
        xParser->parseStream( aInputSource );
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch( SAXException& )
    {
        return sal_False;
    }
    catch( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }

    return sal_False;
}

sal_Bool StatusBarConfiguration::StoreStatusBar(
    const Reference< XMultiServiceFactory >& xServiceFactory,
    const Reference< XOutputStream >& xOutputStream,
    const Reference< XIndexAccess >& rStatusbarConfiguration )
{
    Reference< XDocumentHandler > xWriter( GetSaxWriter( xServiceFactory ) );
    Reference< ::com::sun::star::io::XActiveDataSource> xDataSource( xWriter , UNO_QUERY );
    xDataSource->setOutputStream( xOutputStream );

    try
    {
        OWriteStatusBarDocumentHandler aWriteStatusBarDocumentHandler( rStatusbarConfiguration, xWriter );
        aWriteStatusBarDocumentHandler.WriteStatusBarDocument();
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch ( SAXException& )
    {
        return sal_False;
    }
    catch ( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }

    return sal_False; }

}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.270); FILE MERGED 2005/11/16 15:20:52 pl 1.4.270.1: #i55991# removed warnings<commit_after>
#ifndef __FRAMEWORK_CLASSES_STATUSBARCONFIGURATION_HXX_
#include <xml/statusbarconfiguration.hxx>
#endif

#ifndef __FRAMEWORK_CLASSES_STATUSBARDOCUMENTHANDLER_HXX_
#include <xml/statusbardocumenthandler.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_SAXNAMESPACEFILTER_HXX_
#include <xml/saxnamespacefilter.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::container;

namespace framework
{

SV_IMPL_PTRARR( StatusBarDescriptor, StatusBarItemDescriptorPtr);

static Reference< XParser > GetSaxParser(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    return Reference< XParser >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Parser" )), UNO_QUERY);
}

static Reference< XDocumentHandler > GetSaxWriter(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
    )
{
    return Reference< XDocumentHandler >( xServiceFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.xml.sax.Writer" )), UNO_QUERY) ;
}

sal_Bool StatusBarConfiguration::LoadStatusBar(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&,
    SvStream&, StatusBarDescriptor& )
{
    // obsolete - only support linkage of binary filters!
    return sal_True;
}

sal_Bool StatusBarConfiguration::StoreStatusBar(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&,
    SvStream&, const StatusBarDescriptor& )
{
    // obsolete - only support linkage of binary filters!
    return sal_True;
}

sal_Bool StatusBarConfiguration::LoadStatusBar(
    const Reference< XMultiServiceFactory >& xServiceFactory,
    const Reference< XInputStream >& xInputStream,
    const Reference< XIndexContainer >& rStatusbarConfiguration )
{
    Reference< XParser > xParser( GetSaxParser( xServiceFactory ) );

    // connect stream to input stream to the parser
    InputSource aInputSource;
    aInputSource.aInputStream = xInputStream;

    // create namespace filter and set menudocument handler inside to support xml namespaces
    Reference< XDocumentHandler > xDocHandler( new OReadStatusBarDocumentHandler( rStatusbarConfiguration ));
    Reference< XDocumentHandler > xFilter( new SaxNamespaceFilter( xDocHandler ));

    // connect parser and filter
    xParser->setDocumentHandler( xFilter );

    try
    {
        xParser->parseStream( aInputSource );
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch( SAXException& )
    {
        return sal_False;
    }
    catch( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }
}

sal_Bool StatusBarConfiguration::StoreStatusBar(
    const Reference< XMultiServiceFactory >& xServiceFactory,
    const Reference< XOutputStream >& xOutputStream,
    const Reference< XIndexAccess >& rStatusbarConfiguration )
{
    Reference< XDocumentHandler > xWriter( GetSaxWriter( xServiceFactory ) );
    Reference< ::com::sun::star::io::XActiveDataSource> xDataSource( xWriter , UNO_QUERY );
    xDataSource->setOutputStream( xOutputStream );

    try
    {
        OWriteStatusBarDocumentHandler aWriteStatusBarDocumentHandler( rStatusbarConfiguration, xWriter );
        aWriteStatusBarDocumentHandler.WriteStatusBarDocument();
        return sal_True;
    }
    catch ( RuntimeException& )
    {
        return sal_False;
    }
    catch ( SAXException& )
    {
        return sal_False;
    }
    catch ( ::com::sun::star::io::IOException& )
    {
        return sal_False;
    }
}
}
<|endoftext|>


<commit_before>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <iostream>
#include <cstdlib>
using namespace std;

struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x):val(x), next(NULL){}
};

class RemoveDuplicatesfromSortedList {
public:
    ListNode *deleteDuplicates(ListNode *head) {
	    if (head == NULL){
		    return NULL;
	    }
	    ListNode* cur = head;
	    ListNode* next = head->next;
	    while(cur != NULL){
		    while(next != NULL && cur->val == next->val){
			    next = next->next;
		    }
		    cur->next = next;
		    cur = next;
	    }
	    return head;
    }
};

class MergeSortedArray {
public:
    void merge(int A[], int m, int B[], int n) {
	    int cur = m+n-1;
	    int ac = m-1;
	    int bc = n-1;
	    while(ac >= 0 && bc >= 0){
		    if(A[ac]>B[bc]){
			    A[cur] = A[ac];
			    ac--;
		    }else{
			    A[cur] = B[bc];
			    bc--;
		    }
		    cur--;
	    }
	    if (ac == -1 && bc >= 0){
		    while(cur >= 0){
			    A[cur] = B[bc];
			    bc--;
			    cur--;
		    }
	    }
    }
};

class ClimbingStairs {
public:
    int climbStairs(int n) {
	    int A[n+1];
	    A[1] = 1;
	    A[2] = 2;
	    for (int i = 3; i < n+1; i++) {
		    A[i] = A[i - 1] + A[i - 2];
	    }
	    return A[n];
    }
};

// TODO -符号的处理
class ValidNumber {
public:
	int strlen(const char* s){
		int i = 0;
		while(s[i]!=0){
			i++;
		}
		return i;
	}

	void space_detect(const char *s, int & left, int & right){
		int len = strlen(s);
		cout << "len=" << len<< endl;

		for(int i = 0; i < len; ++i){
			cout << "i=" << i << endl;
			if(s[i] != ' '){
				left = i;
				break;
			}

		}
		for (int i = len-1; i >= 0; --i){
			if(s[i] != ' '){
				right = i+1;
				break;
			}
		}
	}

	bool isNumber(const char *s) {
		int state = 0;
		int left, right;
		space_detect(s, left, right);
		cout << left << ' ' << right << endl;
		for(int i = left; i < right ;++i){
			cout << "state = " << state << endl;

			if (s[i] == ' '){
				return false;
			}
			state = switch_state(state, s[i]);
			if(state < 0){
				return false;
			}
		}
		if(state == 1 || state ==  2 || state == 3 || state==5){
			return true;
		}else{
			return false;
		}
	}

	int switch_state(int now, char c){
		switch(now){
		case 0:
			if (c >= '0' && c <= '9'){
				return 1;
			}
			if (c == '.'){
				return 6;
			}
			return -1;
		case 1:
			if (c >= '0' && c <= '9'){
				return 1;
			}

			if (c == '.'){
				return 2;
			}
			if (c == 'e'){
				return 4;
			}
			return -1;
		case 2:
			if (c >= '0' && c <= '9'){
				return 3;
			}
			return -1;
		case 3:
			if (c >= '0' && c <= '9'){
				return 3;
			}
			if (c == 'e'){
				return 4;
			}
			return -1;
		case 4:
			if (c >= '0' && c <= '9'){
				return 5;
			}
			return -1;
		case 5:
			if (c >= '0' && c <= '9'){
				return 5;
			}
			return -1;
		case 6:
			if (c >= '0' && c <= '9'){
				return 3;
			}
			return -1;
		default:
			return -1;
		}
	}
};

class LengthofLastWord {
        public:
                int lengthOfLastWord(const char *s) {
                        bool in_space_region = true;
                        int i, len = 0;
                        int last_len = 0;
                        for (i = 0; s[i] != 0; ++i) {
                                if (s[i] == ' ' && !in_space_region) {
                                        last_len = len;
                                        len = 0;
                                        in_space_region = true;
                                }
                                if (s[i] != ' ' && in_space_region) {
                                        len = 0;
                                        in_space_region = false;
                                }
                                if (s[i] != ' ' && !in_space_region) {
                                        len++;
                                }
                        }
                        if(i == 0){
                                return 0;
                        }
                        if (s[i - 1] != ' ')
                                return len;
                        else
                                return last_len;
                }
};

int main(int argc, char *argv[])
{
	LengthofLastWord vn;
std::cout << vn.lengthOfLastWord("b a ")<< endl;
std::cout << vn.lengthOfLastWord("aasdfasdf wo")<< endl;
std::cout << vn.lengthOfLastWord("aasdfasdf wo ")<< endl;
std::cout << vn.lengthOfLastWord("hello world")<< endl;
std::cout << vn.lengthOfLastWord(" ")<< endl;

std::cout << vn.lengthOfLastWord("a ")<< endl;
std::cout << vn.lengthOfLastWord("a")<< endl;
std::cout << vn.lengthOfLastWord("")<< endl;

	return 0;
}

<commit_msg>AddBinary<commit_after>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;

struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x):val(x), next(NULL){}
};

class RemoveDuplicatesfromSortedList {
public:
    ListNode *deleteDuplicates(ListNode *head) {
	    if (head == NULL){
		    return NULL;
	    }
	    ListNode* cur = head;
	    ListNode* next = head->next;
	    while(cur != NULL){
		    while(next != NULL && cur->val == next->val){
			    next = next->next;
		    }
		    cur->next = next;
		    cur = next;
	    }
	    return head;
    }
};

class MergeSortedArray {
public:
    void merge(int A[], int m, int B[], int n) {
	    int cur = m+n-1;
	    int ac = m-1;
	    int bc = n-1;
	    while(ac >= 0 && bc >= 0){
		    if(A[ac]>B[bc]){
			    A[cur] = A[ac];
			    ac--;
		    }else{
			    A[cur] = B[bc];
			    bc--;
		    }
		    cur--;
	    }
	    if (ac == -1 && bc >= 0){
		    while(cur >= 0){
			    A[cur] = B[bc];
			    bc--;
			    cur--;
		    }
	    }
    }
};

class ClimbingStairs {
public:
    int climbStairs(int n) {
	    int A[n+1];
	    A[1] = 1;
	    A[2] = 2;
	    for (int i = 3; i < n+1; i++) {
		    A[i] = A[i - 1] + A[i - 2];
	    }
	    return A[n];
    }
};

// TODO -符号的处理
class ValidNumber {
public:
	int strlen(const char* s){
		int i = 0;
		while(s[i]!=0){
			i++;
		}
		return i;
	}

	void space_detect(const char *s, int & left, int & right){
		int len = strlen(s);
		cout << "len=" << len<< endl;

		for(int i = 0; i < len; ++i){
			cout << "i=" << i << endl;
			if(s[i] != ' '){
				left = i;
				break;
			}

		}
		for (int i = len-1; i >= 0; --i){
			if(s[i] != ' '){
				right = i+1;
				break;
			}
		}
	}

	bool isNumber(const char *s) {
		int state = 0;
		int left, right;
		space_detect(s, left, right);
		cout << left << ' ' << right << endl;
		for(int i = left; i < right ;++i){
			cout << "state = " << state << endl;

			if (s[i] == ' '){
				return false;
			}
			state = switch_state(state, s[i]);
			if(state < 0){
				return false;
			}
		}
		if(state == 1 || state ==  2 || state == 3 || state==5){
			return true;
		}else{
			return false;
		}
	}

	int switch_state(int now, char c){
		switch(now){
		case 0:
			if (c >= '0' && c <= '9'){
				return 1;
			}
			if (c == '.'){
				return 6;
			}
			return -1;
		case 1:
			if (c >= '0' && c <= '9'){
				return 1;
			}

			if (c == '.'){
				return 2;
			}
			if (c == 'e'){
				return 4;
			}
			return -1;
		case 2:
			if (c >= '0' && c <= '9'){
				return 3;
			}
			return -1;
		case 3:
			if (c >= '0' && c <= '9'){
				return 3;
			}
			if (c == 'e'){
				return 4;
			}
			return -1;
		case 4:
			if (c >= '0' && c <= '9'){
				return 5;
			}
			return -1;
		case 5:
			if (c >= '0' && c <= '9'){
				return 5;
			}
			return -1;
		case 6:
			if (c >= '0' && c <= '9'){
				return 3;
			}
			return -1;
		default:
			return -1;
		}
	}
};

class LengthofLastWord {
        public:
                int lengthOfLastWord(const char *s) {
                        bool in_space_region = true;
                        int i, len = 0;
                        int last_len = 0;
                        for (i = 0; s[i] != 0; ++i) {
                                if (s[i] == ' ' && !in_space_region) {
                                        last_len = len;
                                        len = 0;
                                        in_space_region = true;
                                }
                                if (s[i] != ' ' && in_space_region) {
                                        len = 0;
                                        in_space_region = false;
                                }
                                if (s[i] != ' ' && !in_space_region) {
                                        len++;
                                }
                        }
                        if(i == 0){
                                return 0;
                        }
                        if (s[i - 1] != ' ')
                                return len;
                        else
                                return last_len;
                }
};

class AddBinary {
public:
    string addBinary(string a, string b) {
            int max_len = max(a.length(), b.length());
            vector<int> va = str2int_vector(a, max_len);
            vector<int> vb = str2int_vector(b, max_len);
            plus(va, vb);
            return vector2str(va);
    }

    string vector2str(vector<int> v){
            string s;
            int start = 0;
            if(v[0] == 0){
                    start++;
            }
            for (int i = start; i< v.size(); ++i) {
                    s.push_back(v[i]+'0');
            }
            return s;
    }
    void plus(vector<int> &a, vector<int> &b){
            for(int i = a.size()-1; i > 0; --i){
                    a[i] += b[i];
            }
            for(int i = a.size()-1; i > 0; --i){
                    if (a[i] > 1){
                            a[i-1] += a[i]/2;
                            a[i] = a[i]%2;
                    }
            }
    }
    vector<int> str2int_vector(string& s, int max_len){
            vector<int> v(max_len+1, 0);
            for(int i = max_len,j = s.length()-1;j >= 0; --i, --j){
                    v[i] = s[j] - '0';
            }
            return v;
    }
};

int main(int argc, char *argv[])
{
	LengthofLastWord vn;
std::cout << vn.lengthOfLastWord("b a ")<< endl;
std::cout << vn.lengthOfLastWord("aasdfasdf wo")<< endl;
std::cout << vn.lengthOfLastWord("aasdfasdf wo ")<< endl;
std::cout << vn.lengthOfLastWord("hello world")<< endl;
std::cout << vn.lengthOfLastWord(" ")<< endl;

std::cout << vn.lengthOfLastWord("a ")<< endl;
std::cout << vn.lengthOfLastWord("a")<< endl;
std::cout << vn.lengthOfLastWord("")<< endl;

	return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2015 Intel(r) 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.
 *
 */

/*
 * This sample demonstrates how to use built-in compression algorithms for metatada saving.
 * Compressed metadata loading is performed as usual for built-in compression algorithms.
 */

#include <iostream>
#include <fstream>
#include <stdexcept>

#include "vmf/vmf.hpp"

#include "compress_common.hpp"
#include "my_lzw.hpp"

using namespace std;
using namespace vmf;

int compress_custom(const string& videoFile)
{
    cout << "Custom compression usage sample:" << endl;

    MetadataStream mdStream;
    if (!mdStream.open(videoFile, MetadataStream::Update | MetadataStream::IgnoreUnknownCompressor))
    {
        cerr << "Can't open file '" + videoFile + "'" << endl;
        exit(1);
    }

    cout << "Generating metadata..." << endl;
    generateMetadata(mdStream);

    cout << "Registering custom compressor..." << endl;
    shared_ptr<Compressor> compressor = make_shared<MyLZWCompressor>();
    Compressor::registerNew(compressor);

    cout << "Trfying to save metadata using unregister compressor..." << endl;
    if (mdStream.save("unknown_compressor_ID"))
        cout << "VMF error: it shouldn't allow saving with unregistered compressor" << endl;
    else
        cout << "VMF is right: it can't use unregistered compressor!" << endl;

    cout << "Saving metadata using custom just registered compressor (" << compressor->getId() << ")..." << endl;
    mdStream.save(compressor->getId());

    mdStream.close();

    cout << "Loading metadata back..." << endl;
    readAndDumpMetadata(videoFile);

    cout << "Unregistering custom '" << compressor->getId() << "' compressor (it's optional here)..." << endl;
    vmf::Compressor::unregister(compressor->getId());

    cout << "That's all!" << endl;
    return 0;
}
<commit_msg>typo fixed<commit_after>/*
 * Copyright 2015 Intel(r) 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.
 *
 */

/*
 * This sample demonstrates how to use built-in compression algorithms for metatada saving.
 * Compressed metadata loading is performed as usual for built-in compression algorithms.
 */

#include <iostream>
#include <fstream>
#include <stdexcept>

#include "vmf/vmf.hpp"

#include "compress_common.hpp"
#include "my_lzw.hpp"

using namespace std;
using namespace vmf;

int compress_custom(const string& videoFile)
{
    cout << "Custom compression usage sample:" << endl;

    MetadataStream mdStream;
    if (!mdStream.open(videoFile, MetadataStream::Update | MetadataStream::IgnoreUnknownCompressor))
    {
        cerr << "Can't open file '" + videoFile + "'" << endl;
        exit(1);
    }

    cout << "Generating metadata..." << endl;
    generateMetadata(mdStream);

    cout << "Registering custom compressor..." << endl;
    shared_ptr<Compressor> compressor = make_shared<MyLZWCompressor>();
    Compressor::registerNew(compressor);

    cout << "Trying to save metadata using unregister compressor..." << endl;
    if (mdStream.save("unknown_compressor_ID"))
        cout << "VMF error: it shouldn't allow saving with unregistered compressor" << endl;
    else
        cout << "VMF is right: it can't use unregistered compressor!" << endl;

    cout << "Saving metadata using custom just registered compressor (" << compressor->getId() << ")..." << endl;
    mdStream.save(compressor->getId());

    mdStream.close();

    cout << "Loading metadata back..." << endl;
    readAndDumpMetadata(videoFile);

    cout << "Unregistering custom '" << compressor->getId() << "' compressor (it's optional here)..." << endl;
    vmf::Compressor::unregister(compressor->getId());

    cout << "That's all!" << endl;
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Make ListBox handier post dispose.<commit_after><|endoftext|>


<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"

#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 15 //in ms
#define WIN_SIZE 16

using namespace std;

bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();

struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;

int main(int argc, char** argv) {

  if(!init(argc, argv)) return -1;

  if(sendFile()) cout << "GET Testfile complete." << endl;

  return 0;
}

bool init(int argc, char** argv){

  if(argc != 6) {
    cout << USAGE << endl;
    return false;
  }

  char * probCorruptStr = argv[2];
  probCorrupt = boost::lexical_cast<int>(probCorruptStr);
  char * probLossStr = argv[3];
  probLoss = boost::lexical_cast<int>(probLossStr);
  char * probDelayStr = argv[4];
  probDelay = boost::lexical_cast<int>(probDelayStr);
  char* delayTStr = argv[5];
  delayT = boost::lexical_cast<int>(delayTStr);

  struct timeval timeout;
  timeout.tv_usec = TIMEOUT * 1000;
  toms = TIMEOUT;

  /* Create our socket. */
  if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    cout << "Socket creation failed. (socket s)" << endl;
    return 0;
  }

  setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));

  /*
   * Bind our socket to an IP (whatever the computer decides)
   * and a specified port.
   *
   */

  if (!loadFile()) {
    cout << "Loading file failed. (filename FILENAME)" << endl;
    return false;
  }

  memset((char *)&a, 0, sizeof(a));
  a.sin_family = AF_INET;
  a.sin_addr.s_addr = htonl(INADDR_ANY);
  a.sin_port = htons(PORT);

  if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
    cout << "Socket binding failed. (socket s, address a)" << endl;
    return 0;
  }

  fstr = string(file);
  cout << "File: " << endl << fstr << endl;

  base = 0;
  dropPck = false;
  calen = sizeof(ca);

  getGet();

  return true;
}

bool getGet(){
	unsigned char packet[PAKSIZE + 1];
	rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
	return (rlen > 0) ? true : false;
}

bool isvpack(unsigned char * p) {
  cout << endl << "=== IS VALID PACKET TESTING" << endl;

  char * sns = new char[2];
  memcpy(sns, &p[0], 1);
  sns[1] = '\0';

  char * css = new char[7];
  memcpy(css, &p[1], 6);
  css[6] = '\0';

  char * db = new char[121 + 1];
  memcpy(db, &p[2], 121);
  db[121] = '\0';

  cout << "Seq. num: " << sns << endl;
  cout << "Checksum: " << css << endl;
  cout << "Message: " << db << endl;

  int sn = boost::lexical_cast<int>(sns);
  int cs = boost::lexical_cast<int>(css);

  Packet pk (0, db);
  pk.setSequenceNum(sn);

  // change to validate based on checksum and sequence number

  if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
  if(cs != pk.generateCheckSum()) return false;
  return true;
}

bool getFile(){

  /* Loop forever, waiting for messages from a client. */
  cout << "Waiting on port " << PORT << "..." << endl;

  ofstream file("Dumpfile");

  for (;;) {
    unsigned char packet[PAKSIZE + 1];
    unsigned char dataPull[PAKSIZE - 7 + 1];
    rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);

    for(int x = 0; x < PAKSIZE - 7; x++) {
      dataPull[x] = packet[x + 7];
    }
    dataPull[PAKSIZE - 7] = '\0';
    packet[PAKSIZE] = '\0';
    if (rlen > 0) {
      char * css = new char[6];
      memcpy(css, &packet[1], 5);
      css[5] = '\0';
      cout << endl << endl << "=== RECEIPT" << endl;
      cout << "Seq. num: " << packet[0] << endl;
      cout << "Checksum: " << css << endl;
      cout << "Received message: " << dataPull << endl;
      cout << "Sent response: ";
      if(isvpack(packet)) {
        ack = ACK;
        //seqNum = (seqNum) ? false : true;
        file << dataPull;
      } else {
        ack = NAK;
      }
      cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
      Packet p (false, reinterpret_cast<const char *>(dataPull));
      p.setCheckSum(boost::lexical_cast<int>(css));
      p.setAckNack(ack);

      if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
        cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
        return 0;
      }
      delete css;
    }
  }
  file.close();
  return true;
}

bool loadFile() {

  ifstream is (FILENAME, ifstream::binary);

  if(is) {
    is.seekg(0, is.end);
    length = is.tellg();
    is.seekg(0, is.beg);

    file = new char[length];

    cout << "Reading " << length << " characters..." << endl;
    is.read(file, length);

    if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
    is.close();
  }
  return true;
}

void loadWindow(){
	for(int i = base; i < base + WIN_SIZE; i++) {
		window[i-base] = createPacket(i);
		if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
			cout << "In loadWindow's secret base, index is: " << i-base << endl;
			for(++i; i < base + WIN_SIZE; i++){
				window[i-base].loadDataBuffer("\0");
			}

		}
		/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
	}

		/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
		cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}

bool sendFile() {
	/*Currently causes the program to only send the first 16 packets of file out
		requires additional code later to sendFile again with updated window*/
	fd_set stReadFDS;

	struct timeval stTimeOut;

	FD_ZERO(&stReadFDS);
	stTimeOut.tv_sec = 0;
	stTimeOut.tv_usec = 1000 * TIMEOUT;
	FD_SET(s, &stReadFDS);

	base = 0;
	int desc_ready;
	int finale = -1;
	int max_sd;
	bool hasRead = false;
	while(base * BUFSIZE < length) {
		loadWindow();

		if(p.str()[0] == '\0') finale = p.getSequenceNum();
		for(int x = 0; x < WIN_SIZE; x++) {
			p = window[x];
			if(!sendPacket()) continue;
		}
		while(finale < 14) {
			cout << endl << "beginning of loop " << finale << endl;
			FD_ZERO(&stReadFDS);
			stTimeOut.tv_sec = 0;
			stTimeOut.tv_usec = 1000 * TIMEOUT;
			FD_SET(s, &stReadFDS);

			max_sd = s;
			cout << endl << "before select" << endl;
			int t = select(max_sd + 1, &stReadFDS, NULL, NULL, &stTimeOut);
			cout << "after select" << endl;
			if (t == -1){
				perror("select()");
			}
			if (t == 0) {
				cout << "=== ACK TIMEOUT (select)" << endl;

			}
			desc_ready = t;
			for(int u = 0; u <= max_sd  &&  desc_ready > 0; u++){
				if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
					cout << "=== ACK TIMEOUT (recvfrom)" << endl;
				} else hasRead = true;
				if(!hasRead) continue;
				if(isAck()) {
					cout << "if isAck()" << endl;
					handleAck();
					finale++;
					cout << "Finale is: " << finale << endl;
				} else {
					cout << "Not an ACK!" << endl;
				}
			}
			cout << "end of loop " << finale << endl;
			/*if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;}
			memset(b, 0, BUFSIZE);
			}*/

		}
	}
	if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
	}
	return true;
}

Packet createPacket(int index){
    string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);

	if(mstr.length() < BUFSIZE) {
		cout << "Null terminated mstr." << endl;
		mstr[length - (index * BUFSIZE)] = '\0';
    }

	cout << "index: " << index << endl;
    return Packet (index, mstr.c_str());
}

bool sendPacket(){
	cout << endl;
    cout << "=== TRANSMISSION START" << endl;
	cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
    int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
	bool* pckStatus = gremlin(&p, pc, pl, pd);

	dropPck = pckStatus[0];
	delayPck = pckStatus[1];

	if (dropPck == true) return false;
	if (delayPck == true) p.setAckNack(1);

    if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
    }
    return true;
}
bool isAck() {
    cout << endl << "=== SERVER RESPONSE TEST" << endl;
    cout << "Data: " << b << endl;
    if(b[6] == '\0') return true;
    else return false;
}
void handleAck() {
	int ack = boost::lexical_cast<int>(b);
	if(base < ack) base = ack;
	cout << "Window base: " << base << endl;
}
void handleNak(int& x) {

      char * sns = new char[2];
      memcpy(sns, &b[0], 1);
      sns[1] = '\0';

      char * css = new char[5];
      memcpy(css, &b[1], 5);

      char * db = new char[BUFSIZE + 1];
      memcpy(db, &b[2], BUFSIZE);
      db[BUFSIZE] = '\0';

      cout << "Sequence number: " << sns << endl;
      cout << "Checksum: " << css << endl;

      Packet pk (0, db);
      pk.setSequenceNum(boost::lexical_cast<int>(sns));
      pk.setCheckSum(boost::lexical_cast<int>(css));

      if(!pk.chksm()) x--;
      else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){

  bool* packStatus = new bool[2];
  int r = rand() % 100;

  cout << "Corruption probability: " << corruptProb << endl;
  cout << "Random number: " << r << endl;

  packStatus[0] = false;
  packStatus[1] = false;

  if(r <= (lossProb)){
	packStatus[0] = true;
    cout << "Dropped!" << endl;
  }
  else if(r <= (delayProb)){
	  packStatus[1] = true;
	  cout << "Delayed!" << endl;
  }
  else if(r <= (corruptProb)){
    cout << "Corrupted!" << endl;
	cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
    pack->loadDataBuffer((char*)"GREMLIN LOL");
  }
  cout << "Seq. num: " << pack->getSequenceNum() << endl;
  cout << "Checksum: " << pack->getCheckSum() << endl;
  //cout << "Message: "  << pack->getDataBuffer() << endl;

  return packStatus;
}<commit_msg>new test statement<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"

#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 15 //in ms
#define WIN_SIZE 16

using namespace std;

bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();

struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;

int main(int argc, char** argv) {

  if(!init(argc, argv)) return -1;

  if(sendFile()) cout << "GET Testfile complete." << endl;

  return 0;
}

bool init(int argc, char** argv){

  if(argc != 6) {
    cout << USAGE << endl;
    return false;
  }

  char * probCorruptStr = argv[2];
  probCorrupt = boost::lexical_cast<int>(probCorruptStr);
  char * probLossStr = argv[3];
  probLoss = boost::lexical_cast<int>(probLossStr);
  char * probDelayStr = argv[4];
  probDelay = boost::lexical_cast<int>(probDelayStr);
  char* delayTStr = argv[5];
  delayT = boost::lexical_cast<int>(delayTStr);

  struct timeval timeout;
  timeout.tv_usec = TIMEOUT * 1000;
  toms = TIMEOUT;

  /* Create our socket. */
  if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    cout << "Socket creation failed. (socket s)" << endl;
    return 0;
  }

  setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));

  /*
   * Bind our socket to an IP (whatever the computer decides)
   * and a specified port.
   *
   */

  if (!loadFile()) {
    cout << "Loading file failed. (filename FILENAME)" << endl;
    return false;
  }

  memset((char *)&a, 0, sizeof(a));
  a.sin_family = AF_INET;
  a.sin_addr.s_addr = htonl(INADDR_ANY);
  a.sin_port = htons(PORT);

  if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
    cout << "Socket binding failed. (socket s, address a)" << endl;
    return 0;
  }

  fstr = string(file);
  cout << "File: " << endl << fstr << endl;

  base = 0;
  dropPck = false;
  calen = sizeof(ca);

  getGet();

  return true;
}

bool getGet(){
	unsigned char packet[PAKSIZE + 1];
	rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
	return (rlen > 0) ? true : false;
}

bool isvpack(unsigned char * p) {
  cout << endl << "=== IS VALID PACKET TESTING" << endl;

  char * sns = new char[2];
  memcpy(sns, &p[0], 1);
  sns[1] = '\0';

  char * css = new char[7];
  memcpy(css, &p[1], 6);
  css[6] = '\0';

  char * db = new char[121 + 1];
  memcpy(db, &p[2], 121);
  db[121] = '\0';

  cout << "Seq. num: " << sns << endl;
  cout << "Checksum: " << css << endl;
  cout << "Message: " << db << endl;

  int sn = boost::lexical_cast<int>(sns);
  int cs = boost::lexical_cast<int>(css);

  Packet pk (0, db);
  pk.setSequenceNum(sn);

  // change to validate based on checksum and sequence number

  if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
  if(cs != pk.generateCheckSum()) return false;
  return true;
}

bool getFile(){

  /* Loop forever, waiting for messages from a client. */
  cout << "Waiting on port " << PORT << "..." << endl;

  ofstream file("Dumpfile");

  for (;;) {
    unsigned char packet[PAKSIZE + 1];
    unsigned char dataPull[PAKSIZE - 7 + 1];
    rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);

    for(int x = 0; x < PAKSIZE - 7; x++) {
      dataPull[x] = packet[x + 7];
    }
    dataPull[PAKSIZE - 7] = '\0';
    packet[PAKSIZE] = '\0';
    if (rlen > 0) {
      char * css = new char[6];
      memcpy(css, &packet[1], 5);
      css[5] = '\0';
      cout << endl << endl << "=== RECEIPT" << endl;
      cout << "Seq. num: " << packet[0] << endl;
      cout << "Checksum: " << css << endl;
      cout << "Received message: " << dataPull << endl;
      cout << "Sent response: ";
      if(isvpack(packet)) {
        ack = ACK;
        //seqNum = (seqNum) ? false : true;
        file << dataPull;
      } else {
        ack = NAK;
      }
      cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
      Packet p (false, reinterpret_cast<const char *>(dataPull));
      p.setCheckSum(boost::lexical_cast<int>(css));
      p.setAckNack(ack);

      if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
        cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
        return 0;
      }
      delete css;
    }
  }
  file.close();
  return true;
}

bool loadFile() {

  ifstream is (FILENAME, ifstream::binary);

  if(is) {
    is.seekg(0, is.end);
    length = is.tellg();
    is.seekg(0, is.beg);

    file = new char[length];

    cout << "Reading " << length << " characters..." << endl;
    is.read(file, length);

    if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
    is.close();
  }
  return true;
}

void loadWindow(){
	for(int i = base; i < base + WIN_SIZE; i++) {
		window[i-base] = createPacket(i);
		if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
			cout << "In loadWindow's secret base, index is: " << i-base << endl;
			for(++i; i < base + WIN_SIZE; i++){
				window[i-base].loadDataBuffer("\0");
			}

		}
		/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
	}

		/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
		cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}

bool sendFile() {
	/*Currently causes the program to only send the first 16 packets of file out
		requires additional code later to sendFile again with updated window*/
	fd_set stReadFDS;

	struct timeval stTimeOut;

	FD_ZERO(&stReadFDS);
	stTimeOut.tv_sec = 0;
	stTimeOut.tv_usec = 1000 * TIMEOUT;
	FD_SET(s, &stReadFDS);

	base = 0;
	int desc_ready;
	int finale = -1;
	int max_sd;
	bool hasRead = false;
	while(base * BUFSIZE < length) {
		cout << "Time to load window!" << endl;
		loadWindow();

		if(p.str()[0] == '\0') finale = p.getSequenceNum();
		for(int x = 0; x < WIN_SIZE; x++) {
			p = window[x];
			if(!sendPacket()) continue;
		}
		while(finale < 14) {
			cout << endl << "beginning of loop " << finale << endl;
			FD_ZERO(&stReadFDS);
			stTimeOut.tv_sec = 0;
			stTimeOut.tv_usec = 1000 * TIMEOUT;
			FD_SET(s, &stReadFDS);

			max_sd = s;
			cout << endl << "before select" << endl;
			int t = select(max_sd + 1, &stReadFDS, NULL, NULL, &stTimeOut);
			cout << "after select" << endl;
			if (t == -1){
				perror("select()");
			}
			if (t == 0) {
				cout << "=== ACK TIMEOUT (select)" << endl;

			}
			desc_ready = t;
			for(int u = 0; u <= max_sd  &&  desc_ready > 0; u++){
				if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
					cout << "=== ACK TIMEOUT (recvfrom)" << endl;
				} else hasRead = true;
				if(!hasRead) continue;
				if(isAck()) {
					cout << "if isAck()" << endl;
					handleAck();
					finale++;
					cout << "Finale is: " << finale << endl;
				} else {
					cout << "Not an ACK!" << endl;
				}
			}
			cout << "end of loop " << finale << endl;
			/*if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;}
			memset(b, 0, BUFSIZE);
			}*/

		}
	}
	if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
	}
	return true;
}

Packet createPacket(int index){
    string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);

	if(mstr.length() < BUFSIZE) {
		cout << "Null terminated mstr." << endl;
		mstr[length - (index * BUFSIZE)] = '\0';
    }

	cout << "index: " << index << endl;
    return Packet (index, mstr.c_str());
}

bool sendPacket(){
	cout << endl;
    cout << "=== TRANSMISSION START" << endl;
	cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
    int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
	bool* pckStatus = gremlin(&p, pc, pl, pd);

	dropPck = pckStatus[0];
	delayPck = pckStatus[1];

	if (dropPck == true) return false;
	if (delayPck == true) p.setAckNack(1);

    if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
		cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
		return false;
    }
    return true;
}
bool isAck() {
    cout << endl << "=== SERVER RESPONSE TEST" << endl;
    cout << "Data: " << b << endl;
    if(b[6] == '\0') return true;
    else return false;
}
void handleAck() {
	int ack = boost::lexical_cast<int>(b);
	if(base < ack) base = ack;
	cout << "Window base: " << base << endl;
}
void handleNak(int& x) {

      char * sns = new char[2];
      memcpy(sns, &b[0], 1);
      sns[1] = '\0';

      char * css = new char[5];
      memcpy(css, &b[1], 5);

      char * db = new char[BUFSIZE + 1];
      memcpy(db, &b[2], BUFSIZE);
      db[BUFSIZE] = '\0';

      cout << "Sequence number: " << sns << endl;
      cout << "Checksum: " << css << endl;

      Packet pk (0, db);
      pk.setSequenceNum(boost::lexical_cast<int>(sns));
      pk.setCheckSum(boost::lexical_cast<int>(css));

      if(!pk.chksm()) x--;
      else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){

  bool* packStatus = new bool[2];
  int r = rand() % 100;

  cout << "Corruption probability: " << corruptProb << endl;
  cout << "Random number: " << r << endl;

  packStatus[0] = false;
  packStatus[1] = false;

  if(r <= (lossProb)){
	packStatus[0] = true;
    cout << "Dropped!" << endl;
  }
  else if(r <= (delayProb)){
	  packStatus[1] = true;
	  cout << "Delayed!" << endl;
  }
  else if(r <= (corruptProb)){
    cout << "Corrupted!" << endl;
	cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
    pack->loadDataBuffer((char*)"GREMLIN LOL");
  }
  cout << "Seq. num: " << pack->getSequenceNum() << endl;
  cout << "Checksum: " << pack->getCheckSum() << endl;
  //cout << "Message: "  << pack->getDataBuffer() << endl;

  return packStatus;
}<|endoftext|>


<commit_before><commit_msg>bSearch has constantly been true<commit_after><|endoftext|>


<commit_before>#include "game.hpp"

int Game::negamax(BitBoard & b, int alpha, int beta, int depth, int real_depth, int rule, bool inNullMove, bool cut) {
	++nodesCounter;

	uint64_t hash = b.getColorHash();
	Hash* currentHash = &boardHash[hash & hash_cutter];

	if(!b.currentState.hash_enable && real_depth > 0) {
		return 0;
	}

	int oldAlpha = alpha;

	if((currentHash->flag != EMPTY && currentHash->key == hash) && b.third_repeat[hash & hash_cutter] <= 1) {
		if(real_depth > 0 && currentHash->depth >= depth) {
			int score = currentHash->score;

			if(score > WHITE_WIN - 100) {
				score -= real_depth;
			} else if(score < -WHITE_WIN + 100) {
				score += real_depth;
			}

			if(currentHash->flag == BETA) {
				alpha = std::max(alpha, score);
			} else if(currentHash->flag == ALPHA) {
				beta = std::min(beta, score);
			} else if(currentHash->flag == EXACT) {
				return score;
			}

			if(alpha >= beta) {
				return score;
			}
		}
	}

	if(depth <= 0 || real_depth >= 100) {
		return quies(b, alpha, beta, rule, real_depth);
	}

	if(depth > 6) {
		if(is_input_available()) {
			std::string input_str;
			std::getline(std::cin, input_str);
			if(input_str == "stop") {
				stopped = true;
			} else if(input_str == "isready") {
				std::cout << "readyok" << std::endl;
			}
		}
	}

	if(real_depth) {
		max_real_depth = std::max(max_real_depth, real_depth);
	} else {
		max_real_depth = 0;
	}

	int eval = -WHITE_WIN;
	int nextDepth = depth - 1;
	int extensions = 0;

	bool checkMateNode = (std::abs(beta) >= WHITE_WIN - 100);

	if(depth > 2) {
		if((rule == FIXED_TIME && timer.getTime() >= time) || stopped) {
			return 0;
		}
	}

	uint8_t color = colorExtended[b.currentState.color];
	uint8_t enemyColor = colorExtended[!b.currentState.color];

	int tmp;
	bool inCheck = b.inCheck(color);
	bool onPV = (beta - alpha) > 1;
	int opposiing_pieces =  b.popcount64(b.currentState.piece_bit_mask[!b.currentState.color]);

	if(!inCheck && !inNullMove && depth < 10 && !onPV && opposiing_pieces > 3) { //Razoring
		int evaluate = b.getEvaluate();
		if(evaluate - RAZOR_MARGIN[depth] >= beta) {
			return beta;
		}
	}

	int num_moves = 0;

	b.bitBoardMoveGenerator(moveArray[real_depth]);
	sortAttacks(moveArray[real_depth]);
	sortMoves(moveArray[real_depth], real_depth);

	if(cut) { //Multi-Cut 82.91 +/- 24.04 (10+0.1)
		if (depth >= 4 && real_depth > 0 && !inCheck && !inNullMove && !extensions && !onPV && !b.currentState.attacked) {
			int c = 0;
			for (int i = 0; i < std::min((int)moveArray[real_depth].count, 6); ++i) {
				b.move(moveArray[real_depth].moveArray[i]);
				if(b.inCheck(color)) {
					b.goBack();
					continue;
				}

				tmp = -negamax(b, -(alpha + 1), -alpha, nextDepth - 4, real_depth + 1, rule, inNullMove, false);

				b.goBack();
				if (tmp >= beta) {
					if (++c == 2) {
						return beta;
					}
				}
			}
		}
	}

	BitMove* local_move = nullptr;

	if(moveArray[real_depth].count > 0) {
		local_move = &moveArray[real_depth].moveArray[0];
	}

	int low_moves_count = 0;

	for(unsigned int i = 0; i < moveArray[real_depth].count; ++i) {
		b.move(moveArray[real_depth].moveArray[i]);

		if(game_board.inCheck(color)) {
			b.goBack();
			continue;
		}

		if(num_moves == 0) {
			local_move = &moveArray[real_depth].moveArray[i];
		}

		++num_moves;

		if(real_depth == 0 && depth >= 12) {
			if((rule != FIXED_TIME || timer.getTime() < time) && !stopped) {
				std::cout << "info currmove " << moveArray[real_depth].moveArray[i].getMoveString() << " currmovenumber " << num_moves << " time " << (int64_t)((clock() - start_timer) / (CLOCKS_PER_SEC / 1000)) << " nodes " << nodesCounter << " nps " << (int64_t)(nodesCounter / ((clock() - start_timer) / CLOCKS_PER_SEC)) << std::endl;
			}
		}

		extensions = 0;
		if(b.inCheck(enemyColor)) {
			++extensions;
		}

		nextDepth = depth - 1;
		nextDepth += extensions;
		double reduction = 0;

		if(!extensions && !inNullMove && !moveArray[real_depth].moveArray[i].isAttack && !onPV && !inCheck) {
			++low_moves_count;

			if(low_moves_count > 3) {
				reduction = 1 + low_moves_count / 6;
				nextDepth -= reduction;
			}

			if(nextDepth <= 2) {
				if(-b.getEvaluate() + PAWN_EV.mg / 2 <= alpha) {
					++nodesCounter;
					b.goBack();
					continue;
				}
			}
		}

		if(num_moves == 1) {
			tmp = -negamax(b, -beta, -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);
		} else {
			tmp = -negamax(b, -(alpha + 1), -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);

			if(reduction > 0 && tmp > alpha) {
				nextDepth += reduction;
				tmp = -negamax(b, -(alpha + 1), -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);
			}

			if(tmp > alpha && tmp < beta) {
				tmp = -negamax(b, -beta, -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);
			}
		}

		b.goBack();

		if(tmp > eval) {
			eval = tmp;
		}

		if(tmp > alpha) {
			alpha = tmp;
			local_move = &moveArray[real_depth].moveArray[i];
			recordHash(depth, tmp, tmp<beta?EXACT:BETA, hash, moveArray[real_depth].moveArray[i], real_depth);
		}

		if(alpha >= beta) {
			if(!local_move->isAttack) {
				historySort[b.currentState.color][local_move->fromY][local_move->fromX][local_move->toY][local_move->toX] += std::pow(depth, 2);

				if(color == WHITE) {
					if(whiteKiller[real_depth].enable) {
						whiteSecondKiller[real_depth] = Killer(whiteKiller[real_depth].move);
					}
					whiteKiller[real_depth] = Killer(*local_move);
				} else {
					if(blackKiller[real_depth].enable) {
						blackSecondKiller[real_depth] = Killer(blackKiller[real_depth].move);
					}
					blackKiller[real_depth] = Killer(*local_move);
				}
			}

			break;
		}
	}

	if(num_moves == 0) {
		if(game_board.inCheck(color)) {
			return BLACK_WIN + real_depth;
		} else {
			return 0;
		}
	}

	if(alpha == oldAlpha) {
		recordHash(depth, eval, ALPHA, hash, *local_move, real_depth);
	}

	if(real_depth == 0) {
		if((rule == FIXED_TIME && timer.getTime() >= time) || stopped) {
			return 0;
		}

		bestMove = *local_move;
		bestScore = alpha;
	}

	if(real_depth == 0) {
		if(num_moves >= 0) {
			std::cout << "info depth " << max_depth << " time " << (int64_t)((clock() - start_timer) / (CLOCKS_PER_SEC / 1000)) << " nodes " << nodesCounter << " nps " << (int64_t)(nodesCounter / ((clock() - start_timer) / CLOCKS_PER_SEC)) << " hashfull " << (int)(hash_filled / max_hash_filled * 1000) << " seldepth " << max_real_depth;
			std::cout << " ";
			printScore(eval);
			std::cout << " pv ";
			printPV(depth);
		} else {
			std::cout << std::endl;
		}
	}

	return eval;
}

uint64_t Game::perft(int depth) {
	uint64_t res = 0;
	if(depth == 0) {
		++combinations;

		return 1;
	}

	game_board.bitBoardMoveGenerator(moveArray[depth]);

	for(unsigned int i = 0; i < moveArray[depth].count; ++i) {
		game_board.move(moveArray[depth].moveArray[i]);
		if(game_board.currentState.color) {
			if(game_board.inCheck(BLACK)) {
				game_board.goBack();
				continue;
			}
		} else {
			if(game_board.inCheck(WHITE)) {
				game_board.goBack();
				continue;
			}
		}

		res += perft(depth - 1);
		game_board.goBack();
	}

	return res;
}

int Game::quies(BitBoard & b, int alpha, int beta, int rule, int real_depth) {
	int val = b.getEvaluate();

	if (val < alpha - QUEEN_EV.mg) {
   		return alpha;
	}

	if(val >= beta) {
		return val;
	}

	if(alpha < val) {
		alpha = val;
	}

	b.bitBoardAttackMoveGenerator(moveArray[real_depth]);
	sortAttacks(moveArray[real_depth]);

	for(unsigned int i = 0; i < moveArray[real_depth].count; ++i) {
		++nodesCounter;
		b.move(moveArray[real_depth].moveArray[i]);

		if(game_board.inCheck(colorExtended[!game_board.currentState.color])) {
			b.goBack();
			continue;
		}

		val = -quies(b, -beta, -alpha, rule, real_depth + 1);
		b.goBack();

		if(val >= beta) {
			return beta;
		}

		if(val > alpha) {
			alpha = val;
		}
	}

	return alpha;
}

bool Game::recordHash(int depth, int score, int flag, uint64_t key, BitMove move, int real_depth) {
	/*if(!game_board.currentState.hash_enable) {
		return false;
	}*/

	Hash* hash = &boardHash[key & hash_cutter];

	if(flag == ALPHA && (hash->flag == EXACT || hash->flag == BETA)) {
		return false;
	}

	if((hash->flag != EMPTY) && hash->depth > depth && hash->age == hashAge) {
		return false;
	}

	if(score > WHITE_WIN - 100) {
		score += real_depth;
	} else if(score < -WHITE_WIN + 100) {
		score -= real_depth;
	}

	if(hash->flag == EMPTY) {
		++hash_filled;
	}

	hash->depth = depth;
	hash->score = score;
	hash->flag = flag;
	hash->key = key;
	hash->age = hashAge;

	if(flag != ALPHA) {
		hash->setMove(move);
	}

	return true;
}

std::vector<BitMove> Game::extractPV(int depth) {
	int k;
	std::vector<BitMove> result;
	MoveArray moves;
	bool stopped;
	int stack_count = 0;
	for(k = 0; k < depth + 10; ++k) {
		stopped = true;
		uint64_t hash = game_board.getColorHash();
		Hash* currentHash = &boardHash[hash & hash_cutter];

		if(currentHash->flag == EXACT || currentHash->flag == BETA) {
			game_board.bitBoardMoveGenerator(moves);

			bool enable;
			BitMove mv = game_board.getMove(currentHash->fromY, currentHash->fromX, currentHash->toY, currentHash->toX, currentHash->replaced, currentHash->replacedFigure, enable);// currentHash->getMove();

			for(int i = 0; i < moves.count; ++i) {
				if(moves.moveArray[i].equal(mv)) {
					game_board.move(mv);
					++stack_count;
					if(game_board.currentState.color) {
						if(game_board.inCheck(BLACK)) {
							stopped = true;
						} else {
							stopped = false;
						}
					} else {
						if(game_board.inCheck(WHITE)) {
							stopped = true;
						} else {
							stopped = false;
						}
					}
				}
			}

			if(stopped || !enable) {
				break;
			}

			result.emplace_back(mv);
		} else {
			break;
		}
	}

	for(int i = 0; i < stack_count; ++i) {
		game_board.goBack();
	}

	return result;
}

bool Game::testMovePossible(BitMove move) {
	MoveArray moves;
	game_board.bitBoardMoveGenerator(moves);

	for(unsigned int i = 0; i < moves.count; ++i) {
		if(move.equal(moves.moveArray[i])) {
			return true;
		}
	}

	return false;
}

void Game::printPV(int depth) {
	std::vector<BitMove> main_pv = extractPV(depth);
	for(unsigned int i = 0; i < main_pv.size(); ++i) {
		std::cout << main_pv[i].getMoveString() << " ";
	}
	std::cout << std::endl;
}<commit_msg>Simplification<commit_after>#include "game.hpp"

int Game::negamax(BitBoard & b, int alpha, int beta, int depth, int real_depth, int rule, bool inNullMove, bool cut) {
	++nodesCounter;

	uint64_t hash = b.getColorHash();
	Hash* currentHash = &boardHash[hash & hash_cutter];

	int oldAlpha = alpha;

	if((currentHash->flag != EMPTY && currentHash->key == hash) && b.third_repeat[hash & hash_cutter] <= 1) {
		if(real_depth > 0 && currentHash->depth >= depth) {
			int score = currentHash->score;

			if(score > WHITE_WIN - 100) {
				score -= real_depth;
			} else if(score < -WHITE_WIN + 100) {
				score += real_depth;
			}

			if(currentHash->flag == BETA) {
				alpha = std::max(alpha, score);
			} else if(currentHash->flag == ALPHA) {
				beta = std::min(beta, score);
			} else if(currentHash->flag == EXACT) {
				return score;
			}

			if(alpha >= beta) {
				return score;
			}
		}
	}

	if(depth <= 0 || real_depth >= 100) {
		return quies(b, alpha, beta, rule, real_depth);
	}

	if(depth > 6) {
		if(is_input_available()) {
			std::string input_str;
			std::getline(std::cin, input_str);
			if(input_str == "stop") {
				stopped = true;
			} else if(input_str == "isready") {
				std::cout << "readyok" << std::endl;
			}
		}
	}

	if(real_depth) {
		max_real_depth = std::max(max_real_depth, real_depth);
	} else {
		max_real_depth = 0;
	}

	int eval = -WHITE_WIN;
	int nextDepth = depth - 1;
	int extensions = 0;

	if(depth > 2) {
		if((rule == FIXED_TIME && timer.getTime() >= time) || stopped) {
			return 0;
		}
	}

	uint8_t color = colorExtended[b.currentState.color];
	uint8_t enemyColor = colorExtended[!b.currentState.color];

	int tmp;
	bool inCheck = b.inCheck(color);
	bool onPV = (beta - alpha) > 1;
	int opposiing_pieces =  b.popcount64(b.currentState.piece_bit_mask[!b.currentState.color]);

	if(!inCheck && !inNullMove && depth < 10 && !onPV && opposiing_pieces > 3) { //Razoring
		int evaluate = b.getEvaluate();
		if(evaluate - RAZOR_MARGIN[depth] >= beta) {
			return beta;
		}
	}

	int num_moves = 0;

	b.bitBoardMoveGenerator(moveArray[real_depth]);
	sortAttacks(moveArray[real_depth]);
	sortMoves(moveArray[real_depth], real_depth);

	if(cut) { //Multi-Cut 82.91 +/- 24.04 (10+0.1)
		if (depth >= 4 && real_depth > 0 && !inCheck && !inNullMove && !extensions && !onPV && !b.currentState.attacked) {
			int c = 0;
			for (int i = 0; i < std::min((int)moveArray[real_depth].count, 6); ++i) {
				b.move(moveArray[real_depth].moveArray[i]);
				if(b.inCheck(color)) {
					b.goBack();
					continue;
				}

				tmp = -negamax(b, -(alpha + 1), -alpha, nextDepth - 4, real_depth + 1, rule, inNullMove, false);

				b.goBack();
				if (tmp >= beta) {
					if (++c == 2) {
						return beta;
					}
				}
			}
		}
	}

	BitMove* local_move = nullptr;

	if(moveArray[real_depth].count > 0) {
		local_move = &moveArray[real_depth].moveArray[0];
	}

	int low_moves_count = 0;

	for(unsigned int i = 0; i < moveArray[real_depth].count; ++i) {
		b.move(moveArray[real_depth].moveArray[i]);

		if(game_board.inCheck(color)) {
			b.goBack();
			continue;
		}

		if(num_moves == 0) {
			local_move = &moveArray[real_depth].moveArray[i];
		}

		++num_moves;

		if(real_depth == 0 && depth >= 12) {
			if((rule != FIXED_TIME || timer.getTime() < time) && !stopped) {
				std::cout << "info currmove " << moveArray[real_depth].moveArray[i].getMoveString() << " currmovenumber " << num_moves << " time " << (int64_t)((clock() - start_timer) / (CLOCKS_PER_SEC / 1000)) << " nodes " << nodesCounter << " nps " << (int64_t)(nodesCounter / ((clock() - start_timer) / CLOCKS_PER_SEC)) << std::endl;
			}
		}

		extensions = 0;
		if(b.inCheck(enemyColor)) {
			++extensions;
		}

		nextDepth = depth - 1;
		nextDepth += extensions;
		double reduction = 0;

		if(!extensions && !inNullMove && !moveArray[real_depth].moveArray[i].isAttack && !onPV && !inCheck) {
			++low_moves_count;

			if(low_moves_count > 3) {
				reduction = 1 + low_moves_count / 6;
				nextDepth -= reduction;
			}

			if(nextDepth <= 2) {
				if(-b.getEvaluate() + PAWN_EV.mg / 2 <= alpha) {
					++nodesCounter;
					b.goBack();
					continue;
				}
			}
		}

		if(num_moves == 1) {
			tmp = -negamax(b, -beta, -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);
		} else {
			tmp = -negamax(b, -(alpha + 1), -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);

			if(reduction > 0 && tmp > alpha) {
				nextDepth += reduction;
				tmp = -negamax(b, -(alpha + 1), -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);
			}

			if(tmp > alpha && tmp < beta) {
				tmp = -negamax(b, -beta, -alpha, nextDepth, real_depth + 1, rule, inNullMove, true);
			}
		}

		b.goBack();

		if(tmp > eval) {
			eval = tmp;
		}

		if(tmp > alpha) {
			alpha = tmp;
			local_move = &moveArray[real_depth].moveArray[i];
			recordHash(depth, tmp, tmp<beta?EXACT:BETA, hash, moveArray[real_depth].moveArray[i], real_depth);
		}

		if(alpha >= beta) {
			if(!local_move->isAttack) {
				historySort[b.currentState.color][local_move->fromY][local_move->fromX][local_move->toY][local_move->toX] += std::pow(depth, 2);

				if(color == WHITE) {
					if(whiteKiller[real_depth].enable) {
						whiteSecondKiller[real_depth] = Killer(whiteKiller[real_depth].move);
					}
					whiteKiller[real_depth] = Killer(*local_move);
				} else {
					if(blackKiller[real_depth].enable) {
						blackSecondKiller[real_depth] = Killer(blackKiller[real_depth].move);
					}
					blackKiller[real_depth] = Killer(*local_move);
				}
			}

			break;
		}
	}

	if(num_moves == 0) {
		if(game_board.inCheck(color)) {
			return BLACK_WIN + real_depth;
		} else {
			return 0;
		}
	}

	if(alpha == oldAlpha) {
		recordHash(depth, eval, ALPHA, hash, *local_move, real_depth);
	}

	if(real_depth == 0) {
		if((rule == FIXED_TIME && timer.getTime() >= time) || stopped) {
			return 0;
		}

		bestMove = *local_move;
		bestScore = alpha;
	}

	if(real_depth == 0) {
		if(num_moves >= 0) {
			std::cout << "info depth " << max_depth << " time " << (int64_t)((clock() - start_timer) / (CLOCKS_PER_SEC / 1000)) << " nodes " << nodesCounter << " nps " << (int64_t)(nodesCounter / ((clock() - start_timer) / CLOCKS_PER_SEC)) << " hashfull " << (int)(hash_filled / max_hash_filled * 1000) << " seldepth " << max_real_depth;
			std::cout << " ";
			printScore(eval);
			std::cout << " pv ";
			printPV(depth);
		} else {
			std::cout << std::endl;
		}
	}

	return eval;
}

uint64_t Game::perft(int depth) {
	uint64_t res = 0;
	if(depth == 0) {
		++combinations;

		return 1;
	}

	game_board.bitBoardMoveGenerator(moveArray[depth]);

	for(unsigned int i = 0; i < moveArray[depth].count; ++i) {
		game_board.move(moveArray[depth].moveArray[i]);
		if(game_board.currentState.color) {
			if(game_board.inCheck(BLACK)) {
				game_board.goBack();
				continue;
			}
		} else {
			if(game_board.inCheck(WHITE)) {
				game_board.goBack();
				continue;
			}
		}

		res += perft(depth - 1);
		game_board.goBack();
	}

	return res;
}

int Game::quies(BitBoard & b, int alpha, int beta, int rule, int real_depth) {
	int val = b.getEvaluate();

	if (val < alpha - QUEEN_EV.mg) {
   		return alpha;
	}

	if(val >= beta) {
		return val;
	}

	if(alpha < val) {
		alpha = val;
	}

	b.bitBoardAttackMoveGenerator(moveArray[real_depth]);
	sortAttacks(moveArray[real_depth]);

	for(unsigned int i = 0; i < moveArray[real_depth].count; ++i) {
		++nodesCounter;
		b.move(moveArray[real_depth].moveArray[i]);

		if(game_board.inCheck(colorExtended[!game_board.currentState.color])) {
			b.goBack();
			continue;
		}

		val = -quies(b, -beta, -alpha, rule, real_depth + 1);
		b.goBack();

		if(val >= beta) {
			return beta;
		}

		if(val > alpha) {
			alpha = val;
		}
	}

	return alpha;
}

bool Game::recordHash(int depth, int score, int flag, uint64_t key, BitMove move, int real_depth) {
	Hash* hash = &boardHash[key & hash_cutter];

	if(flag == ALPHA && (hash->flag == EXACT || hash->flag == BETA)) {
		return false;
	}

	if((hash->flag != EMPTY) && hash->depth > depth && hash->age == hashAge) {
		return false;
	}

	if(score > WHITE_WIN - 100) {
		score += real_depth;
	} else if(score < -WHITE_WIN + 100) {
		score -= real_depth;
	}

	if(hash->flag == EMPTY) {
		++hash_filled;
	}

	hash->depth = depth;
	hash->score = score;
	hash->flag = flag;
	hash->key = key;
	hash->age = hashAge;

	if(flag != ALPHA) {
		hash->setMove(move);
	}

	return true;
}

std::vector<BitMove> Game::extractPV(int depth) {
	int k;
	std::vector<BitMove> result;
	MoveArray moves;
	bool stopped;
	int stack_count = 0;
	for(k = 0; k < depth + 10; ++k) {
		stopped = true;
		uint64_t hash = game_board.getColorHash();
		Hash* currentHash = &boardHash[hash & hash_cutter];

		if(currentHash->flag == EXACT || currentHash->flag == BETA) {
			game_board.bitBoardMoveGenerator(moves);

			bool enable;
			BitMove mv = game_board.getMove(currentHash->fromY, currentHash->fromX, currentHash->toY, currentHash->toX, currentHash->replaced, currentHash->replacedFigure, enable);// currentHash->getMove();

			for(int i = 0; i < moves.count; ++i) {
				if(moves.moveArray[i].equal(mv)) {
					game_board.move(mv);
					++stack_count;
					if(game_board.currentState.color) {
						if(game_board.inCheck(BLACK)) {
							stopped = true;
						} else {
							stopped = false;
						}
					} else {
						if(game_board.inCheck(WHITE)) {
							stopped = true;
						} else {
							stopped = false;
						}
					}
				}
			}

			if(stopped || !enable) {
				break;
			}

			result.emplace_back(mv);
		} else {
			break;
		}
	}

	for(int i = 0; i < stack_count; ++i) {
		game_board.goBack();
	}

	return result;
}

bool Game::testMovePossible(BitMove move) {
	MoveArray moves;
	game_board.bitBoardMoveGenerator(moves);

	for(unsigned int i = 0; i < moves.count; ++i) {
		if(move.equal(moves.moveArray[i])) {
			return true;
		}
	}

	return false;
}

void Game::printPV(int depth) {
	std::vector<BitMove> main_pv = extractPV(depth);
	for(unsigned int i = 0; i < main_pv.size(); ++i) {
		std::cout << main_pv[i].getMoveString() << " ";
	}
	std::cout << std::endl;
}<|endoftext|>


<commit_before>#include "commands.h"

namespace commands {

std::random_device random_device;
std::default_random_engine random_engine{random_device()};

int hardware_threads = std::thread::hardware_concurrency();

bool verbose_grid{true};
int delay_ms{50};

// clang-format off
std::vector<command_structure> commands = {
  {"?",       "?",               "?", nullptr, &help,          "Print this help"},
  {"print",   "(p)rint",         "p", &print_grid, nullptr,    "Print current grid"},
  {"clear",   "(c)lear",         "c", &clear_grid, nullptr,    "Clear the grid"},
  {"resize",  "resi(z)e n",      "z", &resize_grid, nullptr,   "Set grid size to n x n and clear"},
  {"rules",   "rules s b",       "",  &set_rules, nullptr,     "Set game rules (Stay Alive, Born)"},
  {"set",     "(s)et x y",       "s", &set_cell, nullptr,      "Set cell at x y alive"},
  {"unset",   "(u)nset x y",     "u", &unset_cell, nullptr,    "Set cell at x y dead"},
  {"fill",    "(f)ill n",        "f", &fill_grid, nullptr,     "Set up to n cells alive"},
  {"threads", "(t)hreads n",     "t", &set_threads, nullptr,   "Set the amount of threads"},
  {"glider",  "(g)lider x y",    "g", &create_glider, nullptr, "Place a glider at x y"},
  {"load",    "(l)oad file x y", "l", &load_pattern, nullptr,  "Load pattern from file to x y"},
  {"export",  "e(x)port file",   "x", &export_cells, nullptr,  "Export a file to cells format"},
  {"quiet",   "(q)uiet",         "q", nullptr, &quiet,         "Disable output during running"},
  {"verbose", "(v)erbose",       "v", nullptr, &verbose,       "Enable output during running"},
  {"delay",   "(d)elay n",       "d", nullptr, &delay,         "Wait for n milliseconds after each step"},
  {"run",     "(r)un n",         "r", &run, nullptr,           "Run n iterations"},
  {"step",    "st(e)p",          "e", &step, nullptr,          "Run 1 iteration"},
  {"exit",    "exit",            "",  nullptr, &pexit,         "Exit"}
};
// clang-format on

constexpr int max_command_width{16};

bool command(std::string command, gol::Game_of_life &g) {
  for (auto c : commands) {
    if (command == c.name || command == c.shortcut) {
      if (c.function_g != nullptr)
        return c.function_g(g);
      else
        return c.function_w();
    }
  }

  std::cout << "Unknown command.\n";
  return true;
}

void print_command_name(const std::string &name) {
  std::cout.width(max_command_width);
  std::cout << name;
}

bool quiet() {
  verbose_grid = false;
  std::cout << "Grid output is now disabled.\n";
  return true;
}

bool verbose() {
  verbose_grid = true;
  std::cout << "Grid output is now enabled.\n";
  return true;
}

bool delay() {
  int n;
  if (ui::input_int(n, true, true))
    delay_ms = n;
  else
    std::cout << "Invalid value.\n";

  std::cout << "Every step will now be shown for " << delay_ms
            << " milliseconds.\n";
  return true;
}

bool help() {
  std::cout << " === Help ===\n";
  for (auto c : commands) {
    print_command_name(c.help);
    std::cout << " | " << c.description << "\n";
  }

  std::cout << "\nCoordinates are 0-based. (0 0) is top left corner.\n";
  std::cout << "\nCurrent loading the following file formats are supported:\n";
  std::cout << " * Life 1.06 (.lif or .life)\n";
  std::cout << " * Plaintext (.cells)\n";
  std::cout << " * RLE (.rle)\n";
  std::cout << "Please make sure the grid is large enough before loading.\n";

  if (hardware_threads > 1) {
    std::cout << "\nUse as many threads as possible (up to " << gol::max_threads
              << ")\nif you have more than one CPU core.\nYour CPU supports "
              << hardware_threads << " hardware threads.\n";
  }

  std::cout << "\n";
  return true;
}

bool print_grid(gol::Game_of_life &g) {
  std::cout << g;
  return true;
}

bool clear_grid(gol::Game_of_life &g) {
  g.clear();
  std::cout << "Grid cleared.\n";
  return true;
}

bool resize_grid(gol::Game_of_life &g) {
  int size;
  if (ui::input_int(size, true, false)) {
    g.size(size);
    std::cout << "New grid size is " << g.size() << ".\n";
  } else {
    std::cout << "Invalid grid size entered.\n";
  }
  return true;
}

bool set_rules(gol::Game_of_life &g) {
  std::string stay_alive;
  std::string born;

  if (std::cin >> stay_alive && std::cin >> born &&
      util::digit_string(stay_alive) && util::digit_string(born)) {
    g.clear_rules();
    // This looks ugly... sorry :/
    for (char c : stay_alive) {
      g.add_stay_alive(c - '0');
    }
    for (char c : born) {
      g.add_born(c - '0');
    }
  } else {
    std::cout << "Invalid rules. Rules must only contain digits.\n";
  }

  return true;
}

void input_set_cell(gol::Game_of_life &g, bool value) {
  int x, y;
  if (ui::input_int(x, true, true) && ui::input_int(y, true, true)) {
    if (!g.cell(x, y, value)) {
      std::cout << "Invalid coordinates.\n";
    }
  } else {
    std::cout << "Could not parse coordinates.\n";
  }
}

bool set_cell(gol::Game_of_life &g) {
  input_set_cell(g, true);

  return true;
}

bool unset_cell(gol::Game_of_life &g) {
  input_set_cell(g, false);

  return true;
}

bool fill_grid(gol::Game_of_life &g) {
  int n;
  if (ui::input_int(n, true)) {
    std::uniform_int_distribution<int> grid_distribution(0, g.size() - 1);
    for (int i = 0; i < n; i++) {
      int x = grid_distribution(random_engine);
      int y = grid_distribution(random_engine);

      g.cell(x, y, true);
    }
    std::cout << "Grid filled with up to " << n << " alive cells.\n";
  } else {
    std::cout << "Invalid number.\n";
  }
  return true;
}

bool set_threads(gol::Game_of_life &g) {
  int n;
  if (ui::input_int(n, true)) {
    g.threads(n);
    std::cout << "Set to " << g.threads() << " threads.\n";
  } else {
    std::cout << "Invalid number.\n";
  }
  return true;
}

bool create_glider(gol::Game_of_life &g) {
  int x, y;
  if (ui::input_int(x, false, true) && ui::input_int(y, false, true)) {
    g.cell(g.shift_coord(x + 1), g.shift_coord(y), true);
    g.cell(g.shift_coord(x + 2), g.shift_coord(y + 1), true);
    g.cell(g.shift_coord(x + 2), g.shift_coord(y + 2), true);
    g.cell(g.shift_coord(x + 1), g.shift_coord(y + 2), true);
    g.cell(g.shift_coord(x), g.shift_coord(y + 2), true);
    std::cout << "Glider placed.\n";
  } else {
    std::cout << "Invalid coordinates.\n";
  }
  return true;
}

bool load_pattern(gol::Game_of_life &g) {
  std::string filename{""};
  int x, y;

  if (std::cin >> filename && ui::input_int(x, true, true) &&
      ui::input_int(y, true, true)) {
    if (g.load_pattern(filename, x, y)) {
      std::cout << "OK\n";
    }
  } else {
    std::cin.clear();
    std::cin.ignore();
    std::cout << "Invalid parameters.\n";
  }
  return true;
}

bool export_cells(gol::Game_of_life &g) {
  std::string filename{""};

  if (std::cin >> filename && util::file_extension(filename) == "cells") {
    if (import_export::export_cells(filename, g)) {
      std::cout << "Exported to file.\n";
    } else {
      std::cout << "File could not be written.\n";
    }
  } else {
    std::cout << "Invalid filename (has to end with .cells)\n";
  }
  return true;
}

bool run(gol::Game_of_life &g) {
  int n;
  if (ui::input_int(n, true)) {
    for (int i = 0; i < n; i++) {
      if (!g.step()) {
        std::cout << "Aborted after " << (i + 1) << " step"
                  << (i > 0 ? "s" : "")
                  << " because of no change comprared do previous step.\n";
        break;
      };
      if (verbose_grid) {
        std::cout << "Step " << (i + 1) << ":\n";
        std::cout << g << std::endl;
        if (delay_ms) {
          std::chrono::milliseconds wait_for(delay_ms);
          std::this_thread::sleep_for(wait_for);
        }
      }
    }
  } else {
    std::cout << "Invalid number of steps.\n";
  }
  return true;
}

bool step(gol::Game_of_life &g) {
  g.step();
  if (verbose_grid) std::cout << g << std::endl;
  return true;
}

bool pexit() { return false; }
} // namespace commands
<commit_msg>Improved help<commit_after>#include "commands.h"

namespace commands {

std::random_device random_device;
std::default_random_engine random_engine{random_device()};

int hardware_threads = std::thread::hardware_concurrency();

bool verbose_grid{true};
int delay_ms{50};

// clang-format off
std::vector<command_structure> commands = {
  {"?",       "?",               "?", nullptr, &help,          "Print this help"},
  {"print",   "(p)rint",         "p", &print_grid, nullptr,    "Print current grid"},
  {"clear",   "(c)lear",         "c", &clear_grid, nullptr,    "Clear the grid"},
  {"resize",  "resi(z)e n",      "z", &resize_grid, nullptr,   "Set grid size to n x n and clear"},
  {"rules",   "rules s b",       "",  &set_rules, nullptr,     "Set game rules (Stay Alive, Born)"},
  {"set",     "(s)et x y",       "s", &set_cell, nullptr,      "Set cell at x y alive"},
  {"unset",   "(u)nset x y",     "u", &unset_cell, nullptr,    "Set cell at x y dead"},
  {"fill",    "(f)ill n",        "f", &fill_grid, nullptr,     "Set up to n cells alive"},
  {"threads", "(t)hreads n",     "t", &set_threads, nullptr,   "Set the amount of threads"},
  {"glider",  "(g)lider x y",    "g", &create_glider, nullptr, "Place a glider at x y"},
  {"load",    "(l)oad file x y", "l", &load_pattern, nullptr,  "Load pattern from file to x y"},
  {"export",  "e(x)port file",   "x", &export_cells, nullptr,  "Export a file to cells format"},
  {"quiet",   "(q)uiet",         "q", nullptr, &quiet,         "Disable output during running"},
  {"verbose", "(v)erbose",       "v", nullptr, &verbose,       "Enable output during running"},
  {"delay",   "(d)elay n",       "d", nullptr, &delay,         "Wait for n milliseconds after each step"},
  {"run",     "(r)un n",         "r", &run, nullptr,           "Run n iterations"},
  {"step",    "st(e)p",          "e", &step, nullptr,          "Run 1 iteration"},
  {"exit",    "exit",            "",  nullptr, &pexit,         "Exit"}
};
// clang-format on

constexpr int max_command_width{16};

bool command(std::string command, gol::Game_of_life &g) {
  for (auto c : commands) {
    if (command == c.name || command == c.shortcut) {
      if (c.function_g != nullptr)
        return c.function_g(g);
      else
        return c.function_w();
    }
  }

  std::cout << "Unknown command.\n";
  return true;
}

void print_command_name(const std::string &name) {
  std::cout.width(max_command_width);
  std::cout << name;
}

bool quiet() {
  verbose_grid = false;
  std::cout << "Grid output is now disabled.\n";
  return true;
}

bool verbose() {
  verbose_grid = true;
  std::cout << "Grid output is now enabled.\n";
  return true;
}

bool delay() {
  int n;
  if (ui::input_int(n, true, true))
    delay_ms = n;
  else
    std::cout << "Invalid value.\n";

  std::cout << "Every step will now be shown for " << delay_ms
            << " milliseconds.\n";
  return true;
}

bool help() {
  std::cout << " === Help ===\n";
  for (auto c : commands) {
    print_command_name(c.help);
    std::cout << " | " << c.description << "\n";
  }

  std::cout << "\nCoordinates are 0-based. (0 0) is top left corner.\n\n";
  std::cout << "Currently the following file formats\n"
            << "are supported for loading:\n";
  std::cout << " * Life 1.06 (.lif or .life)\n";
  std::cout << " * Plaintext (.cells)\n";
  std::cout << " * RLE (.rle)\n";
  std::cout << "Please make sure the grid is large enough before loading.\n";

  if (hardware_threads > 1) {
    std::cout << "\nUse as many threads as possible (up to " << gol::max_threads
              << ")\nif you have more than one CPU core.\nYour CPU supports "
              << hardware_threads << " hardware threads.\n";
  }

  std::cout << "\n";
  return true;
}

bool print_grid(gol::Game_of_life &g) {
  std::cout << g;
  return true;
}

bool clear_grid(gol::Game_of_life &g) {
  g.clear();
  std::cout << "Grid cleared.\n";
  return true;
}

bool resize_grid(gol::Game_of_life &g) {
  int size;
  if (ui::input_int(size, true, false)) {
    g.size(size);
    std::cout << "New grid size is " << g.size() << ".\n";
  } else {
    std::cout << "Invalid grid size entered.\n";
  }
  return true;
}

bool set_rules(gol::Game_of_life &g) {
  std::string stay_alive;
  std::string born;

  if (std::cin >> stay_alive && std::cin >> born &&
      util::digit_string(stay_alive) && util::digit_string(born)) {
    g.clear_rules();
    // This looks ugly... sorry :/
    for (char c : stay_alive) {
      g.add_stay_alive(c - '0');
    }
    for (char c : born) {
      g.add_born(c - '0');
    }
  } else {
    std::cout << "Invalid rules. Rules must only contain digits.\n";
  }

  return true;
}

void input_set_cell(gol::Game_of_life &g, bool value) {
  int x, y;
  if (ui::input_int(x, true, true) && ui::input_int(y, true, true)) {
    if (!g.cell(x, y, value)) {
      std::cout << "Invalid coordinates.\n";
    }
  } else {
    std::cout << "Could not parse coordinates.\n";
  }
}

bool set_cell(gol::Game_of_life &g) {
  input_set_cell(g, true);

  return true;
}

bool unset_cell(gol::Game_of_life &g) {
  input_set_cell(g, false);

  return true;
}

bool fill_grid(gol::Game_of_life &g) {
  int n;
  if (ui::input_int(n, true)) {
    std::uniform_int_distribution<int> grid_distribution(0, g.size() - 1);
    for (int i = 0; i < n; i++) {
      int x = grid_distribution(random_engine);
      int y = grid_distribution(random_engine);

      g.cell(x, y, true);
    }
    std::cout << "Grid filled with up to " << n << " alive cells.\n";
  } else {
    std::cout << "Invalid number.\n";
  }
  return true;
}

bool set_threads(gol::Game_of_life &g) {
  int n;
  if (ui::input_int(n, true)) {
    g.threads(n);
    std::cout << "Set to " << g.threads() << " threads.\n";
  } else {
    std::cout << "Invalid number.\n";
  }
  return true;
}

bool create_glider(gol::Game_of_life &g) {
  int x, y;
  if (ui::input_int(x, false, true) && ui::input_int(y, false, true)) {
    g.cell(g.shift_coord(x + 1), g.shift_coord(y), true);
    g.cell(g.shift_coord(x + 2), g.shift_coord(y + 1), true);
    g.cell(g.shift_coord(x + 2), g.shift_coord(y + 2), true);
    g.cell(g.shift_coord(x + 1), g.shift_coord(y + 2), true);
    g.cell(g.shift_coord(x), g.shift_coord(y + 2), true);
    std::cout << "Glider placed.\n";
  } else {
    std::cout << "Invalid coordinates.\n";
  }
  return true;
}

bool load_pattern(gol::Game_of_life &g) {
  std::string filename{""};
  int x, y;

  if (std::cin >> filename && ui::input_int(x, true, true) &&
      ui::input_int(y, true, true)) {
    if (g.load_pattern(filename, x, y)) {
      std::cout << "OK\n";
    }
  } else {
    std::cin.clear();
    std::cin.ignore();
    std::cout << "Invalid parameters.\n";
  }
  return true;
}

bool export_cells(gol::Game_of_life &g) {
  std::string filename{""};

  if (std::cin >> filename && util::file_extension(filename) == "cells") {
    if (import_export::export_cells(filename, g)) {
      std::cout << "Exported to file.\n";
    } else {
      std::cout << "File could not be written.\n";
    }
  } else {
    std::cout << "Invalid filename (has to end with .cells)\n";
  }
  return true;
}

bool run(gol::Game_of_life &g) {
  int n;
  if (ui::input_int(n, true)) {
    for (int i = 0; i < n; i++) {
      if (!g.step()) {
        std::cout << "Aborted after " << (i + 1) << " step"
                  << (i > 0 ? "s" : "")
                  << " because of no change comprared do previous step.\n";
        break;
      };
      if (verbose_grid) {
        std::cout << "Step " << (i + 1) << ":\n";
        std::cout << g << std::endl;
        if (delay_ms) {
          std::chrono::milliseconds wait_for(delay_ms);
          std::this_thread::sleep_for(wait_for);
        }
      }
    }
  } else {
    std::cout << "Invalid number of steps.\n";
  }
  return true;
}

bool step(gol::Game_of_life &g) {
  g.step();
  if (verbose_grid) std::cout << g << std::endl;
  return true;
}

bool pexit() { return false; }
} // namespace commands
<|endoftext|>