<commit_before>/*************************************************************************
 *
 *  $RCSfile: LocaleNode.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-10 09:12:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _LOCALE_NODE_
#define _LOCALE_NODE_
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <vector>

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star::xml::sax;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

class OFileWriter
{
public:

OFileWriter(const char *pcFile, const char *locale );
virtual ~OFileWriter();
    virtual void  writeStringCharacters(const ::rtl::OUString& str) const;
    virtual void  writeAsciiString(const char *str)const ;
    virtual void  writeInt(sal_Int16 nb) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const;
    virtual void  writeFunction2(const char *func, const char *style, const char* attr, const char *array) const;
    virtual void  writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const;
    virtual void  writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  flush(void) const ;
    virtual void  closeOutput(void) const;
private:
    char m_pcFile[1024];
    char theLocale[50];
    FILE *m_f;
};

class Attr {
    Sequence <OUString> name;
    Sequence <OUString> value;

public:
    Attr (const Reference< XAttributeList > & attr);
    const OUString& getValueByName (const sal_Char *str) const;
    sal_Int32 getLength() const;
    const OUString& getTypeByIndex (sal_Int32 idx) const;
    const OUString& getValueByIndex (sal_Int32 idx) const ;
};

class LocaleNode
{
    OUString aName;
    OUString aValue;
    Attr * xAttribs;
    LocaleNode * parent;
    LocaleNode* * children;
    sal_Int32 nChildren;
    sal_Int32 childArrSize;
    int nError;

    void setParent ( LocaleNode*  node);

public:
    LocaleNode (const OUString& name, const Reference< XAttributeList > & attr);
    inline void setValue(const OUString &oValue) { aValue += oValue; };
    inline const OUString& getName() const { return aName; };
    inline const OUString& getValue() const { return aValue; };
    inline const Attr* getAttr() const { return xAttribs; };
    inline const sal_Int32 getNumberOfChildren () const { return nChildren; };
    inline  LocaleNode * getChildAt (sal_Int32 idx) const { return children[idx] ; };
    const LocaleNode * findNode ( const sal_Char *name) const;
    void print () const;
    void printR () const;
    virtual ~LocaleNode();
    void addChild (  LocaleNode * node);
    int getError() const;
    virtual void generateCode (const OFileWriter &of) const;
    static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr);
};

class LCInfoNode : public LocaleNode {
public:
    inline LCInfoNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };
    virtual void generateCode (const OFileWriter &of) const;
};

class LCCTYPENode : public LocaleNode {
public:
    inline LCCTYPENode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCFormatNode : public LocaleNode {
public:
    inline LCFormatNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCCollationNode : public LocaleNode {
public:
    inline LCCollationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCIndexNode : public LocaleNode {
public:
    inline LCIndexNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCSearchNode : public LocaleNode {
public:
    inline LCSearchNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCCalendarNode : public LocaleNode {
public:
    inline LCCalendarNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCCurrencyNode : public LocaleNode {
public:
    inline LCCurrencyNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCTransliterationNode : public LocaleNode {
public:
    inline LCTransliterationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCMiscNode : public LocaleNode {
public:
    inline LCMiscNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCNumberingLevelNode : public LocaleNode {
public:
    inline LCNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCOutlineNumberingLevelNode : public LocaleNode {
public:
    inline LCOutlineNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

#endif
<commit_msg>INTEGRATION: CWS localedata3 (1.7.12); FILE MERGED 2005/03/10 22:28:41 er 1.7.12.2: #i44734# grmbl.. checked in wrong version.. this one actually generates the code.. 2005/03/10 17:22:11 er 1.7.12.1: #i44734# implement DTD version check<commit_after>/*************************************************************************
 *
 *  $RCSfile: LocaleNode.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2005-03-15 13:42:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _LOCALE_NODE_
#define _LOCALE_NODE_
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <vector>

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star::xml::sax;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

class OFileWriter
{
public:

OFileWriter(const char *pcFile, const char *locale );
virtual ~OFileWriter();
    virtual void  writeStringCharacters(const ::rtl::OUString& str) const;
    virtual void  writeAsciiString(const char *str)const ;
    virtual void  writeInt(sal_Int16 nb) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const;
    virtual void  writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const;
    virtual void  writeFunction2(const char *func, const char *style, const char* attr, const char *array) const;
    virtual void  writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const;
    virtual void  writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const;
    virtual void  writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const;
    virtual void  writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;
    virtual void  writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;
    virtual void  flush(void) const ;
    virtual void  closeOutput(void) const;
private:
    char m_pcFile[1024];
    char theLocale[50];
    FILE *m_f;
};

class Attr {
    Sequence <OUString> name;
    Sequence <OUString> value;

public:
    Attr (const Reference< XAttributeList > & attr);
    const OUString& getValueByName (const sal_Char *str) const;
    sal_Int32 getLength() const;
    const OUString& getTypeByIndex (sal_Int32 idx) const;
    const OUString& getValueByIndex (sal_Int32 idx) const ;
};

class LocaleNode
{
    OUString aName;
    OUString aValue;
    Attr * xAttribs;
    LocaleNode * parent;
    LocaleNode* * children;
    sal_Int32 nChildren;
    sal_Int32 childArrSize;

    void setParent ( LocaleNode*  node);

protected:
    mutable int nError;

public:
    LocaleNode (const OUString& name, const Reference< XAttributeList > & attr);
    inline void setValue(const OUString &oValue) { aValue += oValue; };
    inline const OUString& getName() const { return aName; };
    inline const OUString& getValue() const { return aValue; };
    inline const Attr* getAttr() const { return xAttribs; };
    inline const sal_Int32 getNumberOfChildren () const { return nChildren; };
    inline  LocaleNode * getChildAt (sal_Int32 idx) const { return children[idx] ; };
    const LocaleNode * findNode ( const sal_Char *name) const;
    void print () const;
    void printR () const;
    virtual ~LocaleNode();
    void addChild (  LocaleNode * node);
    int getError() const;
    virtual void generateCode (const OFileWriter &of) const;
    static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr);
};

class LCInfoNode : public LocaleNode {
public:
    inline LCInfoNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };
    virtual void generateCode (const OFileWriter &of) const;
};

class LCCTYPENode : public LocaleNode {
public:
    inline LCCTYPENode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCFormatNode : public LocaleNode {
public:
    inline LCFormatNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCCollationNode : public LocaleNode {
public:
    inline LCCollationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCIndexNode : public LocaleNode {
public:
    inline LCIndexNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCSearchNode : public LocaleNode {
public:
    inline LCSearchNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCCalendarNode : public LocaleNode {
public:
    inline LCCalendarNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCCurrencyNode : public LocaleNode {
public:
    inline LCCurrencyNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCTransliterationNode : public LocaleNode {
public:
    inline LCTransliterationNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCMiscNode : public LocaleNode {
public:
    inline LCMiscNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCNumberingLevelNode : public LocaleNode {
public:
    inline LCNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

class LCOutlineNumberingLevelNode : public LocaleNode {
public:
    inline LCOutlineNumberingLevelNode (const OUString& name,
                const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };

    virtual void generateCode (const OFileWriter &of) const;
};

#endif
<|endoftext|>


<commit_before>//g++-5 -Wall --std=c++11 -g -o math_find_sqrt math_find_sqrt.cc

/**
 * @file  Integer Square Root
 * @brief Given a positive integer find its integral square root
 */

// https://leetcode.com/problems/sqrtx/

#include <iostream>          /* std::cout                    */
#include <iomanip>           /* std::setw                    */
#include <cmath>             /* pow, tgamma(factorial)       */
#include <cassert>           /* assert                       */
#include <algorithm>         /* std::max                     */
#include <vector>            /* std::vector                  */
#include <string>            /* std::string                  */
using namespace std;

/**
 * Implement int sqrt(int x).
 * Compute and return the square root of x.
 */

/**
 * @brief -                                                  *
 * Time Complexity = O(n) and Space Complexity = O(1)        */
int mySqrtIterative(int num) {
   return 0;
}

/* Binary Search to find out the square root                 *
 * Time Complexity = O(lg n) and Space Complexity = O(1)     */
int mySqrtBS(int num) {
   int b = 1;
   for(int e = num;  e >= b ; ) {
      int mid = b + (e - b)/2;
      if(mid <= num/mid) b = mid + 1;
      else               e = mid - 1;
   }
   return b - 1;
}

/* Newton's integer method to find square-root of a positive *
 * integer. Inspired by solution posted on Leetcode @        *
 * https://leetcode.com/discuss/58631/3-4-short-lines-integer-newton-every-language */
int mySqrtNewton(int num) {
   if(num == 0) return num; /* avoid divide by zero error    */
   long r = num;
   while(r > num / r) r = (r + num/r) / 2;
   return (int)r;
}

struct test_vector {
   int num;
   int exp;
};

const struct test_vector test[11] =  {
   {0,              0},
   {1,              1},
   {2,              1},
   {3,              1},
   {4,              2},
   {15,             3},
   {16,             4},
   {81,             9},
   {250,           15},
   {2147395599, 46339},
   {2147483647, 46340},
};

int main()
{
   for(auto tst : test) {
      auto ans1 = mySqrtBS(tst.num);
      if(ans1 != tst.exp) {
         cout << "Error:mySqrtBS failed. Exp "
              << tst.exp << " Got " << ans1 << " for "
              << tst.num << endl;
         return -1;
      }
      auto ans2 = mySqrtNewton(tst.num);
      if(ans2 != tst.exp) {
         cout << "Error:mySqrtLog failed. Exp "
              << tst.exp << " Got " << ans2 << " for "
              << tst.num << endl;
         return -1;
      }
   }
   cout << "Info: All manual testcases passed" << endl;
   return 0;
}
<commit_msg>Remove incomplete implementation from Math SQRT (leet)<commit_after>//g++-5 -Wall --std=c++11 -g -o math_find_sqrt math_find_sqrt.cc

/**
 * @file  Integer Square Root
 * @brief Given a positive integer find its integral square root
 */

// https://leetcode.com/problems/sqrtx/

#include <iostream>          /* std::cout                    */
#include <iomanip>           /* std::setw                    */
#include <cmath>             /* pow, tgamma(factorial)       */
#include <cassert>           /* assert                       */
#include <algorithm>         /* std::max                     */
#include <vector>            /* std::vector                  */
#include <string>            /* std::string                  */
using namespace std;

/**
 * Implement int sqrt(int x).
 * Compute and return the square root of x.
 */

/* @brief -Binary Search to find out the square root         *
 * Time Complexity = O(lg n) and Space Complexity = O(1)     */
int mySqrtBS(int num) {
   int b = 1;
   for(int e = num;  e >= b ; ) {
      int mid = b + (e - b)/2;
      if(mid <= num/mid) b = mid + 1;
      else               e = mid - 1;
   }
   return b - 1;
}

/* Newton's integer method to find square-root of a positive *
 * integer. Inspired by solution posted on Leetcode @        *
 * https://leetcode.com/discuss/58631/3-4-short-lines-integer-newton-every-language */
int mySqrtNewton(int num) {
   if(num == 0) return num; /* avoid divide by zero error    */
   long r = num;
   while(r > num / r) r = (r + num/r) / 2;
   return (int)r;
}

struct test_vector {
   int num;
   int exp;
};

const struct test_vector test[11] =  {
   {0,              0},
   {1,              1},
   {2,              1},
   {3,              1},
   {4,              2},
   {15,             3},
   {16,             4},
   {81,             9},
   {250,           15},
   {2147395599, 46339},
   {2147483647, 46340},
};

int main()
{
   for(auto tst : test) {
      auto ans1 = mySqrtBS(tst.num);
      if(ans1 != tst.exp) {
         cout << "Error:mySqrtBS failed. Exp "
              << tst.exp << " Got " << ans1 << " for "
              << tst.num << endl;
         return -1;
      }
      auto ans2 = mySqrtNewton(tst.num);
      if(ans2 != tst.exp) {
         cout << "Error:mySqrtLog failed. Exp "
              << tst.exp << " Got " << ans2 << " for "
              << tst.num << endl;
         return -1;
      }
   }
   cout << "Info: All manual testcases passed" << endl;
   return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2011 Vince Durham
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2019 Daniel Kraft
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#include <auxpow.h>

#include <consensus/consensus.h>
#include <consensus/merkle.h>
#include <hash.h>
#include <primitives/block.h>
#include <script/script.h>
#include <util/strencodings.h>
#include <util/system.h>

#include <algorithm>

namespace
{

/**
 * Decodes a 32-bit little endian integer from raw bytes.
 */
uint32_t
DecodeLE32 (const unsigned char* bytes)
{
  uint32_t res = 0;
  for (int i = 0; i < 4; ++i)
    {
      res <<= 8;
      res |= bytes[3 - i];
    }
  return res;
}

} // anonymous namespace

bool
CAuxPow::check (const uint256& hashAuxBlock, int nChainId,
                const Consensus::Params& params) const
{
    if (params.fStrictChainId && parentBlock.GetChainId () == nChainId)
        return error("Aux POW parent has our chain ID");

    if (vChainMerkleBranch.size() > 30)
        return error("Aux POW chain merkle branch too long");

    // Check that the chain merkle root is in the coinbase
    const uint256 nRootHash
      = CheckMerkleBranch (hashAuxBlock, vChainMerkleBranch, nChainIndex);
    valtype vchRootHash(nRootHash.begin (), nRootHash.end ());
    std::reverse (vchRootHash.begin (), vchRootHash.end ()); // correct endian

    // Check that we are in the parent block merkle tree
    if (CheckMerkleBranch(coinbaseTx->GetHash(), vMerkleBranch, 0)
          != parentBlock.hashMerkleRoot)
        return error("Aux POW merkle root incorrect");

    // Check that there is at least one input.
    if (coinbaseTx->vin.empty())
        return error("Aux POW coinbase has no inputs");

    const CScript script = coinbaseTx->vin[0].scriptSig;

    // Check that the same work is not submitted twice to our chain.
    //

    const unsigned char* const mmHeaderBegin = pchMergedMiningHeader;
    const unsigned char* const mmHeaderEnd
        = mmHeaderBegin + sizeof (pchMergedMiningHeader);
    CScript::const_iterator pcHead =
        std::search(script.begin(), script.end(), mmHeaderBegin, mmHeaderEnd);

    CScript::const_iterator pc =
        std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());

    if (pc == script.end())
        return error("Aux POW missing chain merkle root in parent coinbase");

    if (pcHead != script.end())
    {
        // Enforce only one chain merkle root by checking that a single instance of the merged
        // mining header exists just before.
        if (script.end() != std::search(pcHead + 1, script.end(),
                                        mmHeaderBegin, mmHeaderEnd))
            return error("Multiple merged mining headers in coinbase");
        if (pcHead + sizeof(pchMergedMiningHeader) != pc)
            return error("Merged mining header is not just before chain merkle root");
    }
    else
    {
        return error("Missing auxpow header");
    }

    // Ensure we are at a deterministic point in the merkle leaves by hashing
    // a nonce and our chain ID and comparing to the index.
    pc += vchRootHash.size();
    if (script.end() - pc < 8)
        return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");

    const uint32_t nSize = DecodeLE32 (&pc[0]);
    const unsigned merkleHeight = vChainMerkleBranch.size ();
    if (nSize != (1u << merkleHeight))
        return error("Aux POW merkle branch size does not match parent coinbase");

    const uint32_t nNonce = DecodeLE32 (&pc[4]);
    if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight))
        return error("Aux POW wrong index");

    return true;
}

int
CAuxPow::getExpectedIndex (uint32_t nNonce, int nChainId, unsigned h)
{
  // Choose a pseudo-random slot in the chain merkle tree
  // but have it be fixed for a size/nonce/chain combination.
  //
  // This prevents the same work from being used twice for the
  // same chain while reducing the chance that two chains clash
  // for the same slot.

  /* This computation can overflow the uint32 used.  This is not an issue,
     though, since we take the mod against a power-of-two in the end anyway.
     This also ensures that the computation is, actually, consistent
     even if done in 64 bits as it was in the past on some systems.
     Note that h is always <= 30 (enforced by the maximum allowed chain
     merkle branch length), so that 32 bits are enough for the computation.  */

  uint32_t rand = nNonce;
  rand = rand * 1103515245 + 12345;
  rand += nChainId;
  rand = rand * 1103515245 + 12345;

  return rand % (1u << h);
}

uint256
CAuxPow::CheckMerkleBranch (uint256 hash,
                            const std::vector<uint256>& vMerkleBranch,
                            int nIndex)
{
  if (nIndex == -1)
    return uint256 ();
  for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin ());
       it != vMerkleBranch.end (); ++it)
  {
    if (nIndex & 1)
      hash = Hash (it->begin (), it->end (), hash.begin (), hash.end ());
    else
      hash = Hash (hash.begin (), hash.end (), it->begin (), it->end ());
    nIndex >>= 1;
  }
  return hash;
}

std::unique_ptr<CAuxPow>
CAuxPow::createAuxPow (const CPureBlockHeader& header)
{
  assert (header.IsAuxpow ());

  /* Build a minimal coinbase script input for merge-mining.  */
  const uint256 blockHash = header.GetHash ();
  valtype inputData(blockHash.begin (), blockHash.end ());
  std::reverse (inputData.begin (), inputData.end ());
  inputData.push_back (1);
  inputData.insert (inputData.end (), 7, 0);

  /* Fake a parent-block coinbase with just the required input
     script and no outputs.  */
  CMutableTransaction coinbase;
  coinbase.vin.resize (1);
  coinbase.vin[0].prevout.SetNull ();
  coinbase.vin[0].scriptSig = (CScript () << inputData);
  assert (coinbase.vout.empty ());
  CTransactionRef coinbaseRef = MakeTransactionRef (coinbase);

  /* Build a fake parent block with the coinbase.  */
  CBlock parent;
  parent.nVersion = 1;
  parent.vtx.resize (1);
  parent.vtx[0] = coinbaseRef;
  parent.hashMerkleRoot = BlockMerkleRoot (parent);

  /* Construct the auxpow object.  */
  std::unique_ptr<CAuxPow> auxpow(new CAuxPow (std::move (coinbaseRef)));
  assert (auxpow->vMerkleBranch.empty ());
  assert (auxpow->vChainMerkleBranch.empty ());
  auxpow->nChainIndex = 0;
  auxpow->parentBlock = parent;

  return auxpow;
}

CPureBlockHeader&
CAuxPow::initAuxPow (CBlockHeader& header)
{
  /* Set auxpow flag right now, since we take the block hash below when creating
     the minimal auxpow for header.  */
  header.SetAuxpowVersion(true);

  std::unique_ptr<CAuxPow> apow = createAuxPow (header);
  CPureBlockHeader& result = apow->parentBlock;
  header.SetAuxpow (std::move (apow));

  return result;
}<commit_msg>fix hash in auxpow<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2011 Vince Durham
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2019 Daniel Kraft
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#include <auxpow.h>

#include <consensus/consensus.h>
#include <consensus/merkle.h>
#include <hash.h>
#include <primitives/block.h>
#include <script/script.h>
#include <util/strencodings.h>
#include <util/system.h>

#include <algorithm>

namespace
{

/**
 * Decodes a 32-bit little endian integer from raw bytes.
 */
uint32_t
DecodeLE32 (const unsigned char* bytes)
{
  uint32_t res = 0;
  for (int i = 0; i < 4; ++i)
    {
      res <<= 8;
      res |= bytes[3 - i];
    }
  return res;
}

} // anonymous namespace

bool
CAuxPow::check (const uint256& hashAuxBlock, int nChainId,
                const Consensus::Params& params) const
{
    if (params.fStrictChainId && parentBlock.GetChainId () == nChainId)
        return error("Aux POW parent has our chain ID");

    if (vChainMerkleBranch.size() > 30)
        return error("Aux POW chain merkle branch too long");

    // Check that the chain merkle root is in the coinbase
    const uint256 nRootHash
      = CheckMerkleBranch (hashAuxBlock, vChainMerkleBranch, nChainIndex);
    valtype vchRootHash(nRootHash.begin (), nRootHash.end ());
    std::reverse (vchRootHash.begin (), vchRootHash.end ()); // correct endian

    // Check that we are in the parent block merkle tree
    if (CheckMerkleBranch(coinbaseTx->GetHash(), vMerkleBranch, 0)
          != parentBlock.hashMerkleRoot)
        return error("Aux POW merkle root incorrect");

    // Check that there is at least one input.
    if (coinbaseTx->vin.empty())
        return error("Aux POW coinbase has no inputs");

    const CScript script = coinbaseTx->vin[0].scriptSig;

    // Check that the same work is not submitted twice to our chain.
    //

    const unsigned char* const mmHeaderBegin = pchMergedMiningHeader;
    const unsigned char* const mmHeaderEnd
        = mmHeaderBegin + sizeof (pchMergedMiningHeader);
    CScript::const_iterator pcHead =
        std::search(script.begin(), script.end(), mmHeaderBegin, mmHeaderEnd);

    CScript::const_iterator pc =
        std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());

    if (pc == script.end())
        return error("Aux POW missing chain merkle root in parent coinbase");

    if (pcHead != script.end())
    {
        // Enforce only one chain merkle root by checking that a single instance of the merged
        // mining header exists just before.
        if (script.end() != std::search(pcHead + 1, script.end(),
                                        mmHeaderBegin, mmHeaderEnd))
            return error("Multiple merged mining headers in coinbase");
        if (pcHead + sizeof(pchMergedMiningHeader) != pc)
            return error("Merged mining header is not just before chain merkle root");
    }
    else
    {
        return error("Missing auxpow header");
    }

    // Ensure we are at a deterministic point in the merkle leaves by hashing
    // a nonce and our chain ID and comparing to the index.
    pc += vchRootHash.size();
    if (script.end() - pc < 8)
        return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");

    const uint32_t nSize = DecodeLE32 (&pc[0]);
    const unsigned merkleHeight = vChainMerkleBranch.size ();
    if (nSize != (1u << merkleHeight))
        return error("Aux POW merkle branch size does not match parent coinbase");

    const uint32_t nNonce = DecodeLE32 (&pc[4]);
    if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight))
        return error("Aux POW wrong index");

    return true;
}

int
CAuxPow::getExpectedIndex (uint32_t nNonce, int nChainId, unsigned h)
{
  // Choose a pseudo-random slot in the chain merkle tree
  // but have it be fixed for a size/nonce/chain combination.
  //
  // This prevents the same work from being used twice for the
  // same chain while reducing the chance that two chains clash
  // for the same slot.

  /* This computation can overflow the uint32 used.  This is not an issue,
     though, since we take the mod against a power-of-two in the end anyway.
     This also ensures that the computation is, actually, consistent
     even if done in 64 bits as it was in the past on some systems.
     Note that h is always <= 30 (enforced by the maximum allowed chain
     merkle branch length), so that 32 bits are enough for the computation.  */

  uint32_t rand = nNonce;
  rand = rand * 1103515245 + 12345;
  rand += nChainId;
  rand = rand * 1103515245 + 12345;

  return rand % (1u << h);
}

uint256
CAuxPow::CheckMerkleBranch (uint256 hash,
                            const std::vector<uint256>& vMerkleBranch,
                            int nIndex)
{
  if (nIndex == -1)
    return uint256 ();
  for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin ());
       it != vMerkleBranch.end (); ++it)
  {
    if (nIndex & 1)
      hash = Hash (*it, hash);
    else
      hash = Hash (hash, *it);
    nIndex >>= 1;
  }
  return hash;
}

std::unique_ptr<CAuxPow>
CAuxPow::createAuxPow (const CPureBlockHeader& header)
{
  assert (header.IsAuxpow ());

  /* Build a minimal coinbase script input for merge-mining.  */
  const uint256 blockHash = header.GetHash ();
  valtype inputData(blockHash.begin (), blockHash.end ());
  std::reverse (inputData.begin (), inputData.end ());
  inputData.push_back (1);
  inputData.insert (inputData.end (), 7, 0);

  /* Fake a parent-block coinbase with just the required input
     script and no outputs.  */
  CMutableTransaction coinbase;
  coinbase.vin.resize (1);
  coinbase.vin[0].prevout.SetNull ();
  coinbase.vin[0].scriptSig = (CScript () << inputData);
  assert (coinbase.vout.empty ());
  CTransactionRef coinbaseRef = MakeTransactionRef (coinbase);

  /* Build a fake parent block with the coinbase.  */
  CBlock parent;
  parent.nVersion = 1;
  parent.vtx.resize (1);
  parent.vtx[0] = coinbaseRef;
  parent.hashMerkleRoot = BlockMerkleRoot (parent);

  /* Construct the auxpow object.  */
  std::unique_ptr<CAuxPow> auxpow(new CAuxPow (std::move (coinbaseRef)));
  assert (auxpow->vMerkleBranch.empty ());
  assert (auxpow->vChainMerkleBranch.empty ());
  auxpow->nChainIndex = 0;
  auxpow->parentBlock = parent;

  return auxpow;
}

CPureBlockHeader&
CAuxPow::initAuxPow (CBlockHeader& header)
{
  /* Set auxpow flag right now, since we take the block hash below when creating
     the minimal auxpow for header.  */
  header.SetAuxpowVersion(true);

  std::unique_ptr<CAuxPow> apow = createAuxPow (header);
  CPureBlockHeader& result = apow->parentBlock;
  header.SetAuxpow (std::move (apow));

  return result;
}<|endoftext|>


<commit_before>/*
  C++ interface test
*/
#include "libmemcached/memcached.hh"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"

#include "test.h"

#include <string>

using namespace std;

extern "C" {
   void *world_create(void);
   void world_destroy(void *p);
}

static test_return basic_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("This is some data");
  string value;
  size_t value_length;

  foo.set("mine", value_set, 0, 0);
  value= foo.get("mine", &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

static test_return increment_test(memcached_st *memc)
{
  Memcached mcach(memc);
  bool rc;
  const string key("inctest");
  const string inc_value("1");
  string ret_value;
  uint64_t int_inc_value;
  uint64_t int_ret_value;
  size_t value_length;

  mcach.set(key, inc_value, 0, 0);
  ret_value= mcach.get(key, &value_length);
  printf("\nretvalue %s\n",ret_value.c_str());
  int_inc_value= uint64_t(atol(inc_value.c_str()));
  int_ret_value= uint64_t(atol(ret_value.c_str()));
  assert(int_ret_value == int_inc_value);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 2);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 3);

  rc= mcach.increment(key, 5, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 8);

  return TEST_SUCCESS;
}

static test_return basic_master_key_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("Data for server A");
  const string master_key_a("server-a");
  const string master_key_b("server-b");
  const string key("xyz");
  string value;
  size_t value_length;

  foo.set_by_key(master_key_a, key, value_set, 0, 0);
  value= foo.get_by_key(master_key_a, key, &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  value= foo.get_by_key(master_key_b, key, &value_length);
  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

/* Count the results */
static memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                     memcached_result_st *result __attribute__((unused)),
                                     void *context)
{
  unsigned int *counter= static_cast<unsigned int *>(context);

  *counter= *counter + 1;

  return MEMCACHED_SUCCESS;
}

static test_return mget_result_function(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  string key1("fudge");
  string key2("son");
  string key3("food");
  vector<string> keys;
  keys.reserve(3);
  keys.push_back(key1);
  keys.push_back(key2);
  keys.push_back(key3);
  unsigned int counter;
  memcached_execute_function callbacks[1];

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  callbacks[0]= &callback_counter;
  counter= 0;
  rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);

  assert(counter == 3);

  return TEST_SUCCESS;
}

static test_return mget_test(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  memcached_return mc_rc;
  vector<string> keys;
  keys.reserve(3);
  keys.push_back("fudge");
  keys.push_back("son");
  keys.push_back("food");
  uint32_t flags;

  string return_key;
  size_t return_key_length;
  string return_value;
  size_t return_value_length;

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while (mc.fetch(return_key, return_value, &return_key_length,
                  &return_value_length, &flags, &mc_rc))
  {
    assert(return_value.length() != 0);
  }
  assert(return_value_length == 0);
  assert(mc_rc == MEMCACHED_END);

  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while ((mc.fetch(return_key, return_value, &return_key_length,
                   &return_value_length, &flags, &mc_rc)))
  {
    assert(return_value.length() != 0);
    assert(mc_rc == MEMCACHED_SUCCESS);
    assert(return_key_length == return_value_length);
    assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
  }

  return TEST_SUCCESS;
}

test_st tests[] ={
  { "basic", 0, basic_test },
  { "basic_master_key", 0, basic_master_key_test },
  { "increment_test", 0, increment_test },
  { "mget", 1, mget_test },
  { "mget_result_function", 1, mget_result_function },
  {0, 0, 0}
};

collection_st collection[] ={
  {"block", 0, 0, tests},
  {0, 0, 0, 0}
};

#define SERVERS_TO_CREATE 1

extern "C" void *world_create(void)
{
  server_startup_st *construct;

  construct= (server_startup_st *)malloc(sizeof(server_startup_st));
  memset(construct, 0, sizeof(server_startup_st));

  construct->count= SERVERS_TO_CREATE;
  server_startup(construct);

  return construct;
}

void world_destroy(void *p)
{
  server_startup_st *construct= static_cast<server_startup_st *>(p);
  memcached_server_st *servers=
    static_cast<memcached_server_st *>(construct->servers);
  memcached_server_list_free(servers);

  server_shutdown(construct);
  free(construct);
}

void get_world(world_st *world)
{
  world->collections= collection;
  world->create= world_create;
  world->destroy= world_destroy;
}
<commit_msg>Updating the C++ test file to remove some compiler warnings on Solaris.<commit_after>/*
  C++ interface test
*/
#include "libmemcached/memcached.hh"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"

#include "test.h"

#include <string>

using namespace std;

extern "C" {
   test_return basic_test(memcached_st *memc);
   test_return increment_test(memcached_st *memc);
   test_return basic_master_key_test(memcached_st *memc);
   test_return mget_result_function(memcached_st *memc);
   test_return mget_test(memcached_st *memc);
   void *world_create(void);
   void world_destroy(void *p);
}

test_return basic_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("This is some data");
  string value;
  size_t value_length;

  foo.set("mine", value_set, 0, 0);
  value= foo.get("mine", &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

test_return increment_test(memcached_st *memc)
{
  Memcached mcach(memc);
  bool rc;
  const string key("inctest");
  const string inc_value("1");
  string ret_value;
  uint64_t int_inc_value;
  uint64_t int_ret_value;
  size_t value_length;

  mcach.set(key, inc_value, 0, 0);
  ret_value= mcach.get(key, &value_length);
  printf("\nretvalue %s\n",ret_value.c_str());
  int_inc_value= uint64_t(atol(inc_value.c_str()));
  int_ret_value= uint64_t(atol(ret_value.c_str()));
  assert(int_ret_value == int_inc_value);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 2);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 3);

  rc= mcach.increment(key, 5, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 8);

  return TEST_SUCCESS;
}

test_return basic_master_key_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("Data for server A");
  const string master_key_a("server-a");
  const string master_key_b("server-b");
  const string key("xyz");
  string value;
  size_t value_length;

  foo.set_by_key(master_key_a, key, value_set, 0, 0);
  value= foo.get_by_key(master_key_a, key, &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  value= foo.get_by_key(master_key_b, key, &value_length);
  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

/* Count the results */
static memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                     memcached_result_st *result __attribute__((unused)),
                                     void *context)
{
  unsigned int *counter= static_cast<unsigned int *>(context);

  *counter= *counter + 1;

  return MEMCACHED_SUCCESS;
}

test_return mget_result_function(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  string key1("fudge");
  string key2("son");
  string key3("food");
  vector<string> keys;
  keys.reserve(3);
  keys.push_back(key1);
  keys.push_back(key2);
  keys.push_back(key3);
  unsigned int counter;
  memcached_execute_function callbacks[1];

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  callbacks[0]= &callback_counter;
  counter= 0;
  rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);

  assert(counter == 3);

  return TEST_SUCCESS;
}

test_return mget_test(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  memcached_return mc_rc;
  vector<string> keys;
  keys.reserve(3);
  keys.push_back("fudge");
  keys.push_back("son");
  keys.push_back("food");
  uint32_t flags;

  string return_key;
  size_t return_key_length;
  string return_value;
  size_t return_value_length;

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while (mc.fetch(return_key, return_value, &return_key_length,
                  &return_value_length, &flags, &mc_rc))
  {
    assert(return_value.length() != 0);
  }
  assert(return_value_length == 0);
  assert(mc_rc == MEMCACHED_END);

  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while ((mc.fetch(return_key, return_value, &return_key_length,
                   &return_value_length, &flags, &mc_rc)))
  {
    assert(return_value.length() != 0);
    assert(mc_rc == MEMCACHED_SUCCESS);
    assert(return_key_length == return_value_length);
    assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
  }

  return TEST_SUCCESS;
}

test_st tests[] ={
  { "basic", 0, basic_test },
  { "basic_master_key", 0, basic_master_key_test },
  { "increment_test", 0, increment_test },
  { "mget", 1, mget_test },
  { "mget_result_function", 1, mget_result_function },
  {0, 0, 0}
};

collection_st collection[] ={
  {"block", 0, 0, tests},
  {0, 0, 0, 0}
};

#define SERVERS_TO_CREATE 1

extern "C" void *world_create(void)
{
  server_startup_st *construct;

  construct= (server_startup_st *)malloc(sizeof(server_startup_st));
  memset(construct, 0, sizeof(server_startup_st));

  construct->count= SERVERS_TO_CREATE;
  server_startup(construct);

  return construct;
}

void world_destroy(void *p)
{
  server_startup_st *construct= static_cast<server_startup_st *>(p);
  memcached_server_st *servers=
    static_cast<memcached_server_st *>(construct->servers);
  memcached_server_list_free(servers);

  server_shutdown(construct);
  free(construct);
}

void get_world(world_st *world)
{
  world->collections= collection;
  world->create= world_create;
  world->destroy= world_destroy;
}
<|endoftext|>


<commit_before>#include "KeyMotorPopulator.h"

KeyMotorPopulator::KeyMotorPopulator(I_PacketDecoder& packetDecoder, I_KeyMotorData& keyMotorData)
    : packetDecoder_(packetDecoder)
    , keyMotorData_(keyMotorData)
{
    connect(&packetDecoder_, SIGNAL(packetDecoded(const KeyMotorPopulator)), this, SLOT(populateData(const KeyMotorPopulator)));
}

void KeyMotorPopulator::populateData(const KeyMotorMessage message)
{
    keyMotorData_.setM0Alive(message.m0Alive());
    keyMotorData_.setM0SetCurrent(message.m0SetCurrent());
    keyMotorData_.setM0SetVelocity(message.m0SetVelocity());
    keyMotorData_.setM0BusCurrent(message.m0BusCurrent());
    keyMotorData_.setM0BusVoltage(message.m0BusVoltage());
    keyMotorData_.setM0VehicleVelocity(message.m0VehicleVelocity());
    keyMotorData_.setM1Alive(message.m1Alive());
    keyMotorData_.setM1SetCurrent(message.m1SetCurrent());
    keyMotorData_.setM1SetVelocity(message.m1SetVelocity());
    keyMotorData_.setM1BusCurrent(message.m1BusCurrent());
    keyMotorData_.setM1BusVoltage(message.m1BusVoltage());
    keyMotorData_.setM1VehicleVelocity(message.m1VehicleVelocity());
}
<commit_msg>Replace packetDecoded(const KeyMotorPopulator) with packetDecoded(const KeyMotorMessage)<commit_after>#include "KeyMotorPopulator.h"

KeyMotorPopulator::KeyMotorPopulator(I_PacketDecoder& packetDecoder, I_KeyMotorData& keyMotorData)
    : packetDecoder_(packetDecoder)
    , keyMotorData_(keyMotorData)
{
    connect(&packetDecoder_, SIGNAL(packetDecoded(const KeyMotorMessage)), this, SLOT(populateData(const KeyMotorMessage)));
}

void KeyMotorPopulator::populateData(const KeyMotorMessage message)
{
    keyMotorData_.setM0Alive(message.m0Alive());
    keyMotorData_.setM0SetCurrent(message.m0SetCurrent());
    keyMotorData_.setM0SetVelocity(message.m0SetVelocity());
    keyMotorData_.setM0BusCurrent(message.m0BusCurrent());
    keyMotorData_.setM0BusVoltage(message.m0BusVoltage());
    keyMotorData_.setM0VehicleVelocity(message.m0VehicleVelocity());
    keyMotorData_.setM1Alive(message.m1Alive());
    keyMotorData_.setM1SetCurrent(message.m1SetCurrent());
    keyMotorData_.setM1SetVelocity(message.m1SetVelocity());
    keyMotorData_.setM1BusCurrent(message.m1BusCurrent());
    keyMotorData_.setM1BusVoltage(message.m1BusVoltage());
    keyMotorData_.setM1VehicleVelocity(message.m1VehicleVelocity());
}
<|endoftext|>


<commit_before>/*
 * Movie.cpp
 *
 *  Created on: Sep 25, 2009
 *      Author: travel
 */

#include "Movie.hpp"
#include "../io/imageio.hpp"
#include "../include/default_params.h"

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
//#include <iostream>

namespace PV {

Movie::Movie() {
   initialize_base();
}

Movie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames) {
   initialize_base();
   initialize(name, hc, fileOfFileNames, DISPLAY_PERIOD);
}

Movie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {
   initialize_base();
   initialize(name, hc, fileOfFileNames, defaultDisplayPeriod);
}

int Movie::initialize_base() {
   movieOutputPath = NULL;
   skipFrameIndex = 0;
   echoFramePathnameFlag = false;
   filenamestream = NULL;
   displayPeriod = DISPLAY_PERIOD;
   readPvpFile = false;
   fileOfFileNames = NULL;
   frameNumber = 0;
   numFrames = 0;
   newImageFlag = false;
   return PV_SUCCESS;
}

int Movie::checkpointRead(const char * cpDir, double * timef){
   Image::checkpointRead(cpDir, timef);

   if (this->useParamsImage) { //Sets nextDisplayTime = simulationtime (i.e. effectively restarting)
      nextDisplayTime += parent->simulationTime();
   }

   return PV_SUCCESS;
}

//
/*
 * Notes:
 * - writeImages, offsetX, offsetY are initialized by Image::initialize()
 */
int Movie::initialize(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {
   displayPeriod = defaultDisplayPeriod; // Will be replaced with params value when setParams is called.
   int status = Image::initialize(name, hc, NULL);
   if (status != PV_SUCCESS) {
      fprintf(stderr, "Image::initialize failed on Movie layer \"%s\".  Exiting.\n", name);
      exit(PV_FAILURE);
   }

   if (fileOfFileNames != NULL) {
      this->fileOfFileNames = strdup(fileOfFileNames);
      if (this->fileOfFileNames==NULL) {
         fprintf(stderr, "Movie::initialize error in layer \"%s\": unable to copy fileOfFileNames: %s\n", name, strerror(errno));
      }
   }

   PVParams * params = hc->parameters();

   assert(!params->presentAndNotBeenRead(name, "displayPeriod"));
   nextDisplayTime = hc->simulationTime() + displayPeriod;

   assert(!params->presentAndNotBeenRead(name, "randomMovie")); // randomMovie should have been set in setParams
   if (randomMovie) return status; // Nothing else to be done until data buffer is allocated, in allocateDataStructures

   assert(!params->presentAndNotBeenRead(name, "readPvpFile")); // readPvpFile should have been set in setParams

   //If not pvp file, open fileOfFileNames
   if( getParent()->icCommunicator()->commRank()==0 && !readPvpFile) {
      filenamestream = PV_fopen(fileOfFileNames, "r");
      if( filenamestream == NULL ) {
         fprintf(stderr, "Movie::initialize error opening \"%s\": %s\n", fileOfFileNames, strerror(errno));
         abort();
      }
   }

   if (!randomMovie) {
      if(readPvpFile){
         //Set filename as param
         filename = strdup(fileOfFileNames);
         assert(filename != NULL);
         //One indexed start_frame_index needs to be translated to zero indexed pvp file
         if (startFrameIndex <= 1){
            frameNumber = 0;
         }
         else{
            frameNumber = startFrameIndex - 1;
         }
         //Grab number of frames from header
         PV_Stream * pvstream = NULL;
         if (getParent()->icCommunicator()->commRank()==0) {
            pvstream = PV::PV_fopen(filename, "rb");
         }
         int numParams = NUM_PAR_BYTE_PARAMS;
         int params[numParams];
         pvp_read_header(pvstream, getParent()->icCommunicator(), params, &numParams);
         PV::PV_fclose(pvstream); pvstream = NULL;
         if(numParams != NUM_PAR_BYTE_PARAMS || params[INDEX_FILE_TYPE] != PVP_NONSPIKING_ACT_FILE_TYPE) {
            fprintf(stderr, "Movie layer \"%s\" error: file \"%s\" is not a nonspiking-activity pvp file.\n", name, filename);
            abort();
         }
         numFrames = params[INDEX_NBANDS];
      }
      else{
         // echoFramePathnameFlag = params->value(name,"echoFramePathnameFlag", false);
         filename = strdup(getNextFileName(startFrameIndex));
         assert(filename != NULL);
      }
   }

   // getImageInfo/constrainOffsets/readImage calls moved to Movie::allocateDataStructures

   // set output path for movie frames
   if(writeImages){
      // if ( params->stringPresent(name, "movieOutputPath") ) {
      //    movieOutputPath = strdup(params->stringValue(name, "movieOutputPath"));
      //    assert(movieOutputPath != NULL);
      // }
      // else {
      //    movieOutputPath = strdup( hc->getOutputPath());
      //    assert(movieOutputPath != NULL);
      //    printf("movieOutputPath is not specified in params file.\n"
      //          "movieOutputPath set to default \"%s\"\n",movieOutputPath);
      // }
      status = parent->ensureDirExists(movieOutputPath);
   }

   return PV_SUCCESS;
}

int Movie::setParams(PVParams * params) {
   int status = Image::setParams(params);
   displayPeriod = params->value(name,"displayPeriod", displayPeriod);
   randomMovie = (int) params->value(name,"randomMovie",0);
   if (randomMovie) {
      randomMovieProb   = params->value(name,"randomMovieProb", 0.05);  // 100 Hz
   }
   else {
      readPvpFile = (bool)params->value(name, "readPvpFile", 0);
      if (!readPvpFile) {
         echoFramePathnameFlag = params->value(name,"echoFramePathnameFlag", false);
      }
      startFrameIndex = params->value(name,"start_frame_index", 0);
      skipFrameIndex = params->value(name,"skip_frame_index", 0);
      autoResizeFlag = (bool)params->value(name,"autoResizeFlag",false);
   }
   assert(!params->presentAndNotBeenRead(name, "writeImages"));
   if(writeImages){
      if ( params->stringPresent(name, "movieOutputPath") ) {
         movieOutputPath = strdup(params->stringValue(name, "movieOutputPath"));
         assert(movieOutputPath != NULL);
      }
      else {
         movieOutputPath = strdup( parent->getOutputPath());
         assert(movieOutputPath != NULL);
         printf("movieOutputPath is not specified in params file.\n"
               "movieOutputPath set to default \"%s\"\n",movieOutputPath);
      }
   }
   return status;
}

Movie::~Movie()
{
   if (imageData != NULL) {
      delete imageData;
      imageData = NULL;
   }
   if (getParent()->icCommunicator()->commRank()==0 && filenamestream != NULL && filenamestream->isfile) {
      PV_fclose(filenamestream);
   }
   free(fileOfFileNames); fileOfFileNames = NULL;
}

int Movie::allocateDataStructures() {
   int status = Image::allocateDataStructures();

   if (!randomMovie) {
      assert(!parent->parameters()->presentAndNotBeenRead(name, "start_frame_index"));
      assert(!parent->parameters()->presentAndNotBeenRead(name, "skip_frame_index"));
      // skip to start_frame_index if provided
      // int start_frame_index = params->value(name,"start_frame_index", 0);
      // skipFrameIndex = params->value(name,"skip_frame_index", 0);

      // get size info from image so that data buffer can be allocated
      GDALColorInterp * colorbandtypes = NULL;
      status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);
      if(status != 0) {
         fprintf(stderr, "Movie: Unable to get image info for \"%s\"\n", filename);
         abort();
      }

      assert(!parent->parameters()->presentAndNotBeenRead(name, "autoResizeFlag"));
      if (!autoResizeFlag){
         constrainOffsets();  // ensure that offsets keep loc within image bounds
      }

      status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);
      assert(status == PV_SUCCESS);

      free(colorbandtypes); colorbandtypes = NULL;
   }
   else {
      status = randomFrame();
   }

   // exchange border information
   exchange();

   newImageFlag = true;
   return status;
}

pvdata_t * Movie::getImageBuffer()
{
   //   return imageData;
   return data;
}

PVLayerLoc Movie::getImageLoc()
{
   return imageLoc;
   //   return clayer->loc;
   // imageLoc contains size information of the image file being loaded;
   // clayer->loc contains size information of the layer, which may
   // be smaller than the whole image.  To get information on the layer, use
   // getLayerLoc().  --pete 2011-07-10
}

int Movie::updateState(double time, double dt)
{
   updateImage(time, dt);
   return 0;
}

/**
 * - Update the image buffers
 * - If the time is a multiple of biasChangetime then the position of the bias (biasX, biasY) changes.
 * - With probability persistenceProb the offset position (offsetX, offsetY) remains unchanged.
 * - Otherwise, with probability (1-persistenceProb) the offset position performs a random walk
 *   around the bias position (biasX, biasY).
 *
 * - If the time is a multiple of displayPeriod then load the next image.
 * - If nf=1 then the image is converted to grayscale during the call to read(filename, offsetX, offsetY).
 *   If nf>1 then the image is loaded with color information preserved.
 * - Return true if buffers have changed
 */
bool Movie::updateImage(double time, double dt)
{
   InterColComm * icComm = getParent()->icCommunicator();
   if(randomMovie){
      randomFrame();
      lastUpdateTime = time;
   } else {
      bool needNewImage = false;
      while (time >= nextDisplayTime) {
         needNewImage = true;
         if (readPvpFile){
            //If set to 0 or 1, normal frame
            if (skipFrameIndex <= 1){
               frameNumber += 1;
            }
            //Otherwise, skip based on skipFrameIndex
            else{
               frameNumber += skipFrameIndex;
            }
            //Loop when frame number reaches numFrames
            if (frameNumber >= numFrames){
               if( icComm->commRank()==0 ) {
                  fprintf(stderr, "Movie %s: EOF reached, rewinding file \"%s\"\n", name, filename);
               }
               frameNumber = 0;
            }
         }
         else{
            if (filename != NULL) free(filename);
            filename = strdup(getNextFileName(skipFrameIndex));
            assert(filename != NULL);
         }
         nextDisplayTime += displayPeriod;

         if(writePosition && parent->icCommunicator()->commRank()==0){
            fprintf(fp_pos->fp,"%f %s: \n",time,filename);
         }
         lastUpdateTime = time;
      } // time >= nextDisplayTime

      if( jitterFlag ) {
         bool jittered = jitter();
         needNewImage |= jittered;
      } // jitterFlag

      if( needNewImage ){
         GDALColorInterp * colorbandtypes = NULL;
         int status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);
         if( status != PV_SUCCESS ) {
            fprintf(stderr, "Movie %s: Error getting image info \"%s\"\n", name, filename);
            abort();
         }
         //Set frame number (member variable in Image)
         if( status == PV_SUCCESS ) status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);
         free(colorbandtypes); colorbandtypes = NULL;
         if( status != PV_SUCCESS ) {
            fprintf(stderr, "Movie %s: Error reading file \"%s\"\n", name, filename);
            abort();
         }
         newImageFlag = true;
      }
      else{
         newImageFlag = false;
      }
   } // randomMovie

   // exchange border information
   exchange();

   return true;
}

/**
 * When we play a random frame - in order to perform a reverse correlation analysis -
 * we call writeActivitySparse(time) in order to write the "activity" in the image.
 *
 */
int Movie::outputState(double time, bool last)
{
   if (writeImages) {
      char basicFilename[PV_PATH_MAX + 1];
      snprintf(basicFilename, PV_PATH_MAX, "%s/Movie_%.2f.%s", movieOutputPath, time, writeImagesExtension);
      write(basicFilename);
   }

   int status = PV_SUCCESS;
   if (randomMovie != 0) {
      status = writeActivitySparse(time);
   }
   else {
      status = HyPerLayer::outputState(time, last);
   }

   return status;
}

int Movie::copyReducedImagePortion()
{
   const PVLayerLoc * loc = getLayerLoc();

   const int nx = loc->nx;
   const int ny = loc->ny;

   const int nx0 = imageLoc.nx;
   const int ny0 = imageLoc.ny;

   assert(nx0 <= nx);
   assert(ny0 <= ny);

   const int i0 = nx/2 - nx0/2;
   const int j0 = ny/2 - ny0/2;

   int ii = 0;
   for (int j = j0; j < j0+ny0; j++) {
      for (int i = i0; i < i0+nx0; i++) {
         imageData[ii++] = data[i+nx*j];
      }
   }

   return 0;
}

/**
 * This creates a random image patch (frame) that is used to perform a reverse correlation analysis
 * as the input signal propagates up the visual system's hierarchy.
 * NOTE: Check Image::toGrayScale() method which was the inspiration for this routine
 */
int Movie::randomFrame()
{
   assert(randomMovie); // randomMovieProb was set only if randomMovie is true
   for (int kex = 0; kex < clayer->numExtended; kex++) {
      double p = uniformRand01(&rand_state);
      data[kex] = (p < randomMovieProb) ? 1: 0;
   }
   return 0;
}

// skip n_skip lines before reading next frame
const char * Movie::getNextFileName(int n_skip)
{
   for (int i_skip = 0; i_skip < n_skip-1; i_skip++){
      getNextFileName();
   }
   return getNextFileName();
}

const char * Movie::getNextFileName()
{
   InterColComm * icComm = getParent()->icCommunicator();
   if( icComm->commRank()==0 ) {
      int c;
      size_t len = PV_PATH_MAX;

      //TODO: add recovery procedure to handle case where access to file is temporarily unavailable
      // use stat to verify status of filepointer, keep running tally of current frame index so that file can be reopened and advanced to current frame

      // if at end of file (EOF), rewind
      if ((c = fgetc(filenamestream->fp)) == EOF) {
         PV_fseek(filenamestream, 0L, SEEK_SET);
         fprintf(stderr, "Movie %s: EOF reached, rewinding file \"%s\"\n", name, filename);
      }
      else {
         ungetc(c, filenamestream->fp);
      }

      char * path = fgets(inputfile, len, filenamestream->fp);
      if (path) {
         filenamestream->filepos += strlen(path)+1;
      }

      if (echoFramePathnameFlag){
         fprintf(stderr, "%s", path);
      }

      if (path != NULL) {
         path[PV_PATH_MAX-1] = '\0';
         len = strlen(path);
         if (len > 1) {
            if (path[len-1] == '\n') {
               path[len-1] = '\0';
            }
         }
      }
   }
#ifdef PV_USE_MPI
   MPI_Bcast(inputfile, PV_PATH_MAX, MPI_CHAR, 0, icComm->communicator());
#endif // PV_USE_MPI
   return inputfile;
}

bool Movie::getNewImageFlag(){
   return newImageFlag;
}

const char * Movie::getCurrentImage(){
   return inputfile;
}

}
<commit_msg>Movie doesn't clear newImageFlag when updateState is called at time zero<commit_after>/*
 * Movie.cpp
 *
 *  Created on: Sep 25, 2009
 *      Author: travel
 */

#include "Movie.hpp"
#include "../io/imageio.hpp"
#include "../include/default_params.h"

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
//#include <iostream>

namespace PV {

Movie::Movie() {
   initialize_base();
}

Movie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames) {
   initialize_base();
   initialize(name, hc, fileOfFileNames, DISPLAY_PERIOD);
}

Movie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {
   initialize_base();
   initialize(name, hc, fileOfFileNames, defaultDisplayPeriod);
}

int Movie::initialize_base() {
   movieOutputPath = NULL;
   skipFrameIndex = 0;
   echoFramePathnameFlag = false;
   filenamestream = NULL;
   displayPeriod = DISPLAY_PERIOD;
   readPvpFile = false;
   fileOfFileNames = NULL;
   frameNumber = 0;
   numFrames = 0;
   newImageFlag = false;
   return PV_SUCCESS;
}

int Movie::checkpointRead(const char * cpDir, double * timef){
   Image::checkpointRead(cpDir, timef);

   if (this->useParamsImage) { //Sets nextDisplayTime = simulationtime (i.e. effectively restarting)
      nextDisplayTime += parent->simulationTime();
   }

   return PV_SUCCESS;
}

//
/*
 * Notes:
 * - writeImages, offsetX, offsetY are initialized by Image::initialize()
 */
int Movie::initialize(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {
   displayPeriod = defaultDisplayPeriod; // Will be replaced with params value when setParams is called.
   int status = Image::initialize(name, hc, NULL);
   if (status != PV_SUCCESS) {
      fprintf(stderr, "Image::initialize failed on Movie layer \"%s\".  Exiting.\n", name);
      exit(PV_FAILURE);
   }

   if (fileOfFileNames != NULL) {
      this->fileOfFileNames = strdup(fileOfFileNames);
      if (this->fileOfFileNames==NULL) {
         fprintf(stderr, "Movie::initialize error in layer \"%s\": unable to copy fileOfFileNames: %s\n", name, strerror(errno));
      }
   }

   PVParams * params = hc->parameters();

   assert(!params->presentAndNotBeenRead(name, "displayPeriod"));
   nextDisplayTime = hc->simulationTime() + displayPeriod;

   assert(!params->presentAndNotBeenRead(name, "randomMovie")); // randomMovie should have been set in setParams
   if (randomMovie) return status; // Nothing else to be done until data buffer is allocated, in allocateDataStructures

   assert(!params->presentAndNotBeenRead(name, "readPvpFile")); // readPvpFile should have been set in setParams

   //If not pvp file, open fileOfFileNames
   if( getParent()->icCommunicator()->commRank()==0 && !readPvpFile) {
      filenamestream = PV_fopen(fileOfFileNames, "r");
      if( filenamestream == NULL ) {
         fprintf(stderr, "Movie::initialize error opening \"%s\": %s\n", fileOfFileNames, strerror(errno));
         abort();
      }
   }

   if (!randomMovie) {
      if(readPvpFile){
         //Set filename as param
         filename = strdup(fileOfFileNames);
         assert(filename != NULL);
         //One indexed start_frame_index needs to be translated to zero indexed pvp file
         if (startFrameIndex <= 1){
            frameNumber = 0;
         }
         else{
            frameNumber = startFrameIndex - 1;
         }
         //Grab number of frames from header
         PV_Stream * pvstream = NULL;
         if (getParent()->icCommunicator()->commRank()==0) {
            pvstream = PV::PV_fopen(filename, "rb");
         }
         int numParams = NUM_PAR_BYTE_PARAMS;
         int params[numParams];
         pvp_read_header(pvstream, getParent()->icCommunicator(), params, &numParams);
         PV::PV_fclose(pvstream); pvstream = NULL;
         if(numParams != NUM_PAR_BYTE_PARAMS || params[INDEX_FILE_TYPE] != PVP_NONSPIKING_ACT_FILE_TYPE) {
            fprintf(stderr, "Movie layer \"%s\" error: file \"%s\" is not a nonspiking-activity pvp file.\n", name, filename);
            abort();
         }
         numFrames = params[INDEX_NBANDS];
      }
      else{
         // echoFramePathnameFlag = params->value(name,"echoFramePathnameFlag", false);
         filename = strdup(getNextFileName(startFrameIndex));
         assert(filename != NULL);
      }
   }

   // getImageInfo/constrainOffsets/readImage calls moved to Movie::allocateDataStructures

   // set output path for movie frames
   if(writeImages){
      // if ( params->stringPresent(name, "movieOutputPath") ) {
      //    movieOutputPath = strdup(params->stringValue(name, "movieOutputPath"));
      //    assert(movieOutputPath != NULL);
      // }
      // else {
      //    movieOutputPath = strdup( hc->getOutputPath());
      //    assert(movieOutputPath != NULL);
      //    printf("movieOutputPath is not specified in params file.\n"
      //          "movieOutputPath set to default \"%s\"\n",movieOutputPath);
      // }
      status = parent->ensureDirExists(movieOutputPath);
   }

   return PV_SUCCESS;
}

int Movie::setParams(PVParams * params) {
   int status = Image::setParams(params);
   displayPeriod = params->value(name,"displayPeriod", displayPeriod);
   randomMovie = (int) params->value(name,"randomMovie",0);
   if (randomMovie) {
      randomMovieProb   = params->value(name,"randomMovieProb", 0.05);  // 100 Hz
   }
   else {
      readPvpFile = (bool)params->value(name, "readPvpFile", 0);
      if (!readPvpFile) {
         echoFramePathnameFlag = params->value(name,"echoFramePathnameFlag", false);
      }
      startFrameIndex = params->value(name,"start_frame_index", 0);
      skipFrameIndex = params->value(name,"skip_frame_index", 0);
      autoResizeFlag = (bool)params->value(name,"autoResizeFlag",false);
   }
   assert(!params->presentAndNotBeenRead(name, "writeImages"));
   if(writeImages){
      if ( params->stringPresent(name, "movieOutputPath") ) {
         movieOutputPath = strdup(params->stringValue(name, "movieOutputPath"));
         assert(movieOutputPath != NULL);
      }
      else {
         movieOutputPath = strdup( parent->getOutputPath());
         assert(movieOutputPath != NULL);
         printf("movieOutputPath is not specified in params file.\n"
               "movieOutputPath set to default \"%s\"\n",movieOutputPath);
      }
   }
   return status;
}

Movie::~Movie()
{
   if (imageData != NULL) {
      delete imageData;
      imageData = NULL;
   }
   if (getParent()->icCommunicator()->commRank()==0 && filenamestream != NULL && filenamestream->isfile) {
      PV_fclose(filenamestream);
   }
   free(fileOfFileNames); fileOfFileNames = NULL;
}

int Movie::allocateDataStructures() {
   int status = Image::allocateDataStructures();

   if (!randomMovie) {
      assert(!parent->parameters()->presentAndNotBeenRead(name, "start_frame_index"));
      assert(!parent->parameters()->presentAndNotBeenRead(name, "skip_frame_index"));
      // skip to start_frame_index if provided
      // int start_frame_index = params->value(name,"start_frame_index", 0);
      // skipFrameIndex = params->value(name,"skip_frame_index", 0);

      // get size info from image so that data buffer can be allocated
      GDALColorInterp * colorbandtypes = NULL;
      status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);
      if(status != 0) {
         fprintf(stderr, "Movie: Unable to get image info for \"%s\"\n", filename);
         abort();
      }

      assert(!parent->parameters()->presentAndNotBeenRead(name, "autoResizeFlag"));
      if (!autoResizeFlag){
         constrainOffsets();  // ensure that offsets keep loc within image bounds
      }

      status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);
      assert(status == PV_SUCCESS);

      free(colorbandtypes); colorbandtypes = NULL;
   }
   else {
      status = randomFrame();
   }

   // exchange border information
   exchange();

   newImageFlag = true;
   return status;
}

pvdata_t * Movie::getImageBuffer()
{
   //   return imageData;
   return data;
}

PVLayerLoc Movie::getImageLoc()
{
   return imageLoc;
   //   return clayer->loc;
   // imageLoc contains size information of the image file being loaded;
   // clayer->loc contains size information of the layer, which may
   // be smaller than the whole image.  To get information on the layer, use
   // getLayerLoc().  --pete 2011-07-10
}

int Movie::updateState(double time, double dt)
{
   updateImage(time, dt);
   return 0;
}

/**
 * - Update the image buffers
 * - If the time is a multiple of biasChangetime then the position of the bias (biasX, biasY) changes.
 * - With probability persistenceProb the offset position (offsetX, offsetY) remains unchanged.
 * - Otherwise, with probability (1-persistenceProb) the offset position performs a random walk
 *   around the bias position (biasX, biasY).
 *
 * - If the time is a multiple of displayPeriod then load the next image.
 * - If nf=1 then the image is converted to grayscale during the call to read(filename, offsetX, offsetY).
 *   If nf>1 then the image is loaded with color information preserved.
 * - Return true if buffers have changed
 */
bool Movie::updateImage(double time, double dt)
{
   InterColComm * icComm = getParent()->icCommunicator();
   if(randomMovie){
      randomFrame();
      lastUpdateTime = time;
   } else {
      bool needNewImage = false;
      while (time >= nextDisplayTime) {
         needNewImage = true;
         if (readPvpFile){
            //If set to 0 or 1, normal frame
            if (skipFrameIndex <= 1){
               frameNumber += 1;
            }
            //Otherwise, skip based on skipFrameIndex
            else{
               frameNumber += skipFrameIndex;
            }
            //Loop when frame number reaches numFrames
            if (frameNumber >= numFrames){
               if( icComm->commRank()==0 ) {
                  fprintf(stderr, "Movie %s: EOF reached, rewinding file \"%s\"\n", name, filename);
               }
               frameNumber = 0;
            }
         }
         else{
            if (filename != NULL) free(filename);
            filename = strdup(getNextFileName(skipFrameIndex));
            assert(filename != NULL);
         }
         nextDisplayTime += displayPeriod;

         if(writePosition && parent->icCommunicator()->commRank()==0){
            fprintf(fp_pos->fp,"%f %s: \n",time,filename);
         }
         lastUpdateTime = time;
      } // time >= nextDisplayTime

      if( jitterFlag ) {
         bool jittered = jitter();
         needNewImage |= jittered;
      } // jitterFlag

      if( needNewImage ){
         GDALColorInterp * colorbandtypes = NULL;
         int status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);
         if( status != PV_SUCCESS ) {
            fprintf(stderr, "Movie %s: Error getting image info \"%s\"\n", name, filename);
            abort();
         }
         //Set frame number (member variable in Image)
         if( status == PV_SUCCESS ) status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);
         free(colorbandtypes); colorbandtypes = NULL;
         if( status != PV_SUCCESS ) {
            fprintf(stderr, "Movie %s: Error reading file \"%s\"\n", name, filename);
            abort();
         }
         newImageFlag = true;
      }
      else{
         if (time>0.0) newImageFlag = false;
      }
   } // randomMovie

   // exchange border information
   exchange();

   return true;
}

/**
 * When we play a random frame - in order to perform a reverse correlation analysis -
 * we call writeActivitySparse(time) in order to write the "activity" in the image.
 *
 */
int Movie::outputState(double time, bool last)
{
   if (writeImages) {
      char basicFilename[PV_PATH_MAX + 1];
      snprintf(basicFilename, PV_PATH_MAX, "%s/Movie_%.2f.%s", movieOutputPath, time, writeImagesExtension);
      write(basicFilename);
   }

   int status = PV_SUCCESS;
   if (randomMovie != 0) {
      status = writeActivitySparse(time);
   }
   else {
      status = HyPerLayer::outputState(time, last);
   }

   return status;
}

int Movie::copyReducedImagePortion()
{
   const PVLayerLoc * loc = getLayerLoc();

   const int nx = loc->nx;
   const int ny = loc->ny;

   const int nx0 = imageLoc.nx;
   const int ny0 = imageLoc.ny;

   assert(nx0 <= nx);
   assert(ny0 <= ny);

   const int i0 = nx/2 - nx0/2;
   const int j0 = ny/2 - ny0/2;

   int ii = 0;
   for (int j = j0; j < j0+ny0; j++) {
      for (int i = i0; i < i0+nx0; i++) {
         imageData[ii++] = data[i+nx*j];
      }
   }

   return 0;
}

/**
 * This creates a random image patch (frame) that is used to perform a reverse correlation analysis
 * as the input signal propagates up the visual system's hierarchy.
 * NOTE: Check Image::toGrayScale() method which was the inspiration for this routine
 */
int Movie::randomFrame()
{
   assert(randomMovie); // randomMovieProb was set only if randomMovie is true
   for (int kex = 0; kex < clayer->numExtended; kex++) {
      double p = uniformRand01(&rand_state);
      data[kex] = (p < randomMovieProb) ? 1: 0;
   }
   return 0;
}

// skip n_skip lines before reading next frame
const char * Movie::getNextFileName(int n_skip)
{
   for (int i_skip = 0; i_skip < n_skip-1; i_skip++){
      getNextFileName();
   }
   return getNextFileName();
}

const char * Movie::getNextFileName()
{
   InterColComm * icComm = getParent()->icCommunicator();
   if( icComm->commRank()==0 ) {
      int c;
      size_t len = PV_PATH_MAX;

      //TODO: add recovery procedure to handle case where access to file is temporarily unavailable
      // use stat to verify status of filepointer, keep running tally of current frame index so that file can be reopened and advanced to current frame

      // if at end of file (EOF), rewind
      if ((c = fgetc(filenamestream->fp)) == EOF) {
         PV_fseek(filenamestream, 0L, SEEK_SET);
         fprintf(stderr, "Movie %s: EOF reached, rewinding file \"%s\"\n", name, filename);
      }
      else {
         ungetc(c, filenamestream->fp);
      }

      char * path = fgets(inputfile, len, filenamestream->fp);
      if (path) {
         filenamestream->filepos += strlen(path)+1;
      }

      if (echoFramePathnameFlag){
         fprintf(stderr, "%s", path);
      }

      if (path != NULL) {
         path[PV_PATH_MAX-1] = '\0';
         len = strlen(path);
         if (len > 1) {
            if (path[len-1] == '\n') {
               path[len-1] = '\0';
            }
         }
      }
   }
#ifdef PV_USE_MPI
   MPI_Bcast(inputfile, PV_PATH_MAX, MPI_CHAR, 0, icComm->communicator());
#endif // PV_USE_MPI
   return inputfile;
}

bool Movie::getNewImageFlag(){
   return newImageFlag;
}

const char * Movie::getCurrentImage(){
   return inputfile;
}

}
<|endoftext|>