text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
//#include <strstream.h>
#include <sstream>
#else
#include <iostream>
//#include <strstream>
#include <sstream>
#endif
#include <stdio.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
// using std::ostrstream;
using std::ostringstream;
#endif
// XERCES HEADERS...
// Most are included by HarnessInit.hpp
#include <parsers/DOMParser.hpp>
// XALAN HEADERS...
// Most are included by FileUtility.hpp
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "conf dir [-category -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
"output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(const XalanDOMString& currentFile)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (equals(currentFile, excludeStylesheets[i]))
{
return true;
}
}
return false;
}
void
parseWithTransformer(int sourceType, XalanTransformer &xalan, const XSLTInputSource &xmlInput,
const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
XMLFileReporter &logFile)
{
const XalanParsedSource* parsedSource = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
}
else
{
xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree");
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
else
{
xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
}
void
parseWithXerces(XalanTransformer &xalan, const XSLTInputSource &xmlInput,
const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
XMLFileReporter &logFile)
{
h.data.xmlFormat = XalanDOMString("Xerces_DOM");
DOMParser theParser;
theParser.setToCreateXMLDeclTypeNode(false);
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOM_Document theDOM = theParser.getDocument();
theDOM.normalize();
XercesDOMSupport theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId()));
xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
// Call the static initializers for xerces and xalan, and create a transformer
//
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
XalanTransformer xalan;
// Get drive designation for final analysis and generate Unique name for results log.
//
const XalanDOMString drive(h.getDrive()); // This is used to get stylesheet for final analysis
const XalanDOMString resultFilePrefix("conf"); // This & UniqRunid used for log file name.
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
// Open results log, and do some initialization of result data.
//
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet");
// Get the list of Directories that are below conf and iterate through them
//
bool foundDir = false; // Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString currentDir(dirs[j]);
if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
{
continue;
}
// Check that output directory is there.
//
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
if (checkForExclusion(currentFile))
continue;
h.data.testOrFile = currentFile;
const XalanDOMString theXSLFile = h.args.base + currentDir + pathSep + currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
cout << "Failed to PARSE stylesheet for " << currentFile << endl;
h.data.fail += 1;
logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile);
break;
case 2:
parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
XalanTransformer::terminate();
return 0;
}
<commit_msg>Removed unnecessary include<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
//#include <strstream.h>
#include <sstream>
#else
#include <iostream>
//#include <strstream>
#include <sstream>
#endif
#include <stdio.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ostringstream;
#endif
// XERCES HEADERS...
// Most are included by HarnessInit.hpp
#include <parsers/DOMParser.hpp>
// XALAN HEADERS...
// Most are included by FileUtility.hpp
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "conf dir [-category -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
"output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(const XalanDOMString& currentFile)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (equals(currentFile, excludeStylesheets[i]))
{
return true;
}
}
return false;
}
void
parseWithTransformer(int sourceType, XalanTransformer &xalan, const XSLTInputSource &xmlInput,
const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
XMLFileReporter &logFile)
{
const XalanParsedSource* parsedSource = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
}
else
{
xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree");
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
else
{
xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
}
void
parseWithXerces(XalanTransformer &xalan, const XSLTInputSource &xmlInput,
const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
XMLFileReporter &logFile)
{
h.data.xmlFormat = XalanDOMString("Xerces_DOM");
DOMParser theParser;
theParser.setToCreateXMLDeclTypeNode(false);
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOM_Document theDOM = theParser.getDocument();
theDOM.normalize();
XercesDOMSupport theDOMSupport;
XercesParserLiaison theParserLiaison(theDOMSupport);
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId()));
xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
// Call the static initializers for xerces and xalan, and create a transformer
//
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
XalanTransformer xalan;
// Get drive designation for final analysis and generate Unique name for results log.
//
const XalanDOMString drive(h.getDrive()); // This is used to get stylesheet for final analysis
const XalanDOMString resultFilePrefix("conf"); // This & UniqRunid used for log file name.
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
// Open results log, and do some initialization of result data.
//
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet");
// Get the list of Directories that are below conf and iterate through them
//
bool foundDir = false; // Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString currentDir(dirs[j]);
if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
{
continue;
}
// Check that output directory is there.
//
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
if (checkForExclusion(currentFile))
continue;
h.data.testOrFile = currentFile;
const XalanDOMString theXSLFile = h.args.base + currentDir + pathSep + currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
cout << "Failed to PARSE stylesheet for " << currentFile << endl;
h.data.fail += 1;
logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile);
break;
case 2:
parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
XalanTransformer::terminate();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebDevToolsFrontendImpl.h"
#include "InspectorFrontendClientImpl.h"
#include "V8InspectorFrontendHost.h"
#include "V8MouseEvent.h"
#include "V8Node.h"
#include "WebDevToolsFrontendClient.h"
#include "WebFrameImpl.h"
#include "WebScriptSource.h"
#include "WebViewImpl.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/V8Utilities.h"
#include "core/dom/Document.h"
#include "core/dom/Event.h"
#include "core/dom/Node.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendHost.h"
#include "core/page/ContextMenuController.h"
#include "core/page/DOMWindow.h"
#include "core/page/Frame.h"
#include "core/page/Page.h"
#include "core/page/Settings.h"
#include "core/platform/ContextMenuItem.h"
#include "core/platform/Pasteboard.h"
#include "weborigin/SecurityOrigin.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
using namespace WebCore;
namespace WebKit {
class WebDevToolsFrontendImpl::InspectorFrontendResumeObserver : public ActiveDOMObject {
WTF_MAKE_NONCOPYABLE(InspectorFrontendResumeObserver);
public:
InspectorFrontendResumeObserver(WebDevToolsFrontendImpl* webDevToolsFrontendImpl, Document* document)
: ActiveDOMObject(document)
, m_webDevToolsFrontendImpl(webDevToolsFrontendImpl)
{
suspendIfNeeded();
}
private:
virtual bool canSuspend() const OVERRIDE
{
return true;
}
virtual void resume() OVERRIDE
{
m_webDevToolsFrontendImpl->resume();
}
WebDevToolsFrontendImpl* m_webDevToolsFrontendImpl;
};
static v8::Local<v8::String> ToV8String(const String& s)
{
if (s.isNull())
return v8::Local<v8::String>();
// FIXME: Call v8String from the Bindings layer.
return v8::String::New(reinterpret_cast<const uint16_t*>(s.bloatedCharacters()), s.length());
}
WebDevToolsFrontend* WebDevToolsFrontend::create(
WebView* view,
WebDevToolsFrontendClient* client,
const WebString& applicationLocale)
{
return new WebDevToolsFrontendImpl(
static_cast<WebViewImpl*>(view),
client,
applicationLocale);
}
WebDevToolsFrontendImpl::WebDevToolsFrontendImpl(
WebViewImpl* webViewImpl,
WebDevToolsFrontendClient* client,
const String& applicationLocale)
: m_webViewImpl(webViewImpl)
, m_client(client)
, m_applicationLocale(applicationLocale)
, m_inspectorFrontendDispatchTimer(this, &WebDevToolsFrontendImpl::maybeDispatch)
{
InspectorController* ic = m_webViewImpl->page()->inspectorController();
ic->setInspectorFrontendClient(adoptPtr(new InspectorFrontendClientImpl(m_webViewImpl->page(), m_client, this)));
// Put each DevTools frontend Page into a private group so that it's not
// deferred along with the inspected page.
m_webViewImpl->page()->setGroupType(Page::InspectorPageGroup);
}
WebDevToolsFrontendImpl::~WebDevToolsFrontendImpl()
{
}
void WebDevToolsFrontendImpl::dispatchOnInspectorFrontend(const WebString& message)
{
m_messages.append(message);
maybeDispatch(0);
}
void WebDevToolsFrontendImpl::resume()
{
// We should call maybeDispatch asynchronously here because we are not allowed to update activeDOMObjects list in
// resume (See ScriptExecutionContext::resumeActiveDOMObjects).
if (!m_inspectorFrontendDispatchTimer.isActive())
m_inspectorFrontendDispatchTimer.startOneShot(0);
}
void WebDevToolsFrontendImpl::maybeDispatch(WebCore::Timer<WebDevToolsFrontendImpl>*)
{
while (!m_messages.isEmpty()) {
Document* document = m_webViewImpl->page()->mainFrame()->document();
if (document->activeDOMObjectsAreSuspended()) {
m_inspectorFrontendResumeObserver = adoptPtr(new InspectorFrontendResumeObserver(this, document));
return;
}
m_inspectorFrontendResumeObserver.clear();
doDispatchOnInspectorFrontend(m_messages.takeFirst());
}
}
void WebDevToolsFrontendImpl::doDispatchOnInspectorFrontend(const WebString& message)
{
WebFrameImpl* frame = m_webViewImpl->mainFrameImpl();
v8::HandleScope scope;
v8::Handle<v8::Context> frameContext = frame->frame() ? frame->frame()->script()->currentWorldContext() : v8::Local<v8::Context>();
v8::Context::Scope contextScope(frameContext);
v8::Handle<v8::Value> inspectorFrontendApiValue = frameContext->Global()->Get(v8::String::New("InspectorFrontendAPI"));
if (!inspectorFrontendApiValue->IsObject())
return;
v8::Handle<v8::Object> inspectorFrontendApi = v8::Handle<v8::Object>::Cast(inspectorFrontendApiValue);
v8::Handle<v8::Value> dispatchFunction = inspectorFrontendApi->Get(v8::String::New("dispatchMessage"));
// The frame might have navigated away from the front-end page (which is still weird).
if (!dispatchFunction->IsFunction())
return;
v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatchFunction);
Vector< v8::Handle<v8::Value> > args;
args.append(ToV8String(message));
v8::TryCatch tryCatch;
tryCatch.SetVerbose(true);
ScriptController::callFunctionWithInstrumentation(frame->frame() ? frame->frame()->document() : 0, function, inspectorFrontendApi, args.size(), args.data());
}
} // namespace WebKit
<commit_msg>Inspector should use v8String instead of faking it<commit_after>/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebDevToolsFrontendImpl.h"
#include "InspectorFrontendClientImpl.h"
#include "V8InspectorFrontendHost.h"
#include "V8MouseEvent.h"
#include "V8Node.h"
#include "WebDevToolsFrontendClient.h"
#include "WebFrameImpl.h"
#include "WebScriptSource.h"
#include "WebViewImpl.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/V8Utilities.h"
#include "core/dom/Document.h"
#include "core/dom/Event.h"
#include "core/dom/Node.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendHost.h"
#include "core/page/ContextMenuController.h"
#include "core/page/DOMWindow.h"
#include "core/page/Frame.h"
#include "core/page/Page.h"
#include "core/page/Settings.h"
#include "core/platform/ContextMenuItem.h"
#include "core/platform/Pasteboard.h"
#include "weborigin/SecurityOrigin.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
using namespace WebCore;
namespace WebKit {
class WebDevToolsFrontendImpl::InspectorFrontendResumeObserver : public ActiveDOMObject {
WTF_MAKE_NONCOPYABLE(InspectorFrontendResumeObserver);
public:
InspectorFrontendResumeObserver(WebDevToolsFrontendImpl* webDevToolsFrontendImpl, Document* document)
: ActiveDOMObject(document)
, m_webDevToolsFrontendImpl(webDevToolsFrontendImpl)
{
suspendIfNeeded();
}
private:
virtual bool canSuspend() const OVERRIDE
{
return true;
}
virtual void resume() OVERRIDE
{
m_webDevToolsFrontendImpl->resume();
}
WebDevToolsFrontendImpl* m_webDevToolsFrontendImpl;
};
WebDevToolsFrontend* WebDevToolsFrontend::create(
WebView* view,
WebDevToolsFrontendClient* client,
const WebString& applicationLocale)
{
return new WebDevToolsFrontendImpl(
static_cast<WebViewImpl*>(view),
client,
applicationLocale);
}
WebDevToolsFrontendImpl::WebDevToolsFrontendImpl(
WebViewImpl* webViewImpl,
WebDevToolsFrontendClient* client,
const String& applicationLocale)
: m_webViewImpl(webViewImpl)
, m_client(client)
, m_applicationLocale(applicationLocale)
, m_inspectorFrontendDispatchTimer(this, &WebDevToolsFrontendImpl::maybeDispatch)
{
InspectorController* ic = m_webViewImpl->page()->inspectorController();
ic->setInspectorFrontendClient(adoptPtr(new InspectorFrontendClientImpl(m_webViewImpl->page(), m_client, this)));
// Put each DevTools frontend Page into a private group so that it's not
// deferred along with the inspected page.
m_webViewImpl->page()->setGroupType(Page::InspectorPageGroup);
}
WebDevToolsFrontendImpl::~WebDevToolsFrontendImpl()
{
}
void WebDevToolsFrontendImpl::dispatchOnInspectorFrontend(const WebString& message)
{
m_messages.append(message);
maybeDispatch(0);
}
void WebDevToolsFrontendImpl::resume()
{
// We should call maybeDispatch asynchronously here because we are not allowed to update activeDOMObjects list in
// resume (See ScriptExecutionContext::resumeActiveDOMObjects).
if (!m_inspectorFrontendDispatchTimer.isActive())
m_inspectorFrontendDispatchTimer.startOneShot(0);
}
void WebDevToolsFrontendImpl::maybeDispatch(WebCore::Timer<WebDevToolsFrontendImpl>*)
{
while (!m_messages.isEmpty()) {
Document* document = m_webViewImpl->page()->mainFrame()->document();
if (document->activeDOMObjectsAreSuspended()) {
m_inspectorFrontendResumeObserver = adoptPtr(new InspectorFrontendResumeObserver(this, document));
return;
}
m_inspectorFrontendResumeObserver.clear();
doDispatchOnInspectorFrontend(m_messages.takeFirst());
}
}
void WebDevToolsFrontendImpl::doDispatchOnInspectorFrontend(const WebString& message)
{
WebFrameImpl* frame = m_webViewImpl->mainFrameImpl();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope;
v8::Handle<v8::Context> frameContext = frame->frame() ? frame->frame()->script()->currentWorldContext() : v8::Local<v8::Context>();
v8::Context::Scope contextScope(frameContext);
v8::Handle<v8::Value> inspectorFrontendApiValue = frameContext->Global()->Get(v8::String::New("InspectorFrontendAPI"));
if (!inspectorFrontendApiValue->IsObject())
return;
v8::Handle<v8::Object> inspectorFrontendApi = v8::Handle<v8::Object>::Cast(inspectorFrontendApiValue);
v8::Handle<v8::Value> dispatchFunction = inspectorFrontendApi->Get(v8::String::New("dispatchMessage"));
// The frame might have navigated away from the front-end page (which is still weird).
if (!dispatchFunction->IsFunction())
return;
v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatchFunction);
Vector< v8::Handle<v8::Value> > args;
args.append(v8String(message, isolate));
v8::TryCatch tryCatch;
tryCatch.SetVerbose(true);
ScriptController::callFunctionWithInstrumentation(frame->frame() ? frame->frame()->document() : 0, function, inspectorFrontendApi, args.size(), args.data());
}
} // namespace WebKit
<|endoftext|> |
<commit_before>/*
* File: main.cpp
* Project: LinWarrior 3D
* Home: hackcraft.de
*
* Created on March 28, 2008, 21:25 PM (1999)
*/
// Startup code: Dispatching sub program startups.
#include <cstdlib>
#include <cstdio>
using namespace std;
#include "de/hackcraft/game/GameMain.h"
#include <de/hackcraft/util/HashMap.h>
#include <de/hackcraft/util/String.h>
void testHM1() {
HashMap<Object*,Object*>* h = new HashMap<Object*,Object*>();
Object a;
Object b;
h->put(&a, &b);
}
void testHM2() {
HashMap<String*,String*>* h = new HashMap<String*,String*>();
for (int i = 0; i <= ('z'-'a'); i++) {
//std::cout << i << "\n";
char x[] = { char('a' + i), '\0' };
char y[] = { char('A' + i), '\0' };
h->put(new String(x), new String(y));
}
for (int i = 0; i <= ('z'-'a'); i++) {
char x[] = { char('a' + i), '\0' };
String* y = h->get(new String(x));
std::cout << y->c_str();
}
}
void testHM() {
//testHM1();
testHM2();
}
static int test(int argc, char **args) {
cout << "Arguments for test module:\n";
for (int i = 0; i < argc; i++) {
cout << args[i] << "\n";
}
testHM();
return 0;
}
//#ifdef wonly_WIN32
//extern "C" int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* lpCmdLine, int nCmdShow) {
// int argc = 2;
// char *args[] = {"Nothing", "Nothing", "Nothing"};
//#else
//#endif
int main(int argc, char **args) {
try {
string subprogram = (argc >= 2) ? string(args[1]) : string("");
if (subprogram == "game") {
return (new GameMain())->run(argc-1, &args[1]);
} else if (subprogram == "test") {
return test(argc-1, &args[1]);
} else {
cout << "Please specify module to run: <program> <module> [parameters]\n";
cout << " game Run game module\n";
cout << " test Run test module\n";
return 0;
}
} catch (char* s) {
cout << "Fatal exception caught:\n" << s << endl;
} catch (const char* s) {
cout << "Fatal exception caught:\n" << s << endl;
}
return 0;
}
<commit_msg>Refactoring: Cleaning framework classes.<commit_after>/*
* File: main.cpp
* Project: LinWarrior 3D
* Home: hackcraft.de
*
* Created on March 28, 2008, 21:25 PM (1999)
*/
// Startup code: Dispatching sub program startups.
#include <cstdlib>
#include <cstdio>
using namespace std;
#include "de/hackcraft/game/GameMain.h"
#include <de/hackcraft/util/HashMap.h>
#include <de/hackcraft/lang/String.h>
void testHM1() {
HashMap<Object*,Object*>* h = new HashMap<Object*,Object*>();
Object a;
Object b;
h->put(&a, &b);
}
void testHM2() {
HashMap<String*,String*>* h = new HashMap<String*,String*>();
for (int i = 0; i <= ('z'-'a'); i++) {
//std::cout << i << "\n";
char x[] = { char('a' + i), '\0' };
char y[] = { char('A' + i), '\0' };
h->put(new String(x), new String(y));
}
for (int i = 0; i <= ('z'-'a'); i++) {
char x[] = { char('a' + i), '\0' };
String* y = h->get(new String(x));
std::cout << y->c_str();
}
}
void testHM() {
//testHM1();
testHM2();
}
static int test(int argc, char **args) {
cout << "Arguments for test module:\n";
for (int i = 0; i < argc; i++) {
cout << args[i] << "\n";
}
testHM();
return 0;
}
//#ifdef wonly_WIN32
//extern "C" int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* lpCmdLine, int nCmdShow) {
// int argc = 2;
// char *args[] = {"Nothing", "Nothing", "Nothing"};
//#else
//#endif
int main(int argc, char **args) {
try {
string subprogram = (argc >= 2) ? string(args[1]) : string("");
if (subprogram == "game") {
return (new GameMain())->run(argc-1, &args[1]);
} else if (subprogram == "test") {
return test(argc-1, &args[1]);
} else {
cout << "Please specify module to run: <program> <module> [parameters]\n";
cout << " game Run game module\n";
cout << " test Run test module\n";
return 0;
}
} catch (char* s) {
cout << "Fatal exception caught:\n" << s << endl;
} catch (const char* s) {
cout << "Fatal exception caught:\n" << s << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTextProperty.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkTextProperty, "1.6");
vtkStandardNewMacro(vtkTextProperty);
//----------------------------------------------------------------------------
// Control wheter to globally force text antialiasing (ALL),
// disable antialiasing (NONE), allow antialising (SOME) depending on
// the per-object AntiAliasing attribute.
static int vtkTextPropertyGlobalAntiAliasing = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;
void vtkTextProperty::SetGlobalAntiAliasing(int val)
{
if (val == vtkTextPropertyGlobalAntiAliasing)
{
return;
}
if (val < VTK_TEXT_GLOBAL_ANTIALIASING_SOME)
{
val = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;
}
else if (val > VTK_TEXT_GLOBAL_ANTIALIASING_ALL)
{
val = VTK_TEXT_GLOBAL_ANTIALIASING_ALL;
}
vtkTextPropertyGlobalAntiAliasing = val;
}
int vtkTextProperty::GetGlobalAntiAliasing()
{
return vtkTextPropertyGlobalAntiAliasing;
}
//----------------------------------------------------------------------------
// Creates a new text property with Font size 12, bold off, italic off,
// and Arial font
vtkTextProperty::vtkTextProperty()
{
// TOFIX: the default text prop color is set to a special (-1, -1, -1) value
// to maintain backward compatibility for a while. Text mapper classes will
// use the Actor2D color instead of the text prop color if this value is
// found (i.e. if the text prop color has not been set).
this->Color[0] = -1.0;
this->Color[1] = -1.0;
this->Color[2] = -1.0;
// TOFIX: same goes for opacity
this->Opacity = -1.0;
this->FontFamily = VTK_ARIAL;
this->FontSize = 12;
this->Bold = 0;
this->Italic = 0;
this->Shadow = 0;
this->AntiAliasing = 1;
this->Justification = VTK_TEXT_LEFT;
this->VerticalJustification = VTK_TEXT_BOTTOM;
this->LineOffset = 0.0;
this->LineSpacing = 1.0;
this->FaceFileName = NULL;
}
//----------------------------------------------------------------------------
// Shallow copy of a text property.
void vtkTextProperty::ShallowCopy(vtkTextProperty *tprop)
{
if (!tprop)
{
return;
}
this->SetColor(tprop->GetColor());
this->SetOpacity(tprop->GetOpacity());
this->SetFontFamily(tprop->GetFontFamily());
this->SetFontSize(tprop->GetFontSize());
this->SetBold(tprop->GetBold());
this->SetItalic(tprop->GetItalic());
this->SetShadow(tprop->GetShadow());
this->SetAntiAliasing(tprop->GetAntiAliasing());
this->SetJustification(tprop->GetJustification());
this->SetVerticalJustification(tprop->GetVerticalJustification());
this->SetLineOffset(tprop->GetLineOffset());
this->SetLineSpacing(tprop->GetLineSpacing());
this->SetFaceFileName(tprop->GetFaceFileName());
}
//----------------------------------------------------------------------------
vtkTextProperty::~vtkTextProperty()
{
if (this->FaceFileName)
{
delete [] this->FaceFileName;
this->FaceFileName = NULL;
}
}
//----------------------------------------------------------------------------
void vtkTextProperty::SetFaceFileName(const char *name)
{
// Same name
if (this->FaceFileName && name && (!strcmp(this->FaceFileName, name)))
{
return;
}
// Both empty ?
if (!name && !this->FaceFileName)
{
return;
}
// Release old name
if (this->FaceFileName)
{
delete [] this->FaceFileName;
}
// Copy
if (name)
{
this->FaceFileName = new char[strlen(name) + 1];
strcpy(this->FaceFileName, name);
}
else
{
this->FaceFileName = NULL;
}
this->Modified();
}
//----------------------------------------------------------------------------
void vtkTextProperty::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Color: (" << this->Color[0] << ", "
<< this->Color[1] << ", " << this->Color[2] << ")\n";
os << indent << "Opacity: " << this->Opacity << "\n";
os << indent << "FontFamily: " << this->GetFontFamilyAsString() << "\n";
os << indent << "FontSize: " << this->FontSize << "\n";
os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n");
os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n");
os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n");
os << indent << "Justification: "
<< this->GetJustificationAsString() << "\n";
os << indent << "Vertical justification: "
<< this->GetVerticalJustificationAsString() << "\n";
os << indent << "Line Offset: " << this->LineOffset << "\n";
os << indent << "Line Spacing: " << this->LineSpacing << "\n";
os << indent << "AntiAliasing: " << this->AntiAliasing << "\n";
os << indent << "FaceFileName: " << this->FaceFileName << "\n";
}
<commit_msg>FIX: purify NPR<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTextProperty.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkTextProperty, "1.7");
vtkStandardNewMacro(vtkTextProperty);
//----------------------------------------------------------------------------
// Control wheter to globally force text antialiasing (ALL),
// disable antialiasing (NONE), allow antialising (SOME) depending on
// the per-object AntiAliasing attribute.
static int vtkTextPropertyGlobalAntiAliasing = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;
void vtkTextProperty::SetGlobalAntiAliasing(int val)
{
if (val == vtkTextPropertyGlobalAntiAliasing)
{
return;
}
if (val < VTK_TEXT_GLOBAL_ANTIALIASING_SOME)
{
val = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;
}
else if (val > VTK_TEXT_GLOBAL_ANTIALIASING_ALL)
{
val = VTK_TEXT_GLOBAL_ANTIALIASING_ALL;
}
vtkTextPropertyGlobalAntiAliasing = val;
}
int vtkTextProperty::GetGlobalAntiAliasing()
{
return vtkTextPropertyGlobalAntiAliasing;
}
//----------------------------------------------------------------------------
// Creates a new text property with Font size 12, bold off, italic off,
// and Arial font
vtkTextProperty::vtkTextProperty()
{
// TOFIX: the default text prop color is set to a special (-1, -1, -1) value
// to maintain backward compatibility for a while. Text mapper classes will
// use the Actor2D color instead of the text prop color if this value is
// found (i.e. if the text prop color has not been set).
this->Color[0] = -1.0;
this->Color[1] = -1.0;
this->Color[2] = -1.0;
// TOFIX: same goes for opacity
this->Opacity = -1.0;
this->FontFamily = VTK_ARIAL;
this->FontSize = 12;
this->Bold = 0;
this->Italic = 0;
this->Shadow = 0;
this->AntiAliasing = 1;
this->Justification = VTK_TEXT_LEFT;
this->VerticalJustification = VTK_TEXT_BOTTOM;
this->LineOffset = 0.0;
this->LineSpacing = 1.0;
this->FaceFileName = NULL;
}
//----------------------------------------------------------------------------
// Shallow copy of a text property.
void vtkTextProperty::ShallowCopy(vtkTextProperty *tprop)
{
if (!tprop)
{
return;
}
this->SetColor(tprop->GetColor());
this->SetOpacity(tprop->GetOpacity());
this->SetFontFamily(tprop->GetFontFamily());
this->SetFontSize(tprop->GetFontSize());
this->SetBold(tprop->GetBold());
this->SetItalic(tprop->GetItalic());
this->SetShadow(tprop->GetShadow());
this->SetAntiAliasing(tprop->GetAntiAliasing());
this->SetJustification(tprop->GetJustification());
this->SetVerticalJustification(tprop->GetVerticalJustification());
this->SetLineOffset(tprop->GetLineOffset());
this->SetLineSpacing(tprop->GetLineSpacing());
this->SetFaceFileName(tprop->GetFaceFileName());
}
//----------------------------------------------------------------------------
vtkTextProperty::~vtkTextProperty()
{
if (this->FaceFileName)
{
delete [] this->FaceFileName;
this->FaceFileName = NULL;
}
}
//----------------------------------------------------------------------------
void vtkTextProperty::SetFaceFileName(const char *name)
{
// Same name
if (this->FaceFileName && name && (!strcmp(this->FaceFileName, name)))
{
return;
}
// Both empty ?
if (!name && !this->FaceFileName)
{
return;
}
// Release old name
if (this->FaceFileName)
{
delete [] this->FaceFileName;
}
// Copy
if (name)
{
this->FaceFileName = new char[strlen(name) + 1];
strcpy(this->FaceFileName, name);
}
else
{
this->FaceFileName = NULL;
}
this->Modified();
}
//----------------------------------------------------------------------------
void vtkTextProperty::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Color: (" << this->Color[0] << ", "
<< this->Color[1] << ", " << this->Color[2] << ")\n";
os << indent << "Opacity: " << this->Opacity << "\n";
os << indent << "FontFamily: " << this->GetFontFamilyAsString() << "\n";
os << indent << "FontSize: " << this->FontSize << "\n";
os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n");
os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n");
os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n");
os << indent << "Justification: "
<< this->GetJustificationAsString() << "\n";
os << indent << "Vertical justification: "
<< this->GetVerticalJustificationAsString() << "\n";
os << indent << "Line Offset: " << this->LineOffset << "\n";
os << indent << "Line Spacing: " << this->LineSpacing << "\n";
os << indent << "AntiAliasing: " << this->AntiAliasing << "\n";
if (this->FaceFileName)
{
os << indent << "FaceFileName: " << this->FaceFileName << "\n";
}
else
{
os << indent << "FaceFileName: (none)\n";
}
}
<|endoftext|> |
<commit_before><commit_msg>stitching: fix l_gains data type from Eigen solver (float / double)<commit_after><|endoftext|> |
<commit_before>#include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"
FglTFImportOptions::FglTFImportOptions()
: FilePathInOS(TEXT(""))
, FilePathInEngine(TEXT(""))
, MeshScaleRatio(1.0f)
, bInvertNormal(false)
, bImportMaterial(true)
, bRecomputeNormals(true)
, bRecomputeTangents(true)
{
//
}
const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;
<commit_msg>Set the default scale to 100<commit_after>#include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"
FglTFImportOptions::FglTFImportOptions()
: FilePathInOS(TEXT(""))
, FilePathInEngine(TEXT(""))
, MeshScaleRatio(100.0f)
, bInvertNormal(false)
, bImportMaterial(true)
, bRecomputeNormals(true)
, bRecomputeTangents(true)
{
//
}
const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : RenderWindow.cpp
//! Author : Jens Krueger
//! SCI Institute
//! University of Utah
//! Date : July 2008
//
//! Copyright (C) 2008 SCI Institute
#include "RenderWindow.h"
#include "ImageVis3D.h"
#include <QtGui/QtGui>
#include <QtOpenGL/QtOpenGL>
#include <assert.h>
RenderWindow::RenderWindow(MasterController& masterController, QString dataset, unsigned int iCounter, QGLWidget* glShareWidget, QWidget* parent, Qt::WindowFlags flags) :
QGLWidget(parent, glShareWidget, flags),
m_Renderer((GPUSBVR*)masterController.RequestNewVolumerenderer(OPENGL_SBVR)),
m_MasterController(masterController),
m_iTimeSliceMSecsActive(500),
m_iTimeSliceMSecsInActive(100),
m_strDataset(dataset),
m_vWinDim(0,0),
m_MainWindow((MainWindow*)parent)
{
m_strID = tr("[%1] %2").arg(iCounter).arg(m_strDataset);
setWindowTitle(m_strID);
m_Renderer->LoadDataset(m_strDataset.toStdString());
this->setFocusPolicy(Qt::StrongFocus);
}
RenderWindow::~RenderWindow()
{
Cleanup();
}
QSize RenderWindow::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize RenderWindow::sizeHint() const
{
return QSize(400, 400);
}
void RenderWindow::initializeGL()
{
static bool bFirstTime = true;
if (bFirstTime) {
int err = glewInit();
if (err != GLEW_OK) {
m_MasterController.DebugOut()->Error("RenderWindow::initializeGL", "Error initializing GLEW: %s",glewGetErrorString(err));
} else {
const GLubyte *vendor=glGetString(GL_VENDOR);
const GLubyte *renderer=glGetString(GL_RENDERER);
const GLubyte *version=glGetString(GL_VERSION);
m_MasterController.DebugOut()->Message("RenderWindow::initializeGL", "Starting up GL! Running on a %s %s with OpenGL version %s",vendor, renderer, version);
}
bFirstTime = false;
}
if (m_Renderer != NULL) m_Renderer->Initialize();
}
void RenderWindow::paintGL()
{
if (m_Renderer != NULL) {
m_Renderer->Paint();
if (isActiveWindow()) {
m_MainWindow->SetRenderProgress(m_Renderer->GetFrameProgress(), m_Renderer->GetSubFrameProgress());
}
}
}
void RenderWindow::resizeGL(int width, int height)
{
m_vWinDim = UINTVECTOR2((unsigned int)width, (unsigned int)height);
if (m_Renderer != NULL) m_Renderer->Resize(UINTVECTOR2(width, height));
}
void RenderWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
// nothing todo yet
}
if (event->button() == Qt::LeftButton) {
m_Renderer->Click(UINTVECTOR2(event->pos().x(), event->pos().y()));
}
}
void RenderWindow::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
m_Renderer->Release(UINTVECTOR2(event->pos().x(), event->pos().y()));
}
}
float scale(int max, float w) {
if (w < 0) {
return w-(((int)w/max)-1)*max;
} else {
return w-((int)w/max)*max;
}
}
void RenderWindow::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
m_Renderer->Drag(UINTVECTOR2(event->x(), event->y()));
updateGL();
}
}
void RenderWindow::wheelEvent(QWheelEvent *event) {
m_Renderer->Zoom(event->delta());
}
void RenderWindow::keyPressEvent ( QKeyEvent * event ) {
QGLWidget::keyPressEvent(event);
if (event->key() == Qt::Key_Space) {
AbstrRenderer::EViewMode eMode = AbstrRenderer::EViewMode((int(m_Renderer->GetViewmode()) + 1) % int(AbstrRenderer::VM_INVALID));
m_Renderer->SetViewmode(eMode);
emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
updateGL();
}
}
void RenderWindow::ToggleRenderWindowView2x2() {
if (m_Renderer != NULL) {
m_Renderer->SetViewmode(AbstrRenderer::VM_TWOBYTWO);
emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
updateGL();
}
}
void RenderWindow::ToggleRenderWindowViewSingle() {
if (m_Renderer != NULL) {
m_Renderer->SetViewmode(AbstrRenderer::VM_SINGLE);
emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
updateGL();
}
}
void RenderWindow::Cleanup() {
if (m_Renderer == NULL) return;
makeCurrent();
m_Renderer->Cleanup();
m_MasterController.ReleaseVolumerenderer(m_Renderer);
m_Renderer = NULL;
}
void RenderWindow::closeEvent(QCloseEvent *event) {
QGLWidget::closeEvent(event);
emit WindowClosing(this);
}
void RenderWindow::focusInEvent ( QFocusEvent * event ) {
// call superclass method
QGLWidget::focusInEvent(event);
m_Renderer->SetTimeSlice(m_iTimeSliceMSecsActive);
if (event->gotFocus()) {
emit WindowActive(this);
}
}
void RenderWindow::focusOutEvent ( QFocusEvent * event ) {
// call superclass method
QGLWidget::focusOutEvent(event);
m_Renderer->SetTimeSlice(m_iTimeSliceMSecsInActive);
if (!event->gotFocus()) {
emit WindowInActive(this);
}
}
void RenderWindow::CheckForRedraw() {
if (m_Renderer->CheckForRedraw()) {
makeCurrent();
update();
}
}
void RenderWindow::SetBlendPrecision(AbstrRenderer::EBlendPrecision eBlendPrecisionMode) {
makeCurrent();
m_Renderer->SetBlendPrecision(eBlendPrecisionMode);
}
void RenderWindow::SetPerfMeasures(unsigned int iMinFramerate, unsigned int iLODDelay, unsigned int iActiveTS, unsigned int iInactiveTS) {
makeCurrent();
m_iTimeSliceMSecsActive = iActiveTS;
m_iTimeSliceMSecsInActive = iInactiveTS;
m_Renderer->SetPerfMeasures(iMinFramerate, iLODDelay);
}
<commit_msg>fixed warning on linux<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : RenderWindow.cpp
//! Author : Jens Krueger
//! SCI Institute
//! University of Utah
//! Date : July 2008
//
//! Copyright (C) 2008 SCI Institute
#include "RenderWindow.h"
#include "ImageVis3D.h"
#include <QtGui/QtGui>
#include <QtOpenGL/QtOpenGL>
#include <assert.h>
RenderWindow::RenderWindow(MasterController& masterController, QString dataset, unsigned int iCounter, QGLWidget* glShareWidget, QWidget* parent, Qt::WindowFlags flags) :
QGLWidget(parent, glShareWidget, flags),
m_MainWindow((MainWindow*)parent),
m_Renderer((GPUSBVR*)masterController.RequestNewVolumerenderer(OPENGL_SBVR)),
m_MasterController(masterController),
m_iTimeSliceMSecsActive(500),
m_iTimeSliceMSecsInActive(100),
m_strDataset(dataset),
m_vWinDim(0,0)
{
m_strID = tr("[%1] %2").arg(iCounter).arg(m_strDataset);
setWindowTitle(m_strID);
m_Renderer->LoadDataset(m_strDataset.toStdString());
this->setFocusPolicy(Qt::StrongFocus);
}
RenderWindow::~RenderWindow()
{
Cleanup();
}
QSize RenderWindow::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize RenderWindow::sizeHint() const
{
return QSize(400, 400);
}
void RenderWindow::initializeGL()
{
static bool bFirstTime = true;
if (bFirstTime) {
int err = glewInit();
if (err != GLEW_OK) {
m_MasterController.DebugOut()->Error("RenderWindow::initializeGL", "Error initializing GLEW: %s",glewGetErrorString(err));
} else {
const GLubyte *vendor=glGetString(GL_VENDOR);
const GLubyte *renderer=glGetString(GL_RENDERER);
const GLubyte *version=glGetString(GL_VERSION);
m_MasterController.DebugOut()->Message("RenderWindow::initializeGL", "Starting up GL! Running on a %s %s with OpenGL version %s",vendor, renderer, version);
}
bFirstTime = false;
}
if (m_Renderer != NULL) m_Renderer->Initialize();
}
void RenderWindow::paintGL()
{
if (m_Renderer != NULL) {
m_Renderer->Paint();
if (isActiveWindow()) {
m_MainWindow->SetRenderProgress(m_Renderer->GetFrameProgress(), m_Renderer->GetSubFrameProgress());
}
}
}
void RenderWindow::resizeGL(int width, int height)
{
m_vWinDim = UINTVECTOR2((unsigned int)width, (unsigned int)height);
if (m_Renderer != NULL) m_Renderer->Resize(UINTVECTOR2(width, height));
}
void RenderWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
// nothing todo yet
}
if (event->button() == Qt::LeftButton) {
m_Renderer->Click(UINTVECTOR2(event->pos().x(), event->pos().y()));
}
}
void RenderWindow::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
m_Renderer->Release(UINTVECTOR2(event->pos().x(), event->pos().y()));
}
}
float scale(int max, float w) {
if (w < 0) {
return w-(((int)w/max)-1)*max;
} else {
return w-((int)w/max)*max;
}
}
void RenderWindow::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
m_Renderer->Drag(UINTVECTOR2(event->x(), event->y()));
updateGL();
}
}
void RenderWindow::wheelEvent(QWheelEvent *event) {
m_Renderer->Zoom(event->delta());
}
void RenderWindow::keyPressEvent ( QKeyEvent * event ) {
QGLWidget::keyPressEvent(event);
if (event->key() == Qt::Key_Space) {
AbstrRenderer::EViewMode eMode = AbstrRenderer::EViewMode((int(m_Renderer->GetViewmode()) + 1) % int(AbstrRenderer::VM_INVALID));
m_Renderer->SetViewmode(eMode);
emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
updateGL();
}
}
void RenderWindow::ToggleRenderWindowView2x2() {
if (m_Renderer != NULL) {
m_Renderer->SetViewmode(AbstrRenderer::VM_TWOBYTWO);
emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
updateGL();
}
}
void RenderWindow::ToggleRenderWindowViewSingle() {
if (m_Renderer != NULL) {
m_Renderer->SetViewmode(AbstrRenderer::VM_SINGLE);
emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
updateGL();
}
}
void RenderWindow::Cleanup() {
if (m_Renderer == NULL) return;
makeCurrent();
m_Renderer->Cleanup();
m_MasterController.ReleaseVolumerenderer(m_Renderer);
m_Renderer = NULL;
}
void RenderWindow::closeEvent(QCloseEvent *event) {
QGLWidget::closeEvent(event);
emit WindowClosing(this);
}
void RenderWindow::focusInEvent ( QFocusEvent * event ) {
// call superclass method
QGLWidget::focusInEvent(event);
m_Renderer->SetTimeSlice(m_iTimeSliceMSecsActive);
if (event->gotFocus()) {
emit WindowActive(this);
}
}
void RenderWindow::focusOutEvent ( QFocusEvent * event ) {
// call superclass method
QGLWidget::focusOutEvent(event);
m_Renderer->SetTimeSlice(m_iTimeSliceMSecsInActive);
if (!event->gotFocus()) {
emit WindowInActive(this);
}
}
void RenderWindow::CheckForRedraw() {
if (m_Renderer->CheckForRedraw()) {
makeCurrent();
update();
}
}
void RenderWindow::SetBlendPrecision(AbstrRenderer::EBlendPrecision eBlendPrecisionMode) {
makeCurrent();
m_Renderer->SetBlendPrecision(eBlendPrecisionMode);
}
void RenderWindow::SetPerfMeasures(unsigned int iMinFramerate, unsigned int iLODDelay, unsigned int iActiveTS, unsigned int iInactiveTS) {
makeCurrent();
m_iTimeSliceMSecsActive = iActiveTS;
m_iTimeSliceMSecsInActive = iInactiveTS;
m_Renderer->SetPerfMeasures(iMinFramerate, iLODDelay);
}
<|endoftext|> |
<commit_before>//===- ReadInst.cpp - Code to read an instruction from bytecode -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the mechanism to read an instruction from a bytecode
// stream.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//
#include "ReaderInternals.h"
#include "llvm/iTerminators.h"
#include "llvm/iMemory.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
using namespace llvm;
namespace {
struct RawInst { // The raw fields out of the bytecode stream...
unsigned NumOperands;
unsigned Opcode;
unsigned Type;
RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
std::vector<unsigned> &Args);
};
}
RawInst::RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
std::vector<unsigned> &Args) {
unsigned Op = read(Buf, EndBuf);
// bits Instruction format: Common to all formats
// --------------------------
// 01-00: Opcode type, fixed to 1.
// 07-02: Opcode
Opcode = (Op >> 2) & 63;
Args.resize((Op >> 0) & 03);
switch (Args.size()) {
case 1:
// bits Instruction format:
// --------------------------
// 19-08: Resulting type plane
// 31-20: Operand #1 (if set to (2^12-1), then zero operands)
//
Type = (Op >> 8) & 4095;
Args[0] = (Op >> 20) & 4095;
if (Args[0] == 4095) // Handle special encoding for 0 operands...
Args.resize(0);
break;
case 2:
// bits Instruction format:
// --------------------------
// 15-08: Resulting type plane
// 23-16: Operand #1
// 31-24: Operand #2
//
Type = (Op >> 8) & 255;
Args[0] = (Op >> 16) & 255;
Args[1] = (Op >> 24) & 255;
break;
case 3:
// bits Instruction format:
// --------------------------
// 13-08: Resulting type plane
// 19-14: Operand #1
// 25-20: Operand #2
// 31-26: Operand #3
//
Type = (Op >> 8) & 63;
Args[0] = (Op >> 14) & 63;
Args[1] = (Op >> 20) & 63;
Args[2] = (Op >> 26) & 63;
break;
case 0:
Buf -= 4; // Hrm, try this again...
Opcode = read_vbr_uint(Buf, EndBuf);
Opcode >>= 2;
Type = read_vbr_uint(Buf, EndBuf);
unsigned NumOperands = read_vbr_uint(Buf, EndBuf);
Args.resize(NumOperands);
if (NumOperands == 0)
throw std::string("Zero-argument instruction found; this is invalid.");
for (unsigned i = 0; i != NumOperands; ++i)
Args[i] = read_vbr_uint(Buf, EndBuf);
align32(Buf, EndBuf);
break;
}
}
void BytecodeParser::ParseInstruction(const unsigned char *&Buf,
const unsigned char *EndBuf,
std::vector<unsigned> &Args,
BasicBlock *BB) {
Args.clear();
RawInst RI(Buf, EndBuf, Args);
const Type *InstTy = getType(RI.Type);
Instruction *Result = 0;
if (RI.Opcode >= Instruction::BinaryOpsBegin &&
RI.Opcode < Instruction::BinaryOpsEnd && Args.size() == 2)
Result = BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(RI.Type, Args[1]));
switch (RI.Opcode) {
default:
if (Result == 0) throw std::string("Illegal instruction read!");
break;
case Instruction::VAArg:
Result = new VAArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::VANext:
Result = new VANextInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::Cast:
Result = new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::Select:
Result = new SelectInst(getValue(Type::BoolTyID, Args[0]),
getValue(RI.Type, Args[1]),
getValue(RI.Type, Args[2]));
break;
case Instruction::PHI: {
if (Args.size() == 0 || (Args.size() & 1))
throw std::string("Invalid phi node encountered!\n");
PHINode *PN = new PHINode(InstTy);
PN->op_reserve(Args.size());
for (unsigned i = 0, e = Args.size(); i != e; i += 2)
PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
Result = PN;
break;
}
case Instruction::Shl:
case Instruction::Shr:
Result = new ShiftInst((Instruction::OtherOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(Type::UByteTyID, Args[1]));
break;
case Instruction::Ret:
if (Args.size() == 0)
Result = new ReturnInst();
else if (Args.size() == 1)
Result = new ReturnInst(getValue(RI.Type, Args[0]));
else
throw std::string("Unrecognized instruction!");
break;
case Instruction::Br:
if (Args.size() == 1)
Result = new BranchInst(getBasicBlock(Args[0]));
else if (Args.size() == 3)
Result = new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
getValue(Type::BoolTyID , Args[2]));
else
throw std::string("Invalid number of operands for a 'br' instruction!");
break;
case Instruction::Switch: {
if (Args.size() & 1)
throw std::string("Switch statement with odd number of arguments!");
SwitchInst *I = new SwitchInst(getValue(RI.Type, Args[0]),
getBasicBlock(Args[1]));
for (unsigned i = 2, e = Args.size(); i != e; i += 2)
I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
getBasicBlock(Args[i+1]));
Result = I;
break;
}
case Instruction::Call: {
if (Args.size() == 0)
throw std::string("Invalid call instruction encountered!");
Value *F = getValue(RI.Type, Args[0]);
// Check to make sure we have a pointer to function type
const PointerType *PTy = dyn_cast<PointerType>(F->getType());
if (PTy == 0) throw std::string("Call to non function pointer value!");
const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
if (FTy == 0) throw std::string("Call to non function pointer value!");
std::vector<Value *> Params;
if (!FTy->isVarArg()) {
FunctionType::param_iterator It = FTy->param_begin();
for (unsigned i = 1, e = Args.size(); i != e; ++i) {
if (It == FTy->param_end())
throw std::string("Invalid call instruction!");
Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
}
if (It != FTy->param_end())
throw std::string("Invalid call instruction!");
} else {
Args.erase(Args.begin(), Args.begin()+1);
unsigned FirstVariableOperand;
if (Args.size() < FTy->getNumParams())
throw std::string("Call instruction missing operands!");
// Read all of the fixed arguments
for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Args[i]));
FirstVariableOperand = FTy->getNumParams();
if ((Args.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
throw std::string("Invalid call instruction!");
for (unsigned i = FirstVariableOperand, e = Args.size(); i != e; i += 2)
Params.push_back(getValue(Args[i], Args[i+1]));
}
Result = new CallInst(F, Params);
break;
}
case Instruction::Invoke: {
if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
Value *F = getValue(RI.Type, Args[0]);
// Check to make sure we have a pointer to function type
const PointerType *PTy = dyn_cast<PointerType>(F->getType());
if (PTy == 0) throw std::string("Invoke to non function pointer value!");
const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
if (FTy == 0) throw std::string("Invoke to non function pointer value!");
std::vector<Value *> Params;
BasicBlock *Normal, *Except;
if (!FTy->isVarArg()) {
Normal = getBasicBlock(Args[1]);
Except = getBasicBlock(Args[2]);
FunctionType::param_iterator It = FTy->param_begin();
for (unsigned i = 3, e = Args.size(); i != e; ++i) {
if (It == FTy->param_end())
throw std::string("Invalid invoke instruction!");
Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
}
if (It != FTy->param_end())
throw std::string("Invalid invoke instruction!");
} else {
Args.erase(Args.begin(), Args.begin()+1);
Normal = getBasicBlock(Args[0]);
Except = getBasicBlock(Args[1]);
unsigned FirstVariableArgument = FTy->getNumParams()+2;
for (unsigned i = 2; i != FirstVariableArgument; ++i)
Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
Args[i]));
if (Args.size()-FirstVariableArgument & 1) // Must be pairs of type/value
throw std::string("Invalid invoke instruction!");
for (unsigned i = FirstVariableArgument; i < Args.size(); i += 2)
Params.push_back(getValue(Args[i], Args[i+1]));
}
Result = new InvokeInst(F, Normal, Except, Params);
break;
}
case Instruction::Malloc:
if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
if (!isa<PointerType>(InstTy))
throw std::string("Invalid malloc instruction!");
Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID,
Args[0]) : 0);
break;
case Instruction::Alloca:
if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
if (!isa<PointerType>(InstTy))
throw std::string("Invalid alloca instruction!");
Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID, Args[0]) :0);
break;
case Instruction::Free:
if (!isa<PointerType>(InstTy))
throw std::string("Invalid free instruction!");
Result = new FreeInst(getValue(RI.Type, Args[0]));
break;
case Instruction::GetElementPtr: {
if (Args.size() == 0 || !isa<PointerType>(InstTy))
throw std::string("Invalid getelementptr instruction!");
std::vector<Value*> Idx;
const Type *NextTy = InstTy;
for (unsigned i = 1, e = Args.size(); i != e; ++i) {
const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
if (!TopTy) throw std::string("Invalid getelementptr instruction!");
unsigned ValIdx = Args[i];
unsigned IdxTy;
if (!hasRestrictedGEPTypes) {
// Struct indices are always uints, sequential type indices can be any
// of the 32 or 64-bit integer types. The actual choice of type is
// encoded in the low two bits of the slot number.
if (isa<StructType>(TopTy))
IdxTy = Type::UIntTyID;
else {
switch (ValIdx & 3) {
default:
case 0: IdxTy = Type::UIntTyID; break;
case 1: IdxTy = Type::IntTyID; break;
case 2: IdxTy = Type::ULongTyID; break;
case 3: IdxTy = Type::LongTyID; break;
}
ValIdx >>= 2;
}
} else {
IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
}
Idx.push_back(getValue(IdxTy, ValIdx));
// Convert ubyte struct indices into uint struct indices.
if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
}
Result = new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
break;
}
case 62: // volatile load
case Instruction::Load:
if (Args.size() != 1 || !isa<PointerType>(InstTy))
throw std::string("Invalid load instruction!");
Result = new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
break;
case 63: // volatile store
case Instruction::Store: {
if (!isa<PointerType>(InstTy) || Args.size() != 2)
throw std::string("Invalid store instruction!");
Value *Ptr = getValue(RI.Type, Args[1]);
const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
Result = new StoreInst(getValue(getTypeSlot(ValTy), Args[0]), Ptr,
RI.Opcode == 63);
break;
}
case Instruction::Unwind:
if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
Result = new UnwindInst();
break;
} // end switch(RI.Opcode)
unsigned TypeSlot;
if (Result->getType() == InstTy)
TypeSlot = RI.Type;
else
TypeSlot = getTypeSlot(Result->getType());
insertValue(Result, TypeSlot, Values);
BB->getInstList().push_back(Result);
BCR_TRACE(4, *Result);
}
<commit_msg>Squelch compile-time warning (profile build).<commit_after>//===- ReadInst.cpp - Code to read an instruction from bytecode -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the mechanism to read an instruction from a bytecode
// stream.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//
#include "ReaderInternals.h"
#include "llvm/iTerminators.h"
#include "llvm/iMemory.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
using namespace llvm;
namespace {
struct RawInst { // The raw fields out of the bytecode stream...
unsigned NumOperands;
unsigned Opcode;
unsigned Type;
RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
std::vector<unsigned> &Args);
};
}
RawInst::RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
std::vector<unsigned> &Args) {
unsigned Op = read(Buf, EndBuf);
// bits Instruction format: Common to all formats
// --------------------------
// 01-00: Opcode type, fixed to 1.
// 07-02: Opcode
Opcode = (Op >> 2) & 63;
Args.resize((Op >> 0) & 03);
switch (Args.size()) {
case 1:
// bits Instruction format:
// --------------------------
// 19-08: Resulting type plane
// 31-20: Operand #1 (if set to (2^12-1), then zero operands)
//
Type = (Op >> 8) & 4095;
Args[0] = (Op >> 20) & 4095;
if (Args[0] == 4095) // Handle special encoding for 0 operands...
Args.resize(0);
break;
case 2:
// bits Instruction format:
// --------------------------
// 15-08: Resulting type plane
// 23-16: Operand #1
// 31-24: Operand #2
//
Type = (Op >> 8) & 255;
Args[0] = (Op >> 16) & 255;
Args[1] = (Op >> 24) & 255;
break;
case 3:
// bits Instruction format:
// --------------------------
// 13-08: Resulting type plane
// 19-14: Operand #1
// 25-20: Operand #2
// 31-26: Operand #3
//
Type = (Op >> 8) & 63;
Args[0] = (Op >> 14) & 63;
Args[1] = (Op >> 20) & 63;
Args[2] = (Op >> 26) & 63;
break;
case 0:
Buf -= 4; // Hrm, try this again...
Opcode = read_vbr_uint(Buf, EndBuf);
Opcode >>= 2;
Type = read_vbr_uint(Buf, EndBuf);
unsigned NumOperands = read_vbr_uint(Buf, EndBuf);
Args.resize(NumOperands);
if (NumOperands == 0)
throw std::string("Zero-argument instruction found; this is invalid.");
for (unsigned i = 0; i != NumOperands; ++i)
Args[i] = read_vbr_uint(Buf, EndBuf);
align32(Buf, EndBuf);
break;
}
}
void BytecodeParser::ParseInstruction(const unsigned char *&Buf,
const unsigned char *EndBuf,
std::vector<unsigned> &Args,
BasicBlock *BB) {
Args.clear();
RawInst RI(Buf, EndBuf, Args);
const Type *InstTy = getType(RI.Type);
Instruction *Result = 0;
if (RI.Opcode >= Instruction::BinaryOpsBegin &&
RI.Opcode < Instruction::BinaryOpsEnd && Args.size() == 2)
Result = BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(RI.Type, Args[1]));
switch (RI.Opcode) {
default:
if (Result == 0) throw std::string("Illegal instruction read!");
break;
case Instruction::VAArg:
Result = new VAArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::VANext:
Result = new VANextInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::Cast:
Result = new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::Select:
Result = new SelectInst(getValue(Type::BoolTyID, Args[0]),
getValue(RI.Type, Args[1]),
getValue(RI.Type, Args[2]));
break;
case Instruction::PHI: {
if (Args.size() == 0 || (Args.size() & 1))
throw std::string("Invalid phi node encountered!\n");
PHINode *PN = new PHINode(InstTy);
PN->op_reserve(Args.size());
for (unsigned i = 0, e = Args.size(); i != e; i += 2)
PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
Result = PN;
break;
}
case Instruction::Shl:
case Instruction::Shr:
Result = new ShiftInst((Instruction::OtherOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(Type::UByteTyID, Args[1]));
break;
case Instruction::Ret:
if (Args.size() == 0)
Result = new ReturnInst();
else if (Args.size() == 1)
Result = new ReturnInst(getValue(RI.Type, Args[0]));
else
throw std::string("Unrecognized instruction!");
break;
case Instruction::Br:
if (Args.size() == 1)
Result = new BranchInst(getBasicBlock(Args[0]));
else if (Args.size() == 3)
Result = new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
getValue(Type::BoolTyID , Args[2]));
else
throw std::string("Invalid number of operands for a 'br' instruction!");
break;
case Instruction::Switch: {
if (Args.size() & 1)
throw std::string("Switch statement with odd number of arguments!");
SwitchInst *I = new SwitchInst(getValue(RI.Type, Args[0]),
getBasicBlock(Args[1]));
for (unsigned i = 2, e = Args.size(); i != e; i += 2)
I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
getBasicBlock(Args[i+1]));
Result = I;
break;
}
case Instruction::Call: {
if (Args.size() == 0)
throw std::string("Invalid call instruction encountered!");
Value *F = getValue(RI.Type, Args[0]);
// Check to make sure we have a pointer to function type
const PointerType *PTy = dyn_cast<PointerType>(F->getType());
if (PTy == 0) throw std::string("Call to non function pointer value!");
const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
if (FTy == 0) throw std::string("Call to non function pointer value!");
std::vector<Value *> Params;
if (!FTy->isVarArg()) {
FunctionType::param_iterator It = FTy->param_begin();
for (unsigned i = 1, e = Args.size(); i != e; ++i) {
if (It == FTy->param_end())
throw std::string("Invalid call instruction!");
Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
}
if (It != FTy->param_end())
throw std::string("Invalid call instruction!");
} else {
Args.erase(Args.begin(), Args.begin()+1);
unsigned FirstVariableOperand;
if (Args.size() < FTy->getNumParams())
throw std::string("Call instruction missing operands!");
// Read all of the fixed arguments
for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Args[i]));
FirstVariableOperand = FTy->getNumParams();
if ((Args.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
throw std::string("Invalid call instruction!");
for (unsigned i = FirstVariableOperand, e = Args.size(); i != e; i += 2)
Params.push_back(getValue(Args[i], Args[i+1]));
}
Result = new CallInst(F, Params);
break;
}
case Instruction::Invoke: {
if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
Value *F = getValue(RI.Type, Args[0]);
// Check to make sure we have a pointer to function type
const PointerType *PTy = dyn_cast<PointerType>(F->getType());
if (PTy == 0) throw std::string("Invoke to non function pointer value!");
const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
if (FTy == 0) throw std::string("Invoke to non function pointer value!");
std::vector<Value *> Params;
BasicBlock *Normal, *Except;
if (!FTy->isVarArg()) {
Normal = getBasicBlock(Args[1]);
Except = getBasicBlock(Args[2]);
FunctionType::param_iterator It = FTy->param_begin();
for (unsigned i = 3, e = Args.size(); i != e; ++i) {
if (It == FTy->param_end())
throw std::string("Invalid invoke instruction!");
Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
}
if (It != FTy->param_end())
throw std::string("Invalid invoke instruction!");
} else {
Args.erase(Args.begin(), Args.begin()+1);
Normal = getBasicBlock(Args[0]);
Except = getBasicBlock(Args[1]);
unsigned FirstVariableArgument = FTy->getNumParams()+2;
for (unsigned i = 2; i != FirstVariableArgument; ++i)
Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
Args[i]));
if (Args.size()-FirstVariableArgument & 1) // Must be pairs of type/value
throw std::string("Invalid invoke instruction!");
for (unsigned i = FirstVariableArgument; i < Args.size(); i += 2)
Params.push_back(getValue(Args[i], Args[i+1]));
}
Result = new InvokeInst(F, Normal, Except, Params);
break;
}
case Instruction::Malloc:
if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
if (!isa<PointerType>(InstTy))
throw std::string("Invalid malloc instruction!");
Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID,
Args[0]) : 0);
break;
case Instruction::Alloca:
if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
if (!isa<PointerType>(InstTy))
throw std::string("Invalid alloca instruction!");
Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID, Args[0]) :0);
break;
case Instruction::Free:
if (!isa<PointerType>(InstTy))
throw std::string("Invalid free instruction!");
Result = new FreeInst(getValue(RI.Type, Args[0]));
break;
case Instruction::GetElementPtr: {
if (Args.size() == 0 || !isa<PointerType>(InstTy))
throw std::string("Invalid getelementptr instruction!");
std::vector<Value*> Idx;
const Type *NextTy = InstTy;
for (unsigned i = 1, e = Args.size(); i != e; ++i) {
const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
if (!TopTy) throw std::string("Invalid getelementptr instruction!");
unsigned ValIdx = Args[i];
unsigned IdxTy = 0;
if (!hasRestrictedGEPTypes) {
// Struct indices are always uints, sequential type indices can be any
// of the 32 or 64-bit integer types. The actual choice of type is
// encoded in the low two bits of the slot number.
if (isa<StructType>(TopTy))
IdxTy = Type::UIntTyID;
else {
switch (ValIdx & 3) {
default:
case 0: IdxTy = Type::UIntTyID; break;
case 1: IdxTy = Type::IntTyID; break;
case 2: IdxTy = Type::ULongTyID; break;
case 3: IdxTy = Type::LongTyID; break;
}
ValIdx >>= 2;
}
} else {
IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
}
Idx.push_back(getValue(IdxTy, ValIdx));
// Convert ubyte struct indices into uint struct indices.
if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
}
Result = new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
break;
}
case 62: // volatile load
case Instruction::Load:
if (Args.size() != 1 || !isa<PointerType>(InstTy))
throw std::string("Invalid load instruction!");
Result = new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
break;
case 63: // volatile store
case Instruction::Store: {
if (!isa<PointerType>(InstTy) || Args.size() != 2)
throw std::string("Invalid store instruction!");
Value *Ptr = getValue(RI.Type, Args[1]);
const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
Result = new StoreInst(getValue(getTypeSlot(ValTy), Args[0]), Ptr,
RI.Opcode == 63);
break;
}
case Instruction::Unwind:
if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
Result = new UnwindInst();
break;
} // end switch(RI.Opcode)
unsigned TypeSlot;
if (Result->getType() == InstTy)
TypeSlot = RI.Type;
else
TypeSlot = getTypeSlot(Result->getType());
insertValue(Result, TypeSlot, Values);
BB->getInstList().push_back(Result);
BCR_TRACE(4, *Result);
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "LedControllerRequest.h"
#include "GeneratedTypes.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
int main(int argc, const char **argv)
{
LedControllerRequestProxy *device = new LedControllerRequestProxy(IfcNames_LedControllerRequestS2H);
printf("Starting LED test\n");
FILE *pipe = popen("ifconfig eth0", "r");
char buf[256];
// read the first line and discard it
fgets(buf, sizeof(buf), pipe);
// read the second line
fgets(buf, sizeof(buf), pipe);
printf("address line: %s", buf);
// done with the pipe, close it
fclose(pipe);
int addr[5];
memset(addr, 0, sizeof(addr));
int status = sscanf(buf, " inet addr:%d.%d.%d.%d", &addr[0], &addr[1], &addr[2], &addr[3]);
printf("eth0 addr %d.%d.%d.%d\n", addr[0], addr[1], addr[2], addr[3]);
sleep(2);
portalExec_start();
#ifdef BSIM
// BSIM does not run very many cycles per second
int blinkinterval = 10;
#else
int blinkinterval = 100000000; // 100MHz cycles
#endif
int sleepinterval = 1; // seconds
for (int i = 0; i < 20; i++) {
printf("led value %x\n", addr[i % 5]);
device->setLeds(addr[i % 5], blinkinterval);
sleep(sleepinterval);
}
printf("Done.\n");
}
<commit_msg>fix compiler warnings<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "LedControllerRequest.h"
#include "GeneratedTypes.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
int main(int argc, const char **argv)
{
LedControllerRequestProxy *device = new LedControllerRequestProxy(IfcNames_LedControllerRequestS2H);
printf("Starting LED test\n");
FILE *pipe = popen("ifconfig eth0", "r");
char buf[256];
// read the first line and discard it
char *line = fgets(buf, sizeof(buf), pipe);
// read the second line
line = fgets(buf, sizeof(buf), pipe);
printf("address line: %s", line);
// done with the pipe, close it
fclose(pipe);
int addr[5];
memset(addr, 0, sizeof(addr));
int status = sscanf(buf, " inet addr:%d.%d.%d.%d", &addr[0], &addr[1], &addr[2], &addr[3]);
printf("eth0 addr %d.%d.%d.%d\n", addr[0], addr[1], addr[2], addr[3]);
sleep(2);
portalExec_start();
#ifdef BSIM
// BSIM does not run very many cycles per second
int blinkinterval = 10;
#else
int blinkinterval = 100000000; // 100MHz cycles
#endif
int sleepinterval = 1; // seconds
for (int i = 0; i < 20; i++) {
printf("led value %x\n", addr[i % 5]);
device->setLeds(addr[i % 5], blinkinterval);
sleep(sleepinterval);
}
printf("Done.\n");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PolarLabelPositionHelper.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:49:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#include "PolarLabelPositionHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "CommonConverters.hxx"
// header for class Vector2D
#ifndef _VECTOR2D_HXX
#include <tools/vector2d.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
PolarLabelPositionHelper::PolarLabelPositionHelper(
PolarPlottingPositionHelper* pPosHelper
, sal_Int32 nDimensionCount
, const uno::Reference< drawing::XShapes >& xLogicTarget
, ShapeFactory* pShapeFactory )
: LabelPositionHelper( pPosHelper, nDimensionCount, xLogicTarget, pShapeFactory )
, m_pPosHelper(pPosHelper)
{
}
PolarLabelPositionHelper::~PolarLabelPositionHelper()
{
}
awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignment(
LabelAlignment& rAlignment, bool bOutsidePosition
, double fStartLogicValueOnAngleAxis, double fEndLogicValueOnAngleAxis
, double fLogicInnerRadius, double fLogicOuterRadius
, double fLogicZ) const
{
double fWidthAngleDegree = m_pPosHelper->getWidthAngleDegree( fStartLogicValueOnAngleAxis, fEndLogicValueOnAngleAxis );
double fStartAngleDegree = m_pPosHelper->transformToAngleDegree( fStartLogicValueOnAngleAxis );
double fAngleDegree = fStartAngleDegree + fWidthAngleDegree/2.0;
double fAnglePi = fAngleDegree*F_PI/180.0;
double fInnerRadius = m_pPosHelper->transformToRadius(fLogicInnerRadius);
double fOuterRadius = m_pPosHelper->transformToRadius(fLogicOuterRadius);
double fRadius = 0.0;
if( bOutsidePosition ) //e.g. for pure pie chart(one ring only) or for angle axis of polyar coordinate system
{
fRadius = fOuterRadius;
if(3!=m_nDimensionCount)
fRadius += 0.1*fOuterRadius;
}
else
fRadius = fInnerRadius + (fOuterRadius-fInnerRadius)/2.0 ;
if(3==m_nDimensionCount)
fAnglePi *= -1.0;
drawing::Position3D aLogicPos(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ+0.5);
awt::Point aRet( this->transformLogicToScreenPosition( aLogicPos ) );
if(3==m_nDimensionCount)
{
//check wether the upper or the downer edge is more distant from the center
//take the farest point to put the label to
drawing::Position3D aLogicPos2(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5);
drawing::Position3D aLogicCenter(0,0,fLogicZ);
awt::Point aP0( this->transformLogicToScreenPosition(
drawing::Position3D(0,0,fLogicZ) ) );
awt::Point aP1(aRet);
awt::Point aP2( this->transformLogicToScreenPosition(
drawing::Position3D(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5) ) );
Vector2D aV0( aP0.X, aP0.Y );
Vector2D aV1( aP1.X, aP1.Y );
Vector2D aV2( aP2.X, aP2.Y );
double fL1 = (aV1-aV0).GetLength();
double fL2 = (aV2-aV0).GetLength();
if(fL2>fL1)
aRet = aP2;
//calculate new angle for alignment
double fDX = aRet.X-aP0.X;
double fDY = aRet.Y-aP0.Y;
fDY*=-1.0;//drawing layer has inverse y values
if( fDX != 0.0 )
{
fAngleDegree = atan(fDY/fDX)*180.0/F_PI;
if(fDX<0.0)
fAngleDegree+=180.0;
}
else
{
if(fDY>0.0)
fAngleDegree = 90.0;
else
fAngleDegree = 270.0;
}
}
//------------------------------
//set LabelAlignment
if( bOutsidePosition )
{
while(fAngleDegree>360.0)
fAngleDegree-=360.0;
while(fAngleDegree<0.0)
fAngleDegree+=360.0;
if(fAngleDegree==0.0)
rAlignment = LABEL_ALIGN_CENTER;
else if(fAngleDegree<=22.5)
rAlignment = LABEL_ALIGN_RIGHT;
else if(fAngleDegree<67.5)
rAlignment = LABEL_ALIGN_RIGHT_TOP;
else if(fAngleDegree<112.5)
rAlignment = LABEL_ALIGN_TOP;
else if(fAngleDegree<=157.5)
rAlignment = LABEL_ALIGN_LEFT_TOP;
else if(fAngleDegree<=202.5)
rAlignment = LABEL_ALIGN_LEFT;
else if(fAngleDegree<247.5)
rAlignment = LABEL_ALIGN_LEFT_BOTTOM;
else if(fAngleDegree<292.5)
rAlignment = LABEL_ALIGN_BOTTOM;
else if(fAngleDegree<337.5)
rAlignment = LABEL_ALIGN_RIGHT_BOTTOM;
else
rAlignment = LABEL_ALIGN_RIGHT;
}
else
{
rAlignment = LABEL_ALIGN_CENTER;
}
return aRet;
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.80); FILE MERGED 2006/09/01 17:19:01 kaib 1.3.80.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PolarLabelPositionHelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 13:37:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "PolarLabelPositionHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "CommonConverters.hxx"
// header for class Vector2D
#ifndef _VECTOR2D_HXX
#include <tools/vector2d.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
PolarLabelPositionHelper::PolarLabelPositionHelper(
PolarPlottingPositionHelper* pPosHelper
, sal_Int32 nDimensionCount
, const uno::Reference< drawing::XShapes >& xLogicTarget
, ShapeFactory* pShapeFactory )
: LabelPositionHelper( pPosHelper, nDimensionCount, xLogicTarget, pShapeFactory )
, m_pPosHelper(pPosHelper)
{
}
PolarLabelPositionHelper::~PolarLabelPositionHelper()
{
}
awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignment(
LabelAlignment& rAlignment, bool bOutsidePosition
, double fStartLogicValueOnAngleAxis, double fEndLogicValueOnAngleAxis
, double fLogicInnerRadius, double fLogicOuterRadius
, double fLogicZ) const
{
double fWidthAngleDegree = m_pPosHelper->getWidthAngleDegree( fStartLogicValueOnAngleAxis, fEndLogicValueOnAngleAxis );
double fStartAngleDegree = m_pPosHelper->transformToAngleDegree( fStartLogicValueOnAngleAxis );
double fAngleDegree = fStartAngleDegree + fWidthAngleDegree/2.0;
double fAnglePi = fAngleDegree*F_PI/180.0;
double fInnerRadius = m_pPosHelper->transformToRadius(fLogicInnerRadius);
double fOuterRadius = m_pPosHelper->transformToRadius(fLogicOuterRadius);
double fRadius = 0.0;
if( bOutsidePosition ) //e.g. for pure pie chart(one ring only) or for angle axis of polyar coordinate system
{
fRadius = fOuterRadius;
if(3!=m_nDimensionCount)
fRadius += 0.1*fOuterRadius;
}
else
fRadius = fInnerRadius + (fOuterRadius-fInnerRadius)/2.0 ;
if(3==m_nDimensionCount)
fAnglePi *= -1.0;
drawing::Position3D aLogicPos(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ+0.5);
awt::Point aRet( this->transformLogicToScreenPosition( aLogicPos ) );
if(3==m_nDimensionCount)
{
//check wether the upper or the downer edge is more distant from the center
//take the farest point to put the label to
drawing::Position3D aLogicPos2(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5);
drawing::Position3D aLogicCenter(0,0,fLogicZ);
awt::Point aP0( this->transformLogicToScreenPosition(
drawing::Position3D(0,0,fLogicZ) ) );
awt::Point aP1(aRet);
awt::Point aP2( this->transformLogicToScreenPosition(
drawing::Position3D(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5) ) );
Vector2D aV0( aP0.X, aP0.Y );
Vector2D aV1( aP1.X, aP1.Y );
Vector2D aV2( aP2.X, aP2.Y );
double fL1 = (aV1-aV0).GetLength();
double fL2 = (aV2-aV0).GetLength();
if(fL2>fL1)
aRet = aP2;
//calculate new angle for alignment
double fDX = aRet.X-aP0.X;
double fDY = aRet.Y-aP0.Y;
fDY*=-1.0;//drawing layer has inverse y values
if( fDX != 0.0 )
{
fAngleDegree = atan(fDY/fDX)*180.0/F_PI;
if(fDX<0.0)
fAngleDegree+=180.0;
}
else
{
if(fDY>0.0)
fAngleDegree = 90.0;
else
fAngleDegree = 270.0;
}
}
//------------------------------
//set LabelAlignment
if( bOutsidePosition )
{
while(fAngleDegree>360.0)
fAngleDegree-=360.0;
while(fAngleDegree<0.0)
fAngleDegree+=360.0;
if(fAngleDegree==0.0)
rAlignment = LABEL_ALIGN_CENTER;
else if(fAngleDegree<=22.5)
rAlignment = LABEL_ALIGN_RIGHT;
else if(fAngleDegree<67.5)
rAlignment = LABEL_ALIGN_RIGHT_TOP;
else if(fAngleDegree<112.5)
rAlignment = LABEL_ALIGN_TOP;
else if(fAngleDegree<=157.5)
rAlignment = LABEL_ALIGN_LEFT_TOP;
else if(fAngleDegree<=202.5)
rAlignment = LABEL_ALIGN_LEFT;
else if(fAngleDegree<247.5)
rAlignment = LABEL_ALIGN_LEFT_BOTTOM;
else if(fAngleDegree<292.5)
rAlignment = LABEL_ALIGN_BOTTOM;
else if(fAngleDegree<337.5)
rAlignment = LABEL_ALIGN_RIGHT_BOTTOM;
else
rAlignment = LABEL_ALIGN_RIGHT;
}
else
{
rAlignment = LABEL_ALIGN_CENTER;
}
return aRet;
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|> |
<commit_before>#include <map>
#include "test.h"
bool integrity_test(int *unsorted, int *sorted, unsigned int len)
{
return false;
}
bool sort_test(int *arr, unsigned int len)
{
for (unsigned int i = 0; i < len - 1; i++)
{
if (arr[i] > arr[i + 1])
return false;
}
return true;
}<commit_msg>Implemented integrity test.<commit_after>#include <unordered_map>
#include "test.h"
bool integrity_test(int *unsorted, int *sorted, unsigned int len)
{
std::unordered_map<unsigned int, int> counts;
for (unsigned int i = 0; i < len; i++)
{
counts[unsorted[i]]++;
counts[sorted[i]]--;
}
for each (auto count in counts)
{
if (count.second != 0)
return false;
}
return true;
}
bool sort_test(int *arr, unsigned int len)
{
for (unsigned int i = 0; i < len - 1; i++)
{
if (arr[i] > arr[i + 1])
return false;
}
return true;
}<|endoftext|> |
<commit_before>/// @brief computes scales for
#include <boost/foreach.hpp>
#include <boost/range/irange.hpp>
#include <cmath>
namespace core { namespace cordic {
// n is number of iterations in CORDIC algorithm
template<size_t n, typename fp>
double lut<n, fp>::compute_circular_scale(size_t n)
{
double scale(1.0);
BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
{
scale *= std::sqrt(1 + std::powl(2.0, -2.0 * i));
}
return scale;
}
template<size_t n, typename fp>
lut<n, fp> lut<n, fp>::build_circular_scales_lut()
{
base_class scales;
BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
{
scales[i] = std::sqrt(1.0 + std::powl(2.0, -2.0 * i));
}
return this_class(scales);
}
}}
<commit_msg>circular_scales.inl: refactoring<commit_after>/// @brief computes scales for CORDIC-rotations in case of circular coordiantes
namespace core { namespace cordic {
template<size_t n, typename fp>
double lut<n, fp>::circular_scale(size_t n)
{
double scale(1.0);
BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
{
scale *= std::sqrt(1.0 + std::powl(2.0, -2.0 * i));
}
return scale;
}
template<size_t n, typename fp>
lut<n, fp> lut<n, fp>::circular_scales()
{
base_class scales;
BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
{
scales[i] = std::sqrt(1.0 + std::powl(2.0, -2.0 * i));
}
return this_class(scales);
}
}}
<|endoftext|> |
<commit_before>#ifndef VFRAME_NO_3D
#include "V3DScene.h"
#include "V3DObject.h"
#include "V3DBatchModelGroup.h"
#include "V3DShader.h"
#include "V3DCamera.h"
#include <cstring>
V3DScene::V3DScene(float x, float y, unsigned int width, unsigned int height, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
renderTex.create(width, height, settings);
Sprite->Position = sf::Vector2f(x, y);
Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}
V3DScene::V3DScene(sf::Vector2f position, sf::Vector2u size, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
renderTex.create(size.x, size.y, settings);
Sprite->Position = position;
Sprite->Size = sf::Vector2f(size);
}
void V3DScene::SetActive(bool value)
{
renderTex.setActive(value);
}
void V3DScene::PushGLStates()
{
renderTex.pushGLStates();
}
void V3DScene::PopGLStates()
{
renderTex.popGLStates();
}
void V3DScene::ResetGLStates()
{
renderTex.resetGLStates();
}
#include "V3DModel.h"
void V3DScene::Destroy()
{
VSUPERCLASS::Destroy();
renderTex.resetGLStates();
renderTex.setActive(false);
if (V3DModel::DefaultTexture)
{
glDeleteTextures(1, &V3DModel::DefaultTexture);
V3DModel::DefaultTexture = 0;
}
}
void V3DScene::Resize(int width, int height)
{
postProcessTex.create(width, height);
renderTex.create(width, height, contextSettings);
Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}
void V3DScene::Update(float dt)
{
VSUPERCLASS::Update(dt);
}
void V3DScene::RenderGroup(VGroup* group)
{
for (int i = 0; i < group->Length(); i++)
{
V3DObject* base = dynamic_cast<V3DObject*>(group->GetGroupItem(i));
if (base != nullptr)
{
base->UpdateShader(Shader.get(), Camera[CurrentCamera].get());
if (Camera[CurrentCamera]->BoxInView(base->Position, base->GetMinimum(), base->GetMaximum()) && base->exists && base->visible)
{
base->Draw(renderTex); //If Renderable 3D Object
}
}
else
{
V3DBatchModelGroup* batchGroup = dynamic_cast<V3DBatchModelGroup*>(group->GetGroupItem(i));
if (batchGroup != nullptr)
{
batchGroup->UpdateShader(Camera[CurrentCamera].get(), Shader.get()); //If RenderBatch Group
batchGroup->Draw(renderTex);
}
else
{
VGroup* childGroup = dynamic_cast<VGroup*>(group->GetGroupItem(i));
if (childGroup != nullptr)
{
RenderGroup(childGroup); //If regular group.
}
else
{
group->GetGroupItem(i)->Draw(renderTex); //If nothing else, just draw it.
}
}
}
}
}
const sf::Texture& V3DScene::GetTexture()
{
sf::Texture::getMaximumSize();
renderTex.setActive(true);
renderTex.clear(BackgroundTint);
glCheck(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
glCheck(glEnable(GL_BLEND));
glCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
glCheck(glEnable(GL_DEPTH_TEST));
glCheck(glEnable(GL_CULL_FACE));
glCheck(glCullFace(GL_BACK));
for (CurrentCamera = 0; CurrentCamera < Camera.size(); CurrentCamera++)
{
sf::IntRect Viewport(
(int)(Camera[CurrentCamera]->Viewport.left * renderTex.getSize().x),
(int)(Camera[CurrentCamera]->Viewport.top * renderTex.getSize().y),
(int)(Camera[CurrentCamera]->Viewport.width * renderTex.getSize().x),
(int)(Camera[CurrentCamera]->Viewport.height * renderTex.getSize().y)
);
glCheck(glViewport(Viewport.left, Viewport.top, Viewport.width, Viewport.height));
Shader->SetCamera(Camera[CurrentCamera].get());
Shader->Update();
Shader->Bind();
RenderGroup(this);
}
renderTex.display();
renderTex.setActive(false);
return renderTex.getTexture();
}
const sf::Texture V3DScene::GetTexture(V3DShader* shader, V3DCamera* camera)
{
std::unique_ptr<V3DShader> uShader(shader);
std::unique_ptr<V3DCamera> uCamera(camera);
if (Shader.get() != shader)
Shader.swap(uShader);
if (Camera[CurrentCamera].get() != camera)
Camera[CurrentCamera].swap(uCamera);
GetTexture();
if (Shader.get() != shader)
Shader.swap(uShader);
if (Camera[CurrentCamera].get() != camera)
Camera[CurrentCamera].swap(uCamera);
uShader.release();
uCamera.release();
return renderTex.getTexture();
}
void V3DScene::Draw(sf::RenderTarget& RenderTarget)
{
if (!visible)
return;
GetTexture();
RenderTarget.resetGLStates();
if (PostEffect != nullptr && VPostEffectBase::isSupported())
{
if (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)
{
postProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);
}
PostEffect->Apply(renderTex.getTexture(), postProcessTex);
postProcessTex.display();
updateTexture(postProcessTex.getTexture());
}
else
{
updateTexture(renderTex.getTexture());
}
Sprite->Draw(RenderTarget);
}
#endif<commit_msg>Replace dynamic_cast with GroupItemAsType<commit_after>#ifndef VFRAME_NO_3D
#include "V3DScene.h"
#include "V3DObject.h"
#include "V3DBatchModelGroup.h"
#include "V3DShader.h"
#include "V3DCamera.h"
#include <cstring>
V3DScene::V3DScene(float x, float y, unsigned int width, unsigned int height, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
renderTex.create(width, height, settings);
Sprite->Position = sf::Vector2f(x, y);
Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}
V3DScene::V3DScene(sf::Vector2f position, sf::Vector2u size, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
renderTex.create(size.x, size.y, settings);
Sprite->Position = position;
Sprite->Size = sf::Vector2f(size);
}
void V3DScene::SetActive(bool value)
{
renderTex.setActive(value);
}
void V3DScene::PushGLStates()
{
renderTex.pushGLStates();
}
void V3DScene::PopGLStates()
{
renderTex.popGLStates();
}
void V3DScene::ResetGLStates()
{
renderTex.resetGLStates();
}
#include "V3DModel.h"
void V3DScene::Destroy()
{
VSUPERCLASS::Destroy();
renderTex.resetGLStates();
renderTex.setActive(false);
if (V3DModel::DefaultTexture)
{
glDeleteTextures(1, &V3DModel::DefaultTexture);
V3DModel::DefaultTexture = 0;
}
}
void V3DScene::Resize(int width, int height)
{
postProcessTex.create(width, height);
renderTex.create(width, height, contextSettings);
Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}
void V3DScene::Update(float dt)
{
VSUPERCLASS::Update(dt);
}
void V3DScene::RenderGroup(VGroup* group)
{
for (int i = 0; i < group->Length(); i++)
{
V3DObject* base = group->GetGroupItemAsType<V3DObject>(i);
if (base != nullptr)
{
base->UpdateShader(Shader.get(), Camera[CurrentCamera].get());
if (Camera[CurrentCamera]->BoxInView(base->Position, base->GetMinimum(), base->GetMaximum()) && base->exists && base->visible)
{
base->Draw(renderTex); //If Renderable 3D Object
}
}
else
{
V3DBatchModelGroup* batchGroup = group->GetGroupItemAsType<V3DBatchModelGroup>(i);
if (batchGroup != nullptr)
{
batchGroup->UpdateShader(Camera[CurrentCamera].get(), Shader.get()); //If RenderBatch Group
batchGroup->Draw(renderTex);
}
else
{
VGroup* childGroup = group->GetGroupItemAsType<VGroup>(i);
if (childGroup != nullptr)
{
RenderGroup(childGroup); //If regular group.
}
else
{
group->GetGroupItem(i)->Draw(renderTex); //If nothing else, just draw it.
}
}
}
}
}
const sf::Texture& V3DScene::GetTexture()
{
sf::Texture::getMaximumSize();
renderTex.setActive(true);
renderTex.clear(BackgroundTint);
glCheck(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
glCheck(glEnable(GL_BLEND));
glCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
glCheck(glEnable(GL_DEPTH_TEST));
glCheck(glEnable(GL_CULL_FACE));
glCheck(glCullFace(GL_BACK));
for (CurrentCamera = 0; CurrentCamera < Camera.size(); CurrentCamera++)
{
sf::IntRect Viewport(
(int)(Camera[CurrentCamera]->Viewport.left * renderTex.getSize().x),
(int)(Camera[CurrentCamera]->Viewport.top * renderTex.getSize().y),
(int)(Camera[CurrentCamera]->Viewport.width * renderTex.getSize().x),
(int)(Camera[CurrentCamera]->Viewport.height * renderTex.getSize().y)
);
glCheck(glViewport(Viewport.left, Viewport.top, Viewport.width, Viewport.height));
Shader->SetCamera(Camera[CurrentCamera].get());
Shader->Update();
Shader->Bind();
RenderGroup(this);
}
renderTex.display();
renderTex.setActive(false);
return renderTex.getTexture();
}
const sf::Texture V3DScene::GetTexture(V3DShader* shader, V3DCamera* camera)
{
std::unique_ptr<V3DShader> uShader(shader);
std::unique_ptr<V3DCamera> uCamera(camera);
if (Shader.get() != shader)
Shader.swap(uShader);
if (Camera[CurrentCamera].get() != camera)
Camera[CurrentCamera].swap(uCamera);
GetTexture();
if (Shader.get() != shader)
Shader.swap(uShader);
if (Camera[CurrentCamera].get() != camera)
Camera[CurrentCamera].swap(uCamera);
uShader.release();
uCamera.release();
return renderTex.getTexture();
}
void V3DScene::Draw(sf::RenderTarget& RenderTarget)
{
if (!visible)
return;
GetTexture();
RenderTarget.resetGLStates();
if (PostEffect != nullptr && VPostEffectBase::isSupported())
{
if (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)
{
postProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);
}
PostEffect->Apply(renderTex.getTexture(), postProcessTex);
postProcessTex.display();
updateTexture(postProcessTex.getTexture());
}
else
{
updateTexture(renderTex.getTexture());
}
Sprite->Draw(RenderTarget);
}
#endif<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "array.h"
#include "class-inl.h"
#include "gc/accounting/card_table-inl.h"
#include "intern_table.h"
#include "object-inl.h"
#include "runtime.h"
#include "sirt_ref.h"
#include "thread.h"
#include "utf-inl.h"
namespace art {
namespace mirror {
const CharArray* String::GetCharArray() const {
return GetFieldObject<const CharArray*>(ValueOffset(), false);
}
CharArray* String::GetCharArray() {
return GetFieldObject<CharArray*>(ValueOffset(), false);
}
void String::ComputeHashCode() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
SetHashCode(ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()));
}
int32_t String::GetUtfLength() const {
return CountUtf8Bytes(GetCharArray()->GetData() + GetOffset(), GetLength());
}
int32_t String::FastIndexOf(int32_t ch, int32_t start) const {
int32_t count = GetLength();
if (start < 0) {
start = 0;
} else if (start > count) {
start = count;
}
const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
const uint16_t* p = chars + start;
const uint16_t* end = chars + count;
while (p < end) {
if (*p++ == ch) {
return (p - 1) - chars;
}
}
return -1;
}
void String::SetArray(CharArray* new_array) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
DCHECK(new_array != NULL);
SetFieldObject(OFFSET_OF_OBJECT_MEMBER(String, array_), new_array, false);
}
// TODO: get global references for these
Class* String::java_lang_String_ = NULL;
void String::SetClass(Class* java_lang_String) {
CHECK(java_lang_String_ == NULL);
CHECK(java_lang_String != NULL);
java_lang_String_ = java_lang_String;
}
void String::ResetClass() {
CHECK(java_lang_String_ != NULL);
java_lang_String_ = NULL;
}
String* String::Intern() {
return Runtime::Current()->GetInternTable()->InternWeak(this);
}
int32_t String::GetHashCode() {
int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
if (result == 0) {
ComputeHashCode();
}
result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
<< ToModifiedUtf8() << " " << result;
return result;
}
int32_t String::GetLength() const {
int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
return result;
}
uint16_t String::CharAt(int32_t index) const {
// TODO: do we need this? Equals is the only caller, and could
// bounds check itself.
DCHECK_GE(count_, 0); // ensures the unsigned comparison is safe.
if (UNLIKELY(static_cast<uint32_t>(index) >= static_cast<uint32_t>(count_))) {
Thread* self = Thread::Current();
ThrowLocation throw_location = self->GetCurrentLocationForThrow();
self->ThrowNewExceptionF(throw_location, "Ljava/lang/StringIndexOutOfBoundsException;",
"length=%i; index=%i", count_, index);
return 0;
}
return GetCharArray()->Get(index + GetOffset());
}
String* String::AllocFromUtf16(Thread* self,
int32_t utf16_length,
const uint16_t* utf16_data_in,
int32_t hash_code) {
CHECK(utf16_data_in != NULL || utf16_length == 0);
String* string = Alloc(self, utf16_length);
if (UNLIKELY(string == nullptr)) {
return nullptr;
}
// TODO: use 16-bit wide memset variant
CharArray* array = const_cast<CharArray*>(string->GetCharArray());
if (array == NULL) {
return NULL;
}
for (int i = 0; i < utf16_length; i++) {
array->Set(i, utf16_data_in[i]);
}
if (hash_code != 0) {
string->SetHashCode(hash_code);
} else {
string->ComputeHashCode();
}
return string;
}
String* String::AllocFromModifiedUtf8(Thread* self, const char* utf) {
if (UNLIKELY(utf == nullptr)) {
return nullptr;
}
size_t char_count = CountModifiedUtf8Chars(utf);
return AllocFromModifiedUtf8(self, char_count, utf);
}
String* String::AllocFromModifiedUtf8(Thread* self, int32_t utf16_length,
const char* utf8_data_in) {
String* string = Alloc(self, utf16_length);
if (UNLIKELY(string == nullptr)) {
return nullptr;
}
uint16_t* utf16_data_out =
const_cast<uint16_t*>(string->GetCharArray()->GetData());
ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
string->ComputeHashCode();
return string;
}
String* String::Alloc(Thread* self, int32_t utf16_length) {
SirtRef<CharArray> array(self, CharArray::Alloc(self, utf16_length));
if (UNLIKELY(array.get() == nullptr)) {
return nullptr;
}
return Alloc(self, array);
}
String* String::Alloc(Thread* self, const SirtRef<CharArray>& array) {
// Hold reference in case AllocObject causes GC.
String* string = down_cast<String*>(GetJavaLangString()->AllocObject(self));
if (LIKELY(string != nullptr)) {
string->SetArray(array.get());
string->SetCount(array->GetLength());
}
return string;
}
bool String::Equals(const String* that) const {
if (this == that) {
// Quick reference equality test
return true;
} else if (that == NULL) {
// Null isn't an instanceof anything
return false;
} else if (this->GetLength() != that->GetLength()) {
// Quick length inequality test
return false;
} else {
// Note: don't short circuit on hash code as we're presumably here as the
// hash code was already equal
for (int32_t i = 0; i < that->GetLength(); ++i) {
if (this->CharAt(i) != that->CharAt(i)) {
return false;
}
}
return true;
}
}
bool String::Equals(const uint16_t* that_chars, int32_t that_offset, int32_t that_length) const {
if (this->GetLength() != that_length) {
return false;
} else {
for (int32_t i = 0; i < that_length; ++i) {
if (this->CharAt(i) != that_chars[that_offset + i]) {
return false;
}
}
return true;
}
}
bool String::Equals(const char* modified_utf8) const {
for (int32_t i = 0; i < GetLength(); ++i) {
uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
if (ch == '\0' || ch != CharAt(i)) {
return false;
}
}
return *modified_utf8 == '\0';
}
bool String::Equals(const StringPiece& modified_utf8) const {
const char* p = modified_utf8.data();
for (int32_t i = 0; i < GetLength(); ++i) {
uint16_t ch = GetUtf16FromUtf8(&p);
if (ch != CharAt(i)) {
return false;
}
}
return true;
}
// Create a modified UTF-8 encoded std::string from a java/lang/String object.
std::string String::ToModifiedUtf8() const {
const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
size_t byte_count = GetUtfLength();
std::string result(byte_count, static_cast<char>(0));
ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
return result;
}
#ifdef HAVE__MEMCMP16
// "count" is in 16-bit units.
extern "C" uint32_t __memcmp16(const uint16_t* s0, const uint16_t* s1, size_t count);
#define MemCmp16 __memcmp16
#else
static uint32_t MemCmp16(const uint16_t* s0, const uint16_t* s1, size_t count) {
for (size_t i = 0; i < count; i++) {
if (s0[i] != s1[i]) {
return static_cast<int32_t>(s0[i]) - static_cast<int32_t>(s1[i]);
}
}
return 0;
}
#endif
int32_t String::CompareTo(String* rhs) const {
// Quick test for comparison of a string with itself.
const String* lhs = this;
if (lhs == rhs) {
return 0;
}
// TODO: is this still true?
// The annoying part here is that 0x00e9 - 0xffff != 0x00ea,
// because the interpreter converts the characters to 32-bit integers
// *without* sign extension before it subtracts them (which makes some
// sense since "char" is unsigned). So what we get is the result of
// 0x000000e9 - 0x0000ffff, which is 0xffff00ea.
int lhsCount = lhs->GetLength();
int rhsCount = rhs->GetLength();
int countDiff = lhsCount - rhsCount;
int minCount = (countDiff < 0) ? lhsCount : rhsCount;
const uint16_t* lhsChars = lhs->GetCharArray()->GetData() + lhs->GetOffset();
const uint16_t* rhsChars = rhs->GetCharArray()->GetData() + rhs->GetOffset();
int otherRes = MemCmp16(lhsChars, rhsChars, minCount);
if (otherRes != 0) {
return otherRes;
}
return countDiff;
}
void String::VisitRoots(RootVisitor* visitor, void* arg) {
if (java_lang_String_ != nullptr) {
java_lang_String_ = down_cast<Class*>(visitor(java_lang_String_, arg));
}
}
} // namespace mirror
} // namespace art
<commit_msg>am d7b5f474: am 5a2ced51: Merge "Use memcpy instead of Array::Set in mirror::String::AllocFromUtf16."<commit_after>/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "array.h"
#include "class-inl.h"
#include "gc/accounting/card_table-inl.h"
#include "intern_table.h"
#include "object-inl.h"
#include "runtime.h"
#include "sirt_ref.h"
#include "thread.h"
#include "utf-inl.h"
namespace art {
namespace mirror {
const CharArray* String::GetCharArray() const {
return GetFieldObject<const CharArray*>(ValueOffset(), false);
}
CharArray* String::GetCharArray() {
return GetFieldObject<CharArray*>(ValueOffset(), false);
}
void String::ComputeHashCode() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
SetHashCode(ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()));
}
int32_t String::GetUtfLength() const {
return CountUtf8Bytes(GetCharArray()->GetData() + GetOffset(), GetLength());
}
int32_t String::FastIndexOf(int32_t ch, int32_t start) const {
int32_t count = GetLength();
if (start < 0) {
start = 0;
} else if (start > count) {
start = count;
}
const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
const uint16_t* p = chars + start;
const uint16_t* end = chars + count;
while (p < end) {
if (*p++ == ch) {
return (p - 1) - chars;
}
}
return -1;
}
void String::SetArray(CharArray* new_array) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
DCHECK(new_array != NULL);
SetFieldObject(OFFSET_OF_OBJECT_MEMBER(String, array_), new_array, false);
}
// TODO: get global references for these
Class* String::java_lang_String_ = NULL;
void String::SetClass(Class* java_lang_String) {
CHECK(java_lang_String_ == NULL);
CHECK(java_lang_String != NULL);
java_lang_String_ = java_lang_String;
}
void String::ResetClass() {
CHECK(java_lang_String_ != NULL);
java_lang_String_ = NULL;
}
String* String::Intern() {
return Runtime::Current()->GetInternTable()->InternWeak(this);
}
int32_t String::GetHashCode() {
int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
if (result == 0) {
ComputeHashCode();
}
result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
<< ToModifiedUtf8() << " " << result;
return result;
}
int32_t String::GetLength() const {
int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
return result;
}
uint16_t String::CharAt(int32_t index) const {
// TODO: do we need this? Equals is the only caller, and could
// bounds check itself.
DCHECK_GE(count_, 0); // ensures the unsigned comparison is safe.
if (UNLIKELY(static_cast<uint32_t>(index) >= static_cast<uint32_t>(count_))) {
Thread* self = Thread::Current();
ThrowLocation throw_location = self->GetCurrentLocationForThrow();
self->ThrowNewExceptionF(throw_location, "Ljava/lang/StringIndexOutOfBoundsException;",
"length=%i; index=%i", count_, index);
return 0;
}
return GetCharArray()->Get(index + GetOffset());
}
String* String::AllocFromUtf16(Thread* self,
int32_t utf16_length,
const uint16_t* utf16_data_in,
int32_t hash_code) {
CHECK(utf16_data_in != nullptr || utf16_length == 0);
String* string = Alloc(self, utf16_length);
if (UNLIKELY(string == nullptr)) {
return nullptr;
}
CharArray* array = const_cast<CharArray*>(string->GetCharArray());
if (UNLIKELY(array == nullptr)) {
return nullptr;
}
memcpy(array->GetData(), utf16_data_in, utf16_length * sizeof(uint16_t));
if (hash_code != 0) {
DCHECK_EQ(hash_code, ComputeUtf16Hash(utf16_data_in, utf16_length));
string->SetHashCode(hash_code);
} else {
string->ComputeHashCode();
}
return string;
}
String* String::AllocFromModifiedUtf8(Thread* self, const char* utf) {
if (UNLIKELY(utf == nullptr)) {
return nullptr;
}
size_t char_count = CountModifiedUtf8Chars(utf);
return AllocFromModifiedUtf8(self, char_count, utf);
}
String* String::AllocFromModifiedUtf8(Thread* self, int32_t utf16_length,
const char* utf8_data_in) {
String* string = Alloc(self, utf16_length);
if (UNLIKELY(string == nullptr)) {
return nullptr;
}
uint16_t* utf16_data_out =
const_cast<uint16_t*>(string->GetCharArray()->GetData());
ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
string->ComputeHashCode();
return string;
}
String* String::Alloc(Thread* self, int32_t utf16_length) {
SirtRef<CharArray> array(self, CharArray::Alloc(self, utf16_length));
if (UNLIKELY(array.get() == nullptr)) {
return nullptr;
}
return Alloc(self, array);
}
String* String::Alloc(Thread* self, const SirtRef<CharArray>& array) {
// Hold reference in case AllocObject causes GC.
String* string = down_cast<String*>(GetJavaLangString()->AllocObject(self));
if (LIKELY(string != nullptr)) {
string->SetArray(array.get());
string->SetCount(array->GetLength());
}
return string;
}
bool String::Equals(const String* that) const {
if (this == that) {
// Quick reference equality test
return true;
} else if (that == NULL) {
// Null isn't an instanceof anything
return false;
} else if (this->GetLength() != that->GetLength()) {
// Quick length inequality test
return false;
} else {
// Note: don't short circuit on hash code as we're presumably here as the
// hash code was already equal
for (int32_t i = 0; i < that->GetLength(); ++i) {
if (this->CharAt(i) != that->CharAt(i)) {
return false;
}
}
return true;
}
}
bool String::Equals(const uint16_t* that_chars, int32_t that_offset, int32_t that_length) const {
if (this->GetLength() != that_length) {
return false;
} else {
for (int32_t i = 0; i < that_length; ++i) {
if (this->CharAt(i) != that_chars[that_offset + i]) {
return false;
}
}
return true;
}
}
bool String::Equals(const char* modified_utf8) const {
for (int32_t i = 0; i < GetLength(); ++i) {
uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
if (ch == '\0' || ch != CharAt(i)) {
return false;
}
}
return *modified_utf8 == '\0';
}
bool String::Equals(const StringPiece& modified_utf8) const {
const char* p = modified_utf8.data();
for (int32_t i = 0; i < GetLength(); ++i) {
uint16_t ch = GetUtf16FromUtf8(&p);
if (ch != CharAt(i)) {
return false;
}
}
return true;
}
// Create a modified UTF-8 encoded std::string from a java/lang/String object.
std::string String::ToModifiedUtf8() const {
const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
size_t byte_count = GetUtfLength();
std::string result(byte_count, static_cast<char>(0));
ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
return result;
}
#ifdef HAVE__MEMCMP16
// "count" is in 16-bit units.
extern "C" uint32_t __memcmp16(const uint16_t* s0, const uint16_t* s1, size_t count);
#define MemCmp16 __memcmp16
#else
static uint32_t MemCmp16(const uint16_t* s0, const uint16_t* s1, size_t count) {
for (size_t i = 0; i < count; i++) {
if (s0[i] != s1[i]) {
return static_cast<int32_t>(s0[i]) - static_cast<int32_t>(s1[i]);
}
}
return 0;
}
#endif
int32_t String::CompareTo(String* rhs) const {
// Quick test for comparison of a string with itself.
const String* lhs = this;
if (lhs == rhs) {
return 0;
}
// TODO: is this still true?
// The annoying part here is that 0x00e9 - 0xffff != 0x00ea,
// because the interpreter converts the characters to 32-bit integers
// *without* sign extension before it subtracts them (which makes some
// sense since "char" is unsigned). So what we get is the result of
// 0x000000e9 - 0x0000ffff, which is 0xffff00ea.
int lhsCount = lhs->GetLength();
int rhsCount = rhs->GetLength();
int countDiff = lhsCount - rhsCount;
int minCount = (countDiff < 0) ? lhsCount : rhsCount;
const uint16_t* lhsChars = lhs->GetCharArray()->GetData() + lhs->GetOffset();
const uint16_t* rhsChars = rhs->GetCharArray()->GetData() + rhs->GetOffset();
int otherRes = MemCmp16(lhsChars, rhsChars, minCount);
if (otherRes != 0) {
return otherRes;
}
return countDiff;
}
void String::VisitRoots(RootVisitor* visitor, void* arg) {
if (java_lang_String_ != nullptr) {
java_lang_String_ = down_cast<Class*>(visitor(java_lang_String_, arg));
}
}
} // namespace mirror
} // namespace art
<|endoftext|> |
<commit_before>/// This source file contains tests, that are planned to be used with thread sanitizer or Valgrind.
<commit_msg>[Functional Testing] Multithreaded usage.<commit_after>///
/// This source file contains tests, that are planned to be used with thread sanitizer or Valgrind.
///
#include <blackhole/logger.hpp>
#include <blackhole/macro.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/sink/stream.hpp>
#include "../../global.hpp"
using namespace blackhole;
namespace {
static inline void run(logger_base_t& log, int) {
for (int i = 0; i < 10000; ++i) {
if (auto record = log.open_record()) {
aux::logger::make_pusher(log, record, "le message");
}
}
}
} // namespace
TEST(SanitizeThread, Logger) {
using aux::util::make_unique;
typedef formatter::string_t formatter_type;
typedef sink::stream_t sink_type;
typedef frontend_t<formatter_type, sink_type> frontend_type;
typedef logger_base_t logger_type;
std::ostringstream stream;
auto formatter = make_unique<formatter_type>("%(message)s %(...:[:])s");
auto sink = make_unique<sink_type>(stream);
auto frontend = make_unique<frontend_type>(std::move(formatter), std::move(sink));
logger_type log;
log.add_frontend(std::move(frontend));
std::vector<std::thread> threads;
for (int i = 0; i < 8; ++i) {
threads.emplace_back(std::bind(&run, std::ref(log), i));
}
for (auto it = threads.begin(); it != threads.end(); ++it) {
if (it->joinable()) {
it->join();
}
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2011, John Haddon. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/ParameterisedInterface.h"
#include "Gaffer/ParameterisedHolder.h"
#include "Gaffer/CompoundParameterHandler.h"
#include "Gaffer/TypedPlug.h"
#include "Gaffer/NumericPlug.h"
using namespace Gaffer;
template<typename BaseType>
const IECore::RunTimeTyped::TypeDescription<ParameterisedHolder<BaseType> > ParameterisedHolder<BaseType>::g_typeDescription;
template<typename BaseType>
ParameterisedHolder<BaseType>::ParameterisedHolder( const std::string &name )
: BaseType( name ), m_parameterised( 0 ), m_parameterHandler( 0 )
{
BaseType::addChild( new StringPlug( "__className" ) );
BaseType::addChild( new IntPlug( "__classVersion", Plug::In, -1 ) );
BaseType::addChild( new StringPlug( "__searchPathEnvVar" ) );
}
template<typename BaseType>
void ParameterisedHolder<BaseType>::setParameterised( IECore::RunTimeTypedPtr parameterised )
{
IECore::ParameterisedInterface *interface = dynamic_cast<IECore::ParameterisedInterface *>( parameterised.get() );
if( !interface )
{
throw IECore::Exception( "Not a ParameterisedInterface derived type." );
}
m_parameterised = parameterised;
m_parameterHandler = new CompoundParameterHandler( interface->parameters(), this );
m_parameterHandler->setPlugValue();
}
template<typename BaseType>
void ParameterisedHolder<BaseType>::setParameterised( const std::string &className, int classVersion, const std::string &searchPathEnvVar )
{
/// \todo How do we load a class without introducing a python dependency into the main library?
/// Make this function virtual and only implement it in the wrapper class?
/// Give IECore::ClassLoader a C++ base class and implement it in python somehow?
assert( 0 );
}
template<typename BaseType>
IECore::RunTimeTypedPtr ParameterisedHolder<BaseType>::getParameterised( std::string *className, int *classVersion, std::string *searchPathEnvVar ) const
{
Node *node = const_cast<Node *>( static_cast<const Node *>( this ) );
if( className )
{
*className = node->getChild<StringPlug>( "__className" )->getValue();
}
if( classVersion )
{
*classVersion = node->getChild<IntPlug>( "__classVersion" )->getValue();
}
if( searchPathEnvVar )
{
*searchPathEnvVar = node->getChild<StringPlug>( "__searchPathEnvVar" )->getValue();
}
return m_parameterised;
}
template<typename BaseType>
IECore::ParameterisedInterface *ParameterisedHolder<BaseType>::parameterisedInterface( std::string *className, int *classVersion, std::string *searchPathEnvVar )
{
return dynamic_cast<IECore::ParameterisedInterface *>( getParameterised( className, classVersion, searchPathEnvVar ).get() );
}
template<typename BaseType>
CompoundParameterHandlerPtr ParameterisedHolder<BaseType>::parameterHandler()
{
return m_parameterHandler;
}
template<typename BaseType>
ConstCompoundParameterHandlerPtr ParameterisedHolder<BaseType>::parameterHandler() const
{
return m_parameterHandler;
}
template<typename BaseType>
void ParameterisedHolder<BaseType>::setParameterisedValues()
{
if( m_parameterHandler )
{
m_parameterHandler->setParameterValue();
}
}
//////////////////////////////////////////////////////////////////////////
// ParameterModificationContext
//////////////////////////////////////////////////////////////////////////
template<typename BaseType>
ParameterisedHolder<BaseType>::ParameterModificationContext::ParameterModificationContext( Ptr parameterisedHolder )
: m_parameterisedHolder( parameterisedHolder )
{
}
template<typename BaseType>
ParameterisedHolder<BaseType>::ParameterModificationContext::~ParameterModificationContext()
{
if( IECore::ParameterisedInterface *interface = m_parameterisedHolder->parameterisedInterface() )
{
m_parameterisedHolder->m_parameterHandler = new CompoundParameterHandler( interface->parameters(), m_parameterisedHolder );
m_parameterisedHolder->m_parameterHandler->setPlugValue();
}
}
// specialisation
namespace Gaffer
{
IECORE_RUNTIMETYPED_DEFINETEMPLATESPECIALISATION( ParameterisedHolderNode, ParameterisedHolderNodeTypeId )
}
// explicit instantiation
template class ParameterisedHolder<Node>;
<commit_msg>Adding changing which should have been with earlier commit.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2011, John Haddon. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/ParameterisedInterface.h"
#include "Gaffer/ParameterisedHolder.h"
#include "Gaffer/CompoundParameterHandler.h"
#include "Gaffer/TypedPlug.h"
#include "Gaffer/NumericPlug.h"
using namespace Gaffer;
template<typename BaseType>
const IECore::RunTimeTyped::TypeDescription<ParameterisedHolder<BaseType> > ParameterisedHolder<BaseType>::g_typeDescription;
template<typename BaseType>
ParameterisedHolder<BaseType>::ParameterisedHolder( const std::string &name )
: BaseType( name ), m_parameterised( 0 ), m_parameterHandler( 0 )
{
BaseType::addChild( new StringPlug( "__className" ) );
BaseType::addChild( new IntPlug( "__classVersion", Plug::In, -1 ) );
BaseType::addChild( new StringPlug( "__searchPathEnvVar" ) );
}
template<typename BaseType>
void ParameterisedHolder<BaseType>::setParameterised( IECore::RunTimeTypedPtr parameterised )
{
IECore::ParameterisedInterface *interface = dynamic_cast<IECore::ParameterisedInterface *>( parameterised.get() );
if( !interface )
{
throw IECore::Exception( "Not a ParameterisedInterface derived type." );
}
m_parameterised = parameterised;
m_parameterHandler = new CompoundParameterHandler( interface->parameters() );
m_parameterHandler->setupPlug( this );
m_parameterHandler->setPlugValue();
}
template<typename BaseType>
void ParameterisedHolder<BaseType>::setParameterised( const std::string &className, int classVersion, const std::string &searchPathEnvVar )
{
/// \todo How do we load a class without introducing a python dependency into the main library?
/// Make this function virtual and only implement it in the wrapper class?
/// Give IECore::ClassLoader a C++ base class and implement it in python somehow?
assert( 0 );
}
template<typename BaseType>
IECore::RunTimeTypedPtr ParameterisedHolder<BaseType>::getParameterised( std::string *className, int *classVersion, std::string *searchPathEnvVar ) const
{
Node *node = const_cast<Node *>( static_cast<const Node *>( this ) );
if( className )
{
*className = node->getChild<StringPlug>( "__className" )->getValue();
}
if( classVersion )
{
*classVersion = node->getChild<IntPlug>( "__classVersion" )->getValue();
}
if( searchPathEnvVar )
{
*searchPathEnvVar = node->getChild<StringPlug>( "__searchPathEnvVar" )->getValue();
}
return m_parameterised;
}
template<typename BaseType>
IECore::ParameterisedInterface *ParameterisedHolder<BaseType>::parameterisedInterface( std::string *className, int *classVersion, std::string *searchPathEnvVar )
{
return dynamic_cast<IECore::ParameterisedInterface *>( getParameterised( className, classVersion, searchPathEnvVar ).get() );
}
template<typename BaseType>
CompoundParameterHandlerPtr ParameterisedHolder<BaseType>::parameterHandler()
{
return m_parameterHandler;
}
template<typename BaseType>
ConstCompoundParameterHandlerPtr ParameterisedHolder<BaseType>::parameterHandler() const
{
return m_parameterHandler;
}
template<typename BaseType>
void ParameterisedHolder<BaseType>::setParameterisedValues()
{
if( m_parameterHandler )
{
m_parameterHandler->setParameterValue();
}
}
//////////////////////////////////////////////////////////////////////////
// ParameterModificationContext
//////////////////////////////////////////////////////////////////////////
template<typename BaseType>
ParameterisedHolder<BaseType>::ParameterModificationContext::ParameterModificationContext( Ptr parameterisedHolder )
: m_parameterisedHolder( parameterisedHolder )
{
}
template<typename BaseType>
ParameterisedHolder<BaseType>::ParameterModificationContext::~ParameterModificationContext()
{
if( m_parameterisedHolder->m_parameterHandler )
{
m_parameterisedHolder->m_parameterHandler->setupPlug( m_parameterisedHolder );
m_parameterisedHolder->m_parameterHandler->setPlugValue();
}
}
// specialisation
namespace Gaffer
{
IECORE_RUNTIMETYPED_DEFINETEMPLATESPECIALISATION( ParameterisedHolderNode, ParameterisedHolderNodeTypeId )
}
// explicit instantiation
template class ParameterisedHolder<Node>;
<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include <sstream>
using namespace std;
asm(".LC3:");
asm(" .long 1065353216");
asm(".LC4:");
asm(" .long 3212836864");
float evaluateClang(float a, float b) {
asm("subss xmm0, xmm1");
asm("movss xmm1, dword ptr [rip + .LC3]");
asm("addss xmm1, xmm0");
asm("mulss xmm1, xmm0");
asm("addss xmm0, dword ptr [rip + .LC4]");
asm("mulss xmm0, xmm1");
}
float evaluateGCC(float a, float b) {
asm("subss xmm0, xmm1");
asm("movss xmm2, dword ptr [rip + .LC3]");
asm("movaps xmm1, xmm0");
asm("addss xmm1, xmm2");
asm("mulss xmm1, xmm0");
asm("subss xmm0, xmm2");
asm("mulss xmm0, xmm1");
}
int main() {
auto start = std::chrono::steady_clock::now();
for (int j = 0; j < 1000; j++) {
for (int i = 0; i < 65536; i++) {
evaluateClang(4.0f, 9.0f);
}
}
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double, std::nano> ns = now - start;
cout << ns.count() << " ns" << '\n';
start = std::chrono::steady_clock::now();
for (int j = 0; j < 1000; j++) {
for (int i = 0; i < 65536; i++) {
evaluateGCC(4.0f, 9.0f);
}
}
now = std::chrono::steady_clock::now();
ns = now - start;
cout << ns.count() << " ns" << '\n';
}
<commit_msg>Should use a single asm statement per function<commit_after>#include <chrono>
#include <iostream>
#include <sstream>
using namespace std;
asm(".LC3:\n"
" .long 1065353216");
asm(".LC4:\n"
" .long 3212836864");
float evaluateClang(float a, float b) {
asm("subss xmm0, xmm1\n"
"movss xmm1, dword ptr [rip + .LC3]\n"
"addss xmm1, xmm0\n"
"mulss xmm1, xmm0\n"
"addss xmm0, dword ptr [rip + .LC4]\n"
"mulss xmm0, xmm1");
}
float evaluateGCC(float a, float b) {
asm("subss xmm0, xmm1\n"
"movss xmm2, dword ptr [rip + .LC3]\n"
"movaps xmm1, xmm0\n"
"addss xmm1, xmm2\n"
"mulss xmm1, xmm0\n"
"subss xmm0, xmm2\n"
"mulss xmm0, xmm1");
}
int main() {
auto start = std::chrono::steady_clock::now();
for (int j = 0; j < 1000; j++) {
for (int i = 0; i < 65536; i++) {
evaluateClang(4.0f, 9.0f);
}
}
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double, std::nano> ns = now - start;
cout << ns.count() << " ns" << '\n';
start = std::chrono::steady_clock::now();
for (int j = 0; j < 1000; j++) {
for (int i = 0; i < 65536; i++) {
evaluateGCC(4.0f, 9.0f);
}
}
now = std::chrono::steady_clock::now();
ns = now - start;
cout << ns.count() << " ns" << '\n';
}
<|endoftext|> |
<commit_before>/* Copyright 2016 Stanford University, NVIDIA 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.
*/
// Realm logging infrastructure
#include "logging.h"
#ifdef SHARED_LOWLEVEL
#define gasnet_mynode() 0
#define gasnet_nodes() 1
#else
#include "activemsg.h"
#endif
#include "cmdline.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <set>
#include <map>
namespace Realm {
// abstract class for an output stream
class LoggerOutputStream {
public:
LoggerOutputStream(void) {}
virtual ~LoggerOutputStream(void) {}
virtual void write(const char *buffer, size_t len) = 0;
virtual void flush(void) = 0;
};
class LoggerFileStream : public LoggerOutputStream {
public:
LoggerFileStream(FILE *_f, bool _close_file)
: f(_f), close_file(_close_file)
{}
virtual ~LoggerFileStream(void)
{
if(close_file)
fclose(f);
}
virtual void write(const char *buffer, size_t len)
{
#ifndef NDEBUG
size_t amt =
#endif
fwrite(buffer, 1, len, f);
assert(amt == len);
}
virtual void flush(void)
{
fflush(f);
}
protected:
FILE *f;
bool close_file;
};
// use a pthread mutex to prevent simultaneous writes to a stream
template <typename T>
class LoggerStreamSerialized : public LoggerOutputStream {
public:
LoggerStreamSerialized(T *_stream, bool _delete_inner)
: stream(_stream), delete_inner(_delete_inner)
{
#ifndef NDEBUG
int ret =
#endif
pthread_mutex_init(&mutex, 0);
assert(ret == 0);
}
virtual ~LoggerStreamSerialized(void)
{
#ifndef NDEBUG
int ret =
#endif
pthread_mutex_destroy(&mutex);
assert(ret == 0);
if(delete_inner)
delete stream;
}
virtual void write(const char *buffer, size_t len)
{
#ifndef NDEBUG
int ret;
ret =
#endif
pthread_mutex_lock(&mutex);
assert(ret == 0);
stream->write(buffer, len);
#ifndef NDEBUG
ret =
#endif
pthread_mutex_unlock(&mutex);
assert(ret == 0);
}
virtual void flush(void)
{
#ifndef NDEBUG
int ret;
ret =
#endif
pthread_mutex_lock(&mutex);
assert(ret == 0);
stream->flush();
#ifndef NDEBUG
ret =
#endif
pthread_mutex_unlock(&mutex);
assert(ret == 0);
}
protected:
LoggerOutputStream *stream;
bool delete_inner;
pthread_mutex_t mutex;
};
class LoggerConfig {
protected:
LoggerConfig(void);
~LoggerConfig(void);
public:
static LoggerConfig *get_config(void);
static void flush_all_streams(void);
void read_command_line(std::vector<std::string>& cmdline);
// either configures a logger right away or remembers it to config once
// we know the desired settings
void configure(Logger *logger);
protected:
bool parse_level_argument(const std::string& s);
bool cmdline_read;
Logger::LoggingLevel default_level;
std::map<std::string, Logger::LoggingLevel> category_levels;
std::string cats_enabled;
std::set<Logger *> pending_configs;
LoggerOutputStream *stream;
};
LoggerConfig::LoggerConfig(void)
: cmdline_read(false), default_level(Logger::LEVEL_PRINT), stream(0)
{}
LoggerConfig::~LoggerConfig(void)
{
delete stream;
}
/*static*/ LoggerConfig *LoggerConfig::get_config(void)
{
static LoggerConfig cfg;
return &cfg;
}
/*static*/ void LoggerConfig::flush_all_streams(void)
{
LoggerConfig *cfg = get_config();
if(cfg->stream)
cfg->stream->flush();
}
bool LoggerConfig::parse_level_argument(const std::string& s)
{
const char *p1 = s.c_str();
while(true) {
// skip commas
while(*p1 == ',') p1++;
if(!*p1) break;
// numbers may be preceeded by name= to specify a per-category level
std::string catname;
if(!isdigit(*p1)) {
const char *p2 = p1;
while(*p2 != '=') {
if(!*p2) {
fprintf(stderr, "ERROR: category name in -level must be followed by =\n");
return false;
}
p2++;
}
catname.assign(p1, p2 - p1);
p1 = p2 + 1;
}
// levels are small integers
if(isdigit(*p1)) {
char *p2;
errno = 0; // no leftover errors from elsewhere
long v = strtol(p1, &p2, 10);
if((errno == 0) && ((*p2 == 0) || (*p2) == ',') &&
(v >= 0) && (v <= Logger::LEVEL_NONE)) {
if(catname.empty())
default_level = (Logger::LoggingLevel)v;
else
category_levels[catname] = (Logger::LoggingLevel)v;
p1 = p2;
continue;
}
}
fprintf(stderr, "ERROR: logger level malformed or out of range: '%s'\n", p1);
return false;
}
return true;
}
void LoggerConfig::read_command_line(std::vector<std::string>& cmdline)
{
std::string logname;
bool ok = CommandLineParser()
.add_option_string("-cat", cats_enabled)
.add_option_string("-logfile", logname)
.add_option_method("-level", this, &LoggerConfig::parse_level_argument)
.parse_command_line(cmdline);
if(!ok) {
fprintf(stderr, "couldn't parse logger config options\n");
exit(1);
}
// lots of choices for log output
if(logname.empty() || (logname == "stdout")) {
stream = new LoggerStreamSerialized<LoggerFileStream>(new LoggerFileStream(stdout, false),
true);
} else if(logname == "stderr") {
stream = new LoggerStreamSerialized<LoggerFileStream>(new LoggerFileStream(stderr, false),
true);
} else {
// we're going to open a file, but key off a + for appending and
// look for a % for node number insertion
bool append = false;
size_t start = 0;
if(logname[0] == '+') {
append = true;
start++;
}
FILE *f = 0;
size_t pct = logname.find_first_of('%', start);
if(pct == std::string::npos) {
// no node number - everybody uses the same file
if(gasnet_nodes() > 1) {
if(!append) {
if(gasnet_mynode() == 1)
fprintf(stderr, "WARNING: all ranks are logging to the same output file - appending is forced and output may be jumbled\n");
append = true;
}
}
const char *fn = logname.c_str() + start;
f = fopen(fn, append ? "a" : "w");
if(!f) {
fprintf(stderr, "could not open log file '%s': %s\n", fn, strerror(errno));
exit(1);
}
} else {
// replace % with node number
char filename[256];
sprintf(filename, "%.*s%d%s",
(int)(pct - start), logname.c_str() + start, gasnet_mynode(), logname.c_str() + pct + 1);
f = fopen(filename, append ? "a" : "w");
if(!f) {
fprintf(stderr, "could not open log file '%s': %s\n", filename, strerror(errno));
exit(1);
}
}
// TODO: consider buffering in some cases?
setbuf(f, 0); // disable output buffering
stream = new LoggerStreamSerialized<LoggerFileStream>(new LoggerFileStream(f, true),
true);
}
atexit(LoggerConfig::flush_all_streams);
cmdline_read = true;
if(!pending_configs.empty()) {
for(std::set<Logger *>::iterator it = pending_configs.begin();
it != pending_configs.end();
it++)
configure(*it);
pending_configs.clear();
}
}
void LoggerConfig::configure(Logger *logger)
{
// if we haven't read the command line yet, remember this for later
if(!cmdline_read) {
pending_configs.insert(logger);
return;
}
// see if this logger is one of the categories we want
if(!cats_enabled.empty()) {
bool found = false;
const char *p = cats_enabled.c_str();
int l = logger->get_name().length();
const char *n = logger->get_name().c_str();
while(*p) {
if(((p[l] == '\0') || (p[l] == ',')) && !strncmp(p, n, l)) {
found = true;
break;
}
// skip to after next comma
while(*p && (*p != ',')) p++;
while(*p && (*p == ',')) p++;
}
if(!found) {
//printf("'%s' not in '%s'\n", n, cats_enabled);
return;
}
}
// see if the level for this category has been customized
Logger::LoggingLevel level = default_level;
std::map<std::string, Logger::LoggingLevel>::const_iterator it = category_levels.find(logger->get_name());
if(it != category_levels.end())
level = it->second;
// give this logger a copy of the global stream
logger->add_stream(stream, level,
false, /* don't delete */
false); /* don't flush each write */
}
////////////////////////////////////////////////////////////////////////
//
// class Logger
Logger::Logger(const std::string& _name)
: name(_name), log_level(LEVEL_NONE)
{
LoggerConfig::get_config()->configure(this);
}
Logger::~Logger(void)
{
// go through our streams and delete any we're supposed to
for(std::vector<LogStream>::iterator it = streams.begin();
it != streams.end();
it++)
if(it->delete_when_done)
delete it->s;
streams.clear();
}
/*static*/ void Logger::configure_from_cmdline(std::vector<std::string>& cmdline)
{
LoggerConfig::get_config()->read_command_line(cmdline);
}
void Logger::log_msg(LoggingLevel level, const std::string& msg)
{
// no logging of empty messages
if(msg.length() == 0)
return;
// build message string, including prefix
static const int MAXLEN = 4096;
char buffer[MAXLEN];
int len = snprintf(buffer, MAXLEN - 2, "[%d - %lx] {%d}{%s}: ",
gasnet_mynode(), (unsigned long)pthread_self(),
level, name.c_str());
int amt = msg.length();
// Unusual case, but handle it
if((len + amt) >= MAXLEN)
{
// If this is an error or a warning, print out the
// whole message no matter what
if ((level == LEVEL_FATAL) ||
(level == LEVEL_ERROR) || (level == LEVEL_WARNING))
{
const size_t full_len = len + amt + 2;
char *full_buffer = (char*)malloc(full_len);
memcpy(full_buffer, buffer, len);
memcpy(full_buffer + len, msg.data(), amt);
full_buffer[len+amt] = '\n';
full_buffer[len+amt+1] = 0;
// go through all the streams
for(std::vector<LogStream>::iterator it = streams.begin();
it != streams.end();
it++) {
if(level < it->min_level)
continue;
it->s->write(full_buffer, full_len);
if(it->flush_each_write)
it->s->flush();
}
free(full_buffer);
return;
}
amt = MAXLEN - 2 - len;
}
memcpy(buffer + len, msg.data(), amt);
len += amt;
buffer[len++] = '\n';
buffer[len] = 0;
// go through all the streams
for(std::vector<LogStream>::iterator it = streams.begin();
it != streams.end();
it++) {
if(level < it->min_level)
continue;
it->s->write(buffer, len);
if(it->flush_each_write)
it->s->flush();
}
}
void Logger::add_stream(LoggerOutputStream *s, LoggingLevel min_level,
bool delete_when_done, bool flush_each_write)
{
LogStream ls;
ls.s = s;
ls.min_level = min_level;
ls.delete_when_done = delete_when_done;
ls.flush_each_write = flush_each_write;
streams.push_back(ls);
// update our logging level if needed
if(log_level > min_level)
log_level = min_level;
}
////////////////////////////////////////////////////////////////////////
//
// class LoggerMessage
LoggerMessage& LoggerMessage::vprintf(const char *fmt, va_list args)
{
if(active) {
char msg[256];
vsnprintf(msg, 256, fmt, args);
(*oss) << msg;
}
return *this;
}
}; // namespace Realm
<commit_msg>realm: Fix maximum logging message size.<commit_after>/* Copyright 2016 Stanford University, NVIDIA 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.
*/
// Realm logging infrastructure
#include "logging.h"
#ifdef SHARED_LOWLEVEL
#define gasnet_mynode() 0
#define gasnet_nodes() 1
#else
#include "activemsg.h"
#endif
#include "cmdline.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <set>
#include <map>
namespace Realm {
// abstract class for an output stream
class LoggerOutputStream {
public:
LoggerOutputStream(void) {}
virtual ~LoggerOutputStream(void) {}
virtual void write(const char *buffer, size_t len) = 0;
virtual void flush(void) = 0;
};
class LoggerFileStream : public LoggerOutputStream {
public:
LoggerFileStream(FILE *_f, bool _close_file)
: f(_f), close_file(_close_file)
{}
virtual ~LoggerFileStream(void)
{
if(close_file)
fclose(f);
}
virtual void write(const char *buffer, size_t len)
{
#ifndef NDEBUG
size_t amt =
#endif
fwrite(buffer, 1, len, f);
assert(amt == len);
}
virtual void flush(void)
{
fflush(f);
}
protected:
FILE *f;
bool close_file;
};
// use a pthread mutex to prevent simultaneous writes to a stream
template <typename T>
class LoggerStreamSerialized : public LoggerOutputStream {
public:
LoggerStreamSerialized(T *_stream, bool _delete_inner)
: stream(_stream), delete_inner(_delete_inner)
{
#ifndef NDEBUG
int ret =
#endif
pthread_mutex_init(&mutex, 0);
assert(ret == 0);
}
virtual ~LoggerStreamSerialized(void)
{
#ifndef NDEBUG
int ret =
#endif
pthread_mutex_destroy(&mutex);
assert(ret == 0);
if(delete_inner)
delete stream;
}
virtual void write(const char *buffer, size_t len)
{
#ifndef NDEBUG
int ret;
ret =
#endif
pthread_mutex_lock(&mutex);
assert(ret == 0);
stream->write(buffer, len);
#ifndef NDEBUG
ret =
#endif
pthread_mutex_unlock(&mutex);
assert(ret == 0);
}
virtual void flush(void)
{
#ifndef NDEBUG
int ret;
ret =
#endif
pthread_mutex_lock(&mutex);
assert(ret == 0);
stream->flush();
#ifndef NDEBUG
ret =
#endif
pthread_mutex_unlock(&mutex);
assert(ret == 0);
}
protected:
LoggerOutputStream *stream;
bool delete_inner;
pthread_mutex_t mutex;
};
class LoggerConfig {
protected:
LoggerConfig(void);
~LoggerConfig(void);
public:
static LoggerConfig *get_config(void);
static void flush_all_streams(void);
void read_command_line(std::vector<std::string>& cmdline);
// either configures a logger right away or remembers it to config once
// we know the desired settings
void configure(Logger *logger);
protected:
bool parse_level_argument(const std::string& s);
bool cmdline_read;
Logger::LoggingLevel default_level;
std::map<std::string, Logger::LoggingLevel> category_levels;
std::string cats_enabled;
std::set<Logger *> pending_configs;
LoggerOutputStream *stream;
};
LoggerConfig::LoggerConfig(void)
: cmdline_read(false), default_level(Logger::LEVEL_PRINT), stream(0)
{}
LoggerConfig::~LoggerConfig(void)
{
delete stream;
}
/*static*/ LoggerConfig *LoggerConfig::get_config(void)
{
static LoggerConfig cfg;
return &cfg;
}
/*static*/ void LoggerConfig::flush_all_streams(void)
{
LoggerConfig *cfg = get_config();
if(cfg->stream)
cfg->stream->flush();
}
bool LoggerConfig::parse_level_argument(const std::string& s)
{
const char *p1 = s.c_str();
while(true) {
// skip commas
while(*p1 == ',') p1++;
if(!*p1) break;
// numbers may be preceeded by name= to specify a per-category level
std::string catname;
if(!isdigit(*p1)) {
const char *p2 = p1;
while(*p2 != '=') {
if(!*p2) {
fprintf(stderr, "ERROR: category name in -level must be followed by =\n");
return false;
}
p2++;
}
catname.assign(p1, p2 - p1);
p1 = p2 + 1;
}
// levels are small integers
if(isdigit(*p1)) {
char *p2;
errno = 0; // no leftover errors from elsewhere
long v = strtol(p1, &p2, 10);
if((errno == 0) && ((*p2 == 0) || (*p2) == ',') &&
(v >= 0) && (v <= Logger::LEVEL_NONE)) {
if(catname.empty())
default_level = (Logger::LoggingLevel)v;
else
category_levels[catname] = (Logger::LoggingLevel)v;
p1 = p2;
continue;
}
}
fprintf(stderr, "ERROR: logger level malformed or out of range: '%s'\n", p1);
return false;
}
return true;
}
void LoggerConfig::read_command_line(std::vector<std::string>& cmdline)
{
std::string logname;
bool ok = CommandLineParser()
.add_option_string("-cat", cats_enabled)
.add_option_string("-logfile", logname)
.add_option_method("-level", this, &LoggerConfig::parse_level_argument)
.parse_command_line(cmdline);
if(!ok) {
fprintf(stderr, "couldn't parse logger config options\n");
exit(1);
}
// lots of choices for log output
if(logname.empty() || (logname == "stdout")) {
stream = new LoggerStreamSerialized<LoggerFileStream>(new LoggerFileStream(stdout, false),
true);
} else if(logname == "stderr") {
stream = new LoggerStreamSerialized<LoggerFileStream>(new LoggerFileStream(stderr, false),
true);
} else {
// we're going to open a file, but key off a + for appending and
// look for a % for node number insertion
bool append = false;
size_t start = 0;
if(logname[0] == '+') {
append = true;
start++;
}
FILE *f = 0;
size_t pct = logname.find_first_of('%', start);
if(pct == std::string::npos) {
// no node number - everybody uses the same file
if(gasnet_nodes() > 1) {
if(!append) {
if(gasnet_mynode() == 1)
fprintf(stderr, "WARNING: all ranks are logging to the same output file - appending is forced and output may be jumbled\n");
append = true;
}
}
const char *fn = logname.c_str() + start;
f = fopen(fn, append ? "a" : "w");
if(!f) {
fprintf(stderr, "could not open log file '%s': %s\n", fn, strerror(errno));
exit(1);
}
} else {
// replace % with node number
char filename[256];
sprintf(filename, "%.*s%d%s",
(int)(pct - start), logname.c_str() + start, gasnet_mynode(), logname.c_str() + pct + 1);
f = fopen(filename, append ? "a" : "w");
if(!f) {
fprintf(stderr, "could not open log file '%s': %s\n", filename, strerror(errno));
exit(1);
}
}
// TODO: consider buffering in some cases?
setbuf(f, 0); // disable output buffering
stream = new LoggerStreamSerialized<LoggerFileStream>(new LoggerFileStream(f, true),
true);
}
atexit(LoggerConfig::flush_all_streams);
cmdline_read = true;
if(!pending_configs.empty()) {
for(std::set<Logger *>::iterator it = pending_configs.begin();
it != pending_configs.end();
it++)
configure(*it);
pending_configs.clear();
}
}
void LoggerConfig::configure(Logger *logger)
{
// if we haven't read the command line yet, remember this for later
if(!cmdline_read) {
pending_configs.insert(logger);
return;
}
// see if this logger is one of the categories we want
if(!cats_enabled.empty()) {
bool found = false;
const char *p = cats_enabled.c_str();
int l = logger->get_name().length();
const char *n = logger->get_name().c_str();
while(*p) {
if(((p[l] == '\0') || (p[l] == ',')) && !strncmp(p, n, l)) {
found = true;
break;
}
// skip to after next comma
while(*p && (*p != ',')) p++;
while(*p && (*p == ',')) p++;
}
if(!found) {
//printf("'%s' not in '%s'\n", n, cats_enabled);
return;
}
}
// see if the level for this category has been customized
Logger::LoggingLevel level = default_level;
std::map<std::string, Logger::LoggingLevel>::const_iterator it = category_levels.find(logger->get_name());
if(it != category_levels.end())
level = it->second;
// give this logger a copy of the global stream
logger->add_stream(stream, level,
false, /* don't delete */
false); /* don't flush each write */
}
////////////////////////////////////////////////////////////////////////
//
// class Logger
Logger::Logger(const std::string& _name)
: name(_name), log_level(LEVEL_NONE)
{
LoggerConfig::get_config()->configure(this);
}
Logger::~Logger(void)
{
// go through our streams and delete any we're supposed to
for(std::vector<LogStream>::iterator it = streams.begin();
it != streams.end();
it++)
if(it->delete_when_done)
delete it->s;
streams.clear();
}
/*static*/ void Logger::configure_from_cmdline(std::vector<std::string>& cmdline)
{
LoggerConfig::get_config()->read_command_line(cmdline);
}
void Logger::log_msg(LoggingLevel level, const std::string& msg)
{
// no logging of empty messages
if(msg.length() == 0)
return;
// build message string, including prefix
static const int MAXLEN = 4096;
char buffer[MAXLEN];
int len = snprintf(buffer, MAXLEN - 2, "[%d - %lx] {%d}{%s}: ",
gasnet_mynode(), (unsigned long)pthread_self(),
level, name.c_str());
int amt = msg.length();
// Unusual case, but handle it
if((len + amt) >= MAXLEN)
{
// If this is an error or a warning, print out the
// whole message no matter what
if ((level == LEVEL_FATAL) ||
(level == LEVEL_ERROR) || (level == LEVEL_WARNING))
{
const size_t full_len = len + amt + 2;
char *full_buffer = (char*)malloc(full_len);
memcpy(full_buffer, buffer, len);
memcpy(full_buffer + len, msg.data(), amt);
full_buffer[len+amt] = '\n';
full_buffer[len+amt+1] = 0;
// go through all the streams
for(std::vector<LogStream>::iterator it = streams.begin();
it != streams.end();
it++) {
if(level < it->min_level)
continue;
it->s->write(full_buffer, full_len);
if(it->flush_each_write)
it->s->flush();
}
free(full_buffer);
return;
}
amt = MAXLEN - 2 - len;
}
memcpy(buffer + len, msg.data(), amt);
len += amt;
buffer[len++] = '\n';
buffer[len] = 0;
// go through all the streams
for(std::vector<LogStream>::iterator it = streams.begin();
it != streams.end();
it++) {
if(level < it->min_level)
continue;
it->s->write(buffer, len);
if(it->flush_each_write)
it->s->flush();
}
}
void Logger::add_stream(LoggerOutputStream *s, LoggingLevel min_level,
bool delete_when_done, bool flush_each_write)
{
LogStream ls;
ls.s = s;
ls.min_level = min_level;
ls.delete_when_done = delete_when_done;
ls.flush_each_write = flush_each_write;
streams.push_back(ls);
// update our logging level if needed
if(log_level > min_level)
log_level = min_level;
}
////////////////////////////////////////////////////////////////////////
//
// class LoggerMessage
LoggerMessage& LoggerMessage::vprintf(const char *fmt, va_list args)
{
if(active) {
static const int MAXLEN = 4096;
char msg[MAXLEN];
vsnprintf(msg, MAXLEN, fmt, args);
(*oss) << msg;
}
return *this;
}
}; // namespace Realm
<|endoftext|> |
<commit_before>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#include <cmath>
#include "ElectronDustMix.hpp"
#include "Units.hpp"
using namespace std;
//////////////////////////////////////////////////////////////////////
ElectronDustMix::ElectronDustMix()
{
}
//////////////////////////////////////////////////////////////////////
void ElectronDustMix::setupSelfBefore()
{
DustMix::setupSelfBefore();
// get the simulation's wavelength grid
const Array& lambdav = simlambdav();
int Nlambda = lambdav.size();
// arbitrarily set the resolution of the theta grid
int Ntheta = 181;
// create temporary vectors and tables with the appropriate size
Array sigmaabsv(Nlambda), sigmascav(Nlambda), asymmparv(Nlambda);
Table<2> S11vv(Nlambda,Ntheta), S12vv(Nlambda,Ntheta), S33vv(Nlambda,Ntheta), S34vv(Nlambda,Ntheta);
// set the constant scattering cross section, and leave absorption at zero
// (leave asymmpar at zero as well - it is not used since we support polarization)
sigmascav = Units::sigmaThomson();
// calculate the wavelength-independent Sxx values in the Mueller matrix according to
// equation (C.7) of Wolf 2003 (Computer Physics Communications, 150, 99–115)
double dt = M_PI/(Ntheta-1);
for (int t=0; t<Ntheta; t++)
{
double theta = t * dt;
double costheta = cos(theta);
double S11 = 0.5*(costheta*costheta+1.);
double S12 = 0.5*(costheta*costheta-1.);
double S33 = costheta;
for (int ell=0; ell<Nlambda; ell++)
{
S11vv(ell,t) = S11;
S12vv(ell,t) = S12;
S33vv(ell,t) = S33;
}
}
// calculate the weight of an electron per hydrogen atom
double mu = Units::masselectron()/(Units::masselectron()+Units::massproton());
// add a single dust population with these properties
addpopulation(mu, sigmaabsv, sigmascav, asymmparv);
addpolarization(S11vv, S12vv, S33vv, S34vv);
}
//////////////////////////////////////////////////////////////////////
<commit_msg>fix mu for electron dust mix<commit_after>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#include <cmath>
#include "ElectronDustMix.hpp"
#include "Units.hpp"
using namespace std;
//////////////////////////////////////////////////////////////////////
ElectronDustMix::ElectronDustMix()
{
}
//////////////////////////////////////////////////////////////////////
void ElectronDustMix::setupSelfBefore()
{
DustMix::setupSelfBefore();
// get the simulation's wavelength grid
const Array& lambdav = simlambdav();
int Nlambda = lambdav.size();
// arbitrarily set the resolution of the theta grid
int Ntheta = 181;
// create temporary vectors and tables with the appropriate size
Array sigmaabsv(Nlambda), sigmascav(Nlambda), asymmparv(Nlambda);
Table<2> S11vv(Nlambda,Ntheta), S12vv(Nlambda,Ntheta), S33vv(Nlambda,Ntheta), S34vv(Nlambda,Ntheta);
// set the constant scattering cross section, and leave absorption at zero
// (leave asymmpar at zero as well - it is not used since we support polarization)
sigmascav = Units::sigmaThomson();
// calculate the wavelength-independent Sxx values in the Mueller matrix according to
// equation (C.7) of Wolf 2003 (Computer Physics Communications, 150, 99–115)
double dt = M_PI/(Ntheta-1);
for (int t=0; t<Ntheta; t++)
{
double theta = t * dt;
double costheta = cos(theta);
double S11 = 0.5*(costheta*costheta+1.);
double S12 = 0.5*(costheta*costheta-1.);
double S33 = costheta;
for (int ell=0; ell<Nlambda; ell++)
{
S11vv(ell,t) = S11;
S12vv(ell,t) = S12;
S33vv(ell,t) = S33;
}
}
// add a single dust population with these properties
addpopulation(Units::masselectron(), sigmaabsv, sigmascav, asymmparv);
addpolarization(S11vv, S12vv, S33vv, S34vv);
}
//////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "AliAODExtension.h"
//-------------------------------------------------------------------------
// Support class for AOD extensions. This is created by the user analysis
// that requires a separate file for some AOD branches. The name of the
// AliAODExtension object is the file name where the AOD branches will be
// stored.
//-------------------------------------------------------------------------
#include "AliAODBranchReplicator.h"
#include "AliAODEvent.h"
#include "AliCodeTimer.h"
#include "AliLog.h"
#include "Riostream.h"
#include "TDirectory.h"
#include "TFile.h"
#include "TList.h"
#include "TMap.h"
#include "TMap.h"
#include "TObjString.h"
#include "TROOT.h"
#include "TString.h"
#include "TTree.h"
using std::endl;
using std::cout;
ClassImp(AliAODExtension)
//______________________________________________________________________________
AliAODExtension::AliAODExtension() : TNamed(),
fAODEvent(0), fTreeE(0), fFileE(0), fNtotal(0), fNpassed(0),
fSelected(kFALSE), fRepFiMap(0x0), fRepFiList(0x0), fEnableReferences(kTRUE), fObjectList(0x0)
{
// default ctor
}
//______________________________________________________________________________
AliAODExtension::AliAODExtension(const char* name, const char* title, Bool_t isfilter)
:TNamed(name,title),
fAODEvent(0),
fTreeE(0),
fFileE(0),
fNtotal(0),
fNpassed(0),
fSelected(kFALSE),
fRepFiMap(0x0),
fRepFiList(0x0),
fEnableReferences(kTRUE),
fObjectList(0x0)
{
// Constructor.
if (isfilter) {
TObject::SetBit(kFilteredAOD);
printf("####### Added AOD filter %s\n", name);
} else printf("####### Added AOD extension %s\n", name);
KeepUnspecifiedBranches();
}
//______________________________________________________________________________
AliAODExtension::~AliAODExtension()
{
// Destructor.
if(fFileE){
// is already handled in TerminateIO
fFileE->Close();
delete fFileE;
fTreeE = 0;
fAODEvent = 0;
}
if (fTreeE) delete fTreeE;
if (fRepFiMap) fRepFiMap->DeleteAll();
delete fRepFiMap; // the map is owner
delete fRepFiList; // the list is not
delete fObjectList; // not owner
}
//______________________________________________________________________________
void AliAODExtension::AddBranch(const char* cname, void* addobj)
{
// Add a new branch to the aod
if (!fAODEvent) {
char type[20];
gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)%p, \"%%s\", s_tmp.Data());", type));
Init(type);
}
TDirectory *owd = gDirectory;
if (fFileE) {
fFileE->cd();
}
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
fAODEvent->AddObject(obj);
TString bname(obj->GetName());
if (!fTreeE->FindBranch(bname.Data()))
{
Bool_t acceptAdd(kTRUE);
if ( TestBit(kDropUnspecifiedBranches) )
{
// check that this branch is in our list of specified ones...
// otherwise do not add it !
TIter next(fRepFiMap);
TObjString* p;
acceptAdd=kFALSE;
while ( ( p = static_cast<TObjString*>(next()) ) && !acceptAdd )
{
if ( p->String() == bname ) acceptAdd=kTRUE;
}
}
if ( acceptAdd )
{
// Do the same as if we book via
// TTree::Branch(TCollection*)
fObjectList->Add(obj);
const Int_t kSplitlevel = 99; // default value in TTree::Branch()
const Int_t kBufsize = 32000; // default value in TTree::Branch()
fTreeE->Bronch(bname.Data(), cname,
fAODEvent->GetList()->GetObjectRef(obj),
kBufsize, kSplitlevel - 1);
}
}
owd->cd();
}
//______________________________________________________________________________
Bool_t AliAODExtension::FinishEvent()
{
// Fill current event.
fNtotal++;
if (!IsFilteredAOD()) {
fAODEvent->MakeEntriesReferencable();
fTreeE->Fill();
return kTRUE;
}
// Filtered AOD. Fill only if event is selected.
if (!fSelected) return kTRUE;
TIter next(fRepFiList);
AliAODBranchReplicator* repfi;
while ( ( repfi = static_cast<AliAODBranchReplicator*>(next()) ) )
{
repfi->ReplicateAndFilter(*fAODEvent);
}
fNpassed++;
fTreeE->Fill();
fSelected = kFALSE; // so that next event will not be selected unless demanded
return kTRUE;
}
//______________________________________________________________________________
Bool_t AliAODExtension::Init(Option_t *option)
{
// Initialize IO.
AliCodeTimerAuto(GetName(),0);
if(!fAODEvent)
{
fAODEvent = new AliAODEvent();
}
TDirectory *owd = gDirectory;
TString opt(option);
opt.ToLower();
if (opt.Contains("proof"))
{
// proof
// Merging via files. Need to access analysis manager via interpreter.
gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\", \"%s\");", fName.Data()));
fFileE = gFile;
}
else
{
fFileE = new TFile(GetName(), "RECREATE");
}
fTreeE = new TTree("aodTree", "AliAOD tree");
delete fObjectList;
fObjectList = new TList;
fObjectList->SetOwner(kFALSE); // be explicit we're not the owner...
TList* inputList = fAODEvent->GetList();
TIter next(inputList);
TObject* o;
while ( ( o = next() ) )
{
// Loop on the objects that are within the main AOD, and see what to do with them :
// - transmit them to our AOD as they are
// - filter them (by means of an AliAODBranchReplicator)
// - drop them completely
Bool_t mustKeep(kFALSE);
TString test(o->ClassName());
test.ToUpper();
if (test.BeginsWith("ALIAODHEADER"))
{
// do not allow to drop header branch
mustKeep=kTRUE;
}
if ( fRepFiMap && !mustKeep )
{
// we have some replicators, so let's see what the relevant one decides about this object
TObject* specified = fRepFiMap->FindObject(o->GetName()); // FindObject finds key=o->GetName() in the map
if (specified)
{
AliAODBranchReplicator* repfi = dynamic_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(o->GetName())); // GetValue gets the replicator corresponding to key=o->GetName()
if ( repfi )
{
TList* replicatedList = repfi->GetList();
if (replicatedList)
{
AliAODEvent::AssignIDtoCollection(replicatedList);
TIter nextRep(replicatedList);
TObject* objRep;
while ( ( objRep = nextRep() ) )
{
if ( !fObjectList->FindObject(objRep) ) // insure we're not adding several times the same object
{
fObjectList->Add(objRep);
}
}
}
else
{
AliError(Form("replicatedList from %s is null !",repfi->GetName()));
}
}
}
else
{
if ( !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
else
{
// no replicator, so decide based on the policy about dropping unspecified branches
if ( mustKeep || !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
if (fEnableReferences)
{
fTreeE->BranchRef();
}
fTreeE->Branch(fObjectList);
owd->cd();
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::Print(Option_t* opt) const
{
// Print info about this extension
cout << opt << Form("%s - %s - %s - aod %p",IsFilteredAOD() ? "FilteredAOD" : "Extension",
GetName(),GetTitle(),GetAOD()) << endl;
if ( !fEnableReferences )
{
cout << opt << opt << "References are disabled ! Hope you know what you are doing !" << endl;
}
if ( TestBit(kDropUnspecifiedBranches) )
{
cout << opt << opt << "All branches not explicitely specified will be dropped" << endl;
}
TIter next(fRepFiMap);
TObjString* s;
while ( ( s = static_cast<TObjString*>(next()) ) )
{
AliAODBranchReplicator* br = static_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(s->String().Data()));
cout << opt << opt << "Branch " << s->String();
if (br)
{
cout << " will be filtered by class " << br->ClassName();
}
else
{
cout << " will be transmitted as is";
}
cout << endl;
}
}
//______________________________________________________________________________
void AliAODExtension::SetEvent(AliAODEvent* event)
{
// Connects to an external event
if (!IsFilteredAOD()) {
Error("SetEvent", "Not allowed to set external event for non filtered AOD's");
return;
}
fAODEvent = event;
}
//______________________________________________________________________________
void AliAODExtension::AddAODtoTreeUserInfo()
{
// Add aod event to tree user info
if (!fTreeE) return;
AliAODEvent* aodEvent(fAODEvent);
if ( IsFilteredAOD() )
{
// cannot attach fAODEvent (which is shared with our AliAODHandler mother)
// so we create a custom (empty) AliAODEvent
// Has also the advantage we can specify only the list of objects
// that are actually there in this filtered aod
//
aodEvent = new AliAODEvent;
TIter nextObj(fObjectList);
TObject* o;
while ( ( o = nextObj() ) )
{
aodEvent->AddObject(o);
}
}
fTreeE->GetUserInfo()->Add(aodEvent);
}
//______________________________________________________________________________
Bool_t AliAODExtension::TerminateIO()
{
// Terminate IO
if (TObject::TestBit(kFilteredAOD))
printf("AOD Filter %s: events processed: %d passed: %d\n", GetName(), fNtotal, fNpassed);
else
printf("AOD extension %s: events processed: %d\n", GetName(), fNtotal);
if (fFileE)
{
fFileE->Write();
fFileE->Close();
delete fFileE;
fFileE = 0;
fTreeE = 0;
fAODEvent = 0;
}
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::FilterBranch(const char* branchName, AliAODBranchReplicator* repfi)
{
// Specify a filter/replicator for a given branch
//
// If repfi=0x0, this will disable the branch (in the output) completely.
//
// repfi is adopted by this class, i.e. user should not delete it.
//
// WARNING : branch name must be exact.
//
// See also the documentation for AliAODBranchReplicator class.
//
if (!fRepFiMap)
{
fRepFiMap = new TMap;
fRepFiMap->SetOwnerKeyValue(kTRUE,kTRUE);
fRepFiList = new TList;
fRepFiList->SetOwner(kFALSE);
}
fRepFiMap->Add(new TObjString(branchName),repfi);
if (repfi && !fRepFiList->FindObject(repfi))
{
// insure we get unique and non-null replicators in this list
fRepFiList->Add(repfi);
}
}
<commit_msg>From Jens: Allow for custom header replicator in AOD<commit_after>#include "AliAODExtension.h"
//-------------------------------------------------------------------------
// Support class for AOD extensions. This is created by the user analysis
// that requires a separate file for some AOD branches. The name of the
// AliAODExtension object is the file name where the AOD branches will be
// stored.
//-------------------------------------------------------------------------
#include "AliAODBranchReplicator.h"
#include "AliAODEvent.h"
#include "AliCodeTimer.h"
#include "AliLog.h"
#include "Riostream.h"
#include "TDirectory.h"
#include "TFile.h"
#include "TList.h"
#include "TMap.h"
#include "TMap.h"
#include "TObjString.h"
#include "TROOT.h"
#include "TString.h"
#include "TTree.h"
using std::endl;
using std::cout;
ClassImp(AliAODExtension)
//______________________________________________________________________________
AliAODExtension::AliAODExtension() : TNamed(),
fAODEvent(0), fTreeE(0), fFileE(0), fNtotal(0), fNpassed(0),
fSelected(kFALSE), fRepFiMap(0x0), fRepFiList(0x0), fEnableReferences(kTRUE), fObjectList(0x0)
{
// default ctor
}
//______________________________________________________________________________
AliAODExtension::AliAODExtension(const char* name, const char* title, Bool_t isfilter)
:TNamed(name,title),
fAODEvent(0),
fTreeE(0),
fFileE(0),
fNtotal(0),
fNpassed(0),
fSelected(kFALSE),
fRepFiMap(0x0),
fRepFiList(0x0),
fEnableReferences(kTRUE),
fObjectList(0x0)
{
// Constructor.
if (isfilter) {
TObject::SetBit(kFilteredAOD);
printf("####### Added AOD filter %s\n", name);
} else printf("####### Added AOD extension %s\n", name);
KeepUnspecifiedBranches();
}
//______________________________________________________________________________
AliAODExtension::~AliAODExtension()
{
// Destructor.
if(fFileE){
// is already handled in TerminateIO
fFileE->Close();
delete fFileE;
fTreeE = 0;
fAODEvent = 0;
}
if (fTreeE) delete fTreeE;
if (fRepFiMap) fRepFiMap->DeleteAll();
delete fRepFiMap; // the map is owner
delete fRepFiList; // the list is not
delete fObjectList; // not owner
}
//______________________________________________________________________________
void AliAODExtension::AddBranch(const char* cname, void* addobj)
{
// Add a new branch to the aod
if (!fAODEvent) {
char type[20];
gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)%p, \"%%s\", s_tmp.Data());", type));
Init(type);
}
TDirectory *owd = gDirectory;
if (fFileE) {
fFileE->cd();
}
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
fAODEvent->AddObject(obj);
TString bname(obj->GetName());
if (!fTreeE->FindBranch(bname.Data()))
{
Bool_t acceptAdd(kTRUE);
if ( TestBit(kDropUnspecifiedBranches) )
{
// check that this branch is in our list of specified ones...
// otherwise do not add it !
TIter next(fRepFiMap);
TObjString* p;
acceptAdd=kFALSE;
while ( ( p = static_cast<TObjString*>(next()) ) && !acceptAdd )
{
if ( p->String() == bname ) acceptAdd=kTRUE;
}
}
if ( acceptAdd )
{
// Do the same as if we book via
// TTree::Branch(TCollection*)
fObjectList->Add(obj);
const Int_t kSplitlevel = 99; // default value in TTree::Branch()
const Int_t kBufsize = 32000; // default value in TTree::Branch()
fTreeE->Bronch(bname.Data(), cname,
fAODEvent->GetList()->GetObjectRef(obj),
kBufsize, kSplitlevel - 1);
}
}
owd->cd();
}
//______________________________________________________________________________
Bool_t AliAODExtension::FinishEvent()
{
// Fill current event.
fNtotal++;
if (!IsFilteredAOD()) {
fAODEvent->MakeEntriesReferencable();
fTreeE->Fill();
return kTRUE;
}
// Filtered AOD. Fill only if event is selected.
if (!fSelected) return kTRUE;
TIter next(fRepFiList);
AliAODBranchReplicator* repfi;
while ( ( repfi = static_cast<AliAODBranchReplicator*>(next()) ) )
{
repfi->ReplicateAndFilter(*fAODEvent);
}
fNpassed++;
fTreeE->Fill();
fSelected = kFALSE; // so that next event will not be selected unless demanded
return kTRUE;
}
//______________________________________________________________________________
Bool_t AliAODExtension::Init(Option_t *option)
{
// Initialize IO.
AliCodeTimerAuto(GetName(),0);
if(!fAODEvent)
{
fAODEvent = new AliAODEvent();
}
TDirectory *owd = gDirectory;
TString opt(option);
opt.ToLower();
if (opt.Contains("proof"))
{
// proof
// Merging via files. Need to access analysis manager via interpreter.
gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\", \"%s\");", fName.Data()));
fFileE = gFile;
}
else
{
fFileE = new TFile(GetName(), "RECREATE");
}
fTreeE = new TTree("aodTree", "AliAOD tree");
delete fObjectList;
fObjectList = new TList;
fObjectList->SetOwner(kFALSE); // be explicit we're not the owner...
TList* inputList = fAODEvent->GetList();
TIter next(inputList);
TObject* o;
while ( ( o = next() ) )
{
// Loop on the objects that are within the main AOD, and see what to do with them :
// - transmit them to our AOD as they are
// - filter them (by means of an AliAODBranchReplicator)
// - drop them completely
Bool_t mustKeep(kFALSE);
TString test(o->ClassName());
test.ToUpper();
// check if there is a replicator for the header
Bool_t headerHasReplicator = fRepFiMap && (fRepFiMap->FindObject(o->GetName())!=0x0);
if (test.BeginsWith("ALIAODHEADER") && !headerHasReplicator)
{
// do not allow to drop header branch
mustKeep=kTRUE;
}
if ( fRepFiMap && !mustKeep )
{
// we have some replicators, so let's see what the relevant one decides about this object
TObject* specified = fRepFiMap->FindObject(o->GetName()); // FindObject finds key=o->GetName() in the map
if (specified)
{
AliAODBranchReplicator* repfi = dynamic_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(o->GetName())); // GetValue gets the replicator corresponding to key=o->GetName()
if ( repfi )
{
TList* replicatedList = repfi->GetList();
if (replicatedList)
{
AliAODEvent::AssignIDtoCollection(replicatedList);
TIter nextRep(replicatedList);
TObject* objRep;
while ( ( objRep = nextRep() ) )
{
if ( !fObjectList->FindObject(objRep) ) // insure we're not adding several times the same object
{
fObjectList->Add(objRep);
}
}
}
else
{
AliError(Form("replicatedList from %s is null !",repfi->GetName()));
}
}
}
else
{
if ( !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
else
{
// no replicator, so decide based on the policy about dropping unspecified branches
if ( mustKeep || !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
if (fEnableReferences)
{
fTreeE->BranchRef();
}
fTreeE->Branch(fObjectList);
owd->cd();
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::Print(Option_t* opt) const
{
// Print info about this extension
cout << opt << Form("%s - %s - %s - aod %p",IsFilteredAOD() ? "FilteredAOD" : "Extension",
GetName(),GetTitle(),GetAOD()) << endl;
if ( !fEnableReferences )
{
cout << opt << opt << "References are disabled ! Hope you know what you are doing !" << endl;
}
if ( TestBit(kDropUnspecifiedBranches) )
{
cout << opt << opt << "All branches not explicitely specified will be dropped" << endl;
}
TIter next(fRepFiMap);
TObjString* s;
while ( ( s = static_cast<TObjString*>(next()) ) )
{
AliAODBranchReplicator* br = static_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(s->String().Data()));
cout << opt << opt << "Branch " << s->String();
if (br)
{
cout << " will be filtered by class " << br->ClassName();
}
else
{
cout << " will be transmitted as is";
}
cout << endl;
}
}
//______________________________________________________________________________
void AliAODExtension::SetEvent(AliAODEvent* event)
{
// Connects to an external event
if (!IsFilteredAOD()) {
Error("SetEvent", "Not allowed to set external event for non filtered AOD's");
return;
}
fAODEvent = event;
}
//______________________________________________________________________________
void AliAODExtension::AddAODtoTreeUserInfo()
{
// Add aod event to tree user info
if (!fTreeE) return;
AliAODEvent* aodEvent(fAODEvent);
if ( IsFilteredAOD() )
{
// cannot attach fAODEvent (which is shared with our AliAODHandler mother)
// so we create a custom (empty) AliAODEvent
// Has also the advantage we can specify only the list of objects
// that are actually there in this filtered aod
//
aodEvent = new AliAODEvent;
TIter nextObj(fObjectList);
TObject* o;
while ( ( o = nextObj() ) )
{
aodEvent->AddObject(o);
}
}
fTreeE->GetUserInfo()->Add(aodEvent);
}
//______________________________________________________________________________
Bool_t AliAODExtension::TerminateIO()
{
// Terminate IO
if (TObject::TestBit(kFilteredAOD))
printf("AOD Filter %s: events processed: %d passed: %d\n", GetName(), fNtotal, fNpassed);
else
printf("AOD extension %s: events processed: %d\n", GetName(), fNtotal);
if (fFileE)
{
fFileE->Write();
fFileE->Close();
delete fFileE;
fFileE = 0;
fTreeE = 0;
fAODEvent = 0;
}
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::FilterBranch(const char* branchName, AliAODBranchReplicator* repfi)
{
// Specify a filter/replicator for a given branch
//
// If repfi=0x0, this will disable the branch (in the output) completely.
//
// repfi is adopted by this class, i.e. user should not delete it.
//
// WARNING : branch name must be exact.
//
// See also the documentation for AliAODBranchReplicator class.
//
if (!fRepFiMap)
{
fRepFiMap = new TMap;
fRepFiMap->SetOwnerKeyValue(kTRUE,kTRUE);
fRepFiList = new TList;
fRepFiList->SetOwner(kFALSE);
}
fRepFiMap->Add(new TObjString(branchName),repfi);
if (repfi && !fRepFiList->FindObject(repfi))
{
// insure we get unique and non-null replicators in this list
fRepFiList->Add(repfi);
}
}
<|endoftext|> |
<commit_before>// Example items to include
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
#include <math.h>
int foo [5] = { 14, 4, 144, 20, 13411 };
//ARRAY SYNTAX
int main ()
{
//FOR LOOPS
for(int j = 0; j < 4; j++){
cout << j << endl;
//PRINTS NUMBERS. COUT is to print out. CIN is to take input from user
cout << (sizeof(foo)/sizeof(*foo)) << endl;
//(sizeof(foo)/sizeof(*foo)) is how you find the length of an array
cout << foo[j] << endl;
//PRINTS OUT THE J ELEMENT IN THE ARRAY
swap(foo[j-1], foo[j]);
//Swaps elements in an array
while(j > j-1){
cout << "The world is still spinning" << endl;
}
//while loop
}
cout << "test" << endl;
//END ALL C++ MAIN FUNCTIONS WITH RETURNING 0
return 0;
}<commit_msg>Added start of vectors + reference<commit_after>// Example items to include
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
#include <math.h>
int foo [5] = { 14, 4, 144, 20, 13411 };
//ARRAY SYNTAX
vector<int> v;
//Declares a vector, v, of integers
int size_t size = 10;
vector<int> array(size); // make room for 10 integers,
int main ()
{
//FOR LOOPS
for(int j = 0; j < 4; j++){
cout << j << endl;
//PRINTS NUMBERS. COUT is to print out. CIN is to take input from user
cout << (sizeof(foo)/sizeof(*foo)) << endl;
//(sizeof(foo)/sizeof(*foo)) is how you find the length of an array
cout << foo[j] << endl;
//PRINTS OUT THE J ELEMENT IN THE ARRAY
swap(foo[j-1], foo[j]);
//Swaps elements in an array
while(j > j-1){
cout << "The world is still spinning" << endl;
}
//while loop
}
//using vector array right now
// and initialize them to 0
// do something with them:
for(int i=0; i<size; ++i){
array[i] = i;
//print out parts of the vector
}
cout << "test" << endl;
//END ALL C++ MAIN FUNCTIONS WITH RETURNING 0
return 0;
}
/*
//Refrences
http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm
*/<|endoftext|> |
<commit_before>#include "../include/IntegerEncodingInitializer.hpp"
namespace clusterer
{
namespace backend
{
IntegerEncodingInitializer::IntegerEncodingInitializer(
const Graph* g, unsigned maxClusters) : graph(g)
{
if (maxClusters == 0 || maxClusters >= graph->getNoVertices())
{ maxClusters = graph->getNoVertices() - 1; }
std::random_device rd;
rng.seed(rd());
uni_dist = new std::uniform_int_distribution<unsigned>(0, maxClusters);
}
IntegerVectorEncoding IntegerEncodingInitializer::getRandomSolution()
{
IntegerVectorEncoding result(graph);
for (int vert = 0; vert < graph->getNoVertices(); vert++)
{ result.addToCluster(vert, (*uni_dist)(rng)); }
return result;
}
std::vector<IntegerVectorEncoding> IntegerEncodingInitializer::getInitialPopulation(int count)
{
std::vector<IntegerVectorEncoding> result;
for (int i = 0; i < count; i++)
{ result.push_back(getRandomSolution()); }
return result;
}
} // namespace backend
} // namespace clusterer
<commit_msg>initializer fix<commit_after>#include "../include/IntegerEncodingInitializer.hpp"
namespace clusterer
{
namespace backend
{
IntegerEncodingInitializer::IntegerEncodingInitializer(
const Graph* g, unsigned maxClusters) : graph(g)
{
if (maxClusters == 0 || maxClusters >= graph->getNoVertices())
{ maxClusters = graph->getNoVertices() - 1; }
std::random_device rd;
rng.seed(rd());
uni_dist = new std::uniform_int_distribution<unsigned>(0, maxClusters);
}
IntegerVectorEncoding IntegerEncodingInitializer::getRandomSolution()
{
IntegerVectorEncoding result(graph);
for (int vert = 0; vert < graph->getNoVertices(); vert++)
{ result.addToCluster(vert, (*uni_dist)(rng)); }
result.normalize();
return result;
}
std::vector<IntegerVectorEncoding> IntegerEncodingInitializer::getInitialPopulation(int count)
{
std::vector<IntegerVectorEncoding> result;
for (int i = 0; i < count; i++)
{ result.push_back(getRandomSolution()); }
return result;
}
} // namespace backend
} // namespace clusterer
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 ARM. All rights reserved.
*/
#include "include/m2mtimerimpl_mbed.h"
#include "lwm2m-client/m2mtimerobserver.h"
M2MTimerImpl& M2MTimerImpl::operator=(const M2MTimerImpl& other)
{
if( this != &other){
_single_shot= other._single_shot;
_ticker = other._ticker;
_interval = other._interval;
}
return *this;
}
// Prevents the use of copy constructor
M2MTimerImpl::M2MTimerImpl(const M2MTimerImpl& other)
:_observer(other._observer)
{
*this = other;
}
M2MTimerImpl::M2MTimerImpl(M2MTimerObserver& observer)
: _observer(observer),
_single_shot(true),
_interval(0)
{
}
M2MTimerImpl::~M2MTimerImpl()
{
}
void M2MTimerImpl::start_timer( uint64_t interval,
bool single_shot)
{
_single_shot = single_shot;
_interval = interval ;
_ticker.detach();
_ticker.attach_us(this,
&M2MTimerImpl::timer_expired,
_interval * 1000);
}
void M2MTimerImpl::stop_timer()
{
_interval = 0;
_single_shot = false;
_ticker.detach();
}
void M2MTimerImpl::timer_expired()
{
_observer.timer_expired();
if(!_single_shot) {
start_timer(_interval,true);
}
}
<commit_msg>timer fix<commit_after>/*
* Copyright (c) 2015 ARM. All rights reserved.
*/
#include "include/m2mtimerimpl_mbed.h"
#include "lwm2m-client/m2mtimerobserver.h"
M2MTimerImpl& M2MTimerImpl::operator=(const M2MTimerImpl& other)
{
if( this != &other){
_single_shot= other._single_shot;
//_ticker = other._ticker;
_interval = other._interval;
}
return *this;
}
// Prevents the use of copy constructor
M2MTimerImpl::M2MTimerImpl(const M2MTimerImpl& other)
:_observer(other._observer)
{
*this = other;
}
M2MTimerImpl::M2MTimerImpl(M2MTimerObserver& observer)
: _observer(observer),
_single_shot(true),
_interval(0)
{
}
M2MTimerImpl::~M2MTimerImpl()
{
}
void M2MTimerImpl::start_timer( uint64_t interval,
bool single_shot)
{
_single_shot = single_shot;
_interval = interval ;
_ticker.detach();
_ticker.attach_us(this,
&M2MTimerImpl::timer_expired,
_interval * 1000);
}
void M2MTimerImpl::stop_timer()
{
_interval = 0;
_single_shot = false;
_ticker.detach();
}
void M2MTimerImpl::timer_expired()
{
_observer.timer_expired();
if(!_single_shot) {
start_timer(_interval,true);
}
}
<|endoftext|> |
<commit_before>#include <windows.h>
#include <OvRender.h>
#include <sloverlay.h>
#include <overlay.h>
SlOverlayMenu* MnuMenu;
MenuVars MnuOsd[20];
MenuVars MnuCache[10];
WCHAR* GroupOpt[] = {L"", L""};
WCHAR* ItemOpt[] = {L"Off", L"On"};
BOOLEAN MnuInitialized;
//Add menu items to menu
VOID
AddItems()
{
MnuMenu->AddGroup(L"OSD", GroupOpt, &MnuOsd[0].Var);
if (MnuOsd[0].Var)
{
MnuMenu->AddItem(L"GPU Core utilization", ItemOpt, &MnuOsd[1].Var);
MnuMenu->AddItem(L"GPU Core temperature", ItemOpt, &MnuOsd[2].Var);
MnuMenu->AddItem(L"GPU Engine Clock", ItemOpt, &MnuOsd[3].Var);
MnuMenu->AddItem(L"GPU Memory Clock", ItemOpt, &MnuOsd[4].Var);
MnuMenu->AddItem(L"GPU VRAM usage", ItemOpt, &MnuOsd[5].Var);
MnuMenu->AddItem(L"CPU utilization", ItemOpt, &MnuOsd[6].Var);
MnuMenu->AddItem(L"CPU temperature", ItemOpt, &MnuOsd[7].Var);
MnuMenu->AddItem(L"RAM usage", ItemOpt, &MnuOsd[8].Var);
MnuMenu->AddItem(L"Max core usage", ItemOpt, &MnuOsd[9].Var);
MnuMenu->AddItem(L"Max thread usage", ItemOpt, &MnuOsd[10].Var);
MnuMenu->AddItem(L"Disk read-write rate", ItemOpt, &MnuOsd[11].Var);
MnuMenu->AddItem(L"Disk response time", ItemOpt, &MnuOsd[12].Var);
MnuMenu->AddItem(L"Frame Buffer count", ItemOpt, &MnuOsd[13].Var);
MnuMenu->AddItem(L"Show Time", ItemOpt, &MnuOsd[14].Var);
}
MnuMenu->AddGroup(L"CACHE", GroupOpt, &MnuCache[0].Var);
if (MnuCache[0].Var)
{
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[1].Var);
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[2].Var);
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[3].Var);
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[4].Var);
}
}
VOID
ProcessOptions()
{
if (MnuOsd[1].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_LOAD;
/*else
PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/
//this needs to be fixed, if it was enable by main gui
//checkbox then it'll get disabled. too lazy...
if (MnuOsd[2].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_TEMP;
if (MnuOsd[3].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;
if (MnuOsd[4].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;
if (MnuOsd[9].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MCU;
if (MnuOsd[10].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MTU;
}
VOID
MnuRender( OvOverlay* Overlay )
{
if (!MnuInitialized)
{
MnuMenu = new SlOverlayMenu(300);
MnuInitialized = TRUE;
}
if( MnuMenu->mSet.MaxItems == 0 )
AddItems();
//Call drawing and navigation functions
MnuMenu->Render(100, 200, Overlay);
ProcessOptions();
}
<commit_msg>added time to in-game settings<commit_after>#include <windows.h>
#include <OvRender.h>
#include <sloverlay.h>
#include <overlay.h>
SlOverlayMenu* MnuMenu;
MenuVars MnuOsd[20];
MenuVars MnuCache[10];
WCHAR* GroupOpt[] = {L"", L""};
WCHAR* ItemOpt[] = {L"Off", L"On"};
BOOLEAN MnuInitialized;
//Add menu items to menu
VOID
AddItems()
{
MnuMenu->AddGroup(L"OSD", GroupOpt, &MnuOsd[0].Var);
if (MnuOsd[0].Var)
{
MnuMenu->AddItem(L"GPU Core utilization", ItemOpt, &MnuOsd[1].Var);
MnuMenu->AddItem(L"GPU Core temperature", ItemOpt, &MnuOsd[2].Var);
MnuMenu->AddItem(L"GPU Engine Clock", ItemOpt, &MnuOsd[3].Var);
MnuMenu->AddItem(L"GPU Memory Clock", ItemOpt, &MnuOsd[4].Var);
MnuMenu->AddItem(L"GPU VRAM usage", ItemOpt, &MnuOsd[5].Var);
MnuMenu->AddItem(L"CPU utilization", ItemOpt, &MnuOsd[6].Var);
MnuMenu->AddItem(L"CPU temperature", ItemOpt, &MnuOsd[7].Var);
MnuMenu->AddItem(L"RAM usage", ItemOpt, &MnuOsd[8].Var);
MnuMenu->AddItem(L"Max core usage", ItemOpt, &MnuOsd[9].Var);
MnuMenu->AddItem(L"Max thread usage", ItemOpt, &MnuOsd[10].Var);
MnuMenu->AddItem(L"Disk read-write rate", ItemOpt, &MnuOsd[11].Var);
MnuMenu->AddItem(L"Disk response time", ItemOpt, &MnuOsd[12].Var);
MnuMenu->AddItem(L"Frame Buffer count", ItemOpt, &MnuOsd[13].Var);
MnuMenu->AddItem(L"Show Time", ItemOpt, &MnuOsd[14].Var);
}
MnuMenu->AddGroup(L"CACHE", GroupOpt, &MnuCache[0].Var);
if (MnuCache[0].Var)
{
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[1].Var);
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[2].Var);
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[3].Var);
MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[4].Var);
}
}
VOID
ProcessOptions()
{
if (MnuOsd[1].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_LOAD;
/*else
PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/
//this needs to be fixed, if it was enable by main gui
//checkbox then it'll get disabled. too lazy...
if (MnuOsd[2].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_TEMP;
if (MnuOsd[3].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;
if (MnuOsd[4].Var > 0)
PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;
if (MnuOsd[9].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MCU;
if (MnuOsd[10].Var > 0)
PushSharedMemory->OSDFlags |= OSD_MTU;
if (MnuOsd[14].Var > 0)
PushSharedMemory->OSDFlags |= OSD_TIME;
}
VOID
MnuRender( OvOverlay* Overlay )
{
if (!MnuInitialized)
{
MnuMenu = new SlOverlayMenu(300);
MnuInitialized = TRUE;
}
if( MnuMenu->mSet.MaxItems == 0 )
AddItems();
//Call drawing and navigation functions
MnuMenu->Render(100, 200, Overlay);
ProcessOptions();
}
<|endoftext|> |
<commit_before>/*
* paged_grid.cpp
*
* Created on: 06.05.2010
* Author: gmueller
*/
#include "arguments.hpp"
#include "gadget/Grid.hpp"
#include "gadget/Index3.hpp"
#include "gadget/SmoothParticle.hpp"
#include "gadget/GadgetFile.hpp"
#include "gadget/Vector3.hpp"
#include <ctime>
#include <limits>
#include <algorithm>
#include <omp.h>
#include <sstream>
#include <fstream>
int sph(Arguments &arguments) {
int size = arguments.getInt("-size", 240000);
std::cout << "Size: " << size << " kpc" << std::endl;
float h = arguments.getFloat("-h", 0.7);
std::cout << "h: " << h << std::endl;
size_t fileSizeKpc = arguments.getInt("-fileSize", 20000);
std::cout << "FileSize: " << fileSizeKpc << " kpc ";
std::string prefix = arguments.getString("-prefix", "sph");
bool verbose = arguments.hasFlag("-v");
size_t bins = size / fileSizeKpc;
Grid< std::vector<SmoothParticle> > grid(bins, size);
std::vector < std::string > files;
arguments.getVector("-f", files);
for (size_t iArg = 0; iArg < files.size(); iArg++) {
std::cout << "Open " << files[iArg] << " (" << (iArg + 1) << "/"
<< files.size() << ")" << std::endl;
GadgetFile file;
file.open(files[iArg]);
if (file.good() == false) {
std::cerr << "Failed to open file " << files[iArg] << std::endl;
return 1;
}
file.readHeader();
int pn = file.getHeader().particleNumberList[0];
std::cout << " Number of SmoothParticles: " << pn << std::endl;
std::cout << " Read POS block" << std::endl;
std::vector<float> pos;
if (file.readFloatBlock("POS ", pos) == false) {
std::cerr << "Failed to read POS block" << std::endl;
return 1;
}
std::cout << " Read BFLD block" << std::endl;
std::vector<float> bfld;
if (file.readFloatBlock("BFLD", bfld) == false) {
std::cerr << "Failed to read BFLD block" << std::endl;
return 1;
}
std::cout << " Read HSML block" << std::endl;
std::vector<float> hsml;
if (file.readFloatBlock("HSML", hsml) == false) {
std::cerr << "Failed to read HSML block" << std::endl;
return 1;
}
for (int iP = 0; iP < pn; iP++) {
SmoothParticle particle;
particle.smoothingLength = hsml[iP] / h;
particle.position.x = (pos[iP * 3] - size / 2) / h + size / 2;
particle.position.y = (pos[iP * 3 + 1] - size / 2) / h + size / 2;
particle.position.z = (pos[iP * 3 + 2] - size / 2) / h + size / 2;
float norm = 1.0 / M_PI / pow(particle.smoothingLength, 3);
particle.bfield.x = bfld[iP * 3] * norm;
particle.bfield.y = bfld[iP * 3 + 1] * norm;
particle.bfield.z = bfld[iP * 3 + 2] * norm;
Vector3f l = particle.position - Vector3f(
particle.smoothingLength * 2);
l.clamp(0.0, size);
Vector3f u = particle.position + Vector3f(
particle.smoothingLength * 2);
u.clamp(0.0, size);
Index3 lower, upper;
lower.x = (uint32_t) std::floor(l.x / fileSizeKpc);
lower.y = (uint32_t) std::floor(l.y / fileSizeKpc);
lower.z = (uint32_t) std::floor(l.z / fileSizeKpc);
upper.x = (uint32_t) std::ceil(u.x / fileSizeKpc);
upper.y = (uint32_t) std::ceil(u.y / fileSizeKpc);
upper.z = (uint32_t) std::ceil(u.z / fileSizeKpc);
if (verbose && (iP % 100000 ==0)) {
std::cout << "Pos:" << particle.position << std::endl;
std::cout << "SL:" << particle.smoothingLength << std::endl;
std::cout << "Lower:" << lower << std::endl;
std::cout << "Upper:" << upper << std::endl;
}
for (size_t x = lower.x; x < upper.x; x++)
for (size_t y = lower.y; y < upper.y; y++)
for (size_t z = lower.z; z < upper.z; z++)
grid.get(x, y, z).push_back(particle);
}
}
std::cout << "Write output" << std::endl;
for (size_t x = 0; x < bins; x++) {
if (verbose) {
std::cout << "x = " << x << std::endl;
}
for (size_t y = 0; y < bins; y++)
for (size_t z = 0; z < bins; z++) {
std::stringstream sstr;
sstr << prefix << "-" << x << "-" << y << "-" << z << ".raw";
std::ofstream out(sstr.str().c_str(),std::ofstream::binary);
uint32_t s = grid.get(x, y, z).size();
if (verbose)
std::cout << s << std::endl;
out.write((const char *)&s, sizeof(uint32_t));
out.write((const char *)&grid.get(x, y, z)[0], sizeof(SmoothParticle) * s);
}
}
return 0;
}
<commit_msg>add amrgin<commit_after>/*
* paged_grid.cpp
*
* Created on: 06.05.2010
* Author: gmueller
*/
#include "arguments.hpp"
#include "gadget/Grid.hpp"
#include "gadget/Index3.hpp"
#include "gadget/SmoothParticle.hpp"
#include "gadget/GadgetFile.hpp"
#include "gadget/Vector3.hpp"
#include <ctime>
#include <limits>
#include <algorithm>
#include <omp.h>
#include <sstream>
#include <fstream>
int sph(Arguments &arguments) {
int size = arguments.getInt("-size", 240000);
std::cout << "Size: " << size << " kpc" << std::endl;
float h = arguments.getFloat("-h", 0.7);
std::cout << "h: " << h << std::endl;
size_t fileSizeKpc = arguments.getInt("-fileSize", 20000);
std::cout << "FileSize: " << fileSizeKpc << " kpc ";
size_t marginKpc = arguments.getInt("-margin", 500);
std::cout << "Margin: " << marginKpc << " kpc ";
std::string prefix = arguments.getString("-prefix", "sph");
bool verbose = arguments.hasFlag("-v");
size_t bins = size / fileSizeKpc;
Grid< std::vector<SmoothParticle> > grid(bins, size);
std::vector < std::string > files;
arguments.getVector("-f", files);
for (size_t iArg = 0; iArg < files.size(); iArg++) {
std::cout << "Open " << files[iArg] << " (" << (iArg + 1) << "/"
<< files.size() << ")" << std::endl;
GadgetFile file;
file.open(files[iArg]);
if (file.good() == false) {
std::cerr << "Failed to open file " << files[iArg] << std::endl;
return 1;
}
file.readHeader();
int pn = file.getHeader().particleNumberList[0];
std::cout << " Number of SmoothParticles: " << pn << std::endl;
std::cout << " Read POS block" << std::endl;
std::vector<float> pos;
if (file.readFloatBlock("POS ", pos) == false) {
std::cerr << "Failed to read POS block" << std::endl;
return 1;
}
std::cout << " Read BFLD block" << std::endl;
std::vector<float> bfld;
if (file.readFloatBlock("BFLD", bfld) == false) {
std::cerr << "Failed to read BFLD block" << std::endl;
return 1;
}
std::cout << " Read HSML block" << std::endl;
std::vector<float> hsml;
if (file.readFloatBlock("HSML", hsml) == false) {
std::cerr << "Failed to read HSML block" << std::endl;
return 1;
}
for (int iP = 0; iP < pn; iP++) {
SmoothParticle particle;
particle.smoothingLength = hsml[iP] / h;
particle.position.x = (pos[iP * 3] - size / 2) / h + size / 2;
particle.position.y = (pos[iP * 3 + 1] - size / 2) / h + size / 2;
particle.position.z = (pos[iP * 3 + 2] - size / 2) / h + size / 2;
float norm = 1.0 / M_PI / pow(particle.smoothingLength, 3);
particle.bfield.x = bfld[iP * 3] * norm;
particle.bfield.y = bfld[iP * 3 + 1] * norm;
particle.bfield.z = bfld[iP * 3 + 2] * norm;
Vector3f l = particle.position - Vector3f(
particle.smoothingLength * 2 + marginKpc);
l.clamp(0.0, size);
Vector3f u = particle.position + Vector3f(
particle.smoothingLength * 2 + marginKpc);
u.clamp(0.0, size);
Index3 lower, upper;
lower.x = (uint32_t) std::floor(l.x / fileSizeKpc);
lower.y = (uint32_t) std::floor(l.y / fileSizeKpc);
lower.z = (uint32_t) std::floor(l.z / fileSizeKpc);
upper.x = (uint32_t) std::ceil(u.x / fileSizeKpc);
upper.y = (uint32_t) std::ceil(u.y / fileSizeKpc);
upper.z = (uint32_t) std::ceil(u.z / fileSizeKpc);
if (verbose && (iP % 100000 ==0)) {
std::cout << "Pos:" << particle.position << std::endl;
std::cout << "SL:" << particle.smoothingLength << std::endl;
std::cout << "Lower:" << lower << std::endl;
std::cout << "Upper:" << upper << std::endl;
}
for (size_t x = lower.x; x < upper.x; x++)
for (size_t y = lower.y; y < upper.y; y++)
for (size_t z = lower.z; z < upper.z; z++)
grid.get(x, y, z).push_back(particle);
}
}
std::cout << "Write output" << std::endl;
for (size_t x = 0; x < bins; x++) {
if (verbose) {
std::cout << "x = " << x << std::endl;
}
for (size_t y = 0; y < bins; y++)
for (size_t z = 0; z < bins; z++) {
std::stringstream sstr;
sstr << prefix << "-" << x << "-" << y << "-" << z << ".raw";
std::ofstream out(sstr.str().c_str(),std::ofstream::binary);
uint32_t s = grid.get(x, y, z).size();
if (verbose)
std::cout << s << std::endl;
out.write((const char *)&s, sizeof(uint32_t));
out.write((const char *)&grid.get(x, y, z)[0], sizeof(SmoothParticle) * s);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "dg/analysis/PointsTo/Pointer.h"
#include "dg/analysis/PointsTo/PointsToSet.h"
#include "dg/analysis/PointsTo/PointerSubgraph.h"
#include "dg/analysis/PointsTo/PointerAnalysis.h"
namespace dg {
namespace analysis {
namespace pta {
// nodes representing NULL, unknown memory
// and invalidated memory
PSNode NULLPTR_LOC(PSNodeType::NULL_ADDR);
PSNode *NULLPTR = &NULLPTR_LOC;
PSNode UNKNOWN_MEMLOC(PSNodeType::UNKNOWN_MEM);
PSNode *UNKNOWN_MEMORY = &UNKNOWN_MEMLOC;
PSNode INVALIDATED_LOC(PSNodeType::INVALIDATED);
PSNode *INVALIDATED = &INVALIDATED_LOC;
// pointers to those memory
const Pointer PointerUnknown(UNKNOWN_MEMORY, Offset::UNKNOWN);
const Pointer PointerNull(NULLPTR, 0);
// Return true if it makes sense to dereference this pointer.
// PTA is over-approximation, so this is a filter.
static inline bool canBeDereferenced(const Pointer& ptr)
{
if (!ptr.isValid() || ptr.isInvalidated() || ptr.isUnknown())
return false;
// if the pointer points to a function, we can not dereference it
if (ptr.target->getType() == PSNodeType::FUNCTION)
return false;
return true;
}
bool PointerAnalysis::processLoad(PSNode *node)
{
bool changed = false;
PSNode *operand = node->getOperand(0);
if (operand->pointsTo.empty())
return error(operand, "Load's operand has no points-to set");
for (const Pointer& ptr : operand->pointsTo) {
if (ptr.isUnknown()) {
// load from unknown pointer yields unknown pointer
changed |= node->addPointsTo(UNKNOWN_MEMORY);
continue;
}
if (!canBeDereferenced(ptr))
continue;
// find memory objects holding relevant points-to
// information
std::vector<MemoryObject *> objects;
getMemoryObjects(node, ptr, objects);
PSNodeAlloc *target = PSNodeAlloc::get(ptr.target);
assert(target && "Target is not memory allocation");
// no objects found for this target? That is
// load from unknown memory
if (objects.empty()) {
if (target->isZeroInitialized())
// if the memory is zero initialized, then everything
// is fine, we add nullptr
changed |= node->addPointsTo(NULLPTR);
else
changed |= errorEmptyPointsTo(node, target);
continue;
}
for (MemoryObject *o : objects) {
// is the offset to the memory unknown?
// In that case everything can be referenced,
// so we need to copy the whole points-to
if (ptr.offset.isUnknown()) {
// we should load from memory that has
// no pointers in it - it may be an error
// FIXME: don't duplicate the code
if (o->pointsTo.empty()) {
if (target->isZeroInitialized())
changed |= node->addPointsTo(NULLPTR);
else if (objects.size() == 1)
changed |= errorEmptyPointsTo(node, target);
}
// we have some pointers - copy them all,
// since the offset is unknown
for (auto& it : o->pointsTo) {
for (const Pointer &p : it.second) {
changed |= node->addPointsTo(p);
}
}
// this is all that we can do here...
continue;
}
// load from empty points-to set
// - that is load from unknown memory
if (!o->pointsTo.count(ptr.offset)) {
// if the memory is zero initialized, then everything
// is fine, we add nullptr
if (target->isZeroInitialized())
changed |= node->addPointsTo(NULLPTR);
// if we don't have a definition even with unknown offset
// it is an error
// FIXME: don't triplicate the code!
else if (!o->pointsTo.count(Offset::UNKNOWN))
changed |= errorEmptyPointsTo(node, target);
} else {
// we have pointers on that memory, so we can
// do the work
for (const Pointer& memptr : o->pointsTo[ptr.offset])
changed |= node->addPointsTo(memptr);
}
// plus always add the pointers at unknown offset,
// since these can be what we need too
if (o->pointsTo.count(Offset::UNKNOWN)) {
for (const Pointer& memptr : o->pointsTo[Offset::UNKNOWN]) {
changed |= node->addPointsTo(memptr);
}
}
}
}
return changed;
}
bool PointerAnalysis::processMemcpy(PSNode *node)
{
bool changed = false;
PSNodeMemcpy *memcpy = PSNodeMemcpy::get(node);
PSNode *srcNode = memcpy->getSource();
PSNode *destNode = memcpy->getDestination();
std::vector<MemoryObject *> srcObjects;
std::vector<MemoryObject *> destObjects;
// gather srcNode pointer objects
for (const Pointer& ptr : srcNode->pointsTo) {
assert(ptr.target && "Got nullptr as target");
if (!canBeDereferenced(ptr))
continue;
srcObjects.clear();
getMemoryObjects(node, ptr, srcObjects);
if (srcObjects.empty()){
abort();
return changed;
}
// gather destNode objects
for (const Pointer& dptr : destNode->pointsTo) {
assert(dptr.target && "Got nullptr as target");
if (!canBeDereferenced(dptr))
continue;
destObjects.clear();
getMemoryObjects(node, dptr, destObjects);
if (destObjects.empty()) {
abort();
return changed;
}
changed |= processMemcpy(srcObjects, destObjects,
ptr, dptr,
memcpy->getLength());
}
}
return changed;
}
bool PointerAnalysis::processMemcpy(std::vector<MemoryObject *>& srcObjects,
std::vector<MemoryObject *>& destObjects,
const Pointer& sptr, const Pointer& dptr,
Offset len)
{
bool changed = false;
Offset srcOffset = sptr.offset;
Offset destOffset = dptr.offset;
assert(*len > 0 && "Memcpy of length 0");
PSNodeAlloc *sourceAlloc = PSNodeAlloc::get(sptr.target);
assert(sourceAlloc && "Pointer's target in memcpy is not an allocation");
PSNodeAlloc *destAlloc = PSNodeAlloc::get(dptr.target);
assert(destAlloc && "Pointer's target in memcpy is not an allocation");
// set to true if the contents of destination memory
// can contain null
bool contains_null_somewhere = false;
// if the source is zero initialized, we may copy null pointer
if (sourceAlloc->isZeroInitialized()) {
// if we really copy the whole object, just set it zero-initialized
if ((sourceAlloc->getSize() != Offset::UNKNOWN) &&
(sourceAlloc->getSize() == destAlloc->getSize()) &&
len == sourceAlloc->getSize() && sptr.offset == 0) {
destAlloc->setZeroInitialized();
} else {
// we could analyze in a lot of cases where
// shoulde be stored the nullptr, but the question
// is whether it is worth it... For now, just say
// that somewhere may be null in the destination
contains_null_somewhere = true;
}
}
for (MemoryObject *destO : destObjects) {
if (contains_null_somewhere)
changed |= destO->addPointsTo(Offset::UNKNOWN, NULLPTR);
// copy every pointer from srcObjects that is in
// the range to destination's objects
for (MemoryObject *so : srcObjects) {
for (auto& src : so->pointsTo) { // src.first is offset,
// src.second is a PointToSet
// if the offset is inbound of the copied memory
// or we copy from unknown offset, or this pointer
// is on unknown offset, copy this pointer
if (src.first.isUnknown() ||
srcOffset.isUnknown() ||
(srcOffset <= src.first &&
(len.isUnknown() ||
*src.first - *srcOffset < *len))) {
// copy the pointer, but shift it by the offsets
// we are working with
if (!src.first.isUnknown() && !srcOffset.isUnknown() &&
!destOffset.isUnknown()) {
// check that new offset does not overflow Offset::UNKNOWN
if (Offset::UNKNOWN - *destOffset <= *src.first - *srcOffset) {
changed |= destO->addPointsTo(Offset::UNKNOWN, src.second);
continue;
}
Offset newOff = *src.first - *srcOffset + *destOffset;
if (newOff >= destO->node->getSize() ||
newOff >= options.fieldSensitivity) {
changed |= destO->addPointsTo(Offset::UNKNOWN, src.second);
} else {
changed |= destO->addPointsTo(newOff, src.second);
}
} else {
changed |= destO->addPointsTo(Offset::UNKNOWN, src.second);
}
}
}
}
}
return changed;
}
bool PointerAnalysis::processGep(PSNode *node) {
bool changed = false;
PSNodeGep *gep = PSNodeGep::get(node);
assert(gep && "Non-GEP given");
for (const Pointer& ptr : gep->getSource()->pointsTo) {
Offset::type new_offset;
if (ptr.offset.isUnknown() || gep->getOffset().isUnknown())
// set it like this to avoid overflow when adding
new_offset = Offset::UNKNOWN;
else
new_offset = *ptr.offset + *gep->getOffset();
// in the case PSNodeType::the memory has size 0, then every pointer
// will have unknown offset with the exception that it points
// to the begining of the memory - therefore make 0 exception
if ((new_offset == 0 || new_offset < ptr.target->getSize())
&& new_offset < *options.fieldSensitivity)
changed |= node->addPointsTo(ptr.target, new_offset);
else
changed |= node->addPointsTo(ptr.target, Offset::UNKNOWN);
}
return changed;
}
bool PointerAnalysis::processNode(PSNode *node)
{
bool changed = false;
std::vector<MemoryObject *> objects;
#ifdef DEBUG_ENABLED
size_t prev_size = node->pointsTo.size();
#endif
switch(node->type) {
case PSNodeType::LOAD:
changed |= processLoad(node);
break;
case PSNodeType::STORE:
for (const Pointer& ptr : node->getOperand(1)->pointsTo) {
assert(ptr.target && "Got nullptr as target");
if (!canBeDereferenced(ptr))
continue;
objects.clear();
getMemoryObjects(node, ptr, objects);
for (MemoryObject *o : objects) {
for (const Pointer& to : node->getOperand(0)->pointsTo) {
changed |= o->addPointsTo(ptr.offset, to);
}
}
}
break;
case PSNodeType::INVALIDATE_OBJECT:
case PSNodeType::FREE:
break;
case PSNodeType::INVALIDATE_LOCALS:
// FIXME: get rid of this type of node
// (make the analysis extendable and move it there)
node->setParent(node->getOperand(0)->getSingleSuccessor()->getParent());
break;
case PSNodeType::GEP:
changed |= processGep(node);
break;
case PSNodeType::CAST:
// cast only copies the pointers
for (const Pointer& ptr : node->getOperand(0)->pointsTo)
changed |= node->addPointsTo(ptr);
break;
case PSNodeType::CONSTANT:
// maybe warn? It has no sense to insert the constants into the graph.
// On the other hand it is harmless. We can at least check if it is
// correctly initialized 8-)
assert(node->pointsTo.size() == 1
&& "Constant should have exactly one pointer");
break;
case PSNodeType::CALL_RETURN:
if (options.invalidateNodes) {
for (PSNode *op : node->operands) {
for (const Pointer& ptr : op->pointsTo) {
if (!canBeDereferenced(ptr))
continue;
PSNodeAlloc *target = PSNodeAlloc::get(ptr.target);
assert(target && "Target is not memory allocation");
if (!target->isHeap() && !target->isGlobal()) {
changed |= node->addPointsTo(INVALIDATED);
}
}
}
}
// fall-through
case PSNodeType::RETURN:
// gather pointers returned from subprocedure - the same way
// as PHI works
case PSNodeType::PHI:
for (PSNode *op : node->operands)
changed |= node->addPointsTo(op->pointsTo);
break;
case PSNodeType::CALL_FUNCPTR:
// call via function pointer:
// first gather the pointers that can be used to the
// call and if something changes, let backend take some action
// (for example build relevant subgraph)
for (const Pointer& ptr : node->getOperand(0)->pointsTo) {
// do not add pointers that do not point to functions
// (but do not do that when we are looking for invalidated
// memory as this may lead to undefined behavior)
if (!options.invalidateNodes
&& ptr.target->getType() != PSNodeType::FUNCTION)
continue;
if (node->addPointsTo(ptr)) {
changed = true;
if (ptr.isValid() && !ptr.isInvalidated()) {
if (functionPointerCall(node, ptr.target))
recomputeSCCs();
} else {
error(node, "Calling invalid pointer as a function!");
continue;
}
}
}
break;
case PSNodeType::MEMCPY:
changed |= processMemcpy(node);
break;
case PSNodeType::ALLOC:
case PSNodeType::DYN_ALLOC:
case PSNodeType::FUNCTION:
// these two always points to itself
assert(node->doesPointsTo(node, 0));
assert(node->pointsTo.size() == 1);
case PSNodeType::CALL:
case PSNodeType::ENTRY:
case PSNodeType::NOOP:
// just no op
break;
default:
assert(0 && "Unknown type");
}
#ifdef DEBUG_ENABLED
// the change of points-to set is not the only
// change that can happen, so we don't use it as an
// indicator and we use the 'changed' variable instead.
// However, this assertion must hold:
assert((node->pointsTo.size() == prev_size || changed)
&& "BUG: Did not set change but changed points-to sets");
#endif
return changed;
}
void PointerAnalysis::sanityCheck() {
#ifndef NDEBUG
assert(NULLPTR->pointsTo.size() == 1
&& "Null has been assigned a pointer");
assert(NULLPTR->doesPointsTo(NULLPTR)
&& "Null points to a different location");
assert(UNKNOWN_MEMORY->pointsTo.size() == 1
&& "Unknown memory has been assigned a pointer");
assert(UNKNOWN_MEMORY->doesPointsTo(UNKNOWN_MEMORY, Offset::UNKNOWN)
&& "Unknown memory has been assigned a pointer");
assert(INVALIDATED->pointsTo.empty()
&& "Unknown memory has been assigned a pointer");
auto nodes = PS->getNodes(PS->getRoot());
std::set<unsigned> ids;
for (auto nd : nodes) {
assert(ids.insert(nd->getID()).second && "Duplicated node ID");
if (nd->getType() == PSNodeType::ALLOC) {
assert(nd->pointsTo.size() == 1
&& "Alloc does not point only to itself");
assert(nd->doesPointsTo(nd, 0)
&& "Alloc does not point only to itself");
}
}
#endif // not NDEBUG
}
} // namespace pta
} // namespace analysis
} // namespace dg
<commit_msg>PTA: use set operations instead of iterating over the sets<commit_after>#include "dg/analysis/PointsTo/Pointer.h"
#include "dg/analysis/PointsTo/PointsToSet.h"
#include "dg/analysis/PointsTo/PointerSubgraph.h"
#include "dg/analysis/PointsTo/PointerAnalysis.h"
namespace dg {
namespace analysis {
namespace pta {
// nodes representing NULL, unknown memory
// and invalidated memory
PSNode NULLPTR_LOC(PSNodeType::NULL_ADDR);
PSNode *NULLPTR = &NULLPTR_LOC;
PSNode UNKNOWN_MEMLOC(PSNodeType::UNKNOWN_MEM);
PSNode *UNKNOWN_MEMORY = &UNKNOWN_MEMLOC;
PSNode INVALIDATED_LOC(PSNodeType::INVALIDATED);
PSNode *INVALIDATED = &INVALIDATED_LOC;
// pointers to those memory
const Pointer PointerUnknown(UNKNOWN_MEMORY, Offset::UNKNOWN);
const Pointer PointerNull(NULLPTR, 0);
// Return true if it makes sense to dereference this pointer.
// PTA is over-approximation, so this is a filter.
static inline bool canBeDereferenced(const Pointer& ptr)
{
if (!ptr.isValid() || ptr.isInvalidated() || ptr.isUnknown())
return false;
// if the pointer points to a function, we can not dereference it
if (ptr.target->getType() == PSNodeType::FUNCTION)
return false;
return true;
}
bool PointerAnalysis::processLoad(PSNode *node)
{
bool changed = false;
PSNode *operand = node->getOperand(0);
if (operand->pointsTo.empty())
return error(operand, "Load's operand has no points-to set");
for (const Pointer& ptr : operand->pointsTo) {
if (ptr.isUnknown()) {
// load from unknown pointer yields unknown pointer
changed |= node->addPointsTo(UNKNOWN_MEMORY);
continue;
}
if (!canBeDereferenced(ptr))
continue;
// find memory objects holding relevant points-to
// information
std::vector<MemoryObject *> objects;
getMemoryObjects(node, ptr, objects);
PSNodeAlloc *target = PSNodeAlloc::get(ptr.target);
assert(target && "Target is not memory allocation");
// no objects found for this target? That is
// load from unknown memory
if (objects.empty()) {
if (target->isZeroInitialized())
// if the memory is zero initialized, then everything
// is fine, we add nullptr
changed |= node->addPointsTo(NULLPTR);
else
changed |= errorEmptyPointsTo(node, target);
continue;
}
for (MemoryObject *o : objects) {
// is the offset to the memory unknown?
// In that case everything can be referenced,
// so we need to copy the whole points-to
if (ptr.offset.isUnknown()) {
// we should load from memory that has
// no pointers in it - it may be an error
// FIXME: don't duplicate the code
if (o->pointsTo.empty()) {
if (target->isZeroInitialized())
changed |= node->addPointsTo(NULLPTR);
else if (objects.size() == 1)
changed |= errorEmptyPointsTo(node, target);
}
// we have some pointers - copy them all,
// since the offset is unknown
for (auto& it : o->pointsTo) {
changed |= node->addPointsTo(it.second);
}
// this is all that we can do here...
continue;
}
// load from empty points-to set
// - that is load from unknown memory
auto it = o->pointsTo.find(ptr.offset);
if (it == o->pointsTo.end()) {
// if the memory is zero initialized, then everything
// is fine, we add nullptr
if (target->isZeroInitialized())
changed |= node->addPointsTo(NULLPTR);
// if we don't have a definition even with unknown offset
// it is an error
// FIXME: don't triplicate the code!
else if (!o->pointsTo.count(Offset::UNKNOWN))
changed |= errorEmptyPointsTo(node, target);
} else {
// we have pointers on that memory, so we can
// do the work
changed |= node->addPointsTo(it->second);
}
// plus always add the pointers at unknown offset,
// since these can be what we need too
it = o->pointsTo.find(Offset::UNKNOWN);
if (it != o->pointsTo.end()) {
changed |= node->addPointsTo(it->second);
}
}
}
return changed;
}
bool PointerAnalysis::processMemcpy(PSNode *node)
{
bool changed = false;
PSNodeMemcpy *memcpy = PSNodeMemcpy::get(node);
PSNode *srcNode = memcpy->getSource();
PSNode *destNode = memcpy->getDestination();
std::vector<MemoryObject *> srcObjects;
std::vector<MemoryObject *> destObjects;
// gather srcNode pointer objects
for (const Pointer& ptr : srcNode->pointsTo) {
assert(ptr.target && "Got nullptr as target");
if (!canBeDereferenced(ptr))
continue;
srcObjects.clear();
getMemoryObjects(node, ptr, srcObjects);
if (srcObjects.empty()){
abort();
return changed;
}
// gather destNode objects
for (const Pointer& dptr : destNode->pointsTo) {
assert(dptr.target && "Got nullptr as target");
if (!canBeDereferenced(dptr))
continue;
destObjects.clear();
getMemoryObjects(node, dptr, destObjects);
if (destObjects.empty()) {
abort();
return changed;
}
changed |= processMemcpy(srcObjects, destObjects,
ptr, dptr,
memcpy->getLength());
}
}
return changed;
}
bool PointerAnalysis::processMemcpy(std::vector<MemoryObject *>& srcObjects,
std::vector<MemoryObject *>& destObjects,
const Pointer& sptr, const Pointer& dptr,
Offset len)
{
bool changed = false;
Offset srcOffset = sptr.offset;
Offset destOffset = dptr.offset;
assert(*len > 0 && "Memcpy of length 0");
PSNodeAlloc *sourceAlloc = PSNodeAlloc::get(sptr.target);
assert(sourceAlloc && "Pointer's target in memcpy is not an allocation");
PSNodeAlloc *destAlloc = PSNodeAlloc::get(dptr.target);
assert(destAlloc && "Pointer's target in memcpy is not an allocation");
// set to true if the contents of destination memory
// can contain null
bool contains_null_somewhere = false;
// if the source is zero initialized, we may copy null pointer
if (sourceAlloc->isZeroInitialized()) {
// if we really copy the whole object, just set it zero-initialized
if ((sourceAlloc->getSize() != Offset::UNKNOWN) &&
(sourceAlloc->getSize() == destAlloc->getSize()) &&
len == sourceAlloc->getSize() && sptr.offset == 0) {
destAlloc->setZeroInitialized();
} else {
// we could analyze in a lot of cases where
// shoulde be stored the nullptr, but the question
// is whether it is worth it... For now, just say
// that somewhere may be null in the destination
contains_null_somewhere = true;
}
}
for (MemoryObject *destO : destObjects) {
if (contains_null_somewhere)
changed |= destO->addPointsTo(Offset::UNKNOWN, NULLPTR);
// copy every pointer from srcObjects that is in
// the range to destination's objects
for (MemoryObject *so : srcObjects) {
for (auto& src : so->pointsTo) { // src.first is offset,
// src.second is a PointToSet
// if the offset is inbound of the copied memory
// or we copy from unknown offset, or this pointer
// is on unknown offset, copy this pointer
if (src.first.isUnknown() ||
srcOffset.isUnknown() ||
(srcOffset <= src.first &&
(len.isUnknown() ||
*src.first - *srcOffset < *len))) {
// copy the pointer, but shift it by the offsets
// we are working with
if (!src.first.isUnknown() && !srcOffset.isUnknown() &&
!destOffset.isUnknown()) {
// check that new offset does not overflow Offset::UNKNOWN
if (Offset::UNKNOWN - *destOffset <= *src.first - *srcOffset) {
changed |= destO->addPointsTo(Offset::UNKNOWN, src.second);
continue;
}
Offset newOff = *src.first - *srcOffset + *destOffset;
if (newOff >= destO->node->getSize() ||
newOff >= options.fieldSensitivity) {
changed |= destO->addPointsTo(Offset::UNKNOWN, src.second);
} else {
changed |= destO->addPointsTo(newOff, src.second);
}
} else {
changed |= destO->addPointsTo(Offset::UNKNOWN, src.second);
}
}
}
}
}
return changed;
}
bool PointerAnalysis::processGep(PSNode *node) {
bool changed = false;
PSNodeGep *gep = PSNodeGep::get(node);
assert(gep && "Non-GEP given");
for (const Pointer& ptr : gep->getSource()->pointsTo) {
Offset::type new_offset;
if (ptr.offset.isUnknown() || gep->getOffset().isUnknown())
// set it like this to avoid overflow when adding
new_offset = Offset::UNKNOWN;
else
new_offset = *ptr.offset + *gep->getOffset();
// in the case PSNodeType::the memory has size 0, then every pointer
// will have unknown offset with the exception that it points
// to the begining of the memory - therefore make 0 exception
if ((new_offset == 0 || new_offset < ptr.target->getSize())
&& new_offset < *options.fieldSensitivity)
changed |= node->addPointsTo(ptr.target, new_offset);
else
changed |= node->addPointsTo(ptr.target, Offset::UNKNOWN);
}
return changed;
}
bool PointerAnalysis::processNode(PSNode *node)
{
bool changed = false;
std::vector<MemoryObject *> objects;
#ifdef DEBUG_ENABLED
size_t prev_size = node->pointsTo.size();
#endif
switch(node->type) {
case PSNodeType::LOAD:
changed |= processLoad(node);
break;
case PSNodeType::STORE:
for (const Pointer& ptr : node->getOperand(1)->pointsTo) {
assert(ptr.target && "Got nullptr as target");
if (!canBeDereferenced(ptr))
continue;
objects.clear();
getMemoryObjects(node, ptr, objects);
for (MemoryObject *o : objects) {
changed |= o->addPointsTo(ptr.offset,
node->getOperand(0)->pointsTo);
}
}
break;
case PSNodeType::INVALIDATE_OBJECT:
case PSNodeType::FREE:
break;
case PSNodeType::INVALIDATE_LOCALS:
// FIXME: get rid of this type of node
// (make the analysis extendable and move it there)
node->setParent(node->getOperand(0)->getSingleSuccessor()->getParent());
break;
case PSNodeType::GEP:
changed |= processGep(node);
break;
case PSNodeType::CAST:
// cast only copies the pointers
changed |= node->addPointsTo(node->getOperand(0)->pointsTo);
break;
case PSNodeType::CONSTANT:
// maybe warn? It has no sense to insert the constants into the graph.
// On the other hand it is harmless. We can at least check if it is
// correctly initialized 8-)
assert(node->pointsTo.size() == 1
&& "Constant should have exactly one pointer");
break;
case PSNodeType::CALL_RETURN:
if (options.invalidateNodes) {
for (PSNode *op : node->operands) {
for (const Pointer& ptr : op->pointsTo) {
if (!canBeDereferenced(ptr))
continue;
PSNodeAlloc *target = PSNodeAlloc::get(ptr.target);
assert(target && "Target is not memory allocation");
if (!target->isHeap() && !target->isGlobal()) {
changed |= node->addPointsTo(INVALIDATED);
}
}
}
}
// fall-through
case PSNodeType::RETURN:
// gather pointers returned from subprocedure - the same way
// as PHI works
case PSNodeType::PHI:
for (PSNode *op : node->operands)
changed |= node->addPointsTo(op->pointsTo);
break;
case PSNodeType::CALL_FUNCPTR:
// call via function pointer:
// first gather the pointers that can be used to the
// call and if something changes, let backend take some action
// (for example build relevant subgraph)
for (const Pointer& ptr : node->getOperand(0)->pointsTo) {
// do not add pointers that do not point to functions
// (but do not do that when we are looking for invalidated
// memory as this may lead to undefined behavior)
if (!options.invalidateNodes
&& ptr.target->getType() != PSNodeType::FUNCTION)
continue;
if (node->addPointsTo(ptr)) {
changed = true;
if (ptr.isValid() && !ptr.isInvalidated()) {
if (functionPointerCall(node, ptr.target))
recomputeSCCs();
} else {
error(node, "Calling invalid pointer as a function!");
continue;
}
}
}
break;
case PSNodeType::MEMCPY:
changed |= processMemcpy(node);
break;
case PSNodeType::ALLOC:
case PSNodeType::DYN_ALLOC:
case PSNodeType::FUNCTION:
// these two always points to itself
assert(node->doesPointsTo(node, 0));
assert(node->pointsTo.size() == 1);
case PSNodeType::CALL:
case PSNodeType::ENTRY:
case PSNodeType::NOOP:
// just no op
break;
default:
assert(0 && "Unknown type");
}
#ifdef DEBUG_ENABLED
// the change of points-to set is not the only
// change that can happen, so we don't use it as an
// indicator and we use the 'changed' variable instead.
// However, this assertion must hold:
assert((node->pointsTo.size() == prev_size || changed)
&& "BUG: Did not set change but changed points-to sets");
#endif
return changed;
}
void PointerAnalysis::sanityCheck() {
#ifndef NDEBUG
assert(NULLPTR->pointsTo.size() == 1
&& "Null has been assigned a pointer");
assert(NULLPTR->doesPointsTo(NULLPTR)
&& "Null points to a different location");
assert(UNKNOWN_MEMORY->pointsTo.size() == 1
&& "Unknown memory has been assigned a pointer");
assert(UNKNOWN_MEMORY->doesPointsTo(UNKNOWN_MEMORY, Offset::UNKNOWN)
&& "Unknown memory has been assigned a pointer");
assert(INVALIDATED->pointsTo.empty()
&& "Unknown memory has been assigned a pointer");
auto nodes = PS->getNodes(PS->getRoot());
std::set<unsigned> ids;
for (auto nd : nodes) {
assert(ids.insert(nd->getID()).second && "Duplicated node ID");
if (nd->getType() == PSNodeType::ALLOC) {
assert(nd->pointsTo.size() == 1
&& "Alloc does not point only to itself");
assert(nd->doesPointsTo(nd, 0)
&& "Alloc does not point only to itself");
}
}
#endif // not NDEBUG
}
} // namespace pta
} // namespace analysis
} // namespace dg
<|endoftext|> |
<commit_before>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb/utilities.hpp>
// FIXME: I suggest we enable this only if
// TIGHTDB_VISUAL_LEAK_DETECTOR is defined. It is problematic that we
// cannot run the unit tests witout installing this (and indeed
// installing it in that particular location)
/*
#if defined(_MSC_VER) && defined(_DEBUG)
# include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
*/
using namespace std;
using namespace UnitTest;
namespace {
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
}
};
} // anonymous namespace
int main(int argc, char* argv[])
{
bool const no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exit-staus") == 0;
#ifdef TIGHTDB_DEBUG
cerr << "Running Debug unit tests\n";
#else
cerr << "Running Release unit tests\n";
#endif
cerr << "MAX_LIST_SIZE = " << MAX_LIST_SIZE << "\n";
#ifdef TIGHTDB_COMPILER_SSE
cerr << "Compiler supported SSE (auto detect): Yes\n";
#else
cerr << "Compiler supported SSE (auto detect): No\n";
#endif
cerr << "This CPU supports SSE (auto detect): " << (tightdb::cpuid_sse<42>() ? "4.2" : (tightdb::cpuid_sse<30>() ? "3.0" : "None"));
cerr << "\n\n";
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
#ifdef _MSC_VER
getchar(); // wait for key
#endif
return no_error_exit_staus ? 0 : res;
}
<commit_msg>Disable reporting of unit test names as they run<commit_after>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb/utilities.hpp>
// FIXME: I suggest we enable this only if
// TIGHTDB_VISUAL_LEAK_DETECTOR is defined. It is problematic that we
// cannot run the unit tests witout installing this (and indeed
// installing it in that particular location)
/*
#if defined(_MSC_VER) && defined(_DEBUG)
# include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
*/
using namespace std;
using namespace UnitTest;
namespace {
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
static_cast<void>(test);
// cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
}
};
} // anonymous namespace
int main(int argc, char* argv[])
{
bool const no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exit-staus") == 0;
#ifdef TIGHTDB_DEBUG
cerr << "Running Debug unit tests\n";
#else
cerr << "Running Release unit tests\n";
#endif
cerr << "MAX_LIST_SIZE = " << MAX_LIST_SIZE << "\n";
#ifdef TIGHTDB_COMPILER_SSE
cerr << "Compiler supported SSE (auto detect): Yes\n";
#else
cerr << "Compiler supported SSE (auto detect): No\n";
#endif
cerr << "This CPU supports SSE (auto detect): " << (tightdb::cpuid_sse<42>() ? "4.2" : (tightdb::cpuid_sse<30>() ? "3.0" : "None"));
cerr << "\n\n";
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
#ifdef _MSC_VER
getchar(); // wait for key
#endif
return no_error_exit_staus ? 0 : res;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
BDD representState(Cudd manager, std::vector<bool> values) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(values); it != std::end(values); ++it) {
BDD var = manager.bddVar(i);
if (!*it) {
var = !var;
}
bdd = var * bdd;
i++;
}
return bdd;
}
BDD representCnf(Cudd manager, std::vector<int> cnf) {
BDD bdd = manager.bddZero();
for (auto it = std::begin(cnf); it != std::end(cnf); ++it) {
BDD var = manager.bddVar(abs(*it));
if (*it < 0) {
var = !var;
}
bdd = var + bdd;
}
return bdd;
}
BDD representUpdateFunction(Cudd manager, std::vector<std::vector<int>> cnfs) {
BDD bdd = manager.bddOne();
for (auto it = std::begin(cnfs); it != std::end(cnfs); ++it) {
bdd = bdd * representCnf(manager, *it);
}
return bdd;
}
BDD logicalEquivalence(BDD a, BDD b) {
return (a * b) + ((!a) * (!b));
}
BDD representSyncTransitionRelation(Cudd manager, std::vector<std::vector<std::vector<int>>> network) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD f = representUpdateFunction(manager, *it);
BDD vPrime = manager.bddVar(network.size() + i);
BDD transition = logicalEquivalence(vPrime, f);
bdd = transition * bdd;
i++;
}
return bdd;
}
BDD otherVarsDoNotChange(Cudd manager, int i, int numVars) {
BDD bdd = manager.bddOne();
for (int j = 0; j < numVars; j++) {
if (j != i) {
BDD v = manager.bddVar(j);
BDD vPrime = manager.bddVar(numVars + j);
bdd = bdd * logicalEquivalence(v, vPrime);
}
}
return bdd;
}
BDD representAsyncTransitionRelation(Cudd manager, std::vector<std::vector<std::vector<int>>> network) {
BDD fixpoint = manager.bddOne();
for (int i = 0; i < network.size(); i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
fixpoint = fixpoint * logicalEquivalence(v, vPrime);
}
BDD bdd = manager.bddZero();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
BDD vChanges = !logicalEquivalence(v, vPrime);
BDD f = representUpdateFunction(manager, *it);
BDD update = logicalEquivalence(vPrime, f) * otherVarsDoNotChange(manager, i, network.size());
BDD transition = update * (fixpoint + vChanges);
bdd = transition + bdd;
i++;
}
return bdd;
}
BDD renameRemovingPrimes(BDD bdd, int numVars) {
int *permute = new int[numVars * 2];
for (int i = 0; i < numVars; i++) {
permute[i] = i;
permute[i + numVars] = i;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD nonPrimeVariables(Cudd manager, int numVars) {
return representState(manager, std::vector<bool>(numVars, true));
}
BDD primeVariables(Cudd manager, int numVars) {
BDD bdd = manager.bddOne();
for (int i = numVars; i < numVars * 2; i++) {
BDD var = manager.bddVar(i);
bdd = var * bdd;
}
return bdd;
}
BDD immediateSuccessorStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
BDD bdd = transitionBdd * valuesBdd;
bdd = bdd.ExistAbstract(nonPrimeVariables(manager, numVars));
bdd = renameRemovingPrimes(bdd, numVars);
return bdd;
}
BDD forwardReachableStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediateSuccessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD renameAddingPrimes(BDD bdd, int numVars) {
int *permute = new int[numVars * 2];
for (int i = 0; i < numVars; i++) {
permute[i] = i + numVars;
permute[i + numVars] = i + numVars;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD immediatePredecessorStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
valuesBdd = renameAddingPrimes(valuesBdd, numVars);
BDD bdd = transitionBdd * valuesBdd;
bdd = bdd.ExistAbstract(primeVariables(manager, numVars));
return bdd;
}
BDD backwardReachableStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediatePredecessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD randomState(Cudd manager, BDD S, int numVars) {
char *out = new char[numVars * 2];
S.PickOneCube(out);
std::vector<bool> values;
for (int i = 0; i < numVars; i++) {
if (out[i] == 0) {
values.push_back(false);
}
else {
values.push_back(true);
}
}
delete[] out;
return representState(manager, values);
}
std::vector<BDD> attractors(Cudd manager, BDD transitionBdd, int numVars) {
std::vector<BDD> attractors = std::vector<BDD>();
BDD S = manager.bddOne();
while (S != manager.bddZero()) {
BDD s = randomState(manager, S, numVars);
BDD fr = forwardReachableStates(manager, transitionBdd, s, numVars);
BDD br = backwardReachableStates(manager, transitionBdd, s, numVars);
if ((fr * !br) == manager.bddZero()) {
attractors.push_back(fr);
}
S = S * !(s + br);
}
return attractors;
}
int main() {
//Cebpa, Pu.1, Gata2, Gata1, Fog1, EKLF, Fli1, Scl, cJun, EgrNab, Gfi1
std::vector<bool> cmpInitial = { true, true, true, false, false, false, false, false, false, false, false };
std::vector<std::vector<int>> cebpa = { { 0 },{ -7 },{ -3, -4 } };
std::vector<std::vector<int>> pu1 = { { 0, 1 },{ -2 },{ -3 } };
std::vector<std::vector<int>> gata2 = { { 3 },{ -1 },{ -3, -4 } };
std::vector<std::vector<int>> gata1 = { { 2, 3, 6 },{ -1 } };
std::vector<std::vector<int>> fog1 = { { 3 } };
std::vector<std::vector<int>> eklf = { { 3 },{ -6 } };
std::vector<std::vector<int>> fli1 = { { 3 },{ -5 } };
std::vector<std::vector<int>> scl = { { 3 },{ -1 } };
std::vector<std::vector<int>> cJun = { { 1 },{ -10 } };
std::vector<std::vector<int>> egrNab = { { 1 },{ 8 },{ -10 } };
std::vector<std::vector<int>> gfi1 = { { 0 },{ -9 } };
std::vector<std::vector<std::vector<int>>> cmp = { cebpa, pu1, gata2, gata1, fog1, eklf, fli1, scl, cJun, egrNab, gfi1 };
Cudd manager(0, 0);
BDD initialStateBdd = representState(manager, cmpInitial);
BDD transitionBddA = representAsyncTransitionRelation(manager, cmp);
BDD statespace = forwardReachableStates(manager, transitionBddA, initialStateBdd, cmpInitial.size());
std::cout << statespace.CountMinterm(cmpInitial.size());
std::cout << "\n";
std::vector<BDD> attsA = attractors(manager, transitionBddA, cmpInitial.size());
for (BDD attractor : attsA) {
attractor.PrintMinterm();
std::cout << "\n";
}
std::cout << "--------------------------------\n";
BDD transitionBddS = representSyncTransitionRelation(manager, cmp);
std::vector<BDD> attsS = attractors(manager, transitionBddS, cmpInitial.size());
for (BDD attractor : attsS) {
attractor.PrintMinterm();
std::cout << "\n";
}
return 0;
}
<commit_msg>Minor syntax changes<commit_after>#include "stdafx.h"
BDD representState(Cudd manager, std::vector<bool> values) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(values); it != std::end(values); ++it) {
BDD var = manager.bddVar(i);
if (!*it) {
var = !var;
}
bdd = var * bdd;
i++;
}
return bdd;
}
BDD representCnf(Cudd manager, std::vector<int> cnf) {
BDD bdd = manager.bddZero();
for (auto it = std::begin(cnf); it != std::end(cnf); ++it) {
BDD var = manager.bddVar(abs(*it));
if (*it < 0) {
var = !var;
}
bdd = var + bdd;
}
return bdd;
}
BDD representUpdateFunction(Cudd manager, std::vector<std::vector<int>> cnfs) {
BDD bdd = manager.bddOne();
for (auto it = std::begin(cnfs); it != std::end(cnfs); ++it) {
bdd = bdd * representCnf(manager, *it);
}
return bdd;
}
BDD logicalEquivalence(BDD a, BDD b) {
return (a * b) + ((!a) * (!b));
}
BDD representSyncTransitionRelation(Cudd manager, std::vector<std::vector<std::vector<int>>> network) {
BDD bdd = manager.bddOne();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD f = representUpdateFunction(manager, *it);
BDD vPrime = manager.bddVar(network.size() + i);
BDD transition = logicalEquivalence(vPrime, f);
bdd = transition * bdd;
i++;
}
return bdd;
}
BDD otherVarsDoNotChange(Cudd manager, int i, int numVars) {
BDD bdd = manager.bddOne();
for (int j = 0; j < numVars; j++) {
if (j != i) {
BDD v = manager.bddVar(j);
BDD vPrime = manager.bddVar(numVars + j);
bdd = bdd * logicalEquivalence(v, vPrime);
}
}
return bdd;
}
BDD representAsyncTransitionRelation(Cudd manager, std::vector<std::vector<std::vector<int>>> network) {
BDD fixpoint = manager.bddOne();
for (int i = 0; i < network.size(); i++) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
fixpoint = fixpoint * logicalEquivalence(v, vPrime);
}
BDD bdd = manager.bddZero();
int i = 0;
for (auto it = std::begin(network); it != std::end(network); ++it) {
BDD v = manager.bddVar(i);
BDD vPrime = manager.bddVar(network.size() + i);
BDD vChanges = !logicalEquivalence(v, vPrime);
BDD f = representUpdateFunction(manager, *it);
BDD update = logicalEquivalence(vPrime, f) * otherVarsDoNotChange(manager, i, network.size());
BDD transition = update * (fixpoint + vChanges);
bdd = transition + bdd;
i++;
}
return bdd;
}
BDD renameRemovingPrimes(BDD bdd, int numVars) {
int *permute = new int[numVars * 2];
for (int i = 0; i < numVars; i++) {
permute[i] = i;
permute[i + numVars] = i;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD nonPrimeVariables(Cudd manager, int numVars) {
return representState(manager, std::vector<bool>(numVars, true));
}
BDD primeVariables(Cudd manager, int numVars) {
BDD bdd = manager.bddOne();
for (int i = numVars; i < numVars * 2; i++) {
BDD var = manager.bddVar(i);
bdd = var * bdd;
}
return bdd;
}
BDD immediateSuccessorStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
BDD bdd = transitionBdd * valuesBdd;
bdd = bdd.ExistAbstract(nonPrimeVariables(manager, numVars));
bdd = renameRemovingPrimes(bdd, numVars);
return bdd;
}
BDD forwardReachableStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediateSuccessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD renameAddingPrimes(BDD bdd, int numVars) {
int *permute = new int[numVars * 2];
for (int i = 0; i < numVars; i++) {
permute[i] = i + numVars;
permute[i + numVars] = i + numVars;
}
BDD r = bdd.Permute(permute);
delete[] permute;
return r;
}
BDD immediatePredecessorStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
valuesBdd = renameAddingPrimes(valuesBdd, numVars);
BDD bdd = transitionBdd * valuesBdd;
bdd = bdd.ExistAbstract(primeVariables(manager, numVars));
return bdd;
}
BDD backwardReachableStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
BDD reachable = manager.bddZero();
BDD frontier = valuesBdd;
while (frontier != manager.bddZero()) {
frontier = immediatePredecessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
reachable = reachable + frontier;
}
return reachable;
}
BDD randomState(Cudd manager, BDD S, int numVars) {
char *out = new char[numVars * 2];
S.PickOneCube(out);
std::vector<bool> values;
for (int i = 0; i < numVars; i++) {
if (out[i] == 0) {
values.push_back(false);
}
else {
values.push_back(true);
}
}
delete[] out;
return representState(manager, values);
}
std::vector<BDD> attractors(Cudd manager, BDD transitionBdd, int numVars) {
std::vector<BDD> attractors = std::vector<BDD>();
BDD S = manager.bddOne();
while (S != manager.bddZero()) {
BDD s = randomState(manager, S, numVars);
BDD fr = forwardReachableStates(manager, transitionBdd, s, numVars);
BDD br = backwardReachableStates(manager, transitionBdd, s, numVars);
if ((fr * !br) == manager.bddZero()) {
attractors.push_back(fr);
}
S = S * !(s + br);
}
return attractors;
}
int main() {
//Cebpa, Pu.1, Gata2, Gata1, Fog1, EKLF, Fli1, Scl, cJun, EgrNab, Gfi1
std::vector<bool> cmpInitial { true, true, true, false, false, false, false, false, false, false, false };
std::vector<std::vector<int>> cebpa { { 0 },{ -7 },{ -3, -4 } };
std::vector<std::vector<int>> pu1 { { 0, 1 },{ -2 },{ -3 } };
std::vector<std::vector<int>> gata2 { { 3 },{ -1 },{ -3, -4 } };
std::vector<std::vector<int>> gata1 { { 2, 3, 6 },{ -1 } };
std::vector<std::vector<int>> fog1 { { 3 } };
std::vector<std::vector<int>> eklf { { 3 },{ -6 } };
std::vector<std::vector<int>> fli1 { { 3 },{ -5 } };
std::vector<std::vector<int>> scl { { 3 },{ -1 } };
std::vector<std::vector<int>> cJun { { 1 },{ -10 } };
std::vector<std::vector<int>> egrNab { { 1 },{ 8 },{ -10 } };
std::vector<std::vector<int>> gfi1 { { 0 },{ -9 } };
std::vector<std::vector<std::vector<int>>> cmp { cebpa, pu1, gata2, gata1, fog1, eklf, fli1, scl, cJun, egrNab, gfi1 };
Cudd manager(0, 0);
BDD initialStateBdd = representState(manager, cmpInitial);
BDD transitionBddA = representAsyncTransitionRelation(manager, cmp);
BDD statespace = forwardReachableStates(manager, transitionBddA, initialStateBdd, cmpInitial.size());
std::cout << statespace.CountMinterm(cmpInitial.size());
std::cout << "\n";
std::vector<BDD> attsA = attractors(manager, transitionBddA, cmpInitial.size());
for (BDD attractor : attsA) {
attractor.PrintMinterm();
std::cout << "\n";
}
std::cout << "--------------------------------\n";
BDD transitionBddS = representSyncTransitionRelation(manager, cmp);
std::vector<BDD> attsS = attractors(manager, transitionBddS, cmpInitial.size());
for (BDD attractor : attsS) {
attractor.PrintMinterm();
std::cout << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_META_PROMOTE_VAR_MATRIX
#define STAN_MATH_REV_META_PROMOTE_VAR_MATRIX
#include <stan/math/rev/meta/is_var.hpp>
#include <stan/math/prim/meta.hpp>
namespace stan {
template <typename ReturnType, typename... Types>
using promote_var_matrix_t = std::conditional_t<is_any_var_matrix<Types...>::value,
stan::math::var_value<stan::math::promote_scalar_t<double, plain_type_t<ReturnType>>>,
stan::math::promote_scalar_t<stan::math::var, plain_type_t<ReturnType>>>;
}
#endif
<commit_msg>fix includes<commit_after>#ifndef STAN_MATH_REV_META_PROMOTE_VAR_MATRIX
#define STAN_MATH_REV_META_PROMOTE_VAR_MATRIX
#include <stan/math/rev/meta/is_var.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/prim/meta.hpp>
namespace stan {
template <typename ReturnType, typename... Types>
using promote_var_matrix_t = std::conditional_t<is_any_var_matrix<Types...>::value,
stan::math::var_value<stan::math::promote_scalar_t<double, plain_type_t<ReturnType>>>,
stan::math::promote_scalar_t<stan::math::var, plain_type_t<ReturnType>>>;
}
#endif
<|endoftext|> |
<commit_before>#include "mex.h"
#include "matrix.h"
#include <math.h>
#include <iostream>
using std::cout;
using std::endl;
#include <sstream>
using std::ostringstream;
#include <string>
using std::string;
#include <tr1/functional>
#include <tr1/unordered_map>
using std::tr1::hash;
using std::tr1::unordered_map;
extern "C" {
#include <cblas.h>
}
/* convenience macros for input/output indices in case we want to change */
#define A_ARG prhs[0]
#define LABELS_ARG prhs[1]
#define GRAPH_IND_ARG prhs[2]
#define H_ARG prhs[3]
#define KERNEL_MATRIX_ARG plhs[0]
#define INDEX(row, column, num_rows) ((int)(row) + ((int)(num_rows) * (int)(column)))
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwIndex *A_ir, *A_jc;
double *graph_ind, *labels_in, *h_in, *kernel_matrix;
int h, *labels;
int i, j, k, row, column, count, offset, iteration, num_nodes, num_labels, num_new_labels, num_graphs,
num_elements_this_column, index, *counts;
double *feature_vectors;
unordered_map<string, int, hash<string> > signature_hash;
A_ir = mxGetIr(A_ARG);
A_jc = mxGetJc(A_ARG);
labels_in = mxGetPr(LABELS_ARG);
graph_ind = mxGetPr(GRAPH_IND_ARG);
h_in = mxGetPr(H_ARG);
/* dereference to avoid annoying casting and indexing */
h = (int)(h_in[0] + 0.5);
num_nodes = mxGetN(A_ARG);
/* copy label matrix because we will overwrite it */
labels = new int[num_nodes];
for (i = 0; i < num_nodes; i++)
labels[i] = (int)(labels_in[i] + 0.5);
num_labels = 0;
num_graphs = 0;
for (i = 0; i < num_nodes; i++) {
if (labels[i] > num_labels)
num_labels = (int)(labels[i]);
if ((int)(graph_ind[i]) > num_graphs)
num_graphs = (int)(graph_ind[i] + 0.5);
}
KERNEL_MATRIX_ARG = mxCreateDoubleMatrix(num_graphs, num_graphs, mxREAL);
kernel_matrix = mxGetPr(KERNEL_MATRIX_ARG);
feature_vectors = NULL;
counts = NULL;
iteration = 0;
while (true) {
delete[] feature_vectors;
feature_vectors = new double[num_graphs * num_labels]();
for (i = 0; i < num_nodes; i++)
feature_vectors[INDEX(graph_ind[i] - 1, labels[i] - 1, num_graphs)]++;
cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, num_graphs, num_labels,
1.0, feature_vectors, num_graphs, 1.0, kernel_matrix, num_graphs);
if (iteration == h)
break;
delete[] counts;
counts = new int[num_nodes * num_labels];
for (i = 0; i < num_nodes * num_labels; i++)
counts[i] = 0;
count = 0;
for (column = 0; column < num_nodes; column++) {
num_elements_this_column = A_jc[column + 1] - A_jc[column];
for (i = 0; i < num_elements_this_column; i++, count++) {
row = A_ir[count];
counts[INDEX(row, labels[column] - 1, num_nodes)]++;
}
}
num_new_labels = 0;
for (i = 0; i < num_nodes; i++) {
ostringstream signature;
signature << labels[i];
for (j = 0; j < num_labels; j++)
if (counts[INDEX(i, j, num_nodes)])
signature << " " << j << " " << counts[INDEX(i, j, num_nodes)];
if (signature_hash.count(signature.str()) == 0) {
num_new_labels++;
labels[i] = num_new_labels;
signature_hash[signature.str()] = num_labels;
}
else
labels[i] = signature_hash[signature.str()];
}
signature_hash.clear();
num_labels = num_new_labels;
iteration++;
}
delete[] labels;
delete[] feature_vectors;
delete[] counts;
}
<commit_msg>running inline<commit_after>#include "mex.h"
#include "matrix.h"
#include <math.h>
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
#include <sstream>
using std::ostringstream;
#include <string>
using std::string;
#include <tr1/functional>
#include <tr1/unordered_map>
using std::tr1::hash;
using std::tr1::unordered_map;
extern "C" {
#include <cblas.h>
}
/* convenience macros for input/output indices in case we want to change */
#define A_ARG prhs[0]
#define LABELS_ARG prhs[1]
#define GRAPH_IND_ARG prhs[2]
#define H_ARG prhs[3]
#define KERNEL_MATRIX_ARG plhs[0]
#define INDEX(row, column, num_rows) ((int)(row) + ((int)(num_rows) * (int)(column)))
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwIndex *A_ir, *A_jc;
double *graph_ind, *labels_in, *h_in, *kernel_matrix;
int h, *labels, *new_labels;
int i, j, k, count, iteration;
int num_nodes, num_labels, num_new_labels, num_graphs, num_neighbors, *counts;
double *feature_vectors;
unordered_map<string, int, hash<string> > signature_hash;
A_ir = mxGetIr(A_ARG);
A_jc = mxGetJc(A_ARG);
labels_in = mxGetPr(LABELS_ARG);
graph_ind = mxGetPr(GRAPH_IND_ARG);
h_in = mxGetPr(H_ARG);
/* dereference to avoid annoying casting and indexing */
h = (int)(h_in[0] + 0.5);
num_nodes = mxGetN(A_ARG);
/* copy label matrix because we will overwrite it */
labels = new int[num_nodes];
for (i = 0; i < num_nodes; i++)
labels[i] = (int)(labels_in[i] + 0.5);
num_labels = 0;
num_graphs = 0;
for (i = 0; i < num_nodes; i++) {
if (labels[i] > num_labels)
num_labels = (int)(labels[i]);
if ((int)(graph_ind[i]) > num_graphs)
num_graphs = (int)(graph_ind[i] + 0.5);
}
KERNEL_MATRIX_ARG = mxCreateDoubleMatrix(num_graphs, num_graphs, mxREAL);
kernel_matrix = mxGetPr(KERNEL_MATRIX_ARG);
feature_vectors = NULL;
counts = NULL;
new_labels = new int[num_nodes];
iteration = 0;
while (true) {
delete[] feature_vectors;
feature_vectors = new double[num_graphs * num_labels]();
for (i = 0; i < num_nodes; i++)
feature_vectors[INDEX(graph_ind[i] - 1, labels[i] - 1, num_graphs)]++;
cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, num_graphs, num_labels,
1.0, feature_vectors, num_graphs, 1.0, kernel_matrix, num_graphs);
if (iteration == h)
break;
delete[] counts;
counts = new int[num_labels];
num_new_labels = 0;
count = 0;
for (i = 0; i < num_nodes; i++) {
for (j = 0; j < num_labels; j++)
counts[j] = 0;
num_neighbors = A_jc[i + 1] - A_jc[i];
for (j = 0; j < num_neighbors; j++, count++)
counts[labels[A_ir[count]] - 1]++;
ostringstream signature;
signature << labels[i];
for (j = 0; j < num_labels; j++)
signature << " " << j << " " << counts[j];
if (signature_hash.count(signature.str()) == 0) {
num_new_labels++;
new_labels[i] = num_new_labels;
signature_hash[signature.str()] = num_new_labels;
}
else
new_labels[i] = signature_hash[signature.str()];
}
signature_hash.clear();
num_labels = num_new_labels;
memcpy(new_labels, labels, num_nodes * sizeof(int));
iteration++;
}
delete[] labels;
delete[] feature_vectors;
delete[] counts;
}
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <cstring>
#include <bh.h>
#include "bh_fuse.h"
#include "bh_fuse_cache.h"
#include <fstream>
#include <exception>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/version.hpp>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
using namespace std;
using namespace boost;
using namespace boost::filesystem;
namespace bohrium {
/* * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS
* When designing an instruction hash function REMEMBER:
* The hash string should either be of fixed length and all feilds
* contained also be of fixed legth OR unique seperators should be
* used for each variable length field and to seperate instruction
* hashed. The function hashOpcodeIdShapeSweepdim may be used as
* inspiration.
*/
static const size_t inst_sep = SIZE_MAX;
static const size_t op_sep = SIZE_MAX-1;
static void hashOpcodeOpidShapeidSweepdim(std::ostream& os, const bh_instruction& instr,
BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* <opcode> (<operant-id> <ndim> <shape> <op_sep>)[1] <sweep-dim>[2] <inst_sep>
* 1: for each operand
* 2: if the operation is a sweep operation
*/
int noperands = bh_operands(instr.opcode);
os.write((const char*)&instr.opcode, sizeof(instr.opcode)); // <opcode>
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
std::pair<size_t,bool> sidp = batchHash.shapes.insert(std::vector<bh_index>(view.shape,view.shape+view.ndim));
os.write((char*)&sidp.first, sizeof(sidp.first)); // <shape-id>
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
}
if (bh_opcode_is_sweep(instr.opcode))
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator>
* 1: for each operand
* 2: if the operation is a sweep operation
*/
int noperands = bh_operands(instr.opcode);
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
if (bh_opcode_is_sweep(instr.opcode))
{
const bh_view& view = instr.operand[1];
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashScalarOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* <is_scalar> (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator>
* 1: for each operand
* 2: if the operation is a sweep operation
*/
bool scalar = (bh_is_scalar(&(instr.operand[0])) ||
(bh_opcode_is_accumulate(instr.opcode) && instr.operand[0].ndim == 1));
os.write((char*)&scalar, sizeof(scalar)); // <is_scalar>
int noperands = bh_operands(instr.opcode);
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
if (bh_opcode_is_sweep(instr.opcode))
{
const bh_view& view = instr.operand[1];
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashScalarShapeidOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* <is_scalar> <shape-id> (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator>
* 1: for each operand
* 2: if the operation is a sweep operation
*/
bool scalar = (bh_is_scalar(&(instr.operand[0])) ||
(bh_opcode_is_accumulate(instr.opcode) && instr.operand[0].ndim == 1));
os.write((char*)&scalar, sizeof(scalar)); // <is_scalar>
const bh_view& view = (bh_opcode_is_sweep(instr.opcode) ? instr.operand[1] : instr.operand[0]);
std::pair<size_t,bool> sidp = batchHash.shapes.insert(std::vector<bh_index>(view.shape,view.shape+view.ndim));
os.write((char*)&sidp.first, sizeof(sidp.first)); // <shape-id>
int noperands = bh_operands(instr.opcode);
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
if (bh_opcode_is_sweep(instr.opcode))
{
const bh_view& view = instr.operand[1];
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashOpid(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* (<operant-id>)[1] <seperator>
* 1: for each operand
*/
int noperands = bh_operands(instr.opcode);
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
#define __scalar(i) (bh_is_scalar(&(i)->operand[0]) || \
(bh_opcode_is_accumulate((i)->opcode) && (i)->operand[0].ndim == 1))
typedef void (*InstrHash)(std::ostream& os, const bh_instruction &instr, BatchHash& batchHash);
static InstrHash getInstrHash(FuseModel fuseModel)
{
switch(fuseModel)
{
case BROADEST:
return &hashOpid;
case NO_XSWEEP:
return &hashOpidSweepdim;
case NO_XSWEEP_SCALAR_SEPERATE:
return &hashScalarOpidSweepdim;
case NO_XSWEEP_SCALAR_SEPERATE_SHAPE_MATCH:
return &hashScalarShapeidOpidSweepdim;
case SAME_SHAPE:
case SAME_SHAPE_RANGE:
case SAME_SHAPE_RANDOM:
case SAME_SHAPE_RANGE_RANDOM:
case SAME_SHAPE_GENERATE_1DREDUCE:
return &hashOpcodeOpidShapeidSweepdim;
default:
throw runtime_error("Could not find valid hash function for fuse model.");
}
}
//Constructor of the BatchHash class
BatchHash::BatchHash(const vector<bh_instruction> &instr_list)
{
InstrHash hashFn = getInstrHash(fuse_get_selected_model());
std::ostringstream data(std::ios_base::ate);
for(const bh_instruction& instr: instr_list)
{
hashFn(data, instr, *this);
}
boost::hash<string> hasher;
_hash = hasher(data.str());
}
InstrIndexesList &FuseCache::insert(const BatchHash &batch,
const vector<bh_ir_kernel> &kernel_list)
{
cache[batch.hash()] = InstrIndexesList(kernel_list, batch.hash(), fuser_name);
return cache[batch.hash()];
}
bool FuseCache::lookup(const BatchHash &batch,
bh_ir &bhir,
vector<bh_ir_kernel> &kernel_list) const
{
assert(kernel_list.size() == 0);
CacheMap::const_iterator it = cache.find(batch.hash());
if(deactivated or it == cache.end())
{
return false;
}
else
{
it->second.fill_kernel_list(bhir, kernel_list);
return true;
}
}
void FuseCache::write_to_files() const
{
if(deactivated)
return;
if(dir_path == NULL)
{
cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \
"the configure file thus no cache files are written to disk!" << endl;
return;
}
path cache_dir(dir_path);
if(create_directories(cache_dir))
{
cout << "[FUSE-CACHE] Creating cache diretory " << cache_dir << endl;
#if BOOST_VERSION > 104900
permissions(cache_dir, all_all);
#endif
}
path tmp_dir = cache_dir / unique_path();
create_directories(tmp_dir);
for(CacheMap::const_iterator it=cache.begin(); it != cache.end(); ++it)
{
string name;
it->second.get_filename(name);
path shared_name = cache_dir / name;
if(exists(shared_name))
continue;//No need to overwrite an existing file
path unique_name = tmp_dir / name;
ofstream ofs(unique_name.string().c_str());
boost::archive::text_oarchive oa(ofs);
oa << it->second;
ofs.close();
#if BOOST_VERSION > 104900
permissions(unique_name, all_all);
#endif
rename(unique_name, shared_name);
}
remove(tmp_dir);
}
void FuseCache::load_from_files()
{
if(dir_path == NULL)
{
cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \
"the configure file thus no cache files are loaded from disk!" << endl;
return;
}
path p(dir_path);
if(not (exists(p) and is_directory(p)))
return;
string fuse_model_name;
fuse_model_text(fuse_get_selected_model(), fuse_model_name);
//Iterate the 'dir_path' diretory and load each file
directory_iterator it(p), eod;
BOOST_FOREACH(const path &f, make_pair(it, eod))
{
if(is_regular_file(f))
{
int tries = 0;
while(1)
{
try
{
ifstream ifs(f.string().c_str());
boost::archive::text_iarchive ia(ifs);
InstrIndexesList t;
ia >> t;
if(iequals(t.fuser_name(), fuser_name) and
iequals(t.fuse_model(), fuse_model_name))
{
cache[t.hash()] = t;
}
}
catch(const std::exception &e)
{
if(++tries >= 10)
{
cerr << "[FUSE-CACHE] failed to open file '" << f.string();
cerr << "' (" << tries << " tries): " << e.what() << endl;
}
else
continue;
}
break;
}
}
}
}
} //namespace bohrium
<commit_msg>fuse-cache: fixed BUG where hashScalarShapeidOpidSweepdim() didn't ignore BH_NONE operations<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <cstring>
#include <bh.h>
#include "bh_fuse.h"
#include "bh_fuse_cache.h"
#include <fstream>
#include <exception>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/version.hpp>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
using namespace std;
using namespace boost;
using namespace boost::filesystem;
namespace bohrium {
/* * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS
* When designing an instruction hash function REMEMBER:
* The hash string should either be of fixed length and all feilds
* contained also be of fixed legth OR unique seperators should be
* used for each variable length field and to seperate instruction
* hashed. The function hashOpcodeIdShapeSweepdim may be used as
* inspiration.
*/
static const size_t inst_sep = SIZE_MAX;
static const size_t op_sep = SIZE_MAX-1;
static void hashOpcodeOpidShapeidSweepdim(std::ostream& os, const bh_instruction& instr,
BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* <opcode> (<operant-id> <ndim> <shape> <op_sep>)[1] <sweep-dim>[2] <inst_sep>
* 1: for each operand
* 2: if the operation is a sweep operation
*/
int noperands = bh_operands(instr.opcode);
os.write((const char*)&instr.opcode, sizeof(instr.opcode)); // <opcode>
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
std::pair<size_t,bool> sidp = batchHash.shapes.insert(std::vector<bh_index>(view.shape,view.shape+view.ndim));
os.write((char*)&sidp.first, sizeof(sidp.first)); // <shape-id>
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
}
if (bh_opcode_is_sweep(instr.opcode))
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator>
* 1: for each operand
* 2: if the operation is a sweep operation
*/
int noperands = bh_operands(instr.opcode);
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
if (bh_opcode_is_sweep(instr.opcode))
{
const bh_view& view = instr.operand[1];
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashScalarOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* <is_scalar> (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator>
* 1: for each operand
* 2: if the operation is a sweep operation
*/
bool scalar = (bh_is_scalar(&(instr.operand[0])) ||
(bh_opcode_is_accumulate(instr.opcode) && instr.operand[0].ndim == 1));
os.write((char*)&scalar, sizeof(scalar)); // <is_scalar>
int noperands = bh_operands(instr.opcode);
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
if (bh_opcode_is_sweep(instr.opcode))
{
const bh_view& view = instr.operand[1];
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashScalarShapeidOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* <is_scalar> <shape-id> (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator>
* 1: for each operand
* 2: if the operation is a sweep operation
* NB: but ignores instructions that takes no arguments, such as BH_NONE
*/
int noperands = bh_operands(instr.opcode);
if(noperands == 0)
return;
bool scalar = (bh_is_scalar(&(instr.operand[0])) ||
(bh_opcode_is_accumulate(instr.opcode) && instr.operand[0].ndim == 1));
os.write((char*)&scalar, sizeof(scalar)); // <is_scalar>
const bh_view& view = (bh_opcode_is_sweep(instr.opcode) ? instr.operand[1] : instr.operand[0]);
std::pair<size_t,bool> sidp = batchHash.shapes.insert(std::vector<bh_index>(view.shape,view.shape+view.ndim));
os.write((char*)&sidp.first, sizeof(sidp.first)); // <shape-id>
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep>
if (bh_opcode_is_sweep(instr.opcode))
{
const bh_view& view = instr.operand[1];
os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim>
os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
static void hashOpid(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash)
{
/* The Instruction hash consists of the following fields:
* (<operant-id>)[1] <seperator>
* 1: for each operand
*/
int noperands = bh_operands(instr.opcode);
for(int oidx=0; oidx<noperands; ++oidx) {
const bh_view& view = instr.operand[oidx];
if (bh_is_constant(&view))
continue; // Ignore constants
std::pair<size_t,bool> vid = batchHash.views.insert(view);
size_t id = vid.first;
os.write((char*)&id, sizeof(id)); // <operant-id>
}
os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep>
}
#define __scalar(i) (bh_is_scalar(&(i)->operand[0]) || \
(bh_opcode_is_accumulate((i)->opcode) && (i)->operand[0].ndim == 1))
typedef void (*InstrHash)(std::ostream& os, const bh_instruction &instr, BatchHash& batchHash);
static InstrHash getInstrHash(FuseModel fuseModel)
{
switch(fuseModel)
{
case BROADEST:
return &hashOpid;
case NO_XSWEEP:
return &hashOpidSweepdim;
case NO_XSWEEP_SCALAR_SEPERATE:
return &hashScalarOpidSweepdim;
case NO_XSWEEP_SCALAR_SEPERATE_SHAPE_MATCH:
return &hashScalarShapeidOpidSweepdim;
case SAME_SHAPE:
case SAME_SHAPE_RANGE:
case SAME_SHAPE_RANDOM:
case SAME_SHAPE_RANGE_RANDOM:
case SAME_SHAPE_GENERATE_1DREDUCE:
return &hashOpcodeOpidShapeidSweepdim;
default:
throw runtime_error("Could not find valid hash function for fuse model.");
}
}
//Constructor of the BatchHash class
BatchHash::BatchHash(const vector<bh_instruction> &instr_list)
{
InstrHash hashFn = getInstrHash(fuse_get_selected_model());
std::ostringstream data(std::ios_base::ate);
for(const bh_instruction& instr: instr_list)
{
hashFn(data, instr, *this);
}
boost::hash<string> hasher;
_hash = hasher(data.str());
}
InstrIndexesList &FuseCache::insert(const BatchHash &batch,
const vector<bh_ir_kernel> &kernel_list)
{
cache[batch.hash()] = InstrIndexesList(kernel_list, batch.hash(), fuser_name);
return cache[batch.hash()];
}
bool FuseCache::lookup(const BatchHash &batch,
bh_ir &bhir,
vector<bh_ir_kernel> &kernel_list) const
{
assert(kernel_list.size() == 0);
CacheMap::const_iterator it = cache.find(batch.hash());
if(deactivated or it == cache.end())
{
return false;
}
else
{
it->second.fill_kernel_list(bhir, kernel_list);
return true;
}
}
void FuseCache::write_to_files() const
{
if(deactivated)
return;
if(dir_path == NULL)
{
cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \
"the configure file thus no cache files are written to disk!" << endl;
return;
}
path cache_dir(dir_path);
if(create_directories(cache_dir))
{
cout << "[FUSE-CACHE] Creating cache diretory " << cache_dir << endl;
#if BOOST_VERSION > 104900
permissions(cache_dir, all_all);
#endif
}
path tmp_dir = cache_dir / unique_path();
create_directories(tmp_dir);
for(CacheMap::const_iterator it=cache.begin(); it != cache.end(); ++it)
{
string name;
it->second.get_filename(name);
path shared_name = cache_dir / name;
if(exists(shared_name))
continue;//No need to overwrite an existing file
path unique_name = tmp_dir / name;
ofstream ofs(unique_name.string().c_str());
boost::archive::text_oarchive oa(ofs);
oa << it->second;
ofs.close();
#if BOOST_VERSION > 104900
permissions(unique_name, all_all);
#endif
rename(unique_name, shared_name);
}
remove(tmp_dir);
}
void FuseCache::load_from_files()
{
if(dir_path == NULL)
{
cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \
"the configure file thus no cache files are loaded from disk!" << endl;
return;
}
path p(dir_path);
if(not (exists(p) and is_directory(p)))
return;
string fuse_model_name;
fuse_model_text(fuse_get_selected_model(), fuse_model_name);
//Iterate the 'dir_path' diretory and load each file
directory_iterator it(p), eod;
BOOST_FOREACH(const path &f, make_pair(it, eod))
{
if(is_regular_file(f))
{
int tries = 0;
while(1)
{
try
{
ifstream ifs(f.string().c_str());
boost::archive::text_iarchive ia(ifs);
InstrIndexesList t;
ia >> t;
if(iequals(t.fuser_name(), fuser_name) and
iequals(t.fuse_model(), fuse_model_name))
{
cache[t.hash()] = t;
}
}
catch(const std::exception &e)
{
if(++tries >= 10)
{
cerr << "[FUSE-CACHE] failed to open file '" << f.string();
cerr << "' (" << tries << " tries): " << e.what() << endl;
}
else
continue;
}
break;
}
}
}
}
} //namespace bohrium
<|endoftext|> |
<commit_before>// @(#)root/meta:$Id$
// Author: Fons Rademakers 08/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TBaseClass.h"
#include "TClass.h"
#include "TInterpreter.h"
//////////////////////////////////////////////////////////////////////////
// //
// Each class (see TClass) has a linked list of its base class(es). //
// This class describes one single base class. //
// The base class info is obtained via the CINT api. //
// see class TCint. //
// //
// The base class information is used a.o. in to find all inherited //
// methods. //
// //
//////////////////////////////////////////////////////////////////////////
ClassImp(TBaseClass)
//______________________________________________________________________________
TBaseClass::TBaseClass(BaseClassInfo_t *info, TClass *cl) : TDictionary()
{
// Default TBaseClass ctor. TBaseClasses are constructed in TClass
// via a call to TCint::CreateListOfBaseClasses().
fInfo = info;
fClass = cl;
fClassPtr = 0;
if (fInfo) SetName(gCint->BaseClassInfo_FullName(fInfo));
}
//______________________________________________________________________________
TBaseClass::~TBaseClass()
{
// TBaseClass dtor deletes adopted CINT BaseClassInfo object.
gCint->BaseClassInfo_Delete(fInfo);
}
//______________________________________________________________________________
void TBaseClass::Browse(TBrowser *b)
{
// Called by the browser, to browse a baseclass.
TClass *c = GetClassPointer();
if (c) c->Browse(b);
}
//______________________________________________________________________________
TClass *TBaseClass::GetClassPointer(Bool_t load)
{
// Get pointer to the base class TClass.
if (!fClassPtr) fClassPtr = TClass::GetClass(fName, load);
return fClassPtr;
}
//______________________________________________________________________________
Int_t TBaseClass::GetDelta() const
{
// Get offset from "this" to part of base class.
return (Int_t)gCint->BaseClassInfo_Offset(fInfo);
}
//______________________________________________________________________________
const char *TBaseClass::GetTitle() const
{
// Get base class description (comment).
TClass *c = ((TBaseClass *)this)->GetClassPointer();
return c ? c->GetTitle() : "";
}
//______________________________________________________________________________
int TBaseClass::IsSTLContainer()
{
// Return which type (if any) of STL container the data member is.
if (!fInfo) return kNone;
const char *type = gCint->BaseClassInfo_TmpltName(fInfo);
if (!type) return kNone;
if (!strcmp(type, "vector")) return kVector;
if (!strcmp(type, "list")) return kList;
if (!strcmp(type, "deque")) return kDeque;
if (!strcmp(type, "map")) return kMap;
if (!strcmp(type, "multimap")) return kMultimap;
if (!strcmp(type, "set")) return kSet;
if (!strcmp(type, "multiset")) return kMultiset;
return kNone;
}
//______________________________________________________________________________
Long_t TBaseClass::Property() const
{
// Get property description word. For meaning of bits see EProperty.
return gCint->BaseClassInfo_Property(fInfo);
}
<commit_msg>Lock cache of TClassRef<commit_after>// @(#)root/meta:$Id$
// Author: Fons Rademakers 08/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TBaseClass.h"
#include "TClass.h"
#include "TInterpreter.h"
#include "TVirtualMutex.h"
//////////////////////////////////////////////////////////////////////////
// //
// Each class (see TClass) has a linked list of its base class(es). //
// This class describes one single base class. //
// The base class info is obtained via the CINT api. //
// see class TCint. //
// //
// The base class information is used a.o. in to find all inherited //
// methods. //
// //
//////////////////////////////////////////////////////////////////////////
ClassImp(TBaseClass)
//______________________________________________________________________________
TBaseClass::TBaseClass(BaseClassInfo_t *info, TClass *cl) : TDictionary()
{
// Default TBaseClass ctor. TBaseClasses are constructed in TClass
// via a call to TCint::CreateListOfBaseClasses().
fInfo = info;
fClass = cl;
fClassPtr = 0;
if (fInfo) SetName(gCint->BaseClassInfo_FullName(fInfo));
}
//______________________________________________________________________________
TBaseClass::~TBaseClass()
{
// TBaseClass dtor deletes adopted CINT BaseClassInfo object.
gCint->BaseClassInfo_Delete(fInfo);
}
//______________________________________________________________________________
void TBaseClass::Browse(TBrowser *b)
{
// Called by the browser, to browse a baseclass.
TClass *c = GetClassPointer();
if (c) c->Browse(b);
}
//______________________________________________________________________________
TClass *TBaseClass::GetClassPointer(Bool_t load)
{
// Get pointer to the base class TClass.
R__LOCKGUARD(gCINTMutex);
if (!fClassPtr) fClassPtr = TClass::GetClass(fName, load);
return fClassPtr;
}
//______________________________________________________________________________
Int_t TBaseClass::GetDelta() const
{
// Get offset from "this" to part of base class.
return (Int_t)gCint->BaseClassInfo_Offset(fInfo);
}
//______________________________________________________________________________
const char *TBaseClass::GetTitle() const
{
// Get base class description (comment).
TClass *c = ((TBaseClass *)this)->GetClassPointer();
return c ? c->GetTitle() : "";
}
//______________________________________________________________________________
int TBaseClass::IsSTLContainer()
{
// Return which type (if any) of STL container the data member is.
if (!fInfo) return kNone;
const char *type = gCint->BaseClassInfo_TmpltName(fInfo);
if (!type) return kNone;
if (!strcmp(type, "vector")) return kVector;
if (!strcmp(type, "list")) return kList;
if (!strcmp(type, "deque")) return kDeque;
if (!strcmp(type, "map")) return kMap;
if (!strcmp(type, "multimap")) return kMultimap;
if (!strcmp(type, "set")) return kSet;
if (!strcmp(type, "multiset")) return kMultiset;
return kNone;
}
//______________________________________________________________________________
Long_t TBaseClass::Property() const
{
// Get property description word. For meaning of bits see EProperty.
return gCint->BaseClassInfo_Property(fInfo);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef BUDDY_ALLOCATOR_H
#define BUDDY_ALLOCATOR_H
#include <array.hpp>
#include "bitmap.hpp"
//For problems during boot
#include "kernel.hpp"
#include "console.hpp"
template <class T>
inline constexpr T pow(T const& x, size_t n){
return n > 0 ? x * pow(x, n - 1) : 1;
}
template<size_t Levels, size_t Unit>
struct buddy_allocator {
static constexpr const size_t levels = Levels;
static constexpr const size_t max_block = pow(2, levels - 1);
std::array<static_bitmap, levels> bitmaps;
size_t first_address;
size_t last_address;
public:
void set_memory_range(size_t first, size_t last){
first_address = first;
last_address = last;
}
template<size_t I>
void init(size_t words, uint64_t* data){
bitmaps[I].init(words, data);
}
void init(){
//By default all blocks are free
for(auto& bitmap : bitmaps){
bitmap.set_all();
}
}
size_t allocate(size_t pages){
if(pages > max_block){
if(pages > max_block * static_bitmap::bits_per_word){
k_print_line("Virtual block too big");
suspend_boot();
//That means we try to allocate more than 33M at the same time
//probably not a good idea
//TODO Implement it all the same
return 0;
} else {
auto l = bitmaps.size() - 1;
auto index = bitmaps[l].free_word();
auto address = block_start(l, index);
if(address + level_size(pages) >= last_address){
return 0;
}
//Mark all bits of the word as used
for(size_t b = 0; b < static_bitmap::bits_per_word; ++b){
mark_used(l, index + b);
}
return address;
}
} else {
auto l = level(pages);
auto index = bitmaps[l].free_bit();
auto address = block_start(l, index);
if(address + level_size(pages) >= last_address){
return 0;
}
mark_used(l, index);
return address;
}
}
void free(size_t address, size_t pages){
if(pages > max_block){
if(pages > max_block * static_bitmap::bits_per_word){
k_print_line("Virtual block too big");
suspend_boot();
//That means we try to allocate more than 33M at the same time
//probably not a good idea
//TODO Implement it all the same
} else {
auto l = level(pages);
auto index = get_block_index(address, l);
//Mark all bits of the word as free
for(size_t b = 0; b < static_bitmap::bits_per_word; ++b){
mark_free(l, index + b);
}
}
} else {
auto l = level(pages);
auto index = get_block_index(address, l);
mark_free(l, index);
}
}
static size_t level_size(size_t level){
size_t size = 1;
for(size_t i = 0; i < level; ++i){
size *= 2;
}
return size;
}
private:
static size_t level(size_t pages){
if(pages > 64){
return 7;
} else if(pages > 32){
return 6;
} else if(pages > 16){
return 5;
} else if(pages > 8){
return 4;
} else if(pages > 4){
return 3;
} else if(pages > 2){
return 2;
} else if(pages > 1){
return 1;
} else {
return 0;
}
}
void mark_used(size_t l, size_t index){
//Mark all sub blocks as taken
taken_down(l, index);
//The current level block is not free anymore
bitmaps[l].unset(index);
//Mark all up blocks as taken
taken_up(l, index);
}
void mark_free(size_t l, size_t index){
//Free all sub blocks
free_down(l, index);
//Free block at the current level
bitmaps[l].set(index);
//Free higher blocks if buddies are free too
free_up(l, index);
}
uintptr_t block_start(size_t l, size_t index) const {
return first_address + index * level_size(l) * Unit;
}
size_t get_block_index(size_t address, size_t l) const {
return (address - first_address) / (level_size(l) * Unit);
}
void taken_down(size_t start_level, size_t index){
auto start = index * 2;
auto end = start + 1;
for(size_t l = start_level; l > 0; --l){
for(size_t i = start; i <= end; ++i){
bitmaps[l-1].unset(i);
}
start *= 2;
end = (end * 2) + 1;
}
}
void free_down(size_t start_level, size_t index){
auto start = index * 2;
auto end = start + 1;
for(size_t l = start_level; l > 0; --l){
for(size_t i = start; i <= end; ++i){
bitmaps[l-1].set(i);
}
start *= 2;
end = (end * 2) + 1;
}
}
void taken_up(size_t start_level, size_t index){
for(size_t l = start_level + 1; l < bitmaps.size(); ++l){
index /= 2;
bitmaps[l].unset(index);
}
}
void free_up(size_t start_level, size_t index){
for(size_t l = start_level; l + 1 < bitmaps.size(); ++l){
size_t buddy_index;
if(index % 2 == 0){
buddy_index = index + 1;
} else {
buddy_index = index - 1;
}
//If buddy is also free, free the block one level higher
if(bitmaps[l].is_set(buddy_index)){
index /= 2;
bitmaps[l+1].set(index);
} else {
break;
}
}
}
};
#endif
<commit_msg>Improve debugging<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef BUDDY_ALLOCATOR_H
#define BUDDY_ALLOCATOR_H
#include <array.hpp>
#include "bitmap.hpp"
#include "logging.hpp"
template <class T>
inline constexpr T pow(T const& x, size_t n){
return n > 0 ? x * pow(x, n - 1) : 1;
}
template<size_t Levels, size_t Unit>
struct buddy_allocator {
static constexpr const size_t levels = Levels;
static constexpr const size_t max_block = pow(2, levels - 1);
std::array<static_bitmap, levels> bitmaps;
size_t first_address;
size_t last_address;
public:
void set_memory_range(size_t first, size_t last){
first_address = first;
last_address = last;
}
template<size_t I>
void init(size_t words, uint64_t* data){
bitmaps[I].init(words, data);
}
void init(){
//By default all blocks are free
for(auto& bitmap : bitmaps){
bitmap.set_all();
}
}
size_t allocate(size_t pages){
if(pages > max_block){
if(pages > max_block * static_bitmap::bits_per_word){
logging::logf(logging::log_level::ERROR, "buddy: Impossible to allocate mor than 33M block:%u\n", pages);
//TODO Implement larger allocation
return 0;
} else {
auto l = bitmaps.size() - 1;
auto index = bitmaps[l].free_word();
auto address = block_start(l, index);
if(address + level_size(pages) >= last_address){
logging::logf(logging::log_level::ERROR, "buddy: Address too high level:%u index:%u address:%h\n", l, index, address);
return 0;
}
//Mark all bits of the word as used
for(size_t b = 0; b < static_bitmap::bits_per_word; ++b){
mark_used(l, index + b);
}
return address;
}
} else {
auto l = level(pages);
auto index = bitmaps[l].free_bit();
auto address = block_start(l, index);
if(address + level_size(pages) >= last_address){
logging::logf(logging::log_level::ERROR, "buddy: Address too high pages:%u level:%u index:%u address:%h\n", pages, l, index, address);
return 0;
}
mark_used(l, index);
return address;
}
}
void free(size_t address, size_t pages){
if(pages > max_block){
if(pages > max_block * static_bitmap::bits_per_word){
logging::logf(logging::log_level::ERROR, "buddy: Impossible to free more than 33M block:%u\n", pages);
//TODO Implement larger allocation
} else {
auto l = level(pages);
auto index = get_block_index(address, l);
//Mark all bits of the word as free
for(size_t b = 0; b < static_bitmap::bits_per_word; ++b){
mark_free(l, index + b);
}
}
} else {
auto l = level(pages);
auto index = get_block_index(address, l);
mark_free(l, index);
}
}
static size_t level_size(size_t level){
size_t size = 1;
for(size_t i = 0; i < level; ++i){
size *= 2;
}
return size;
}
private:
static size_t level(size_t pages){
if(pages > 64){
return 7;
} else if(pages > 32){
return 6;
} else if(pages > 16){
return 5;
} else if(pages > 8){
return 4;
} else if(pages > 4){
return 3;
} else if(pages > 2){
return 2;
} else if(pages > 1){
return 1;
} else {
return 0;
}
}
void mark_used(size_t l, size_t index){
//Mark all sub blocks as taken
taken_down(l, index);
//The current level block is not free anymore
bitmaps[l].unset(index);
//Mark all up blocks as taken
taken_up(l, index);
}
void mark_free(size_t l, size_t index){
//Free all sub blocks
free_down(l, index);
//Free block at the current level
bitmaps[l].set(index);
//Free higher blocks if buddies are free too
free_up(l, index);
}
uintptr_t block_start(size_t l, size_t index) const {
return first_address + index * level_size(l) * Unit;
}
size_t get_block_index(size_t address, size_t l) const {
return (address - first_address) / (level_size(l) * Unit);
}
void taken_down(size_t start_level, size_t index){
auto start = index * 2;
auto end = start + 1;
for(size_t l = start_level; l > 0; --l){
for(size_t i = start; i <= end; ++i){
bitmaps[l-1].unset(i);
}
start *= 2;
end = (end * 2) + 1;
}
}
void free_down(size_t start_level, size_t index){
auto start = index * 2;
auto end = start + 1;
for(size_t l = start_level; l > 0; --l){
for(size_t i = start; i <= end; ++i){
bitmaps[l-1].set(i);
}
start *= 2;
end = (end * 2) + 1;
}
}
void taken_up(size_t start_level, size_t index){
for(size_t l = start_level + 1; l < bitmaps.size(); ++l){
index /= 2;
bitmaps[l].unset(index);
}
}
void free_up(size_t start_level, size_t index){
for(size_t l = start_level; l + 1 < bitmaps.size(); ++l){
size_t buddy_index;
if(index % 2 == 0){
buddy_index = index + 1;
} else {
buddy_index = index - 1;
}
//If buddy is also free, free the block one level higher
if(bitmaps[l].is_set(buddy_index)){
index /= 2;
bitmaps[l+1].set(index);
} else {
break;
}
}
}
};
#endif
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2015 Martin Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef TWPP_DETAIL_FILE_ENV_HPP
#define TWPP_DETAIL_FILE_ENV_HPP
// =============
// Twpp specific
namespace Twpp {
namespace Detail {
enum {
ProtoMajor = 2,
ProtoMinor = 3,
Dsm2 = 0x10000000L,
App2 = 0x20000000L,
Ds2 = 0x40000000L
};
}
}
#if defined(TWPP_IS_DS)
# define TWPP_DETAIL_IS_DS 1
#else
# define TWPP_DETAIL_IS_DS 0
#endif
// ===========
// OS specific
// Windows
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
# define TWPP_DETAIL_OS_WIN 1
# if defined(WIN64) || defined(_WIN64)
# define TWPP_DETAIL_OS_WIN64 1
# else
# define TWPP_DETAIL_OS_WIN32 1
# endif
# define WIN32_LEAN_AND_MEAN
# define NOMINMAX
extern "C" {
# include <windows.h>
}
# define TWPP_DETAIL_CALLSTYLE PASCAL
# define TWPP_DETAIL_EXPORT __declspec(dllexport)
namespace Twpp {
namespace Detail {
typedef HANDLE RawHandle;
}
}
// Mac OS
#elif defined(__APPLE__)
# pragma warning "No testing has been done on this platform, this framework might not work correctly."
# define TWPP_DETAIL_OS_MAC 1
extern "C" {
# if defined(__MWERKS__)
# include <Carbon.h>
# else
# include <Carbon/Carbon.h>
# endif
# include <MacMemory.h>
# include <dlfcn.h>
}
# define TWPP_DETAIL_CALLSTYLE pascal
namespace Twpp {
namespace Detail {
typedef Handle RawHandle;
}
}
// Linux
#elif defined(__linux__)
# warning "No testing has been done on this platform, this framework might not work correctly."
# define TWPP_DETAIL_OS_LINUX 1
extern "C" {
# include <dlfcn.h>
}
# define TWPP_DETAIL_CALLSTYLE
namespace Twpp {
namespace Detail {
typedef void* RawHandle;
}
}
// fail everything else
#else
# error "unsupported platform, supports only Windows, Mac OS and Linux"
#endif
// =================
// compiler specific
// MSVC
#if defined(_MSC_VER)
# define TWPP_DETAIL_PACK_BEGIN \
__pragma(pack (push, beforeTwpp)) \
__pragma(pack (2))
# define TWPP_DETAIL_PACK_END __pragma(pack (pop, beforeTwpp));
// GNU or CLang
#elif defined(__GNUC__) || defined(__clang__)
# if defined(TWPP_DETAIL_OS_MAC)
# define TWPP_DETAIL_PACK_BEGIN _Pragma("options align = power")
# define TWPP_DETAIL_PACK_END _Pragma("options align = reset")
# else
# define TWPP_DETAIL_PACK_BEGIN \
_Pragma("pack (push, beforeTwpp)") \
_Pragma("pack (2)")
# define TWPP_DETAIL_PACK_END _Pragma("pack (pop, beforeTwpp)")
# endif
# if !defined(TWPP_DETAIL_EXPORT)
# define TWPP_DETAIL_EXPORT __attribute__((__visibility__("default")))
# endif
// Borland
#elif defined(__BORLAND__) || defined(__BORLANDC__) || defined(__CODEGEARC__)
# define TWPP_DETAIL_PACK_BEGIN _Pragma("option -a2")
# define TWPP_DETAIL_PACK_END _Pragma("option -a")
// fail everything else
#else
# error unsupported compiler, please define your own TWPP_DETAIL_PACK_BEGIN \
and TWPP_DETAIL_PACK_END and possibly TWPP_DETAIL_EXPORT in twpp/env.hpp and send me your patch
#endif
#if (!defined(_MSC_VER) && __cplusplus < 201103L) || (defined(_MSC_VER) && _MSC_VER < 1900) // msvc2015
# error "C++11 or later is required"
#endif
#endif // TWPP_DETAIL_FILE_ENV_HPP
<commit_msg>Fixed possible NOMINMAX and WIN32_LEAN_AND_MEAN related warnings.<commit_after>/*
The MIT License (MIT)
Copyright (c) 2015 Martin Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef TWPP_DETAIL_FILE_ENV_HPP
#define TWPP_DETAIL_FILE_ENV_HPP
// =============
// Twpp specific
namespace Twpp {
namespace Detail {
enum {
ProtoMajor = 2,
ProtoMinor = 3,
Dsm2 = 0x10000000L,
App2 = 0x20000000L,
Ds2 = 0x40000000L
};
}
}
#if defined(TWPP_IS_DS)
# define TWPP_DETAIL_IS_DS 1
#else
# define TWPP_DETAIL_IS_DS 0
#endif
// ===========
// OS specific
// Windows
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
# define TWPP_DETAIL_OS_WIN 1
# if defined(WIN64) || defined(_WIN64)
# define TWPP_DETAIL_OS_WIN64 1
# else
# define TWPP_DETAIL_OS_WIN32 1
# endif
# if !defined(WIN32_LEAN_AND_MEAN)
# define WIN32_LEAN_AND_MEAN
# endif
# if !defined(NOMINMAX)
# define NOMINMAX
# endif
extern "C" {
# include <windows.h>
}
# define TWPP_DETAIL_CALLSTYLE PASCAL
# define TWPP_DETAIL_EXPORT __declspec(dllexport)
namespace Twpp {
namespace Detail {
typedef HANDLE RawHandle;
}
}
// Mac OS
#elif defined(__APPLE__)
# pragma warning "No testing has been done on this platform, this framework might not work correctly."
# define TWPP_DETAIL_OS_MAC 1
extern "C" {
# if defined(__MWERKS__)
# include <Carbon.h>
# else
# include <Carbon/Carbon.h>
# endif
# include <MacMemory.h>
# include <dlfcn.h>
}
# define TWPP_DETAIL_CALLSTYLE pascal
namespace Twpp {
namespace Detail {
typedef Handle RawHandle;
}
}
// Linux
#elif defined(__linux__)
# warning "No testing has been done on this platform, this framework might not work correctly."
# define TWPP_DETAIL_OS_LINUX 1
extern "C" {
# include <dlfcn.h>
}
# define TWPP_DETAIL_CALLSTYLE
namespace Twpp {
namespace Detail {
typedef void* RawHandle;
}
}
// fail everything else
#else
# error "unsupported platform, supports only Windows, Mac OS and Linux"
#endif
// =================
// compiler specific
// MSVC
#if defined(_MSC_VER)
# define TWPP_DETAIL_PACK_BEGIN \
__pragma(pack (push, beforeTwpp)) \
__pragma(pack (2))
# define TWPP_DETAIL_PACK_END __pragma(pack (pop, beforeTwpp));
// GNU or CLang
#elif defined(__GNUC__) || defined(__clang__)
# if defined(TWPP_DETAIL_OS_MAC)
# define TWPP_DETAIL_PACK_BEGIN _Pragma("options align = power")
# define TWPP_DETAIL_PACK_END _Pragma("options align = reset")
# else
# define TWPP_DETAIL_PACK_BEGIN \
_Pragma("pack (push, beforeTwpp)") \
_Pragma("pack (2)")
# define TWPP_DETAIL_PACK_END _Pragma("pack (pop, beforeTwpp)")
# endif
# if !defined(TWPP_DETAIL_EXPORT)
# define TWPP_DETAIL_EXPORT __attribute__((__visibility__("default")))
# endif
// Borland
#elif defined(__BORLAND__) || defined(__BORLANDC__) || defined(__CODEGEARC__)
# define TWPP_DETAIL_PACK_BEGIN _Pragma("option -a2")
# define TWPP_DETAIL_PACK_END _Pragma("option -a")
// fail everything else
#else
# error unsupported compiler, please define your own TWPP_DETAIL_PACK_BEGIN \
and TWPP_DETAIL_PACK_END and possibly TWPP_DETAIL_EXPORT in twpp/env.hpp and send me your patch
#endif
#if (!defined(_MSC_VER) && __cplusplus < 201103L) || (defined(_MSC_VER) && _MSC_VER < 1900) // msvc2015
# error "C++11 or later is required"
#endif
#endif // TWPP_DETAIL_FILE_ENV_HPP
<|endoftext|> |
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#include <algorithm>
#include "third_party/eigen3/Eigen/SVD"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
template <class Scalar>
class SvdOp : public LinearAlgebraOp<Scalar> {
public:
typedef LinearAlgebraOp<Scalar> Base;
explicit SvdOp(OpKernelConstruction* context) : Base(context) {
OP_REQUIRES_OK(context, context->GetAttr("compute_uv", &compute_uv_));
OP_REQUIRES_OK(context, context->GetAttr("full_matrices", &full_matrices_));
}
using TensorShapes = typename Base::TensorShapes;
void ValidateInputMatrixShapes(
OpKernelContext* context,
const TensorShapes& input_matrix_shapes) const final {
Base::ValidateSingleMatrix(context, input_matrix_shapes);
}
TensorShapes GetOutputMatrixShapes(
const TensorShapes& input_matrix_shapes) const final {
int64 m = input_matrix_shapes[0].dim_size(0);
int64 n = input_matrix_shapes[0].dim_size(1);
int64 min_size = std::min(m, n);
if (compute_uv_) {
return TensorShapes({TensorShape({min_size}),
TensorShape({m, full_matrices_ ? m : min_size}),
TensorShape({n, full_matrices_ ? n : min_size})});
} else {
return TensorShapes({TensorShape({min_size})});
}
}
// TODO(rmlarsen): This should depend on compute_uv. See b/30409375.
int64 GetCostPerUnit(const TensorShapes& input_matrix_shapes) const final {
double m = static_cast<double>(input_matrix_shapes[0].dim_size(0));
double n = static_cast<double>(input_matrix_shapes[0].dim_size(1));
double cost = 12 * std::max(m, n) * std::min(m, n) * std::min(m, n);
return cost >= static_cast<double>(kint64max) ? kint64max
: static_cast<int64>(cost);
}
using Matrix = typename Base::Matrix;
using MatrixMaps = typename Base::MatrixMaps;
using ConstMatrixMap = typename Base::ConstMatrixMap;
using ConstMatrixMaps = typename Base::ConstMatrixMaps;
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs,
MatrixMaps* outputs) final {
Eigen::BDCSVD<Matrix> svd;
if (compute_uv_) {
svd.compute(inputs[0],
(full_matrices_ ? Eigen::ComputeFullU | Eigen::ComputeFullV
: Eigen::ComputeThinU | Eigen::ComputeThinV));
outputs->at(0) = svd.singularValues().template cast<Scalar>();
outputs->at(1) = svd.matrixU();
outputs->at(2) = svd.matrixV();
} else {
svd.compute(inputs[0]);
outputs->at(0) = svd.singularValues().template cast<Scalar>();
}
}
private:
bool compute_uv_;
bool full_matrices_;
TF_DISALLOW_COPY_AND_ASSIGN(SvdOp);
};
REGISTER_LINALG_OP("Svd", (SvdOp<float>), float);
REGISTER_LINALG_OP("Svd", (SvdOp<double>), double);
REGISTER_LINALG_OP("Svd", (SvdOp<complex64>), complex64);
REGISTER_LINALG_OP("Svd", (SvdOp<complex128>), complex128);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<float>), float);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<double>), double);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<complex64>), complex64);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<complex128>), complex128);
} // namespace tensorflow
<commit_msg>Simplify SvdOp slightly. Change: 134447786<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#include <algorithm>
#include "third_party/eigen3/Eigen/SVD"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
template <class Scalar>
class SvdOp : public LinearAlgebraOp<Scalar> {
public:
typedef LinearAlgebraOp<Scalar> Base;
explicit SvdOp(OpKernelConstruction* context) : Base(context) {
OP_REQUIRES_OK(context, context->GetAttr("compute_uv", &compute_uv_));
OP_REQUIRES_OK(context, context->GetAttr("full_matrices", &full_matrices_));
}
using TensorShapes = typename Base::TensorShapes;
void ValidateInputMatrixShapes(
OpKernelContext* context,
const TensorShapes& input_matrix_shapes) const final {
Base::ValidateSingleMatrix(context, input_matrix_shapes);
}
TensorShapes GetOutputMatrixShapes(
const TensorShapes& input_matrix_shapes) const final {
int64 m = input_matrix_shapes[0].dim_size(0);
int64 n = input_matrix_shapes[0].dim_size(1);
int64 min_size = std::min(m, n);
if (compute_uv_) {
return TensorShapes({TensorShape({min_size}),
TensorShape({m, full_matrices_ ? m : min_size}),
TensorShape({n, full_matrices_ ? n : min_size})});
} else {
return TensorShapes({TensorShape({min_size})});
}
}
// TODO(rmlarsen): This should depend on compute_uv. See b/30409375.
int64 GetCostPerUnit(const TensorShapes& input_matrix_shapes) const final {
double m = static_cast<double>(input_matrix_shapes[0].dim_size(0));
double n = static_cast<double>(input_matrix_shapes[0].dim_size(1));
double cost = 12 * std::max(m, n) * std::min(m, n) * std::min(m, n);
return cost >= static_cast<double>(kint64max) ? kint64max
: static_cast<int64>(cost);
}
using Matrix = typename Base::Matrix;
using MatrixMaps = typename Base::MatrixMaps;
using ConstMatrixMap = typename Base::ConstMatrixMap;
using ConstMatrixMaps = typename Base::ConstMatrixMaps;
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs,
MatrixMaps* outputs) final {
int options = 0; // Don't compute singular vectors;
if (compute_uv_) {
options = full_matrices_ ? Eigen::ComputeFullU | Eigen::ComputeFullV
: Eigen::ComputeThinU | Eigen::ComputeThinV;
}
Eigen::BDCSVD<Matrix> svd(inputs[0], options);
outputs->at(0) = svd.singularValues().template cast<Scalar>();
if (compute_uv_) {
outputs->at(1) = svd.matrixU();
outputs->at(2) = svd.matrixV();
}
}
private:
bool compute_uv_;
bool full_matrices_;
TF_DISALLOW_COPY_AND_ASSIGN(SvdOp);
};
REGISTER_LINALG_OP("Svd", (SvdOp<float>), float);
REGISTER_LINALG_OP("Svd", (SvdOp<double>), double);
REGISTER_LINALG_OP("Svd", (SvdOp<complex64>), complex64);
REGISTER_LINALG_OP("Svd", (SvdOp<complex128>), complex128);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<float>), float);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<double>), double);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<complex64>), complex64);
REGISTER_LINALG_OP("BatchSvd", (SvdOp<complex128>), complex128);
} // namespace tensorflow
<|endoftext|> |
<commit_before>/*expense.cc KPilot
**
** Copyright (C) 2000-2001 by Adriaan de Groot, Christopher Molnar
**
** This file is part of the Expense conduit, a conduit for KPilot that
** synchronises the Pilot's expense application with .. something?
** Actually it just writes a CSV file.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/
/*
** Bug reports and questions can be sent to [email protected]
*/
#include "options.h"
// Only include what we really need:
// First UNIX system stuff, then std C++,
// then Qt, then KDE, then local includes.
//
//
#include <stream.h>
#include <time.h>
#ifndef QDIR_H
#include <qdir.h>
#endif
#ifndef QMAP_H
#include <qmap.h>
#endif
#ifndef _KGLOBAL_H
#include <kglobal.h>
#endif
#ifndef _KSTDDIRS_H
#include <kstddirs.h>
#endif
#ifndef _KMESSAGEBOX_H
#include <kmessagebox.h>
#endif
#ifndef _KSIMPLECONFIG_H
#include <ksimpleconfig.h>
#endif
#ifndef _KCONFIG_H
#include <kconfig.h>
#endif
#ifndef _DCOPCLIENT_H
#include <dcopclient.h>
#endif
#ifndef _KDEBUG_H
#include <kdebug.h>
#endif
#ifndef _PILOT_EXPENSE_H_
#include <pi-expense.h>
#endif
#ifndef _KPILOT_CONDUITAPP_H
#include "conduitApp.h"
#endif
#ifndef _KPILOT_KPILOTCONFIG_H
#include "kpilotConfig.h"
#endif
#ifndef _KPILOT_EXPENSE_H
#include "expense.h"
#endif
#ifndef _KPILOT_SETUPDIALOG_H
#include "setupDialog.h"
#endif
#ifndef _KPILOT_PILOTDATEENTRY_H
#include "pilotDateEntry.h"
#endif
#ifndef _KPILOT_PILOTDATABASE_H
#include "pilotDatabase.h"
#endif
#ifndef _KPILOT_PILOTRECORD_H
#include "pilotRecord.h"
#endif
#define DATESIZE 10
#include <kdb/connection.h>
#include <pi-expense.h>
#include <stdlib.h>
#include <qcstring.h>
#include <qdatetime.h>
#include <qtextstream.h>
#include <stdio.h>
#include <string.h>
/* This was copied out of the pilot-link package.
* I just like it here for quick reference.
struct Expense {
struct tm date;
enum ExpenseType type;
enum ExpensePayment payment;
int currency;
char * amount;
char * vendor;
char * city;
char * attendees;
char * note;
};
*/
char *
get_entry_type(enum ExpenseType type)
{
switch(type) {
case etAirfare:
return "Airfare";
case etBreakfast:
return "Breakfast";
case etBus:
return "Bus";
case etBusinessMeals:
return "BusinessMeals";
case etCarRental:
return "CarRental";
case etDinner:
return "Dinner";
case etEntertainment:
return "Entertainment";
case etFax:
return "Fax";
case etGas:
return "Gas";
case etGifts:
return "Gifts";
case etHotel:
return "Hotel";
case etIncidentals:
return "Incidentals";
case etLaundry:
return "Laundry";
case etLimo:
return "Limo";
case etLodging:
return "Lodging";
case etLunch:
return "Lunch";
case etMileage:
return "Mileage";
case etOther:
return "Other";
case etParking:
return "Parking";
case etPostage:
return "Postage";
case etSnack:
return "Snack";
case etSubway:
return "Subway";
case etSupplies:
return "Supplies";
case etTaxi:
return "Taxi";
case etTelephone:
return "Telephone";
case etTips:
return "Tips";
case etTolls:
return "Tolls";
case etTrain:
return "Train";
default:
return NULL;
}
}
char *
get_pay_type(enum ExpensePayment type)
{
switch (type) {
case epAmEx:
return "AmEx";
case epCash:
return "Cash";
case epCheck:
return "Check";
case epCreditCard:
return "CreditCard";
case epMasterCard:
return "MasterCard";
case epPrepaid:
return "Prepaid";
case epVISA:
return "VISA";
case epUnfiled:
return "Unfiled";
default:
return NULL;
}
}
// Something to allow us to check what revision
// the modules are that make up a binary distribution.
//
//
static const char *expense_id =
"$Id$";
// This is a generic main() function, all
// conduits look basically the same,
// except for the name of the conduit.
//
//
int main(int argc, char* argv[])
{
ConduitApp a(argc,argv,"conduitExpense",
I18N_NOOP("Expense Conduit"),
KPILOT_VERSION);
a.addAuthor("Adriaan de Groot",
"Expense Conduit author",
"[email protected]");
a.addAuthor("Christopher Molnar",
"Expense Conduit author",
"[email protected]");
ExpenseConduit conduit(a.getMode());
a.setConduit(&conduit);
return a.exec();
}
ExpenseConduit::ExpenseConduit(eConduitMode mode) :
BaseConduit(mode)
{
FUNCTIONSETUP;
}
ExpenseConduit::~ExpenseConduit()
{
FUNCTIONSETUP;
}
void
ExpenseConduit::doSync()
{
FUNCTIONSETUP;
struct Expense e;
kdDebug() << "expense" << ": In expense doSync" << endl;
KConfig& config=KPilotConfig::getConfig();
config.setGroup(ExpenseOptions::ExpenseGroup);
QString mDBType=config.readEntry("DBTypePolicy");
QString mDBnm=config.readEntry("DBname");
QString mDBsrv=config.readEntry("DBServer");
QString mDBtable=config.readEntry("DBtable");
QString mDBlogin=config.readEntry("DBlogin");
QString mDBpasswd=config.readEntry("DBpasswd");
QString mCSVname=config.readEntry("CSVFileName");
kdDebug() << "expense" << ": Read config entry \n" << "Db name: " << mDBnm << endl;
PilotRecord* rec;
int recordcount=0;
int index=0;
// Now let's open databases
if (mDBType=="1")
{
DEBUGCONDUIT << "MySQL database requested" << endl;
}
if (mDBType=="2")
{
DEBUGCONDUIT << "PostgreSQL database requested" << endl;
}
// Now let's read records
while ((rec=readRecordByIndex(index++)))
{
if (rec->isDeleted())
{
FUNCTIONSETUP;
}
else
{
FUNCTIONSETUP;
DEBUGCONDUIT << fname
<< ": Got record "
<< index-1
<< " @"
<< (int) rec
<< endl;
(void) unpack_Expense(&e,(unsigned char *)rec->getData(),rec->getLen());
rec=0L;
if (!mCSVname.isEmpty())
{
DEBUGCONDUIT << fname
<< mCSVname
<< endl;
//open file
QFile fp(mCSVname);
fp.open(IO_ReadWrite|IO_Append);
//format date for csv file
int tmpyr=e.date.tm_year+1900;
char dtstng[DATESIZE];
int tmpday=e.date.tm_mday;
int tmpmon=e.date.tm_mon+1;
sprintf(dtstng,"%d-%d-%d",tmpyr,tmpmon,tmpday);
const char* mesg=dtstng;
fp.writeBlock(mesg,qstrlen(mesg));
const char* delim=",";
fp.writeBlock(delim,qstrlen(delim));
//write rest of record
mesg=e.amount;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=get_pay_type(e.payment);
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=e.vendor;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=get_entry_type(e.type);
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=e.city;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
// remove line breaks from list of attendees - can't have in csv files
QString tmpatt=e.attendees;
QString tmpatt2=tmpatt.simplifyWhiteSpace();
mesg=tmpatt2.latin1();
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
// remove extra formatting from notes - can't have in csv files
QString tmpnotes=e.note;
QString tmpnotes2=tmpnotes.simplifyWhiteSpace();
DEBUGCONDUIT << tmpnotes2 << endl;
mesg=tmpnotes2.latin1();
DEBUGCONDUIT << mesg << endl;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
//Finish line
const char* endline="\n";
fp.writeBlock(endline,qstrlen(endline));
//be nice and close file
fp.close();
}
// Now let's write record to correct database
if (mDBType=="0")
{
DEBUGCONDUIT << fname << "No database requested" << endl;
}
if (mDBType=="1")
{
DEBUGCONDUIT << fname << "MySQL database requested" << endl;
}
if (mDBType=="2")
{
DEBUGCONDUIT << fname << "PostgreSQL database requested" << endl;
}
// REMEMBER to CLOSE database
}
DEBUGCONDUIT << fname << "Records: " << recordcount << endl;
}
}
// aboutAndSetup is pretty much the same
// on all conduits as well.
//
//
QWidget*
ExpenseConduit::aboutAndSetup()
{
FUNCTIONSETUP;
return new ExpenseOptions(0L);
}
const char *
ExpenseConduit::dbInfo()
{
return "ExpenseDB";
}
/* virtual */ void
ExpenseConduit::doTest()
{
FUNCTIONSETUP;
(void) expense_id;
}
// $Log$
// Revision 1.6 2001/03/16 13:31:33 molnarc
//
// all data now written to csv file and formatted.
// data is in the following order:
//
// transaction date,
// amount,
// payment type (cash, visa, amex,....),
// vendor name,
// Expense Type (car, tolls, parking, food, ....),
// location,
// attendees (strips all line breaks - can't have in csv file),
// notes (again, strips all line breaks - can't have in csv file)
//
// Revision 1.5 2001/03/16 01:19:49 molnarc
//
// added date to csv output
//
// Revision 1.4 2001/03/15 21:10:07 molnarc
//
//
// CJM - now it saves a csv file to the path in kpilotrc if
// the path exists. csv file needs some work, but its
// a start.
//
// Revision 1.3 2001/03/09 09:46:14 adridg
// Large-scale #include cleanup
//
// Revision 1.2 2001/03/05 23:57:53 adridg
// Added KPILOT_VERSION
//
// Revision 1.1 2001/03/04 21:45:30 adridg
// New expense conduit, non-functional but it compiles
//
<commit_msg><commit_after>/*expense.cc KPilot
**
** Copyright (C) 2000-2001 by Adriaan de Groot, Christopher Molnar
**
** This file is part of the Expense conduit, a conduit for KPilot that
** synchronises the Pilot's expense application with .. something?
** Actually it just writes a CSV file.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/
/*
** Bug reports and questions can be sent to [email protected]
*/
#include "options.h"
// Only include what we really need:
// First UNIX system stuff, then std C++,
// then Qt, then KDE, then local includes.
//
//
#include <stream.h>
#include <time.h>
#ifndef QDIR_H
#include <qdir.h>
#endif
#ifndef QMAP_H
#include <qmap.h>
#endif
#ifndef _KGLOBAL_H
#include <kglobal.h>
#endif
#ifndef _KSTDDIRS_H
#include <kstddirs.h>
#endif
#ifndef _KMESSAGEBOX_H
#include <kmessagebox.h>
#endif
#ifndef _KSIMPLECONFIG_H
#include <ksimpleconfig.h>
#endif
#ifndef _KCONFIG_H
#include <kconfig.h>
#endif
#ifndef _DCOPCLIENT_H
#include <dcopclient.h>
#endif
#ifndef _KDEBUG_H
#include <kdebug.h>
#endif
#ifndef _PILOT_EXPENSE_H_
#include <pi-expense.h>
#endif
#ifndef _KPILOT_CONDUITAPP_H
#include "conduitApp.h"
#endif
#ifndef _KPILOT_KPILOTCONFIG_H
#include "kpilotConfig.h"
#endif
#ifndef _KPILOT_EXPENSE_H
#include "expense.h"
#endif
#ifndef _KPILOT_SETUPDIALOG_H
#include "setupDialog.h"
#endif
#ifndef _KPILOT_PILOTDATEENTRY_H
#include "pilotDateEntry.h"
#endif
#ifndef _KPILOT_PILOTDATABASE_H
#include "pilotDatabase.h"
#endif
#ifndef _KPILOT_PILOTRECORD_H
#include "pilotRecord.h"
#endif
#define DATESIZE 10
#include <kdb/connection.h>
#include <pi-expense.h>
#include <stdlib.h>
#include <qcstring.h>
#include <qobject.h>
#include <qdatetime.h>
#include <qtextstream.h>
#include <stdio.h>
#include <string.h>
/* This was copied out of the pilot-link package.
* I just like it here for quick reference.
struct Expense {
struct tm date;
enum ExpenseType type;
enum ExpensePayment payment;
int currency;
char * amount;
char * vendor;
char * city;
char * attendees;
char * note;
};
*/
char *
get_entry_type(enum ExpenseType type)
{
switch(type) {
case etAirfare:
return "Airfare";
case etBreakfast:
return "Breakfast";
case etBus:
return "Bus";
case etBusinessMeals:
return "BusinessMeals";
case etCarRental:
return "CarRental";
case etDinner:
return "Dinner";
case etEntertainment:
return "Entertainment";
case etFax:
return "Fax";
case etGas:
return "Gas";
case etGifts:
return "Gifts";
case etHotel:
return "Hotel";
case etIncidentals:
return "Incidentals";
case etLaundry:
return "Laundry";
case etLimo:
return "Limo";
case etLodging:
return "Lodging";
case etLunch:
return "Lunch";
case etMileage:
return "Mileage";
case etOther:
return "Other";
case etParking:
return "Parking";
case etPostage:
return "Postage";
case etSnack:
return "Snack";
case etSubway:
return "Subway";
case etSupplies:
return "Supplies";
case etTaxi:
return "Taxi";
case etTelephone:
return "Telephone";
case etTips:
return "Tips";
case etTolls:
return "Tolls";
case etTrain:
return "Train";
default:
return NULL;
}
}
char *
get_pay_type(enum ExpensePayment type)
{
switch (type) {
case epAmEx:
return "AmEx";
case epCash:
return "Cash";
case epCheck:
return "Check";
case epCreditCard:
return "CreditCard";
case epMasterCard:
return "MasterCard";
case epPrepaid:
return "Prepaid";
case epVISA:
return "VISA";
case epUnfiled:
return "Unfiled";
default:
return NULL;
}
}
// Something to allow us to check what revision
// the modules are that make up a binary distribution.
//
//
static const char *expense_id =
"$Id$";
// This is a generic main() function, all
// conduits look basically the same,
// except for the name of the conduit.
//
//
int main(int argc, char* argv[])
{
ConduitApp a(argc,argv,"conduitExpense",
I18N_NOOP("Expense Conduit"),
KPILOT_VERSION);
a.addAuthor("Adriaan de Groot",
"Expense Conduit author",
"[email protected]");
a.addAuthor("Christopher Molnar",
"Expense Conduit author",
"[email protected]");
ExpenseConduit conduit(a.getMode());
a.setConduit(&conduit);
return a.exec();
}
ExpenseConduit::ExpenseConduit(eConduitMode mode) :
BaseConduit(mode)
{
FUNCTIONSETUP;
}
ExpenseConduit::~ExpenseConduit()
{
FUNCTIONSETUP;
}
void
ExpenseConduit::doSync()
{
FUNCTIONSETUP;
struct Expense e;
kdDebug() << "expense" << ": In expense doSync" << endl;
KConfig& config=KPilotConfig::getConfig();
config.setGroup(ExpenseOptions::ExpenseGroup);
QString mDBType=config.readEntry("DBTypePolicy");
QString mDBnm=config.readEntry("DBname");
QString mDBsrv=config.readEntry("DBServer");
QString mDBtable=config.readEntry("DBtable");
QString mDBlogin=config.readEntry("DBlogin");
QString mDBpasswd=config.readEntry("DBpasswd");
QString mCSVname=config.readEntry("CSVFileName");
kdDebug() << "expense" << ": Read config entry \n" << "Db name: " << mDBnm << endl;
PilotRecord* rec;
QString mDBDType="pg";
KDB::Connection* dbconn;
//KDB::Connection(mDBType, mDBsrv, 5424, *dbMobject);
int recordcount=0;
int index=0;
// Now let's open databases
if (mDBType=="1")
{
DEBUGCONDUIT << "MySQL database requested" << endl;
// QString mDBDType="pg";
dbconn->setPassword(mDBpasswd);
dbconn->setUser(mDBlogin);
}
if (mDBType=="2")
{
DEBUGCONDUIT << "PostgreSQL database requested" << endl;
}
// Now let's read records
while ((rec=readRecordByIndex(index++)))
{
if (rec->isDeleted())
{
FUNCTIONSETUP;
}
else
{
FUNCTIONSETUP;
DEBUGCONDUIT << fname
<< ": Got record "
<< index-1
<< " @"
<< (int) rec
<< endl;
(void) unpack_Expense(&e,(unsigned char *)rec->getData(),rec->getLen());
rec=0L;
if (!mCSVname.isEmpty())
{
DEBUGCONDUIT << fname
<< mCSVname
<< endl;
//open file
QFile fp(mCSVname);
fp.open(IO_ReadWrite|IO_Append);
//format date for csv file
int tmpyr=e.date.tm_year+1900;
char dtstng[DATESIZE];
int tmpday=e.date.tm_mday;
int tmpmon=e.date.tm_mon+1;
sprintf(dtstng,"%d-%d-%d",tmpyr,tmpmon,tmpday);
const char* mesg=dtstng;
fp.writeBlock(mesg,qstrlen(mesg));
const char* delim=",";
fp.writeBlock(delim,qstrlen(delim));
//write rest of record
mesg=e.amount;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=get_pay_type(e.payment);
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=e.vendor;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=get_entry_type(e.type);
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
mesg=e.city;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
// remove line breaks from list of attendees - can't have in csv files
QString tmpatt=e.attendees;
QString tmpatt2=tmpatt.simplifyWhiteSpace();
mesg=tmpatt2.latin1();
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
// remove extra formatting from notes - can't have in csv files
QString tmpnotes=e.note;
QString tmpnotes2=tmpnotes.simplifyWhiteSpace();
DEBUGCONDUIT << tmpnotes2 << endl;
mesg=tmpnotes2.latin1();
DEBUGCONDUIT << mesg << endl;
fp.writeBlock(mesg,qstrlen(mesg));
fp.writeBlock(delim,qstrlen(delim));
//Finish line
const char* endline="\n";
fp.writeBlock(endline,qstrlen(endline));
//be nice and close file
fp.close();
}
// Now let's write record to correct database
if (mDBType=="0")
{
DEBUGCONDUIT << fname << "No database requested" << endl;
}
if (mDBType=="1")
{
DEBUGCONDUIT << fname << "MySQL database requested" << endl;
}
if (mDBType=="2")
{
DEBUGCONDUIT << fname << "PostgreSQL database requested" << endl;
}
// REMEMBER to CLOSE database
}
DEBUGCONDUIT << fname << "Records: " << recordcount << endl;
}
}
// aboutAndSetup is pretty much the same
// on all conduits as well.
//
//
QWidget*
ExpenseConduit::aboutAndSetup()
{
FUNCTIONSETUP;
return new ExpenseOptions(0L);
}
const char *
ExpenseConduit::dbInfo()
{
return "ExpenseDB";
}
/* virtual */ void
ExpenseConduit::doTest()
{
FUNCTIONSETUP;
(void) expense_id;
}
// $Log$
// Revision 1.7 2001/03/17 00:15:11 molnarc
//
// expenses.cc --> some fixes
// Makefile.am --> added libkdbcore libkdb_mysql libkdb_postgres
// if this is the wrong way someone please fix this and tell me
// the right way to do it.
//
// Revision 1.6 2001/03/16 13:31:33 molnarc
//
// all data now written to csv file and formatted.
// data is in the following order:
//
// transaction date,
// amount,
// payment type (cash, visa, amex,....),
// vendor name,
// Expense Type (car, tolls, parking, food, ....),
// location,
// attendees (strips all line breaks - can't have in csv file),
// notes (again, strips all line breaks - can't have in csv file)
//
// Revision 1.5 2001/03/16 01:19:49 molnarc
//
// added date to csv output
//
// Revision 1.4 2001/03/15 21:10:07 molnarc
//
//
// CJM - now it saves a csv file to the path in kpilotrc if
// the path exists. csv file needs some work, but its
// a start.
//
// Revision 1.3 2001/03/09 09:46:14 adridg
// Large-scale #include cleanup
//
// Revision 1.2 2001/03/05 23:57:53 adridg
// Added KPILOT_VERSION
//
// Revision 1.1 2001/03/04 21:45:30 adridg
// New expense conduit, non-functional but it compiles
//
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/android/net/android_stream_reader_url_request_job.h"
#include <string>
#include <vector>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/lazy_instance.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task_runner.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/io_buffer.h"
#include "net/base/mime_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job_manager.h"
#include "xwalk/runtime/browser/android/net/input_stream.h"
#include "xwalk/runtime/browser/android/net/input_stream_reader.h"
#include "xwalk/runtime/browser/android/net/url_constants.h"
using base::android::AttachCurrentThread;
using base::PostTaskAndReplyWithResult;
using content::BrowserThread;
using xwalk::InputStream;
using xwalk::InputStreamReader;
namespace {
const int kHTTPOk = 200;
const int kHTTPBadRequest = 400;
const int kHTTPForbidden = 403;
const int kHTTPNotFound = 404;
const int kHTTPNotImplemented = 501;
const char kHTTPOkText[] = "OK";
const char kHTTPBadRequestText[] = "Bad Request";
const char kHTTPForbiddenText[] = "Forbidden";
const char kHTTPNotFoundText[] = "Not Found";
const char kHTTPNotImplementedText[] = "Not Implemented";
} // namespace
// The requests posted to the worker thread might outlive the job. Thread-safe
// ref counting is used to ensure that the InputStream and InputStreamReader
// members of this class are still there when the closure is run on the worker
// thread.
class InputStreamReaderWrapper
: public base::RefCountedThreadSafe<InputStreamReaderWrapper> {
public:
InputStreamReaderWrapper(
scoped_ptr<InputStream> input_stream,
scoped_ptr<InputStreamReader> input_stream_reader)
: input_stream_(input_stream.Pass()),
input_stream_reader_(input_stream_reader.Pass()) {
DCHECK(input_stream_);
DCHECK(input_stream_reader_);
}
xwalk::InputStream* input_stream() {
return input_stream_.get();
}
int Seek(const net::HttpByteRange& byte_range) {
return input_stream_reader_->Seek(byte_range);
}
int ReadRawData(net::IOBuffer* buffer, int buffer_size) {
return input_stream_reader_->ReadRawData(buffer, buffer_size);
}
private:
friend class base::RefCountedThreadSafe<InputStreamReaderWrapper>;
~InputStreamReaderWrapper() {}
scoped_ptr<xwalk::InputStream> input_stream_;
scoped_ptr<xwalk::InputStreamReader> input_stream_reader_;
DISALLOW_COPY_AND_ASSIGN(InputStreamReaderWrapper);
};
AndroidStreamReaderURLRequestJob::AndroidStreamReaderURLRequestJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
scoped_ptr<Delegate> delegate,
const std::string& content_security_policy)
: URLRequestJob(request, network_delegate),
delegate_(delegate.Pass()),
content_security_policy_(content_security_policy),
weak_factory_(this) {
DCHECK(delegate_);
}
AndroidStreamReaderURLRequestJob::~AndroidStreamReaderURLRequestJob() {
}
namespace {
typedef base::Callback<
void(scoped_ptr<AndroidStreamReaderURLRequestJob::Delegate>,
scoped_ptr<InputStream>)> OnInputStreamOpenedCallback;
// static
void OpenInputStreamOnWorkerThread(
scoped_refptr<base::MessageLoopProxy> job_thread_proxy,
scoped_ptr<AndroidStreamReaderURLRequestJob::Delegate> delegate,
const GURL& url,
OnInputStreamOpenedCallback callback) {
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
scoped_ptr<InputStream> input_stream = delegate->OpenInputStream(env, url);
job_thread_proxy->PostTask(FROM_HERE,
base::Bind(callback,
base::Passed(delegate.Pass()),
base::Passed(input_stream.Pass())));
}
} // namespace
void AndroidStreamReaderURLRequestJob::Start() {
DCHECK(thread_checker_.CalledOnValidThread());
GURL url = request()->url();
// Generate the HTTP header response for app scheme.
if (url.SchemeIs(xwalk::kAppScheme)) {
// Once the unpermitted request was received, the job should be marked
// as complete, and the function should return, so that the request task
// won't be posted.
if (request()->method() != "GET") {
HeadersComplete(kHTTPNotImplemented, kHTTPNotImplementedText);
return;
} else if (url.path().empty()) {
HeadersComplete(kHTTPBadRequest, kHTTPBadRequestText);
return;
} else {
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
std::string package_name;
delegate_->GetPackageName(env, &package_name);
// The host should be the same as the lower case of the package
// name, otherwise the resource request should be rejected.
// TODO(Xingnan): More permission control policy will be added here,
// if it's needed.
if (request()->url().host() != base::StringToLowerASCII(package_name)) {
HeadersComplete(kHTTPForbidden, kHTTPForbiddenText);
return;
}
}
}
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING,
net::ERR_IO_PENDING));
// This could be done in the InputStreamReader but would force more
// complex synchronization in the delegate.
GetWorkerThreadRunner()->PostTask(
FROM_HERE,
base::Bind(
&OpenInputStreamOnWorkerThread,
base::MessageLoop::current()->message_loop_proxy(),
// This is intentional - the job could be deleted while the callback
// is executing on the background thread.
// The delegate will be "returned" to the job once the InputStream
// open attempt is completed.
base::Passed(&delegate_),
request()->url(),
base::Bind(&AndroidStreamReaderURLRequestJob::OnInputStreamOpened,
weak_factory_.GetWeakPtr())));
}
void AndroidStreamReaderURLRequestJob::Kill() {
DCHECK(thread_checker_.CalledOnValidThread());
weak_factory_.InvalidateWeakPtrs();
URLRequestJob::Kill();
}
scoped_ptr<InputStreamReader>
AndroidStreamReaderURLRequestJob::CreateStreamReader(InputStream* stream) {
return make_scoped_ptr(new InputStreamReader(stream));
}
void AndroidStreamReaderURLRequestJob::OnInputStreamOpened(
scoped_ptr<Delegate> returned_delegate,
scoped_ptr<xwalk::InputStream> input_stream) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(returned_delegate);
delegate_ = returned_delegate.Pass();
if (!input_stream) {
bool restart_required = false;
delegate_->OnInputStreamOpenFailed(request(), &restart_required);
if (restart_required) {
NotifyRestartRequired();
} else {
// Clear the IO_PENDING status set in Start().
SetStatus(net::URLRequestStatus());
HeadersComplete(kHTTPNotFound, kHTTPNotFoundText);
}
return;
}
scoped_ptr<InputStreamReader> input_stream_reader(
CreateStreamReader(input_stream.get()));
DCHECK(input_stream_reader);
DCHECK(!input_stream_reader_wrapper_.get());
input_stream_reader_wrapper_ = new InputStreamReaderWrapper(
input_stream.Pass(), input_stream_reader.Pass());
PostTaskAndReplyWithResult(
GetWorkerThreadRunner(),
FROM_HERE,
base::Bind(&InputStreamReaderWrapper::Seek,
input_stream_reader_wrapper_,
byte_range_),
base::Bind(&AndroidStreamReaderURLRequestJob::OnReaderSeekCompleted,
weak_factory_.GetWeakPtr()));
}
void AndroidStreamReaderURLRequestJob::OnReaderSeekCompleted(int result) {
DCHECK(thread_checker_.CalledOnValidThread());
// Clear the IO_PENDING status set in Start().
SetStatus(net::URLRequestStatus());
if (result >= 0) {
set_expected_content_size(result);
HeadersComplete(kHTTPOk, kHTTPOkText);
} else {
NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, result));
}
}
void AndroidStreamReaderURLRequestJob::OnReaderReadCompleted(int result) {
DCHECK(thread_checker_.CalledOnValidThread());
// The URLRequest API contract requires that:
// * NotifyDone be called once, to set the status code, indicate the job is
// finished (there will be no further IO),
// * NotifyReadComplete be called if false is returned from ReadRawData to
// indicate that the IOBuffer will not be used by the job anymore.
// There might be multiple calls to ReadRawData (and thus multiple calls to
// NotifyReadComplete), which is why NotifyDone is called only on errors
// (result < 0) and end of data (result == 0).
if (result == 0) {
NotifyDone(net::URLRequestStatus());
} else if (result < 0) {
NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, result));
} else {
// Clear the IO_PENDING status.
SetStatus(net::URLRequestStatus());
}
NotifyReadComplete(result);
}
base::TaskRunner* AndroidStreamReaderURLRequestJob::GetWorkerThreadRunner() {
return static_cast<base::TaskRunner*>(BrowserThread::GetBlockingPool());
}
bool AndroidStreamReaderURLRequestJob::ReadRawData(net::IOBuffer* dest,
int dest_size,
int* bytes_read) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!input_stream_reader_wrapper_.get()) {
// This will happen if opening the InputStream fails in which case the
// error is communicated by setting the HTTP response status header rather
// than failing the request during the header fetch phase.
*bytes_read = 0;
return true;
}
PostTaskAndReplyWithResult(
GetWorkerThreadRunner(),
FROM_HERE,
base::Bind(&InputStreamReaderWrapper::ReadRawData,
input_stream_reader_wrapper_,
make_scoped_refptr(dest),
dest_size),
base::Bind(&AndroidStreamReaderURLRequestJob::OnReaderReadCompleted,
weak_factory_.GetWeakPtr()));
SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING,
net::ERR_IO_PENDING));
return false;
}
bool AndroidStreamReaderURLRequestJob::GetMimeType(
std::string* mime_type) const {
DCHECK(thread_checker_.CalledOnValidThread());
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
if (!input_stream_reader_wrapper_.get())
return false;
// Since it's possible for this call to alter the InputStream a
// Seek or ReadRawData operation running in the background is not permitted.
DCHECK(!request_->status().is_io_pending());
return delegate_->GetMimeType(
env, request(), input_stream_reader_wrapper_->input_stream(), mime_type);
}
bool AndroidStreamReaderURLRequestJob::GetCharset(std::string* charset) {
DCHECK(thread_checker_.CalledOnValidThread());
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
if (!input_stream_reader_wrapper_.get())
return false;
// Since it's possible for this call to alter the InputStream a
// Seek or ReadRawData operation running in the background is not permitted.
DCHECK(!request_->status().is_io_pending());
return delegate_->GetCharset(
env, request(), input_stream_reader_wrapper_->input_stream(), charset);
}
void AndroidStreamReaderURLRequestJob::HeadersComplete(
int status_code,
const std::string& status_text) {
std::string status("HTTP/1.1 ");
status.append(base::IntToString(status_code));
status.append(" ");
status.append(status_text);
// HttpResponseHeaders expects its input string to be terminated by two NULs.
status.append("\0\0", 2);
net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status);
if (status_code == kHTTPOk) {
if (expected_content_size() != -1) {
std::string content_length_header(
net::HttpRequestHeaders::kContentLength);
content_length_header.append(": ");
content_length_header.append(
base::Int64ToString(expected_content_size()));
headers->AddHeader(content_length_header);
}
std::string mime_type;
if (GetMimeType(&mime_type) && !mime_type.empty()) {
std::string content_type_header(net::HttpRequestHeaders::kContentType);
content_type_header.append(": ");
content_type_header.append(mime_type);
headers->AddHeader(content_type_header);
}
if (!content_security_policy_.empty()) {
std::string content_security_policy("Content-Security-Policy: ");
content_security_policy.append(content_security_policy_);
headers->AddHeader(content_security_policy);
}
}
response_info_.reset(new net::HttpResponseInfo());
response_info_->headers = headers;
NotifyHeadersComplete();
}
int AndroidStreamReaderURLRequestJob::GetResponseCode() const {
if (response_info_)
return response_info_->headers->response_code();
return URLRequestJob::GetResponseCode();
}
void AndroidStreamReaderURLRequestJob::GetResponseInfo(
net::HttpResponseInfo* info) {
if (response_info_)
*info = *response_info_;
}
void AndroidStreamReaderURLRequestJob::SetExtraRequestHeaders(
const net::HttpRequestHeaders& headers) {
std::string range_header;
if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) {
// We only extract the "Range" header so that we know how many bytes in the
// stream to skip and how many to read after that.
std::vector<net::HttpByteRange> ranges;
if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) {
if (ranges.size() == 1) {
byte_range_ = ranges[0];
} else {
// We don't support multiple range requests in one single URL request,
// because we need to do multipart encoding here.
NotifyDone(net::URLRequestStatus(
net::URLRequestStatus::FAILED,
net::ERR_REQUEST_RANGE_NOT_SATISFIABLE));
}
}
}
}
<commit_msg>[Android] Fix app crash when two pages load each other for more than 512 times<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/android/net/android_stream_reader_url_request_job.h"
#include <string>
#include <vector>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/lazy_instance.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task_runner.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/io_buffer.h"
#include "net/base/mime_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job_manager.h"
#include "xwalk/runtime/browser/android/net/input_stream.h"
#include "xwalk/runtime/browser/android/net/input_stream_reader.h"
#include "xwalk/runtime/browser/android/net/url_constants.h"
using base::android::AttachCurrentThread;
using base::android::DetachFromVM;
using base::PostTaskAndReplyWithResult;
using content::BrowserThread;
using xwalk::InputStream;
using xwalk::InputStreamReader;
namespace {
const int kHTTPOk = 200;
const int kHTTPBadRequest = 400;
const int kHTTPForbidden = 403;
const int kHTTPNotFound = 404;
const int kHTTPNotImplemented = 501;
const char kHTTPOkText[] = "OK";
const char kHTTPBadRequestText[] = "Bad Request";
const char kHTTPForbiddenText[] = "Forbidden";
const char kHTTPNotFoundText[] = "Not Found";
const char kHTTPNotImplementedText[] = "Not Implemented";
} // namespace
// The requests posted to the worker thread might outlive the job. Thread-safe
// ref counting is used to ensure that the InputStream and InputStreamReader
// members of this class are still there when the closure is run on the worker
// thread.
class InputStreamReaderWrapper
: public base::RefCountedThreadSafe<InputStreamReaderWrapper> {
public:
InputStreamReaderWrapper(
scoped_ptr<InputStream> input_stream,
scoped_ptr<InputStreamReader> input_stream_reader)
: input_stream_(input_stream.Pass()),
input_stream_reader_(input_stream_reader.Pass()) {
DCHECK(input_stream_);
DCHECK(input_stream_reader_);
}
xwalk::InputStream* input_stream() {
return input_stream_.get();
}
int Seek(const net::HttpByteRange& byte_range) {
return input_stream_reader_->Seek(byte_range);
}
int ReadRawData(net::IOBuffer* buffer, int buffer_size) {
return input_stream_reader_->ReadRawData(buffer, buffer_size);
}
private:
friend class base::RefCountedThreadSafe<InputStreamReaderWrapper>;
~InputStreamReaderWrapper() {}
scoped_ptr<xwalk::InputStream> input_stream_;
scoped_ptr<xwalk::InputStreamReader> input_stream_reader_;
DISALLOW_COPY_AND_ASSIGN(InputStreamReaderWrapper);
};
AndroidStreamReaderURLRequestJob::AndroidStreamReaderURLRequestJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
scoped_ptr<Delegate> delegate,
const std::string& content_security_policy)
: URLRequestJob(request, network_delegate),
delegate_(delegate.Pass()),
content_security_policy_(content_security_policy),
weak_factory_(this) {
DCHECK(delegate_);
}
AndroidStreamReaderURLRequestJob::~AndroidStreamReaderURLRequestJob() {
}
namespace {
typedef base::Callback<
void(scoped_ptr<AndroidStreamReaderURLRequestJob::Delegate>,
scoped_ptr<InputStream>)> OnInputStreamOpenedCallback;
// static
void OpenInputStreamOnWorkerThread(
scoped_refptr<base::MessageLoopProxy> job_thread_proxy,
scoped_ptr<AndroidStreamReaderURLRequestJob::Delegate> delegate,
const GURL& url,
OnInputStreamOpenedCallback callback) {
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
scoped_ptr<InputStream> input_stream = delegate->OpenInputStream(env, url);
job_thread_proxy->PostTask(FROM_HERE,
base::Bind(callback,
base::Passed(delegate.Pass()),
base::Passed(input_stream.Pass())));
DetachFromVM();
}
} // namespace
void AndroidStreamReaderURLRequestJob::Start() {
DCHECK(thread_checker_.CalledOnValidThread());
GURL url = request()->url();
// Generate the HTTP header response for app scheme.
if (url.SchemeIs(xwalk::kAppScheme)) {
// Once the unpermitted request was received, the job should be marked
// as complete, and the function should return, so that the request task
// won't be posted.
if (request()->method() != "GET") {
HeadersComplete(kHTTPNotImplemented, kHTTPNotImplementedText);
return;
} else if (url.path().empty()) {
HeadersComplete(kHTTPBadRequest, kHTTPBadRequestText);
return;
} else {
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
std::string package_name;
delegate_->GetPackageName(env, &package_name);
// The host should be the same as the lower case of the package
// name, otherwise the resource request should be rejected.
// TODO(Xingnan): More permission control policy will be added here,
// if it's needed.
if (request()->url().host() != base::StringToLowerASCII(package_name)) {
HeadersComplete(kHTTPForbidden, kHTTPForbiddenText);
return;
}
}
}
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING,
net::ERR_IO_PENDING));
// This could be done in the InputStreamReader but would force more
// complex synchronization in the delegate.
GetWorkerThreadRunner()->PostTask(
FROM_HERE,
base::Bind(
&OpenInputStreamOnWorkerThread,
base::MessageLoop::current()->message_loop_proxy(),
// This is intentional - the job could be deleted while the callback
// is executing on the background thread.
// The delegate will be "returned" to the job once the InputStream
// open attempt is completed.
base::Passed(&delegate_),
request()->url(),
base::Bind(&AndroidStreamReaderURLRequestJob::OnInputStreamOpened,
weak_factory_.GetWeakPtr())));
}
void AndroidStreamReaderURLRequestJob::Kill() {
DCHECK(thread_checker_.CalledOnValidThread());
weak_factory_.InvalidateWeakPtrs();
URLRequestJob::Kill();
}
scoped_ptr<InputStreamReader>
AndroidStreamReaderURLRequestJob::CreateStreamReader(InputStream* stream) {
return make_scoped_ptr(new InputStreamReader(stream));
}
void AndroidStreamReaderURLRequestJob::OnInputStreamOpened(
scoped_ptr<Delegate> returned_delegate,
scoped_ptr<xwalk::InputStream> input_stream) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(returned_delegate);
delegate_ = returned_delegate.Pass();
if (!input_stream) {
bool restart_required = false;
delegate_->OnInputStreamOpenFailed(request(), &restart_required);
if (restart_required) {
NotifyRestartRequired();
} else {
// Clear the IO_PENDING status set in Start().
SetStatus(net::URLRequestStatus());
HeadersComplete(kHTTPNotFound, kHTTPNotFoundText);
}
return;
}
scoped_ptr<InputStreamReader> input_stream_reader(
CreateStreamReader(input_stream.get()));
DCHECK(input_stream_reader);
DCHECK(!input_stream_reader_wrapper_.get());
input_stream_reader_wrapper_ = new InputStreamReaderWrapper(
input_stream.Pass(), input_stream_reader.Pass());
PostTaskAndReplyWithResult(
GetWorkerThreadRunner(),
FROM_HERE,
base::Bind(&InputStreamReaderWrapper::Seek,
input_stream_reader_wrapper_,
byte_range_),
base::Bind(&AndroidStreamReaderURLRequestJob::OnReaderSeekCompleted,
weak_factory_.GetWeakPtr()));
}
void AndroidStreamReaderURLRequestJob::OnReaderSeekCompleted(int result) {
DCHECK(thread_checker_.CalledOnValidThread());
// Clear the IO_PENDING status set in Start().
SetStatus(net::URLRequestStatus());
if (result >= 0) {
set_expected_content_size(result);
HeadersComplete(kHTTPOk, kHTTPOkText);
} else {
NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, result));
}
}
void AndroidStreamReaderURLRequestJob::OnReaderReadCompleted(int result) {
DCHECK(thread_checker_.CalledOnValidThread());
// The URLRequest API contract requires that:
// * NotifyDone be called once, to set the status code, indicate the job is
// finished (there will be no further IO),
// * NotifyReadComplete be called if false is returned from ReadRawData to
// indicate that the IOBuffer will not be used by the job anymore.
// There might be multiple calls to ReadRawData (and thus multiple calls to
// NotifyReadComplete), which is why NotifyDone is called only on errors
// (result < 0) and end of data (result == 0).
if (result == 0) {
NotifyDone(net::URLRequestStatus());
} else if (result < 0) {
NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, result));
} else {
// Clear the IO_PENDING status.
SetStatus(net::URLRequestStatus());
}
NotifyReadComplete(result);
}
base::TaskRunner* AndroidStreamReaderURLRequestJob::GetWorkerThreadRunner() {
return static_cast<base::TaskRunner*>(BrowserThread::GetBlockingPool());
}
bool AndroidStreamReaderURLRequestJob::ReadRawData(net::IOBuffer* dest,
int dest_size,
int* bytes_read) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!input_stream_reader_wrapper_.get()) {
// This will happen if opening the InputStream fails in which case the
// error is communicated by setting the HTTP response status header rather
// than failing the request during the header fetch phase.
*bytes_read = 0;
return true;
}
PostTaskAndReplyWithResult(
GetWorkerThreadRunner(),
FROM_HERE,
base::Bind(&InputStreamReaderWrapper::ReadRawData,
input_stream_reader_wrapper_,
make_scoped_refptr(dest),
dest_size),
base::Bind(&AndroidStreamReaderURLRequestJob::OnReaderReadCompleted,
weak_factory_.GetWeakPtr()));
SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING,
net::ERR_IO_PENDING));
return false;
}
bool AndroidStreamReaderURLRequestJob::GetMimeType(
std::string* mime_type) const {
DCHECK(thread_checker_.CalledOnValidThread());
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
if (!input_stream_reader_wrapper_.get())
return false;
// Since it's possible for this call to alter the InputStream a
// Seek or ReadRawData operation running in the background is not permitted.
DCHECK(!request_->status().is_io_pending());
return delegate_->GetMimeType(
env, request(), input_stream_reader_wrapper_->input_stream(), mime_type);
}
bool AndroidStreamReaderURLRequestJob::GetCharset(std::string* charset) {
DCHECK(thread_checker_.CalledOnValidThread());
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
if (!input_stream_reader_wrapper_.get())
return false;
// Since it's possible for this call to alter the InputStream a
// Seek or ReadRawData operation running in the background is not permitted.
DCHECK(!request_->status().is_io_pending());
return delegate_->GetCharset(
env, request(), input_stream_reader_wrapper_->input_stream(), charset);
}
void AndroidStreamReaderURLRequestJob::HeadersComplete(
int status_code,
const std::string& status_text) {
std::string status("HTTP/1.1 ");
status.append(base::IntToString(status_code));
status.append(" ");
status.append(status_text);
// HttpResponseHeaders expects its input string to be terminated by two NULs.
status.append("\0\0", 2);
net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status);
if (status_code == kHTTPOk) {
if (expected_content_size() != -1) {
std::string content_length_header(
net::HttpRequestHeaders::kContentLength);
content_length_header.append(": ");
content_length_header.append(
base::Int64ToString(expected_content_size()));
headers->AddHeader(content_length_header);
}
std::string mime_type;
if (GetMimeType(&mime_type) && !mime_type.empty()) {
std::string content_type_header(net::HttpRequestHeaders::kContentType);
content_type_header.append(": ");
content_type_header.append(mime_type);
headers->AddHeader(content_type_header);
}
if (!content_security_policy_.empty()) {
std::string content_security_policy("Content-Security-Policy: ");
content_security_policy.append(content_security_policy_);
headers->AddHeader(content_security_policy);
}
}
response_info_.reset(new net::HttpResponseInfo());
response_info_->headers = headers;
NotifyHeadersComplete();
}
int AndroidStreamReaderURLRequestJob::GetResponseCode() const {
if (response_info_)
return response_info_->headers->response_code();
return URLRequestJob::GetResponseCode();
}
void AndroidStreamReaderURLRequestJob::GetResponseInfo(
net::HttpResponseInfo* info) {
if (response_info_)
*info = *response_info_;
}
void AndroidStreamReaderURLRequestJob::SetExtraRequestHeaders(
const net::HttpRequestHeaders& headers) {
std::string range_header;
if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) {
// We only extract the "Range" header so that we know how many bytes in the
// stream to skip and how many to read after that.
std::vector<net::HttpByteRange> ranges;
if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) {
if (ranges.size() == 1) {
byte_range_ = ranges[0];
} else {
// We don't support multiple range requests in one single URL request,
// because we need to do multipart encoding here.
NotifyDone(net::URLRequestStatus(
net::URLRequestStatus::FAILED,
net::ERR_REQUEST_RANGE_NOT_SATISFIABLE));
}
}
}
}
<|endoftext|> |
<commit_before>#include "InstructionParser.hpp"
#include "gtest/gtest.h"
using namespace ::testing;
struct InstructionParserTest : public Test
{
InstructionParser parser;
};
TEST_F(InstructionParserTest, ParserShouldDeclineUnknownInstruction)
{
EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}
TEST_F(InstructionParserTest, ParserShouldRejectInstuctionLd)
{
const Tokens expectedTokens{TokenType::Ld, TokenType::A};
parser.parseInstructions("ld a,");
}
TEST_F(InstructionParserTest, ParserShouldAcceptInstructionOut)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions("out (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldAcceptEmptyLine)
{
const Tokens expectedTokens{};
EXPECT_EQ(expectedTokens, parser.parseInstructions(""));
}
TEST_F(InstructionParserTest, ParserShouldAcceptInstructionOutWithWhitespaces)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions(" \t out (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldAcceptTwoInstructions)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A,
TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions("out (0),a\nout (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldThrowIfSecondInstructionIsInvalid)
{
EXPECT_THROW(parser.parseInstructions("out (0),a\ninvalid"), InstructionParser::UnknownInstruction);
}
TEST_F(InstructionParserTest, ParserShouldAcceptTwoInstructionsWithEmptyLine)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A,
TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions("out (0),a\n\nout (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldAbleToGet0AsToken)
{
const Tokens expectedTokens{TokenType::Number8Bit};
parser.parseInstructions("0");
}
TEST_F(InstructionParserTest, ParserShouldAbleToGet255AsToken)
{
const Tokens expectedTokens{TokenType::Number8Bit};
parser.parseInstructions("255");
}<commit_msg>InstructionParser is able to reject -1<commit_after>#include "InstructionParser.hpp"
#include "gtest/gtest.h"
using namespace ::testing;
struct InstructionParserTest : public Test
{
InstructionParser parser;
};
TEST_F(InstructionParserTest, ParserShouldDeclineUnknownInstruction)
{
EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}
TEST_F(InstructionParserTest, ParserShouldRejectInstuctionLd)
{
const Tokens expectedTokens{TokenType::Ld, TokenType::A};
parser.parseInstructions("ld a,");
}
TEST_F(InstructionParserTest, ParserShouldAcceptInstructionOut)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions("out (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldAcceptEmptyLine)
{
const Tokens expectedTokens{};
EXPECT_EQ(expectedTokens, parser.parseInstructions(""));
}
TEST_F(InstructionParserTest, ParserShouldAcceptInstructionOutWithWhitespaces)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions(" \t out (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldAcceptTwoInstructions)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A,
TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions("out (0),a\nout (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldThrowIfSecondInstructionIsInvalid)
{
EXPECT_THROW(parser.parseInstructions("out (0),a\ninvalid"), InstructionParser::UnknownInstruction);
}
TEST_F(InstructionParserTest, ParserShouldAcceptTwoInstructionsWithEmptyLine)
{
const Tokens expectedTokens{TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A,
TokenType::Out, TokenType::ZeroWithBrackets, TokenType::A};
EXPECT_EQ(expectedTokens, parser.parseInstructions("out (0),a\n\nout (0),a"));
}
TEST_F(InstructionParserTest, ParserShouldAbleToGet0AsToken)
{
const Tokens expectedTokens{TokenType::Number8Bit};
parser.parseInstructions("0");
}
TEST_F(InstructionParserTest, ParserShouldAbleToGet255AsToken)
{
const Tokens expectedTokens{TokenType::Number8Bit};
parser.parseInstructions("255");
}
TEST_F(InstructionParserTest, ParserShouldAbleToGetMinusOneAsToken)
{
EXPECT_THROW(parser.parseInstructions("-1"), InstructionParser::UnknownInstruction);
}<|endoftext|> |
<commit_before>#include <array>
#include <utility>
#include <type_traits>
#include <gtest/gtest.h>
#include "apply_ref_from_to.h"
#ifdef WITH_STATIC_ASSERT
namespace {
template <typename T>
constexpr bool static_assert_tests(const T it, const T end);
template <typename T>
constexpr bool static_assert_tests_implem(const T it, const T end)
{
/* this is pure bullshit, constexpr environment, but can use neither:
* . it->first as condition for static_assert
* . it->second as string for static_assert (actully, not even a basic constexpr const* const char works...)
*/
//static_assert((it->first == true), "apply_ref_from_t failure");
return static_assert_tests(it + 1, end);
}
template <typename T>
constexpr bool static_assert_tests(const T it, const T end)
{
return it == end || static_assert_tests_implem(it, end);
}
}
#endif // WITH_STATIC_ASSERT
TEST(apply_ref_from_to_tTest, Foo) {
struct From {};
struct To {};
using namespace broken_algo;
constexpr auto tests = {
std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "From& -> To&")
, std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "From&& -> To&&")
, std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "const From& -> const To&")
, std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "const From&& -> const To&&")
};
#ifdef WITH_STATIC_ASSERT
{
constexpr auto begin = tests.begin();
constexpr auto end = tests.end();
constexpr auto dummy = static_assert_tests(begin, end);
{
constexpr auto condition = (begin + 0)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
{
constexpr auto condition = (begin + 1)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
{
constexpr auto condition = (begin + 2)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
{
constexpr auto condition = (begin + 3)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
}
#endif // WITH_STATIC_ASSERT
for (auto& test : tests)
{
ASSERT_TRUE((test.first)) << test.second;
}
}
<commit_msg>removed useless include<commit_after>#include <utility>
#include <type_traits>
#include <gtest/gtest.h>
#include "apply_ref_from_to.h"
#ifdef WITH_STATIC_ASSERT
namespace {
template <typename T>
constexpr bool static_assert_tests(const T it, const T end);
template <typename T>
constexpr bool static_assert_tests_implem(const T it, const T end)
{
/* this is pure bullshit, constexpr environment, but can use neither:
* . it->first as condition for static_assert
* . it->second as string for static_assert (actully, not even a basic constexpr const* const char works...)
*/
//static_assert((it->first == true), "apply_ref_from_t failure");
return static_assert_tests(it + 1, end);
}
template <typename T>
constexpr bool static_assert_tests(const T it, const T end)
{
return it == end || static_assert_tests_implem(it, end);
}
}
#endif // WITH_STATIC_ASSERT
TEST(apply_ref_from_to_tTest, Foo) {
struct From {};
struct To {};
using namespace broken_algo;
constexpr auto tests = {
std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "From& -> To&")
, std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "From&& -> To&&")
, std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "const From& -> const To&")
, std::make_pair(std::is_same<apply_ref_from_to_t<From&, To>, To& >(), "const From&& -> const To&&")
};
#ifdef WITH_STATIC_ASSERT
{
constexpr auto begin = tests.begin();
constexpr auto end = tests.end();
constexpr auto dummy = static_assert_tests(begin, end);
{
constexpr auto condition = (begin + 0)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
{
constexpr auto condition = (begin + 1)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
{
constexpr auto condition = (begin + 2)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
{
constexpr auto condition = (begin + 3)->first;
static_assert(condition, "apply_ref_from_to_t failure");
}
}
#endif // WITH_STATIC_ASSERT
for (auto& test : tests)
{
ASSERT_TRUE((test.first)) << test.second;
}
}
<|endoftext|> |
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
// system
#include <map>
#include <set>
// dune-common
#include <dune/common/shared_ptr.hh>
// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
#include <dune/fem/gridpart/gridpartview.hh>
// dune-detailed-discretizations includes
#include <dune/detailed/discretizations/basefunctionset/continuous/lagrange.hh>
#include <dune/detailed/discretizations/mapper/continuous/lagrange.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace DiscreteFunctionSpace {
namespace Continuous {
template <class FunctionSpaceImp, class GridPartImp, int polOrder>
class Lagrange
{
public:
typedef FunctionSpaceImp FunctionSpaceType;
typedef GridPartImp GridPartType;
typedef Dune::GridPartView<GridPartType> GridViewType;
enum
{
polynomialOrder = polOrder
};
typedef Lagrange<FunctionSpaceType, GridPartType, polynomialOrder> ThisType;
typedef Dune::Detailed::Discretizations::Mapper::Continuous::Lagrange<FunctionSpaceType, GridPartType,
polynomialOrder> MapperType;
typedef Dune::Detailed::Discretizations::BaseFunctionSet::Continuous::Lagrange<ThisType> BaseFunctionSetType;
typedef typename FunctionSpaceType::DomainFieldType DomainFieldType;
typedef typename FunctionSpaceType::DomainType DomainType;
typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;
typedef typename FunctionSpaceType::RangeType RangeType;
typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType;
typedef typename FunctionSpaceType::HessianRangeType HessianRangeType;
static const unsigned int dimDomain = FunctionSpaceType::dimDomain;
static const unsigned int dimRange = FunctionSpaceType::dimRange;
typedef std::map<unsigned int, std::set<unsigned int>> PatternType;
/**
@name Convenience typedefs
@{
**/
typedef typename GridPartType::template Codim<0>::IteratorType IteratorType;
typedef typename IteratorType::Entity EntityType;
/**
@}
**/
Lagrange(const GridPartType& gridPart)
: gridPart_(gridPart)
, gridView_(gridPart_)
, mapper_(gridPart_)
, baseFunctionSet_(*this)
{
}
private:
//! copy constructor
Lagrange(const ThisType& other);
public:
const GridPartType& gridPart() const
{
return gridPart_;
}
const GridViewType& gridView() const
{
return gridView_;
}
const MapperType& map() const
{
return mapper_;
}
const BaseFunctionSetType& baseFunctionSet() const
{
return baseFunctionSet_;
}
int order() const
{
return polynomialOrder;
}
bool continuous() const
{
if (order() > 0)
return false;
else
return true;
}
/**
@name Convenience methods
@{
**/
IteratorType begin() const
{
return gridPart_.template begin<0>();
}
IteratorType end() const
{
return gridPart_.template end<0>();
}
/**
@}
**/
template <class OtherDiscreteFunctionSpaceType>
PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
{
std::map<unsigned int, std::set<unsigned int>> ret;
// generate sparsity pattern
for (IteratorType it = begin(); it != end(); ++it) {
const EntityType& entity = *it;
for (unsigned int i = 0; i < baseFunctionSet().local(entity).size(); ++i) {
for (unsigned int j = 0; j < other.baseFunctionSet().local(entity).size(); ++j) {
const unsigned int globalI = map().toGlobal(entity, i);
const unsigned int globalJ = other.map().toGlobal(entity, j);
std::map<unsigned int, std::set<unsigned int>>::iterator result = ret.find(globalI);
if (result == ret.end())
ret.insert(std::pair<unsigned int, std::set<unsigned int>>(globalI, std::set<unsigned int>()));
result = ret.find(globalI);
assert(result != ret.end());
result->second.insert(globalJ);
}
}
} // generate sparsity pattern
return ret;
} // PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
PatternType computePattern() const
{
return computePattern(*this);
}
protected:
//! assignment operator
ThisType& operator=(const ThisType&);
const GridPartType& gridPart_;
const GridViewType gridView_;
const MapperType mapper_;
const BaseFunctionSetType baseFunctionSet_;
}; // end class Lagrange
} // end namespace Continuous
} // end namespace DiscreteFunctionSpace
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
<commit_msg>[discretefunctionspace.continuous.lagrange] minor change (should perform better)<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
// system
#include <map>
#include <set>
// dune-common
#include <dune/common/shared_ptr.hh>
// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
#include <dune/fem/gridpart/gridpartview.hh>
// dune-detailed-discretizations includes
#include <dune/detailed/discretizations/basefunctionset/continuous/lagrange.hh>
#include <dune/detailed/discretizations/mapper/continuous/lagrange.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace DiscreteFunctionSpace {
namespace Continuous {
template <class FunctionSpaceImp, class GridPartImp, int polOrder>
class Lagrange
{
public:
typedef FunctionSpaceImp FunctionSpaceType;
typedef GridPartImp GridPartType;
typedef Dune::GridPartView<GridPartType> GridViewType;
enum
{
polynomialOrder = polOrder
};
typedef Lagrange<FunctionSpaceType, GridPartType, polynomialOrder> ThisType;
typedef Dune::Detailed::Discretizations::Mapper::Continuous::Lagrange<FunctionSpaceType, GridPartType,
polynomialOrder> MapperType;
typedef Dune::Detailed::Discretizations::BaseFunctionSet::Continuous::Lagrange<ThisType> BaseFunctionSetType;
typedef typename FunctionSpaceType::DomainFieldType DomainFieldType;
typedef typename FunctionSpaceType::DomainType DomainType;
typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;
typedef typename FunctionSpaceType::RangeType RangeType;
typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType;
typedef typename FunctionSpaceType::HessianRangeType HessianRangeType;
static const unsigned int dimDomain = FunctionSpaceType::dimDomain;
static const unsigned int dimRange = FunctionSpaceType::dimRange;
typedef std::map<unsigned int, std::set<unsigned int>> PatternType;
/**
@name Convenience typedefs
@{
**/
typedef typename GridPartType::template Codim<0>::IteratorType IteratorType;
typedef typename IteratorType::Entity EntityType;
/**
@}
**/
Lagrange(const GridPartType& gridPart)
: gridPart_(gridPart)
, gridView_(gridPart_)
, mapper_(gridPart_)
, baseFunctionSet_(*this)
{
}
private:
//! copy constructor
Lagrange(const ThisType& other);
public:
const GridPartType& gridPart() const
{
return gridPart_;
}
const GridViewType& gridView() const
{
return gridView_;
}
const MapperType& map() const
{
return mapper_;
}
const BaseFunctionSetType& baseFunctionSet() const
{
return baseFunctionSet_;
}
int order() const
{
return polynomialOrder;
}
bool continuous() const
{
if (order() > 0)
return false;
else
return true;
}
/**
@name Convenience methods
@{
**/
IteratorType begin() const
{
return gridPart_.template begin<0>();
}
IteratorType end() const
{
return gridPart_.template end<0>();
}
/**
@}
**/
template <class OtherDiscreteFunctionSpaceType>
PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
{
std::map<unsigned int, std::set<unsigned int>> ret;
// generate sparsity pattern
for (IteratorType it = begin(); it != end(); ++it) {
const EntityType& entity = *it;
for (unsigned int i = 0; i < baseFunctionSet().local(entity).size(); ++i) {
const unsigned int globalI = map().toGlobal(entity, i);
std::map<unsigned int, std::set<unsigned int>>::iterator result = ret.find(globalI);
if (result == ret.end())
ret.insert(std::pair<unsigned int, std::set<unsigned int>>(globalI, std::set<unsigned int>()));
result = ret.find(globalI);
assert(result != ret.end());
for (unsigned int j = 0; j < other.baseFunctionSet().local(entity).size(); ++j) {
const unsigned int globalJ = other.map().toGlobal(entity, j);
result->second.insert(globalJ);
}
}
} // generate sparsity pattern
return ret;
} // PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
PatternType computePattern() const
{
return computePattern(*this);
}
protected:
//! assignment operator
ThisType& operator=(const ThisType&);
const GridPartType& gridPart_;
const GridViewType gridView_;
const MapperType mapper_;
const BaseFunctionSetType baseFunctionSet_;
}; // end class Lagrange
} // end namespace Continuous
} // end namespace DiscreteFunctionSpace
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
<|endoftext|> |
<commit_before>/** \file FullTextCache.cc
* \brief Implementation of functions relating to our full-text cache.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "FullTextCache.h"
#include "SqlUtil.h"
#include <ctime>
#include <kchashdb.h>
#include "Compiler.h"
#include "DbRow.h"
#include "Random.h"
#include "util.h"
namespace FullTextCache {
const unsigned MIN_CACHE_EXPIRE_TIME(84600 * 60); // About 2 months in seconds.
const unsigned MAX_CACHE_EXPIRE_TIME(84600 * 120); // About 4 months in seconds.
bool CacheExpired(DbConnection * const db_connection, const std::string &full_text_db_path, const std::string &id) {
db_connection->queryOrDie("SELECT expiration FROM full_text_cache WHERE id=\"" + db_connection->escapeString(id)
+ "\"");
DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty())
return true;
const DbRow row(result_set.getNextRow());
const time_t expiration(SqlUtil::DatetimeToTimeT(row["expiration"]));
const time_t now(std::time(nullptr));
if (expiration < now)
return false;
kyotocabinet::HashDB db;
if (not db.open(full_text_db_path, kyotocabinet::HashDB::OCREATE))
Error("in FullTextCache::CacheExpired: Failed to open database \"" + full_text_db_path + "\" for writing ("
+ std::string(db.error().message()) + ")!");
db.remove(id);
db_connection->queryOrDie("DELETE FROM full_text_cache WHERE id=\"" + db_connection->escapeString(id) + "\"");
return true;
}
void InsertIntoCache(DbConnection * const db_connection, const std::string &full_text_db_path,
const std::string &key, const std::string &data)
{
if (not data.empty()) {
kyotocabinet::HashDB db;
if (not db.open(full_text_db_path, kyotocabinet::HashDB::OCREATE))
Error("in FullTextCache::InsertIntoCache: Failed to open database \"" + full_text_db_path
+ "\" for writing (" + std::string(db.error().message()) + ")!");
if (unlikely(not db.set(key, data)))
Error("in FullTextCache::InsertIntoCache: Failed to insert into database \"" + full_text_db_path + "\" ("
+ std::string(db.error().message()) + ")!");
}
const time_t now(std::time(nullptr));
Random::Rand rand(now);
const time_t expiration(now + MIN_CACHE_EXPIRE_TIME + rand(MAX_CACHE_EXPIRE_TIME - MIN_CACHE_EXPIRE_TIME));
db_connection->queryOrDie("REPLACE INTO full_text_cache SET id=\"" + db_connection->escapeString(key)
+ "\",expiration=\"" + SqlUtil::TimeTToDatetime(expiration) + "\"");
}
} // namespace FullTextCache
<commit_msg>I don't know why, but it seems to work.<commit_after>/** \file FullTextCache.cc
* \brief Implementation of functions relating to our full-text cache.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "FullTextCache.h"
#include "SqlUtil.h"
#include <ctime>
#include <kchashdb.h>
#include "Compiler.h"
#include "DbRow.h"
#include "Random.h"
#include "util.h"
namespace FullTextCache {
const unsigned MIN_CACHE_EXPIRE_TIME(84600 * 60); // About 2 months in seconds.
const unsigned MAX_CACHE_EXPIRE_TIME(84600 * 120); // About 4 months in seconds.
bool CacheExpired(DbConnection * const db_connection, const std::string &full_text_db_path, const std::string &id) {
db_connection->queryOrDie("SELECT expiration FROM full_text_cache WHERE id=\"" + db_connection->escapeString(id)
+ "\"");
DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty())
return true;
const DbRow row(result_set.getNextRow());
const time_t expiration(SqlUtil::DatetimeToTimeT(row["expiration"]));
const time_t now(std::time(nullptr));
if (expiration < now)
return false;
kyotocabinet::HashDB db;
if (not db.open(full_text_db_path, kyotocabinet::HashDB::OCREATE | kyotocabinet::HashDB::OWRITER))
Error("in FullTextCache::CacheExpired: Failed to open database \"" + full_text_db_path + "\" for writing ("
+ std::string(db.error().message()) + ")!");
db.remove(id);
db_connection->queryOrDie("DELETE FROM full_text_cache WHERE id=\"" + db_connection->escapeString(id) + "\"");
return true;
}
void InsertIntoCache(DbConnection * const db_connection, const std::string &full_text_db_path,
const std::string &key, const std::string &data)
{
if (not data.empty()) {
kyotocabinet::HashDB db;
if (not db.open(full_text_db_path, kyotocabinet::HashDB::OCREATE | kyotocabinet::HashDB::OWRITER))
Error("in FullTextCache::InsertIntoCache: Failed to open database \"" + full_text_db_path
+ "\" for writing (" + std::string(db.error().message()) + ")!");
if (unlikely(not db.set(key, data)))
Error("in FullTextCache::InsertIntoCache: Failed to insert into database \"" + full_text_db_path + "\" ("
+ std::string(db.error().message()) + ")!");
}
const time_t now(std::time(nullptr));
Random::Rand rand(now);
const time_t expiration(now + MIN_CACHE_EXPIRE_TIME + rand(MAX_CACHE_EXPIRE_TIME - MIN_CACHE_EXPIRE_TIME));
db_connection->queryOrDie("REPLACE INTO full_text_cache SET id=\"" + db_connection->escapeString(key)
+ "\",expiration=\"" + SqlUtil::TimeTToDatetime(expiration) + "\"");
}
} // namespace FullTextCache
<|endoftext|> |
<commit_before>/*
* ping_pong_impl.cpp
*
* Created on: May 6, 2016
* Author: zmij
*/
#include "ping_pong_impl.hpp"
#include <wire/core/invocation.hpp>
#include <iostream>
namespace wire {
namespace test {
static_assert(!core::detail::is_sync_dispatch<decltype(&::test::ping_pong::test_string)>::value,
"test_string is async");
static_assert(core::detail::is_sync_dispatch<decltype(&::test::ping_pong::test_int)>::value,
"test_int is sync");
static_assert(!core::detail::is_sync_dispatch<decltype(&::test::ping_pong::async_error)>::value,
"test_string is async");
static_assert(::std::is_same<
::psst::meta::function_traits<decltype(&::test::ping_pong::async_error)>::class_type,
::test::ping_pong>::value, "Correct class owner");
::std::int32_t
ping_pong_server::test_int(::std::int32_t val, ::wire::core::current const&) const
{
::std::ostringstream os;
os << ::getpid() << " " << __FUNCTION__ << "\n";
::std::cerr << os.str();
return val;
}
void
ping_pong_server::test_string(::std::string const& val,
test_string_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
::std::ostringstream os;
os << ::getpid() << __FUNCTION__ << "\n";
::std::cerr << os.str();
__resp(val);
}
void
ping_pong_server::test_struct(::test::data const& val,
test_struct_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&) const
{
::std::ostringstream os;
os << ::getpid() << __FUNCTION__ << " " << val << "\n";
::std::cerr << os.str();
__resp(val);
}
void
ping_pong_server::test_callback(::test::ping_pong::callback_prx cb,
test_callback_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
::std::ostringstream os;
os << ::getpid() << __FUNCTION__ << " " << *cb << "\n";
::std::cerr << os.str();
__resp(cb);
}
void
ping_pong_server::test_ball(::test::ball_ptr b,
test_ball_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
::std::ostringstream os;
os << ::getpid() << __FUNCTION__ << " ";
::std::cerr << os.str();
if (b) {
::std::ostringstream os;
os << ::getpid() << "Ball size " << b->size << "\n";
::std::cerr << os.str();
} else {
::std::ostringstream os;
os << ::getpid() << "No ball\n";
::std::cerr << os.str();
}
__resp(b);
}
void
ping_pong_server::error(::wire::core::current const&)
{
throw ::test::oops{ "Shit happens!" };
}
void
ping_pong_server::async_error(::wire::core::functional::void_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&) const
{
::std::ostringstream os;
os << ::getpid() << __FUNCTION__ << "\n";
::std::cerr << os.str();
__exception(::std::make_exception_ptr(::test::oops{ "Async shit happens!" }));
}
void
ping_pong_server::stop(::wire::core::functional::void_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
::std::ostringstream os;
os << ::getpid() << __FUNCTION__ << "\n";
::std::cerr << os.str();
__resp();
if (on_stop_)
on_stop_();
}
} /* namespace test */
} /* namespace wire */
<commit_msg>Reduce logs in tests<commit_after>/*
* ping_pong_impl.cpp
*
* Created on: May 6, 2016
* Author: zmij
*/
#include "ping_pong_impl.hpp"
#include <wire/core/invocation.hpp>
#include <iostream>
namespace wire {
namespace test {
static_assert(!core::detail::is_sync_dispatch<decltype(&::test::ping_pong::test_string)>::value,
"test_string is async");
static_assert(core::detail::is_sync_dispatch<decltype(&::test::ping_pong::test_int)>::value,
"test_int is sync");
static_assert(!core::detail::is_sync_dispatch<decltype(&::test::ping_pong::async_error)>::value,
"test_string is async");
static_assert(::std::is_same<
::psst::meta::function_traits<decltype(&::test::ping_pong::async_error)>::class_type,
::test::ping_pong>::value, "Correct class owner");
::std::int32_t
ping_pong_server::test_int(::std::int32_t val, ::wire::core::current const&) const
{
#if DEBUG_OUTPUT >= 3
::std::ostringstream os;
os << ::getpid() << " " << __FUNCTION__ << "\n";
::std::cerr << os.str();
#endif
return val;
}
void
ping_pong_server::test_string(::std::string const& val,
test_string_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
#if DEBUG_OUTPUT >= 3
::std::ostringstream os;
os << ::getpid() << " " << __FUNCTION__ << "\n";
::std::cerr << os.str();
#endif
__resp(val);
}
void
ping_pong_server::test_struct(::test::data const& val,
test_struct_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&) const
{
#if DEBUG_OUTPUT >= 3
::std::ostringstream os;
os << ::getpid() << " " << __FUNCTION__ << " " << val << "\n";
::std::cerr << os.str();
#endif
__resp(val);
}
void
ping_pong_server::test_callback(::test::ping_pong::callback_prx cb,
test_callback_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
#if DEBUG_OUTPUT >= 3
::std::ostringstream os;
os << ::getpid() << " " << __FUNCTION__ << " " << *cb << "\n";
::std::cerr << os.str();
#endif
__resp(cb);
}
void
ping_pong_server::test_ball(::test::ball_ptr b,
test_ball_return_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
::std::ostringstream os;
#if DEBUG_OUTPUT >= 3
os << ::getpid() << " " << __FUNCTION__ << " ";
::std::cerr << os.str();
if (b) {
::std::ostringstream os;
os << ::getpid() << " Ball size " << b->size << "\n";
::std::cerr << os.str();
} else {
::std::ostringstream os;
os << ::getpid() << " No ball\n";
::std::cerr << os.str();
}
#endif
__resp(b);
}
void
ping_pong_server::error(::wire::core::current const&)
{
throw ::test::oops{ "Shit happens!" };
}
void
ping_pong_server::async_error(::wire::core::functional::void_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&) const
{
#if DEBUG_OUTPUT >= 3
::std::ostringstream os;
os << ::getpid() << " " << __FUNCTION__ << "\n";
::std::cerr << os.str();
#endif
__exception(::std::make_exception_ptr(::test::oops{ "Async shit happens!" }));
}
void
ping_pong_server::stop(::wire::core::functional::void_callback __resp,
::wire::core::functional::exception_callback __exception,
::wire::core::current const&)
{
#if DEBUG_OUTPUT >= 3
::std::ostringstream os;
os << ::getpid() << " " << __FUNCTION__ << "\n";
::std::cerr << os.str();
#endif
__resp();
if (on_stop_)
on_stop_();
}
} /* namespace test */
} /* namespace wire */
<|endoftext|> |
<commit_before>#include "util/cowvector/cowvector.h"
#include "util/Assert.h"
using namespace std;
namespace srch2is = srch2::instantsearch;
using namespace srch2is;
void* writer(void* arg);
void* reader(void* arg);
void* writer2(void* arg);
void* reader2(void* arg);
void* writer3(void* arg);
void* reader3(void* arg);
cowvector<int> cowv;
// test type of vectorview
// main logic: it first push_back 10 elements [0,9] in the writeview and commit it.
// then it will check the writeview type it should be true(writeview), and readview type, it should be false(readview).
// And it will test needToFreeOldArray, it should be false
// it will further push_back 10 elements [0,9] and test needToFreeOldArray, it should be true.
void test1()
{
vectorview<int>* &write = cowv.getWriteView();
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
cowv.commit();
ASSERT(write->isWriteView() == true);
ASSERT(write->isReadView() == false);
ASSERT(write->getNeedToFreeOldArray() == false);
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
ASSERT(read->isWriteView() == false);
ASSERT(read->isReadView() == true);
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
ASSERT(write->getNeedToFreeOldArray() == true);
}
// single reader and single writer
// main logic: it will first push_back 10 elements [0,9] and commit
// then it will start two threads. One for reader, one for writer.
// the writer will first forceCreateCopy and do a modification, at the same time the reader will read it.
// the reader will not see the change until the writer commits the change(it change the 3 element to be 100).
// the writer will then push_back 90 elements. After it do the commit, the reader will detect it(it will find there are 100 elements in the vecterview).
// the writer will then push_back 1000 elements. After it do the commit, the reader will detect it(it will find 1100 elements in the vecterview).
void test2() {
pthread_t t1,t2 ;
vectorview<int>* &write = cowv.getWriteView();
write->clear();
cowv.commit();
write = cowv.getWriteView();
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
cowv.commit();
int create1 = pthread_create( &t1, NULL, writer, NULL);
if (create1 != 0) cout << "error" << endl;
int create2 = pthread_create( &t2, NULL, reader, NULL);
if (create2 != 0) cout << "error" << endl;
pthread_join(t1,NULL) ;
pthread_join(t2,NULL) ;
}
// write view test at operation
void* writer(void* arg) {
vectorview<int>* &write = cowv.getWriteView();
write->forceCreateCopy();
sleep(1);
// do change
write->at(3) = 100;
sleep(2);
// commit the change
cowv.commit();
sleep(2);
// push_back 90 elements with wirteview and commit
write = cowv.getWriteView();
for(int i = 0; i < 90; i++)
write->push_back(i);
cowv.commit();
sleep(2);
// push_back 1000 elements with wirteview and commit
for(int i = 0; i < 1000; i++)
write->push_back(i);
cowv.commit();
return NULL;
}
//read view test at operation
void* reader(void* arg) {
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
//check the reader with no change
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
//do not change before commit
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
// see the change after commit
cowv.getReadView(read);
cout << read->at(3) << endl;
ASSERT(read->at(3) == 100);
sleep(2);
// see the change of new insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 100);
sleep(2);
// see the change of further insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 1100);
return NULL;
}
// multi reader and single writer
// main logic: we will first push_back 10 elemnts [0,9] and commit it. After that we will start 11 threads.
// 10 of the threads is reader, and one is a writer.
// the reader will not see the change before the writer commit it(it change the 3 element to be 100).
void test3() {
pthread_t t1,t2[10];
vectorview<int>* &write = cowv.getWriteView();
write->clear();
cowv.commit();
write = cowv.getWriteView();
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
cowv.commit();
cout << write->size()<<endl;
int create1 = pthread_create( &t1, NULL, writer2, NULL);
if (create1 != 0) cout << "error" << endl;
for (int i = 0; i< 10; i++) {
int create2 = pthread_create( &t2[i], NULL, reader2, NULL);
if (create2 != 0) cout << "error" << endl;
}
pthread_join(t1,NULL) ;
for (int i = 0; i< 10; i++)
pthread_join(t2[i],NULL) ;
}
//read view test push_back operation
void* reader2(void* arg) {
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
sleep(1);
//do not change before commit
//cout << read->size() << endl;
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
return NULL;
}
// write view test push_back operation
void* writer2(void* arg) {
vectorview<int>* &write = cowv.getWriteView();
write->push_back(100);
sleep(1);
cowv.commit();
return NULL;
}
// multi reader and single writer for larger data
// main logic: the logic is the same with test 2, we test the 1 writer and 10 reader for larger data size(all the size is multiple 1000).
void test4() {
pthread_t t1,t2[10];
vectorview<int>* &write = cowv.getWriteView();
write->clear();
cowv.commit();
write = cowv.getWriteView();
for (int i= 0; i< 10000; i++) {
write->push_back(i);
}
cowv.commit();
cout << write->size()<<endl;
int create1 = pthread_create( &t1, NULL, writer3, NULL);
if (create1 != 0) cout << "error" << endl;
for (int i = 0; i< 10; i++) {
int create2 = pthread_create( &t2[i], NULL, reader3, NULL);
if (create2 != 0) cout << "error" << endl;
}
pthread_join(t1,NULL) ;
for (int i = 0; i< 10; i++)
pthread_join(t2[i],NULL) ;
}
// write view test at operation
void* writer3(void* arg) {
vectorview<int>* &write = cowv.getWriteView();
write->forceCreateCopy();
sleep(1);
// do change
write->at(3) = 100;
write->at(200) = 100;
write->at(1000) = 100;
write->at(9999) = 100;
sleep(2);
// commit the change
cowv.commit();
sleep(2);
// push_back 90 elements with wirteview and commit
write = cowv.getWriteView();
for(int i = 0; i < 90000; i++)
write->push_back(i);
cowv.commit();
sleep(2);
// push_back 1000 elements with wirteview and commit
for(int i = 0; i < 1000000; i++)
write->push_back(i);
cowv.commit();
return NULL;
}
//read view test at operation
void* reader3(void* arg) {
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
//check the reader with no change
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
//do not change before commit
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
// see the change after commit
cowv.getReadView(read);
cout << read->at(3) << endl;
ASSERT(read->at(3) == 100);
ASSERT(read->at(200) == 100);
ASSERT(read->at(1000) == 100);
ASSERT(read->at(9999) == 100);
sleep(2);
// see the change of new insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 100000);
sleep(2);
// see the change of further insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 1100000);
return NULL;
}
int main( void ) {
test1();
test2();
test3();
test4();
return 0;
}
<commit_msg>Polished by Chen<commit_after>#include "util/cowvector/cowvector.h"
#include "util/Assert.h"
using namespace std;
namespace srch2is = srch2::instantsearch;
using namespace srch2is;
void* writer(void* arg);
void* reader(void* arg);
void* writer2(void* arg);
void* reader2(void* arg);
void* writer3(void* arg);
void* reader3(void* arg);
cowvector<int> cowv;
// Main logic of this test case: it first uses push_back()
// to add 10 elements (0, 1, ..., 90 to the writeview and commits.
// Then it checks the vector view type, which should be a writeview.
// And it tests the needToFreeOldArray flag, it should be false.
// It will again call push_back() to add 10 elements (0, 1, ..., 9)
// and test the needToFreeOldArray flag. The flag should be true,
// since we have reallocated the memory of the array due to the more pushback calls.
void test1()
{
vectorview<int>* &write = cowv.getWriteView();
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
cowv.commit();
ASSERT(write->isWriteView() == true);
ASSERT(write->isReadView() == false);
ASSERT(write->getNeedToFreeOldArray() == false);
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
ASSERT(read->isWriteView() == false);
ASSERT(read->isReadView() == true);
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
ASSERT(write->getNeedToFreeOldArray() == true);
}
// single reader and single writer
// main logic: it will first push_back 10 elements [0,9] and commit
// then it will start two threads. One for reader, one for writer.
// the writer will first forceCreateCopy and do a modification by changing the element 3 to 100, at the same time the reader will read it.
// the reader will not see the change until the writer commits the change.
// the writer will then push_back 90 elements. After it does the commit, the reader will detect it(it will find there are 100 elements in the vecterview).
// the writer will then push_back 1000 elements. After it does the commit, the reader will detect it(it will find 1100 elements in the vecterview).
void test2() {
pthread_t t1,t2 ;
vectorview<int>* &write = cowv.getWriteView();
write->clear();
cowv.commit();
write = cowv.getWriteView();
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
cowv.commit();
int create1 = pthread_create( &t1, NULL, writer, NULL);
if (create1 != 0) cout << "error" << endl;
int create2 = pthread_create( &t2, NULL, reader, NULL);
if (create2 != 0) cout << "error" << endl;
pthread_join(t1,NULL) ;
pthread_join(t2,NULL) ;
}
// write view test at operation
void* writer(void* arg) {
vectorview<int>* &write = cowv.getWriteView();
write->forceCreateCopy();
sleep(1);
// do change
write->at(3) = 100;
sleep(2);
// commit the change
cowv.commit();
sleep(2);
// push_back 90 elements with wirteview and commit
write = cowv.getWriteView();
for(int i = 0; i < 90; i++)
write->push_back(i);
cowv.commit();
sleep(2);
// push_back 1000 elements with wirteview and commit
for(int i = 0; i < 1000; i++)
write->push_back(i);
cowv.commit();
return NULL;
}
//read view test at operation
void* reader(void* arg) {
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
//check the reader with no change
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
//do not change before commit
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
// see the change after commit
cowv.getReadView(read);
cout << read->at(3) << endl;
ASSERT(read->at(3) == 100);
sleep(2);
// see the change of new insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 100);
sleep(2);
// see the change of further insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 1100);
return NULL;
}
// multi reader and single writer
// main logic: we will first push_back 10 elements [0,9] and commit it. After that we will start 11 threads.
// 10 of the threads are readers, and one is a writer.
// the readers will not see the change made by the writer (element 3 -> 100) before the writer commits it.
void test3() {
pthread_t t1,t2[10];
vectorview<int>* &write = cowv.getWriteView();
write->clear();
cowv.commit();
write = cowv.getWriteView();
for (int i= 0; i< 10; i++) {
write->push_back(i);
}
cowv.commit();
cout << write->size()<<endl;
int create1 = pthread_create( &t1, NULL, writer2, NULL);
if (create1 != 0) cout << "error" << endl;
for (int i = 0; i< 10; i++) {
int create2 = pthread_create( &t2[i], NULL, reader2, NULL);
if (create2 != 0) cout << "error" << endl;
}
pthread_join(t1,NULL) ;
for (int i = 0; i< 10; i++)
pthread_join(t2[i],NULL) ;
}
//read view test push_back operation
void* reader2(void* arg) {
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
sleep(1);
//do not change before commit
//cout << read->size() << endl;
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
return NULL;
}
// write view test push_back operation
void* writer2(void* arg) {
vectorview<int>* &write = cowv.getWriteView();
write->push_back(100);
sleep(1);
cowv.commit();
return NULL;
}
// multi reader and single writer for larger data
// The main logic is the same as test 2. We have 1 writer and 10 readers for a larger data size (1000 times larger).
void test4() {
pthread_t t1,t2[10];
vectorview<int>* &write = cowv.getWriteView();
write->clear();
cowv.commit();
write = cowv.getWriteView();
for (int i= 0; i< 10000; i++) {
write->push_back(i);
}
cowv.commit();
cout << write->size()<<endl;
int create1 = pthread_create( &t1, NULL, writer3, NULL);
if (create1 != 0) cout << "error" << endl;
for (int i = 0; i< 10; i++) {
int create2 = pthread_create( &t2[i], NULL, reader3, NULL);
if (create2 != 0) cout << "error" << endl;
}
pthread_join(t1,NULL) ;
for (int i = 0; i< 10; i++)
pthread_join(t2[i],NULL) ;
}
// write view test at operation
void* writer3(void* arg) {
vectorview<int>* &write = cowv.getWriteView();
write->forceCreateCopy();
sleep(1);
// do change
write->at(3) = 100;
write->at(200) = 100;
write->at(1000) = 100;
write->at(9999) = 100;
sleep(2);
// commit the change
cowv.commit();
sleep(2);
// push_back 90 elements with wirteview and commit
write = cowv.getWriteView();
for(int i = 0; i < 90000; i++)
write->push_back(i);
cowv.commit();
sleep(2);
// push_back 1000 elements with wirteview and commit
for(int i = 0; i < 1000000; i++)
write->push_back(i);
cowv.commit();
return NULL;
}
//read view test at operation
void* reader3(void* arg) {
shared_ptr<vectorview<int> > read;
cowv.getReadView(read);
//check the reader with no change
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
//do not change before commit
for (int i = 0; i< read->size(); i++) {
ASSERT(i == read->at(i));
}
sleep(2);
// see the change after commit
cowv.getReadView(read);
cout << read->at(3) << endl;
ASSERT(read->at(3) == 100);
ASSERT(read->at(200) == 100);
ASSERT(read->at(1000) == 100);
ASSERT(read->at(9999) == 100);
sleep(2);
// see the change of new insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 100000);
sleep(2);
// see the change of further insert item
cowv.getReadView(read);
cout << read->size() << endl;
ASSERT(read->size() == 1100000);
return NULL;
}
int main( void ) {
test1();
test2();
test3();
test4();
return 0;
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s
// XFAIL: *
template <typename T, typename U>
struct same_type { static const bool value = false; };
template <typename T>
struct same_type<T, T> { static const bool value = true; };
namespace std {
typedef decltype(sizeof(int)) size_t;
// libc++'s implementation
template <class _E>
class initializer_list
{
const _E* __begin_;
size_t __size_;
initializer_list(const _E* __b, size_t __s)
: __begin_(__b),
__size_(__s)
{}
public:
typedef _E value_type;
typedef const _E& reference;
typedef const _E& const_reference;
typedef size_t size_type;
typedef const _E* iterator;
typedef const _E* const_iterator;
initializer_list() : __begin_(nullptr), __size_(0) {}
size_t size() const {return __size_;}
const _E* begin() const {return __begin_;}
const _E* end() const {return __begin_ + __size_;}
};
}
namespace integral {
void initialization() {
{ const int a{}; static_assert(a == 0, ""); }
{ const int a = {}; static_assert(a == 0, ""); }
{ const int a{1}; static_assert(a == 1, ""); }
{ const int a = {1}; static_assert(a == 1, ""); }
{ const int a{1, 2}; } // expected-error {{excess elements}}
{ const int a = {1, 2}; } // expected-error {{excess elements}}
{ const short a{100000}; } // expected-error {{narrowing conversion}}
{ const short a = {100000}; } // expected-error {{narrowing conversion}}
}
int function_call() {
void takes_int(int);
takes_int({1});
int ar[10];
(void) ar[{1}]; // expected-error {{initializer list is illegal with the built-in index operator}}
return {1};
}
void inline_init() {
(void) int{1};
(void) new int{1};
}
void initializer_list() {
auto l = {1, 2, 3, 4};
static_assert(same_type<decltype(l), std::initializer_list<int>>::value, "");
for (int i : {1, 2, 3, 4}) {}
}
struct A {
int i;
A() : i{1} {}
};
}
namespace objects {
template <int N>
struct A {
A() { static_assert(N == 0, ""); }
A(int, double) { static_assert(N == 1, ""); }
A(int, int) { static_assert(N == 2, ""); }
A(std::initializer_list<int>) { static_assert(N == 3, ""); }
};
void initialization() {
// FIXME: how to ensure correct overloads are called?
{ A<0> a{}; }
{ A<0> a = {}; }
{ A<1> a{1, 1.0}; }
{ A<1> a = {1, 1.0}; }
{ A<3> a{1, 2, 3, 4, 5, 6, 7, 8}; }
{ A<3> a = {1, 2, 3, 4, 5, 6, 7, 8}; }
{ A<3> a{1, 2, 3, 4, 5, 6, 7, 8}; }
{ A<3> a{1, 2}; }
}
struct C {
C();
C(int, double);
C(int, int);
C(std::initializer_list<int>);
int operator[](C);
};
C function_call() {
void takes_C(C);
takes_C({1, 1.0});
C c;
c[{1, 1.0}];
return {1, 1.0};
}
void inline_init() {
(void) A<1>{1, 1.0};
(void) new A<1>{1, 1.0};
}
struct B {
B(C, int, C);
};
void nested_init() {
B b{{1, 1.0}, 2, {3, 4, 5, 6, 7}};
}
}
namespace litb {
// invalid
struct A { int a[2]; A():a({1, 2}) { } }; // expected-error {{}}
// invalid
int a({0}); // expected-error {{}}
// invalid
int const &b({0}); // expected-error {{}}
struct C { explicit C(int, int); C(int, long); };
// invalid
C c({1, 2}); // expected-error {{}}
// valid (by copy constructor).
C d({1, 2L}); // expected-error {{}}
// valid
C e{1, 2};
struct B {
template<typename ...T>
B(std::initializer_list<int>, T ...);
};
// invalid (the first phase only considers init-list ctors)
// (for the second phase, no constructor is viable)
B f{1, 2, 3};
// valid (T deduced to <>).
B g({1, 2, 3});
}
<commit_msg>More std::initializer_list tests.<commit_after>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s
// XFAIL: *
template <typename T, typename U>
struct same_type { static const bool value = false; };
template <typename T>
struct same_type<T, T> { static const bool value = true; };
namespace std {
typedef decltype(sizeof(int)) size_t;
// libc++'s implementation
template <class _E>
class initializer_list
{
const _E* __begin_;
size_t __size_;
initializer_list(const _E* __b, size_t __s)
: __begin_(__b),
__size_(__s)
{}
public:
typedef _E value_type;
typedef const _E& reference;
typedef const _E& const_reference;
typedef size_t size_type;
typedef const _E* iterator;
typedef const _E* const_iterator;
initializer_list() : __begin_(nullptr), __size_(0) {}
size_t size() const {return __size_;}
const _E* begin() const {return __begin_;}
const _E* end() const {return __begin_ + __size_;}
};
}
namespace integral {
void initialization() {
{ const int a{}; static_assert(a == 0, ""); }
{ const int a = {}; static_assert(a == 0, ""); }
{ const int a{1}; static_assert(a == 1, ""); }
{ const int a = {1}; static_assert(a == 1, ""); }
{ const int a{1, 2}; } // expected-error {{excess elements}}
{ const int a = {1, 2}; } // expected-error {{excess elements}}
{ const short a{100000}; } // expected-error {{narrowing conversion}}
{ const short a = {100000}; } // expected-error {{narrowing conversion}}
}
int function_call() {
void takes_int(int);
takes_int({1});
int ar[10];
(void) ar[{1}]; // expected-error {{initializer list is illegal with the built-in index operator}}
return {1};
}
void inline_init() {
(void) int{1};
(void) new int{1};
}
void initializer_list() {
std::initializer_list<int> il = { 1, 2, 3 };
std::initializer_list<double> dl = { 1.0, 2.0, 3 };
auto l = {1, 2, 3, 4};
static_assert(same_type<decltype(l), std::initializer_list<int>>::value, "");
auto bl = {1, 2.0}; // expected-error {{cannot deduce}}
for (int i : {1, 2, 3, 4}) {}
}
struct A {
int i;
A() : i{1} {}
};
}
namespace objects {
template <int N>
struct A {
A() { static_assert(N == 0, ""); }
A(int, double) { static_assert(N == 1, ""); }
A(int, int) { static_assert(N == 2, ""); }
A(std::initializer_list<int>) { static_assert(N == 3, ""); }
};
void initialization() {
{ A<0> a{}; }
{ A<0> a = {}; }
{ A<1> a{1, 1.0}; }
{ A<1> a = {1, 1.0}; }
{ A<3> a{1, 2, 3, 4, 5, 6, 7, 8}; }
{ A<3> a = {1, 2, 3, 4, 5, 6, 7, 8}; }
{ A<3> a{1, 2, 3, 4, 5, 6, 7, 8}; }
{ A<3> a{1, 2}; }
}
struct C {
C();
C(int, double);
C(int, int);
C(std::initializer_list<int>);
int operator[](C);
};
C function_call() {
void takes_C(C);
takes_C({1, 1.0});
C c;
c[{1, 1.0}];
return {1, 1.0};
}
void inline_init() {
(void) A<1>{1, 1.0};
(void) new A<1>{1, 1.0};
}
struct B {
B(C, int, C);
};
void nested_init() {
B b{{1, 1.0}, 2, {3, 4, 5, 6, 7}};
}
}
namespace litb {
// invalid
struct A { int a[2]; A():a({1, 2}) { } }; // expected-error {{}}
// invalid
int a({0}); // expected-error {{}}
// invalid
int const &b({0}); // expected-error {{}}
struct C { explicit C(int, int); C(int, long); };
// invalid
C c({1, 2}); // expected-error {{}}
// valid (by copy constructor).
C d({1, 2L}); // expected-error {{}}
// valid
C e{1, 2};
struct B {
template<typename ...T>
B(std::initializer_list<int>, T ...);
};
// invalid (the first phase only considers init-list ctors)
// (for the second phase, no constructor is viable)
B f{1, 2, 3};
// valid (T deduced to <>).
B g({1, 2, 3});
}
<|endoftext|> |
<commit_before>#include <stan/math/mix/mat.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/prob/lkj_corr_cholesky_test_functors.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <test/unit/math/mix/mat/prob/higher_order_utils.hpp>
#include <vector>
TEST(ProbDistributionsLkjCorr, fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<var>, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_ = 1.0;
fvar<var> eta = stan::math::uniform_rng(0, 2, rng);
fvar<var> f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(2.5177896, stan::math::lkj_corr_log(Sigma, eta).d_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(f.d_.val(), stan::math::lkj_corr_log(Sigma, eta).d_.val());
}
TEST(ProbDistributionsLkjCorrCholesky, fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<var>, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_ = 1.0;
fvar<var> eta = stan::math::uniform_rng(0, 2, rng);
fvar<var> f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(6.7766843,
stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(3, stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val());
}
TEST(ProbDistributionsLkjCorr, fvar_fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<fvar<var> >, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_.val_ = 1.0;
fvar<fvar<var> > eta = stan::math::uniform_rng(0, 2, rng);
fvar<fvar<var> > f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(2.5177896,
stan::math::lkj_corr_log(Sigma, eta).d_.val_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(f.d_.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).d_.val_.val());
}
TEST(ProbDistributionsLkjCorrCholesky, fvar_fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<fvar<var> >, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_.val_ = 1.0;
fvar<fvar<var> > eta = stan::math::uniform_rng(0, 2, rng);
fvar<fvar<var> > f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(
f.val_.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(6.7766843,
stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(
f.val_.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(3,
stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val_.val());
}
TEST(ProbDistributionsLkjCorrCholesky, hessian) {
int dim_mat = 3;
Eigen::Matrix<double, Eigen::Dynamic, 1> x1(dim_mat);
Eigen::Matrix<double, Eigen::Dynamic, 1> x2(1);
Eigen::Matrix<double, Eigen::Dynamic, 1> x3(dim_mat + 1);
x2(0) = 2.0;
for (int i = 0; i < dim_mat; ++i) {
x1(i) = i / 10.0;
x3(i + 1) = x1(i);
}
x3(0) = 0.5;
stan::math::lkj_corr_cholesky_dc test_func_1(dim_mat);
stan::math::lkj_corr_cholesky_cd test_func_2(dim_mat);
stan::math::lkj_corr_cholesky_dd test_func_3(dim_mat);
using stan::math::finite_diff_hessian;
using stan::math::hessian;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_3;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_3;
double fx_hess_3;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_ad_3;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_ad_3;
double fx_hess_ad_3;
finite_diff_hessian(test_func_3, x3, fx_hess_3, grad_hess_3, hess_3);
hessian(test_func_3, x3, fx_hess_ad_3, grad_hess_ad_3, hess_ad_3);
test_hess_eq(hess_3, hess_ad_3);
EXPECT_FLOAT_EQ(fx_hess_3, fx_hess_ad_3);
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_2;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_2;
double fx_hess_2;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_ad_2;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_ad_2;
double fx_hess_ad_2;
finite_diff_hessian(test_func_2, x2, fx_hess_2, grad_hess_2, hess_2);
hessian(test_func_2, x2, fx_hess_ad_2, grad_hess_ad_2, hess_ad_2);
test_hess_eq(hess_2, hess_ad_2);
EXPECT_FLOAT_EQ(fx_hess_2, fx_hess_ad_2);
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_1;
double fx_hess_1;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_ad_1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_ad_1;
double fx_hess_ad_1;
finite_diff_hessian(test_func_1, x1, fx_hess_1, grad_hess_1, hess_1);
hessian(test_func_1, x1, fx_hess_ad_1, grad_hess_ad_1, hess_ad_1);
test_hess_eq(hess_1, hess_ad_1);
EXPECT_FLOAT_EQ(fx_hess_1, fx_hess_ad_1);
}
TEST(ProbDistributionsLkjCorrCholesky, grad_hessian) {
int dim_mat = 3;
Eigen::Matrix<double, Eigen::Dynamic, 1> x1(dim_mat);
Eigen::Matrix<double, Eigen::Dynamic, 1> x2(1);
Eigen::Matrix<double, Eigen::Dynamic, 1> x3(dim_mat + 1);
x2(0) = 2.0;
for (int i = 0; i < dim_mat; ++i) {
x1(i) = i / 10.0;
x3(i + 1) = x1(i);
}
x3(0) = 0.5;
stan::math::lkj_corr_cholesky_dc test_func_1(dim_mat);
stan::math::lkj_corr_cholesky_cd test_func_2(dim_mat);
stan::math::lkj_corr_cholesky_dd test_func_3(dim_mat);
using stan::math::finite_diff_grad_hessian;
using stan::math::grad_hessian;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_3;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_3;
double fx_gh_3;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_ad_3;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_ad_3;
double fx_gh_ad_3;
finite_diff_grad_hessian(test_func_3, x3, fx_gh_3, hess_gh_3, gh_3);
grad_hessian(test_func_3, x3, fx_gh_ad_3, hess_gh_ad_3, gh_ad_3);
test_grad_hess_eq(gh_3, gh_ad_3);
EXPECT_FLOAT_EQ(fx_gh_3, fx_gh_ad_3);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_2;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_2;
double fx_gh_2;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_ad_2;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_ad_2;
double fx_gh_ad_2;
finite_diff_grad_hessian(test_func_2, x2, fx_gh_2, hess_gh_2, gh_2);
grad_hessian(test_func_2, x2, fx_gh_ad_2, hess_gh_ad_2, gh_ad_2);
test_grad_hess_eq(gh_2, gh_ad_2);
EXPECT_FLOAT_EQ(fx_gh_2, fx_gh_ad_2);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_1;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_1;
double fx_gh_1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_ad_1;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_ad_1;
double fx_gh_ad_1;
finite_diff_grad_hessian(test_func_1, x1, fx_gh_1, hess_gh_1, gh_1);
grad_hessian(test_func_1, x1, fx_gh_ad_1, hess_gh_ad_1, gh_ad_1);
test_grad_hess_eq(gh_1, gh_ad_1);
EXPECT_FLOAT_EQ(fx_gh_1, fx_gh_ad_1);
}
<commit_msg>fix includes of mix/prob<commit_after>#include <stan/math/mix/mat.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/prob/lkj_corr_cholesky_test_functors.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <test/unit/math/mix/prob/higher_order_utils.hpp>
#include <vector>
TEST(ProbDistributionsLkjCorr, fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<var>, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_ = 1.0;
fvar<var> eta = stan::math::uniform_rng(0, 2, rng);
fvar<var> f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(2.5177896, stan::math::lkj_corr_log(Sigma, eta).d_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(f.d_.val(), stan::math::lkj_corr_log(Sigma, eta).d_.val());
}
TEST(ProbDistributionsLkjCorrCholesky, fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<var>, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_ = 1.0;
fvar<var> eta = stan::math::uniform_rng(0, 2, rng);
fvar<var> f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(6.7766843,
stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val());
EXPECT_FLOAT_EQ(3, stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val());
}
TEST(ProbDistributionsLkjCorr, fvar_fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<fvar<var> >, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_.val_ = 1.0;
fvar<fvar<var> > eta = stan::math::uniform_rng(0, 2, rng);
fvar<fvar<var> > f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(2.5177896,
stan::math::lkj_corr_log(Sigma, eta).d_.val_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(f.val_.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(f.d_.val_.val(),
stan::math::lkj_corr_log(Sigma, eta).d_.val_.val());
}
TEST(ProbDistributionsLkjCorrCholesky, fvar_fvar_var) {
using stan::math::fvar;
using stan::math::var;
boost::random::mt19937 rng;
int K = 4;
Eigen::Matrix<fvar<fvar<var> >, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);
Sigma.setZero();
Sigma.diagonal().setOnes();
for (int i = 0; i < K * K; i++)
Sigma(i).d_.val_ = 1.0;
fvar<fvar<var> > eta = stan::math::uniform_rng(0, 2, rng);
fvar<fvar<var> > f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(
f.val_.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(6.7766843,
stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val_.val());
eta = 1.0;
f = stan::math::do_lkj_constant(eta, K);
EXPECT_FLOAT_EQ(
f.val_.val_.val(),
stan::math::lkj_corr_cholesky_log(Sigma, eta).val_.val_.val());
EXPECT_FLOAT_EQ(3,
stan::math::lkj_corr_cholesky_log(Sigma, eta).d_.val_.val());
}
TEST(ProbDistributionsLkjCorrCholesky, hessian) {
int dim_mat = 3;
Eigen::Matrix<double, Eigen::Dynamic, 1> x1(dim_mat);
Eigen::Matrix<double, Eigen::Dynamic, 1> x2(1);
Eigen::Matrix<double, Eigen::Dynamic, 1> x3(dim_mat + 1);
x2(0) = 2.0;
for (int i = 0; i < dim_mat; ++i) {
x1(i) = i / 10.0;
x3(i + 1) = x1(i);
}
x3(0) = 0.5;
stan::math::lkj_corr_cholesky_dc test_func_1(dim_mat);
stan::math::lkj_corr_cholesky_cd test_func_2(dim_mat);
stan::math::lkj_corr_cholesky_dd test_func_3(dim_mat);
using stan::math::finite_diff_hessian;
using stan::math::hessian;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_3;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_3;
double fx_hess_3;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_ad_3;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_ad_3;
double fx_hess_ad_3;
finite_diff_hessian(test_func_3, x3, fx_hess_3, grad_hess_3, hess_3);
hessian(test_func_3, x3, fx_hess_ad_3, grad_hess_ad_3, hess_ad_3);
test_hess_eq(hess_3, hess_ad_3);
EXPECT_FLOAT_EQ(fx_hess_3, fx_hess_ad_3);
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_2;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_2;
double fx_hess_2;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_ad_2;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_ad_2;
double fx_hess_ad_2;
finite_diff_hessian(test_func_2, x2, fx_hess_2, grad_hess_2, hess_2);
hessian(test_func_2, x2, fx_hess_ad_2, grad_hess_ad_2, hess_ad_2);
test_hess_eq(hess_2, hess_ad_2);
EXPECT_FLOAT_EQ(fx_hess_2, fx_hess_ad_2);
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_1;
double fx_hess_1;
Eigen::Matrix<double, Eigen::Dynamic, 1> grad_hess_ad_1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_ad_1;
double fx_hess_ad_1;
finite_diff_hessian(test_func_1, x1, fx_hess_1, grad_hess_1, hess_1);
hessian(test_func_1, x1, fx_hess_ad_1, grad_hess_ad_1, hess_ad_1);
test_hess_eq(hess_1, hess_ad_1);
EXPECT_FLOAT_EQ(fx_hess_1, fx_hess_ad_1);
}
TEST(ProbDistributionsLkjCorrCholesky, grad_hessian) {
int dim_mat = 3;
Eigen::Matrix<double, Eigen::Dynamic, 1> x1(dim_mat);
Eigen::Matrix<double, Eigen::Dynamic, 1> x2(1);
Eigen::Matrix<double, Eigen::Dynamic, 1> x3(dim_mat + 1);
x2(0) = 2.0;
for (int i = 0; i < dim_mat; ++i) {
x1(i) = i / 10.0;
x3(i + 1) = x1(i);
}
x3(0) = 0.5;
stan::math::lkj_corr_cholesky_dc test_func_1(dim_mat);
stan::math::lkj_corr_cholesky_cd test_func_2(dim_mat);
stan::math::lkj_corr_cholesky_dd test_func_3(dim_mat);
using stan::math::finite_diff_grad_hessian;
using stan::math::grad_hessian;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_3;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_3;
double fx_gh_3;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_ad_3;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_ad_3;
double fx_gh_ad_3;
finite_diff_grad_hessian(test_func_3, x3, fx_gh_3, hess_gh_3, gh_3);
grad_hessian(test_func_3, x3, fx_gh_ad_3, hess_gh_ad_3, gh_ad_3);
test_grad_hess_eq(gh_3, gh_ad_3);
EXPECT_FLOAT_EQ(fx_gh_3, fx_gh_ad_3);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_2;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_2;
double fx_gh_2;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_ad_2;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_ad_2;
double fx_gh_ad_2;
finite_diff_grad_hessian(test_func_2, x2, fx_gh_2, hess_gh_2, gh_2);
grad_hessian(test_func_2, x2, fx_gh_ad_2, hess_gh_ad_2, gh_ad_2);
test_grad_hess_eq(gh_2, gh_ad_2);
EXPECT_FLOAT_EQ(fx_gh_2, fx_gh_ad_2);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_1;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_1;
double fx_gh_1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> hess_gh_ad_1;
std::vector<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > gh_ad_1;
double fx_gh_ad_1;
finite_diff_grad_hessian(test_func_1, x1, fx_gh_1, hess_gh_1, gh_1);
grad_hessian(test_func_1, x1, fx_gh_ad_1, hess_gh_ad_1, gh_ad_1);
test_grad_hess_eq(gh_1, gh_ad_1);
EXPECT_FLOAT_EQ(fx_gh_1, fx_gh_ad_1);
}
<|endoftext|> |
<commit_before><commit_msg>planning: updated pull over boundary in path_bounds_decider<commit_after><|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/MediaStreamDescriptor.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/IServiceId.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DefaultDVBTTransport.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ServiceId>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);
#endif
}
}}
<commit_msg>register system update actions<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/MediaStreamDescriptor.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/IServiceId.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DefaultDVBTTransport.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ServiceId>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "Inception.h"
#include "Agency/Agent.h"
#include "Agency/GossipCallback.h"
#include "Agency/MeasureCallback.h"
#include "Basics/ConditionLocker.h"
#include "Cluster/ClusterComm.h"
#include <chrono>
#include <numeric>
#include <thread>
using namespace arangodb::consensus;
Inception::Inception() : Thread("Inception"), _agent(nullptr) {}
Inception::Inception(Agent* agent) : Thread("Inception"), _agent(agent) {}
// Shutdown if not already
Inception::~Inception() { shutdown(); }
/// Gossip to others
/// - Get snapshot of gossip peers and agent pool
/// - Create outgoing gossip.
/// - Send to all peers
void Inception::gossip() {
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(120);
size_t i = 0;
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
config_t config = _agent->config(); // get a copy of conf
// Build gossip message
query_t out = std::make_shared<Builder>();
out->openObject();
out->add("endpoint", VPackValue(config.endpoint()));
out->add("id", VPackValue(config.id()));
out->add("pool", VPackValue(VPackValueType::Object));
for (auto const& i : config.pool()) {
out->add(i.first, VPackValue(i.second));
}
out->close();
out->close();
std::string path = privApiPrefix + "gossip";
// gossip peers
for (auto const& p : config.gossipPeers()) {
if (p != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, p, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// pool entries
for (auto const& pair : config.pool()) {
if (pair.second != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, pair.second, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// don't panic
_cv.wait(100000);
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (config.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
// We're done
if (config.poolComplete()) {
_agent->startConstituent();
break;
}
}
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromPersistence() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
// Contact hosts on pool in hopes of finding a leader Id
for (auto const& pair : myConfig.pool()) {
if (pair.first != myConfig.id()) {
auto comres = arangodb::ClusterComm::instance()->syncRequest(
myConfig.id(), 1, pair.second, rest::RequestType::GET, path,
std::string(), std::unordered_map<std::string, std::string>(), 1.0);
if (comres->status == CL_COMM_SENT) {
auto body = comres->result->getBodyVelocyPack();
auto theirConfig = body->slice();
std::string leaderId;
// LeaderId in configuration?
try {
leaderId = theirConfig.get("leaderId").copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
if (leaderId != "") { // Got leaderId. Let's get do it.
try {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Found active agency with leader " << leaderId
<< " at endpoint "
<< theirConfig.get("configuration").get(
"pool").get(leaderId).copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
auto agency = std::make_shared<Builder>();
agency->openObject();
agency->add("term", theirConfig.get("term"));
agency->add("id", VPackValue(leaderId));
agency->add("active", theirConfig.get("configuration").get("active"));
agency->add("pool", theirConfig.get("configuration").get("pool"));
agency->close();
_agent->notify(agency);
return true;
} else { // No leaderId. Move on.
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second;
}
}
}
}
}
return false;
}
bool Inception::restartingActiveAgent() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(60);
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
auto pool = myConfig.pool();
auto active = myConfig.active();
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
active.erase(
std::remove(active.begin(), active.end(), myConfig.id()), active.end());
active.erase(
std::remove(active.begin(), active.end(), ""), active.end());
if (active.empty()) {
return true;
}
for (auto& i : active) {
if (i != myConfig.id() && i != "") {
auto clientId = myConfig.id();
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, pool.at(i), rest::RequestType::GET, path, std::string(),
std::unordered_map<std::string, std::string>(), 2.0);
if (comres->status == CL_COMM_SENT) {
try {
auto theirActive = comres->result->getBodyVelocyPack()->
slice().get("configuration").get("active").toJson();
auto myActive = myConfig.activeToBuilder()->toJson();
if (theirActive != myActive) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer and I disagree on active membership."
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
} else {
i = "";
}
} catch (std::exception const& e) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer has no active agency list: " << e.what()
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
}
}
}
}
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (myConfig.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
_cv.wait(500000);
}
}
return false;
}
inline static int64_t timeStamp() {
using namespace std::chrono;
return duration_cast<microseconds>(
steady_clock::now().time_since_epoch()).count();
}
void Inception::reportIn(std::string const& peerId, uint64_t start) {
MUTEX_LOCKER(lock, _pLock);
_pings.push_back(1.0e-3*(double)(timeStamp()-start));
}
void Inception::reportIn(query_t const& query) {
VPackSlice slice = query->slice();
TRI_ASSERT(slice.isObject());
TRI_ASSERT(slice.hasKey("mean"));
TRI_ASSERT(slice.hasKey("stdev"));
TRI_ASSERT(slice.hasKey("min"));
TRI_ASSERT(slice.hasKey("max"));
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(
std::vector<double>(
{slice.get("mean").getDouble(), slice.get("stdev").getDouble(),
slice.get("max").getDouble(), slice.get("min").getDouble()} ));
}
bool Inception::estimateRAFTInterval() {
using namespace std::chrono;
std::string path("/_api/agency/config");
auto pool = _agent->config().pool();
auto myid = _agent->id();
for (size_t i = 0; i < 25; ++i) {
for (auto const& peer : pool) {
if (peer.first != myid) {
std::string clientid = peer.first + std::to_string(i);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, peer.second, rest::RequestType::GET, path,
std::make_shared<std::string>(), hf,
std::make_shared<MeasureCallback>(this, peer.second, timeStamp()),
2.0, true);
}
}
std::this_thread::sleep_for(std::chrono::duration<double,std::milli>(5));
}
auto s = system_clock::now();
seconds timeout(3);
CONDITION_LOCKER(guard, _cv);
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _pLock);
if (_pings.size() == 25*(pool.size()-1)) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All pings are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Timed out waiting for pings";
break;
}
}
if (! _pings.empty()) {
double mean, stdev, mx, mn;
MUTEX_LOCKER(lock, _pLock);
size_t num = _pings.size();
mean = std::accumulate(_pings.begin(), _pings.end(), 0.0) / num;
mx = *std::max_element(_pings.begin(), _pings.end());
mn = *std::min_element(_pings.begin(), _pings.end());
std::transform(_pings.begin(), _pings.end(), _pings.begin(),
std::bind2nd(std::minus<double>(), mean));
stdev =
std::sqrt(
std::inner_product(
_pings.begin(), _pings.end(), _pings.begin(), 0.0) / num);
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "mean(" << mean << ") stdev(" << stdev<< ")";
Builder measurement;
measurement.openObject();
measurement.add("mean", VPackValue(mean));
measurement.add("stdev", VPackValue(stdev));
measurement.add("min", VPackValue(mn));
measurement.add("max", VPackValue(mx));
measurement.close();
std::string measjson = measurement.toJson();
path = privApiPrefix + "measure";
for (auto const& peer : pool) {
if (peer.first != myid) {
auto clientId = "1";
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, peer.second, rest::RequestType::POST, path,
measjson, std::unordered_map<std::string, std::string>(), 2.0);
}
}
{
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(std::vector<double>({mean, stdev, mx, mn}));
}
s = system_clock::now();
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _mLock);
if (_measurements.size() == pool.size()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All measurements are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "Timed out waiting for other measurements. Auto-adaptation failed! Will stick to command line arguments";
return false;
}
}
double maxmean = .0;
double maxstdev = .0;
for (auto const& meas : _measurements) {
if (maxmean < meas[0]) {
maxmean = meas[0];
}
if (maxstdev < meas[1]) {
maxstdev = meas[1];
}
}
maxmean = 1.e-3*std::ceil(1.e3*(.1 + 1.0e-3*(maxmean+maxstdev)));
LOG_TOPIC(INFO, Logger::AGENCY)
<< "Auto-adapting RAFT timing to: {" << maxmean
<< ", " << 5.0*maxmean << "}s";
_agent->resetRAFTTimes(maxmean, 5.0*maxmean);
}
return true;
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromCommandLine() {
return false;
}
// @brief Thread main
void Inception::run() {
// 1. If active agency, do as you're told
if (activeAgencyFromPersistence()) {
_agent->ready(true);
}
// 2. If we think that we used to be active agent
if (!_agent->ready() && restartingActiveAgent()) {
_agent->ready(true);
}
// 3. Else gossip
config_t config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
gossip();
}
// 4. If still incomplete bail out :(
config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Failed to build environment for RAFT algorithm. Bailing out!";
FATAL_ERROR_EXIT();
}
estimateRAFTInterval();
_agent->ready(true);
}
// @brief Graceful shutdown
void Inception::beginShutdown() {
Thread::beginShutdown();
CONDITION_LOCKER(guard, _cv);
guard.broadcast();
}
<commit_msg>well tested auto adaptation<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "Inception.h"
#include "Agency/Agent.h"
#include "Agency/GossipCallback.h"
#include "Agency/MeasureCallback.h"
#include "Basics/ConditionLocker.h"
#include "Cluster/ClusterComm.h"
#include <chrono>
#include <numeric>
#include <thread>
using namespace arangodb::consensus;
Inception::Inception() : Thread("Inception"), _agent(nullptr) {}
Inception::Inception(Agent* agent) : Thread("Inception"), _agent(agent) {}
// Shutdown if not already
Inception::~Inception() { shutdown(); }
/// Gossip to others
/// - Get snapshot of gossip peers and agent pool
/// - Create outgoing gossip.
/// - Send to all peers
void Inception::gossip() {
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(120);
size_t i = 0;
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
config_t config = _agent->config(); // get a copy of conf
// Build gossip message
query_t out = std::make_shared<Builder>();
out->openObject();
out->add("endpoint", VPackValue(config.endpoint()));
out->add("id", VPackValue(config.id()));
out->add("pool", VPackValue(VPackValueType::Object));
for (auto const& i : config.pool()) {
out->add(i.first, VPackValue(i.second));
}
out->close();
out->close();
std::string path = privApiPrefix + "gossip";
// gossip peers
for (auto const& p : config.gossipPeers()) {
if (p != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, p, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// pool entries
for (auto const& pair : config.pool()) {
if (pair.second != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, pair.second, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// don't panic
_cv.wait(100000);
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (config.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
// We're done
if (config.poolComplete()) {
_agent->startConstituent();
break;
}
}
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromPersistence() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
// Contact hosts on pool in hopes of finding a leader Id
for (auto const& pair : myConfig.pool()) {
if (pair.first != myConfig.id()) {
auto comres = arangodb::ClusterComm::instance()->syncRequest(
myConfig.id(), 1, pair.second, rest::RequestType::GET, path,
std::string(), std::unordered_map<std::string, std::string>(), 1.0);
if (comres->status == CL_COMM_SENT) {
auto body = comres->result->getBodyVelocyPack();
auto theirConfig = body->slice();
std::string leaderId;
// LeaderId in configuration?
try {
leaderId = theirConfig.get("leaderId").copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
if (leaderId != "") { // Got leaderId. Let's get do it.
try {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Found active agency with leader " << leaderId
<< " at endpoint "
<< theirConfig.get("configuration").get(
"pool").get(leaderId).copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
auto agency = std::make_shared<Builder>();
agency->openObject();
agency->add("term", theirConfig.get("term"));
agency->add("id", VPackValue(leaderId));
agency->add("active", theirConfig.get("configuration").get("active"));
agency->add("pool", theirConfig.get("configuration").get("pool"));
agency->close();
_agent->notify(agency);
return true;
} else { // No leaderId. Move on.
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second;
}
}
}
}
}
return false;
}
bool Inception::restartingActiveAgent() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(60);
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
auto pool = myConfig.pool();
auto active = myConfig.active();
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
active.erase(
std::remove(active.begin(), active.end(), myConfig.id()), active.end());
active.erase(
std::remove(active.begin(), active.end(), ""), active.end());
if (active.empty()) {
return true;
}
for (auto& i : active) {
if (i != myConfig.id() && i != "") {
auto clientId = myConfig.id();
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, pool.at(i), rest::RequestType::GET, path, std::string(),
std::unordered_map<std::string, std::string>(), 2.0);
if (comres->status == CL_COMM_SENT) {
try {
auto theirActive = comres->result->getBodyVelocyPack()->
slice().get("configuration").get("active").toJson();
auto myActive = myConfig.activeToBuilder()->toJson();
if (theirActive != myActive) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer and I disagree on active membership."
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
} else {
i = "";
}
} catch (std::exception const& e) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer has no active agency list: " << e.what()
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
}
}
}
}
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (myConfig.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
_cv.wait(500000);
}
}
return false;
}
inline static int64_t timeStamp() {
using namespace std::chrono;
return duration_cast<microseconds>(
steady_clock::now().time_since_epoch()).count();
}
void Inception::reportIn(std::string const& peerId, uint64_t start) {
MUTEX_LOCKER(lock, _pLock);
_pings.push_back(1.0e-3*(double)(timeStamp()-start));
}
void Inception::reportIn(query_t const& query) {
VPackSlice slice = query->slice();
TRI_ASSERT(slice.isObject());
TRI_ASSERT(slice.hasKey("mean"));
TRI_ASSERT(slice.hasKey("stdev"));
TRI_ASSERT(slice.hasKey("min"));
TRI_ASSERT(slice.hasKey("max"));
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(
std::vector<double>(
{slice.get("mean").getDouble(), slice.get("stdev").getDouble(),
slice.get("max").getDouble(), slice.get("min").getDouble()} ));
}
bool Inception::estimateRAFTInterval() {
using namespace std::chrono;
std::string path("/_api/agency/config");
auto pool = _agent->config().pool();
auto myid = _agent->id();
for (size_t i = 0; i < 25; ++i) {
for (auto const& peer : pool) {
if (peer.first != myid) {
std::string clientid = peer.first + std::to_string(i);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, peer.second, rest::RequestType::GET, path,
std::make_shared<std::string>(), hf,
std::make_shared<MeasureCallback>(this, peer.second, timeStamp()),
2.0, true);
}
}
std::this_thread::sleep_for(std::chrono::duration<double,std::milli>(5));
}
auto s = system_clock::now();
seconds timeout(3);
CONDITION_LOCKER(guard, _cv);
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _pLock);
if (_pings.size() == 25*(pool.size()-1)) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All pings are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Timed out waiting for pings";
break;
}
}
if (! _pings.empty()) {
double mean, stdev, mx, mn;
MUTEX_LOCKER(lock, _pLock);
size_t num = _pings.size();
mean = std::accumulate(_pings.begin(), _pings.end(), 0.0) / num;
mx = *std::max_element(_pings.begin(), _pings.end());
mn = *std::min_element(_pings.begin(), _pings.end());
std::transform(_pings.begin(), _pings.end(), _pings.begin(),
std::bind2nd(std::minus<double>(), mean));
stdev =
std::sqrt(
std::inner_product(
_pings.begin(), _pings.end(), _pings.begin(), 0.0) / num);
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "mean(" << mean << ") stdev(" << stdev<< ")";
Builder measurement;
measurement.openObject();
measurement.add("mean", VPackValue(mean));
measurement.add("stdev", VPackValue(stdev));
measurement.add("min", VPackValue(mn));
measurement.add("max", VPackValue(mx));
measurement.close();
std::string measjson = measurement.toJson();
path = privApiPrefix + "measure";
for (auto const& peer : pool) {
if (peer.first != myid) {
auto clientId = "1";
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, peer.second, rest::RequestType::POST, path,
measjson, std::unordered_map<std::string, std::string>(), 2.0);
}
}
{
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(std::vector<double>({mean, stdev, mx, mn}));
}
s = system_clock::now();
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _mLock);
if (_measurements.size() == pool.size()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All measurements are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "Timed out waiting for other measurements. Auto-adaptation failed! Will stick to command line arguments";
return false;
}
}
double maxmean = .0;
double maxstdev = .0;
for (auto const& meas : _measurements) {
if (maxmean < meas[0]) {
maxmean = meas[0];
}
if (maxstdev < meas[1]) {
maxstdev = meas[1];
}
}
maxmean = 1.e-3*std::ceil(1.e3*(.1 + 1.0e-3*(maxmean+3*maxstdev)));
LOG_TOPIC(INFO, Logger::AGENCY)
<< "Auto-adapting RAFT timing to: {" << maxmean
<< ", " << 5.0*maxmean << "}s";
_agent->resetRAFTTimes(maxmean, 5.0*maxmean);
}
return true;
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromCommandLine() {
return false;
}
// @brief Thread main
void Inception::run() {
// 1. If active agency, do as you're told
if (activeAgencyFromPersistence()) {
_agent->ready(true);
}
// 2. If we think that we used to be active agent
if (!_agent->ready() && restartingActiveAgent()) {
_agent->ready(true);
}
// 3. Else gossip
config_t config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
gossip();
}
// 4. If still incomplete bail out :(
config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Failed to build environment for RAFT algorithm. Bailing out!";
FATAL_ERROR_EXIT();
}
estimateRAFTInterval();
_agent->ready(true);
}
// @brief Graceful shutdown
void Inception::beginShutdown() {
Thread::beginShutdown();
CONDITION_LOCKER(guard, _cv);
guard.broadcast();
}
<|endoftext|> |
<commit_before>//
// Matrix/instance_method_set.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_MATRIX_INSTANCE_METHOD_SET_HPP
#define EIGENJS_MATRIX_INSTANCE_METHOD_SET_HPP
namespace EigenJS {
EIGENJS_INSTANCE_METHOD(Matrix, set,
{
Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
typename Matrix::value_type& matrix = **obj;
NanScope();
if (args.Length() == 1 && args[0]->IsArray()) {
const v8::Local<v8::Array>& array = args[0].As<v8::Array>();
uint32_t len = array->Length();
const typename Matrix::value_type::Index& rows = matrix.rows();
const typename Matrix::value_type::Index& cols = matrix.cols();
const typename Matrix::value_type::Index& elems = rows * cols;
if (len != elems) {
len < rows * cols
? NanThrowError("Too few coefficients")
: NanThrowError("Too many coefficients");
NanReturnUndefined();
}
for (uint32_t i = 0; i < len; ++i) {
v8::Local<v8::Value> elem = array->Get(i);
matrix(i / cols, i % cols) = elem->NumberValue();
}
} else if (args.Length() == 3 &&
args[0]->IsNumber() &&
args[1]->IsNumber() &&
Matrix::is_scalar(args[2])
) {
const typename Matrix::value_type::Index& row = args[0]->Int32Value();
const typename Matrix::value_type::Index& col = args[1]->Int32Value();
const typename Matrix::scalar_type& value = args[2]->NumberValue();
if (Matrix::is_out_of_range(matrix, row, col)) {
NanReturnUndefined();
}
matrix(row, col) = value;
} else if (true) {
EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
NanReturnUndefined();
}
NanReturnValue(args.This());
})
} // namespace EigenJS
#endif // EIGENJS_MATRIX_INSTANCE_METHOD_SET_HPP
<commit_msg>src: abstract code<commit_after>//
// Matrix/instance_method_set.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_MATRIX_INSTANCE_METHOD_SET_HPP
#define EIGENJS_MATRIX_INSTANCE_METHOD_SET_HPP
namespace EigenJS {
EIGENJS_INSTANCE_METHOD(Matrix, set,
{
T* obj = node::ObjectWrap::Unwrap<T>(args.This());
typename T::value_type& matrix = **obj;
NanScope();
if (args.Length() == 1 && args[0]->IsArray()) {
const v8::Local<v8::Array>& array = args[0].As<v8::Array>();
uint32_t len = array->Length();
const typename T::value_type::Index& rows = matrix.rows();
const typename T::value_type::Index& cols = matrix.cols();
const typename T::value_type::Index& elems = rows * cols;
if (len != elems) {
len < rows * cols
? NanThrowError("Too few coefficients")
: NanThrowError("Too many coefficients");
NanReturnUndefined();
}
for (uint32_t i = 0; i < len; ++i) {
v8::Local<v8::Value> elem = array->Get(i);
matrix(i / cols, i % cols) = elem->NumberValue();
}
} else if (args.Length() == 3 &&
args[0]->IsNumber() &&
args[1]->IsNumber() &&
Matrix::is_scalar(args[2])
) {
const typename T::value_type::Index& row = args[0]->Int32Value();
const typename T::value_type::Index& col = args[1]->Int32Value();
const typename T::scalar_type& value = args[2]->NumberValue();
if (T::is_out_of_range(matrix, row, col)) {
NanReturnUndefined();
}
matrix(row, col) = value;
} else if (true) {
EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
NanReturnUndefined();
}
NanReturnValue(args.This());
})
} // namespace EigenJS
#endif // EIGENJS_MATRIX_INSTANCE_METHOD_SET_HPP
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// ok is an experimental test harness, maybe to replace DM. Key features:
// * work is balanced across separate processes for stability and isolation;
// * ok is entirely opt-in. No more maintaining huge --blacklists.
#include "SkGraphics.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkSurface.h"
#include "gm.h"
#include <chrono>
#include <functional>
#include <future>
#include <list>
#include <map>
#include <memory>
#include <regex>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
enum class Status { OK, Failed, Crashed, Skipped, None };
struct Engine {
virtual ~Engine() {}
virtual bool spawn(std::function<Status(void)>) = 0;
virtual Status wait_one() = 0;
};
struct SerialEngine : Engine {
Status last = Status::None;
bool spawn(std::function<Status(void)> fn) override {
last = fn();
return true;
}
Status wait_one() override {
Status s = last;
last = Status::None;
return s;
}
};
struct ThreadEngine : Engine {
std::list<std::future<Status>> live;
bool spawn(std::function<Status(void)> fn) override {
live.push_back(std::async(std::launch::async, fn));
return true;
}
Status wait_one() override {
if (live.empty()) {
return Status::None;
}
for (;;) {
for (auto it = live.begin(); it != live.end(); it++) {
if (it->wait_for(std::chrono::seconds::zero()) == std::future_status::ready) {
Status s = it->get();
live.erase(it);
return s;
}
}
}
}
};
#if defined(_MSC_VER)
using ForkEngine = ThreadEngine;
#else
#include <sys/wait.h>
#include <unistd.h>
struct ForkEngine : Engine {
bool spawn(std::function<Status(void)> fn) override {
switch (fork()) {
case 0: exit((int)fn());
case -1: return false;
default: return true;
}
}
Status wait_one() override {
do {
int status;
if (wait(&status) > 0) {
return WIFEXITED(status) ? (Status)WEXITSTATUS(status)
: Status::Crashed;
}
} while (errno == EINTR);
return Status::None;
}
};
#endif
struct Src {
virtual ~Src() {}
virtual std::string name() = 0;
virtual SkISize size() = 0;
virtual void draw(SkCanvas*) = 0;
};
struct Stream {
virtual ~Stream() {}
virtual std::unique_ptr<Src> next() = 0;
};
struct Options {
std::map<std::string, std::string> kv;
explicit Options(std::string str) {
std::string k,v, *curr = &k;
for (auto c : str) {
switch(c) {
case ',': kv[k] = v;
curr = &(k = "");
break;
case '=': curr = &(v = "");
break;
default: *curr += c;
}
}
kv[k] = v;
}
std::string lookup(std::string k, std::string fallback) {
for (auto it = kv.find(k); it != kv.end(); ) {
return it->second;
}
return fallback;
}
};
struct GMStream : Stream {
const skiagm::GMRegistry* registry = skiagm::GMRegistry::Head();
struct GMSrc : Src {
skiagm::GM* (*factory)(void*);
std::unique_ptr<skiagm::GM> gm;
std::string name() override {
gm.reset(factory(nullptr));
return gm->getName();
}
SkISize size() override {
return gm->getISize();
}
void draw(SkCanvas* canvas) override {
canvas->clear(0xffffffff);
canvas->concat(gm->getInitialTransform());
gm->draw(canvas);
}
};
std::unique_ptr<Src> next() override {
if (!registry) {
return nullptr;
}
GMSrc src;
src.factory = registry->factory();
registry = registry->next();
return std::unique_ptr<Src>{new GMSrc{std::move(src)}};
}
};
struct SKPStream : Stream {
std::string dir;
std::vector<std::string> skps;
explicit SKPStream(Options options) : dir(options.lookup("dir", "skps")) {
SkOSFile::Iter it{dir.c_str(), ".skp"};
for (SkString path; it.next(&path); ) {
skps.push_back(path.c_str());
}
}
struct SKPSrc : Src {
std::string dir, path;
sk_sp<SkPicture> pic;
std::string name() override {
return path;
}
SkISize size() override {
auto skp = SkData::MakeFromFileName((dir+"/"+path).c_str());
pic = SkPicture::MakeFromData(skp.get());
return pic->cullRect().roundOut().size();
}
void draw(SkCanvas* canvas) override {
canvas->clear(0xffffffff);
pic->playback(canvas);
}
};
std::unique_ptr<Src> next() override {
if (skps.empty()) {
return nullptr;
}
SKPSrc src;
src.dir = dir;
src.path = skps.back();
skps.pop_back();
return std::unique_ptr<Src>{new SKPSrc{std::move(src)}};
}
};
struct {
const char* name;
std::unique_ptr<Stream> (*factory)(Options);
} streams[] = {
{"gm", [](Options options) { return std::unique_ptr<Stream>{new GMStream}; }},
{"skp", [](Options options) { return std::unique_ptr<Stream>{new SKPStream{options}}; }},
};
int main(int argc, char** argv) {
SkGraphics::Init();
int jobs {1};
std::regex match {".*"};
std::regex search {".*"};
std::string write_dir {""};
std::unique_ptr<Stream> stream;
auto help = [&] {
std::string stream_types;
for (auto st : streams) {
if (!stream_types.empty()) {
stream_types += ", ";
}
stream_types += st.name;
}
printf("%s [-j N] [-m regex] [-s regex] [-w dir] [-h] stream[:k=v,k=v,...] \n"
" -j: Run at most N processes at any time. \n"
" If <0, use -N threads instead. \n"
" If 0, use one thread in one process. \n"
" If 1 (default) or -1, auto-detect N. \n"
" -m: Run only names matching regex exactly. \n"
" -s: Run only names matching regex anywhere. \n"
" -w: If set, write .pngs into dir. \n"
" -h: Print this message and exit. \n"
" stream: content to draw: %s \n"
" Some streams have options, e.g. skp:dir=skps \n",
argv[0], stream_types.c_str());
return 1;
};
for (int i = 1; i < argc; i++) {
if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); }
if (0 == strcmp("-m", argv[i])) { match = argv[++i] ; }
if (0 == strcmp("-s", argv[i])) { search = argv[++i] ; }
if (0 == strcmp("-w", argv[i])) { write_dir = argv[++i] ; }
if (0 == strcmp("-h", argv[i])) { return help(); }
for (auto st : streams) {
size_t len = strlen(st.name);
if (0 == strncmp(st.name, argv[i], len)) {
switch (argv[i][len]) {
case ':': len++;
case '\0': stream = st.factory(Options{argv[i]+len});
}
}
}
}
if (!stream) { return help(); }
std::unique_ptr<Engine> engine;
if (jobs == 0) { engine.reset(new SerialEngine); }
if (jobs > 0) { engine.reset(new ForkEngine); }
if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; }
if (jobs == 1) { jobs = std::thread::hardware_concurrency(); }
if (!write_dir.empty()) {
sk_mkdir(write_dir.c_str());
}
int ok = 0, failed = 0, crashed = 0, skipped = 0;
auto update_stats = [&](Status s) {
switch (s) {
case Status::OK: ok++; break;
case Status::Failed: failed++; break;
case Status::Crashed: crashed++; break;
case Status::Skipped: skipped++; break;
case Status::None: return;
}
const char* leader = "\r";
auto print = [&](int count, const char* label) {
if (count) {
printf("%s%d %s", leader, count, label);
leader = ", ";
}
};
print(ok, "ok");
print(failed, "failed");
print(crashed, "crashed");
print(skipped, "skipped");
fflush(stdout);
};
auto spawn = [&](std::function<Status(void)> fn) {
if (--jobs < 0) {
update_stats(engine->wait_one());
}
while (!engine->spawn(fn)) {
update_stats(engine->wait_one());
}
};
for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) {
Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :(
spawn([=] {
std::unique_ptr<Src> src{raw};
auto name = src->name();
if (!std::regex_match (name, match) ||
!std::regex_search(name, search)) {
return Status::Skipped;
}
auto size = src->size();
auto surface = SkSurface::MakeRasterN32Premul(size.width(), size.height());
src->draw(surface->getCanvas());
if (!write_dir.empty()) {
auto image = surface->makeImageSnapshot();
sk_sp<SkData> png{image->encode()};
std::string path = write_dir + "/" + name + ".png";
SkFILEWStream{path.c_str()}.write(png->data(), png->size());
}
return Status::OK;
});
}
for (Status s = Status::OK; s != Status::None; ) {
s = engine->wait_one();
update_stats(s);
}
printf("\n");
return (failed || crashed) ? 1 : 0;
}
<commit_msg>ok: basic crash handling and stack trace dumps<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// ok is an experimental test harness, maybe to replace DM. Key features:
// * work is balanced across separate processes for stability and isolation;
// * ok is entirely opt-in. No more maintaining huge --blacklists.
#include "SkGraphics.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkSurface.h"
#include "gm.h"
#include <chrono>
#include <functional>
#include <future>
#include <list>
#include <map>
#include <memory>
#include <regex>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#if !defined(__has_include)
#define __has_include(x) 0
#endif
static thread_local const char* tls_name = "";
#if __has_include(<execinfo.h>) && __has_include(<fcntl.h>) && __has_include(<signal.h>)
#include <execinfo.h>
#include <fcntl.h>
#include <signal.h>
static int crash_stacktrace_fd = 2/*stderr*/;
static void setup_crash_handler() {
static void (*original_handlers[32])(int);
for (int sig : std::vector<int>{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }) {
original_handlers[sig] = signal(sig, [](int sig) {
auto ez_write = [](const char* str) {
write(crash_stacktrace_fd, str, strlen(str));
};
ez_write("\ncaught signal ");
switch (sig) {
#define CASE(s) case s: ez_write(#s); break
CASE(SIGABRT);
CASE(SIGBUS);
CASE(SIGFPE);
CASE(SIGILL);
CASE(SIGSEGV);
#undef CASE
}
ez_write(" while running '");
ez_write(tls_name);
ez_write("'\n");
void* stack[128];
int frames = backtrace(stack, sizeof(stack)/sizeof(*stack));
backtrace_symbols_fd(stack, frames, crash_stacktrace_fd);
signal(sig, original_handlers[sig]);
raise(sig);
});
}
}
static void defer_crash_stacktraces() {
crash_stacktrace_fd = fileno(tmpfile());
atexit([] {
lseek(crash_stacktrace_fd, 0, SEEK_SET);
char buf[1024];
while (size_t bytes = read(crash_stacktrace_fd, buf, sizeof(buf))) {
write(2, buf, bytes);
}
});
}
#else
static void setup_crash_handler() {}
static void defer_crash_stacktraces() {}
#endif
enum class Status { OK, Failed, Crashed, Skipped, None };
struct Engine {
virtual ~Engine() {}
virtual bool spawn(std::function<Status(void)>) = 0;
virtual Status wait_one() = 0;
};
struct SerialEngine : Engine {
Status last = Status::None;
bool spawn(std::function<Status(void)> fn) override {
last = fn();
return true;
}
Status wait_one() override {
Status s = last;
last = Status::None;
return s;
}
};
struct ThreadEngine : Engine {
std::list<std::future<Status>> live;
bool spawn(std::function<Status(void)> fn) override {
live.push_back(std::async(std::launch::async, fn));
return true;
}
Status wait_one() override {
if (live.empty()) {
return Status::None;
}
for (;;) {
for (auto it = live.begin(); it != live.end(); it++) {
if (it->wait_for(std::chrono::seconds::zero()) == std::future_status::ready) {
Status s = it->get();
live.erase(it);
return s;
}
}
}
}
};
#if defined(_MSC_VER)
using ForkEngine = ThreadEngine;
#else
#include <sys/wait.h>
#include <unistd.h>
struct ForkEngine : Engine {
bool spawn(std::function<Status(void)> fn) override {
switch (fork()) {
case 0: _exit((int)fn());
case -1: return false;
default: return true;
}
}
Status wait_one() override {
do {
int status;
if (wait(&status) > 0) {
return WIFEXITED(status) ? (Status)WEXITSTATUS(status)
: Status::Crashed;
}
} while (errno == EINTR);
return Status::None;
}
};
#endif
struct Src {
virtual ~Src() {}
virtual std::string name() = 0;
virtual SkISize size() = 0;
virtual void draw(SkCanvas*) = 0;
};
struct Stream {
virtual ~Stream() {}
virtual std::unique_ptr<Src> next() = 0;
};
struct Options {
std::map<std::string, std::string> kv;
explicit Options(std::string str) {
std::string k,v, *curr = &k;
for (auto c : str) {
switch(c) {
case ',': kv[k] = v;
curr = &(k = "");
break;
case '=': curr = &(v = "");
break;
default: *curr += c;
}
}
kv[k] = v;
}
std::string lookup(std::string k, std::string fallback) {
for (auto it = kv.find(k); it != kv.end(); ) {
return it->second;
}
return fallback;
}
};
struct GMStream : Stream {
const skiagm::GMRegistry* registry = skiagm::GMRegistry::Head();
struct GMSrc : Src {
skiagm::GM* (*factory)(void*);
std::unique_ptr<skiagm::GM> gm;
std::string name() override {
gm.reset(factory(nullptr));
return gm->getName();
}
SkISize size() override {
return gm->getISize();
}
void draw(SkCanvas* canvas) override {
canvas->clear(0xffffffff);
canvas->concat(gm->getInitialTransform());
gm->draw(canvas);
}
};
std::unique_ptr<Src> next() override {
if (!registry) {
return nullptr;
}
GMSrc src;
src.factory = registry->factory();
registry = registry->next();
return std::unique_ptr<Src>{new GMSrc{std::move(src)}};
}
};
struct SKPStream : Stream {
std::string dir;
std::vector<std::string> skps;
explicit SKPStream(Options options) : dir(options.lookup("dir", "skps")) {
SkOSFile::Iter it{dir.c_str(), ".skp"};
for (SkString path; it.next(&path); ) {
skps.push_back(path.c_str());
}
}
struct SKPSrc : Src {
std::string dir, path;
sk_sp<SkPicture> pic;
std::string name() override {
return path;
}
SkISize size() override {
auto skp = SkData::MakeFromFileName((dir+"/"+path).c_str());
pic = SkPicture::MakeFromData(skp.get());
return pic->cullRect().roundOut().size();
}
void draw(SkCanvas* canvas) override {
canvas->clear(0xffffffff);
pic->playback(canvas);
}
};
std::unique_ptr<Src> next() override {
if (skps.empty()) {
return nullptr;
}
SKPSrc src;
src.dir = dir;
src.path = skps.back();
skps.pop_back();
return std::unique_ptr<Src>{new SKPSrc{std::move(src)}};
}
};
struct {
const char* name;
std::unique_ptr<Stream> (*factory)(Options);
} streams[] = {
{"gm", [](Options options) { return std::unique_ptr<Stream>{new GMStream}; }},
{"skp", [](Options options) { return std::unique_ptr<Stream>{new SKPStream{options}}; }},
};
int main(int argc, char** argv) {
SkGraphics::Init();
setup_crash_handler();
int jobs {1};
std::regex match {".*"};
std::regex search {".*"};
std::string write_dir {""};
std::unique_ptr<Stream> stream;
auto help = [&] {
std::string stream_types;
for (auto st : streams) {
if (!stream_types.empty()) {
stream_types += ", ";
}
stream_types += st.name;
}
printf("%s [-j N] [-m regex] [-s regex] [-w dir] [-h] stream[:k=v,k=v,...] \n"
" -j: Run at most N processes at any time. \n"
" If <0, use -N threads instead. \n"
" If 0, use one thread in one process. \n"
" If 1 (default) or -1, auto-detect N. \n"
" -m: Run only names matching regex exactly. \n"
" -s: Run only names matching regex anywhere. \n"
" -w: If set, write .pngs into dir. \n"
" -h: Print this message and exit. \n"
" stream: content to draw: %s \n"
" Some streams have options, e.g. skp:dir=skps \n",
argv[0], stream_types.c_str());
return 1;
};
for (int i = 1; i < argc; i++) {
if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); }
if (0 == strcmp("-m", argv[i])) { match = argv[++i] ; }
if (0 == strcmp("-s", argv[i])) { search = argv[++i] ; }
if (0 == strcmp("-w", argv[i])) { write_dir = argv[++i] ; }
if (0 == strcmp("-h", argv[i])) { return help(); }
for (auto st : streams) {
size_t len = strlen(st.name);
if (0 == strncmp(st.name, argv[i], len)) {
switch (argv[i][len]) {
case ':': len++;
case '\0': stream = st.factory(Options{argv[i]+len});
}
}
}
}
if (!stream) { return help(); }
std::unique_ptr<Engine> engine;
if (jobs == 0) { engine.reset(new SerialEngine); }
if (jobs > 0) { engine.reset(new ForkEngine); defer_crash_stacktraces(); }
if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; }
if (jobs == 1) { jobs = std::thread::hardware_concurrency(); }
if (!write_dir.empty()) {
sk_mkdir(write_dir.c_str());
}
int ok = 0, failed = 0, crashed = 0, skipped = 0;
auto update_stats = [&](Status s) {
switch (s) {
case Status::OK: ok++; break;
case Status::Failed: failed++; break;
case Status::Crashed: crashed++; break;
case Status::Skipped: skipped++; break;
case Status::None: return;
}
const char* leader = "\r";
auto print = [&](int count, const char* label) {
if (count) {
printf("%s%d %s", leader, count, label);
leader = ", ";
}
};
print(ok, "ok");
print(failed, "failed");
print(crashed, "crashed");
print(skipped, "skipped");
fflush(stdout);
};
auto spawn = [&](std::function<Status(void)> fn) {
if (--jobs < 0) {
update_stats(engine->wait_one());
}
while (!engine->spawn(fn)) {
update_stats(engine->wait_one());
}
};
for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) {
Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :(
spawn([=] {
std::unique_ptr<Src> src{raw};
auto name = src->name();
tls_name = name.c_str();
if (!std::regex_match (name, match) ||
!std::regex_search(name, search)) {
return Status::Skipped;
}
auto size = src->size();
auto surface = SkSurface::MakeRasterN32Premul(size.width(), size.height());
src->draw(surface->getCanvas());
if (!write_dir.empty()) {
auto image = surface->makeImageSnapshot();
sk_sp<SkData> png{image->encode()};
std::string path = write_dir + "/" + name + ".png";
SkFILEWStream{path.c_str()}.write(png->data(), png->size());
}
return Status::OK;
});
}
for (Status s = Status::OK; s != Status::None; ) {
s = engine->wait_one();
update_stats(s);
}
printf("\n");
return (failed || crashed) ? 1 : 0;
}
<|endoftext|> |
<commit_before>#ifndef ATOMIC_HH
#define ATOMIC_HH
#include <pthread.h>
#include <queue>
#include "locks.hh"
#define MAX_THREADS 100
template<typename T>
class ThreadLocal {
public:
ThreadLocal(void (*destructor)(void *) = NULL) {
int rc = pthread_key_create(&key, destructor);
if (rc != 0) {
throw std::runtime_error("Failed to create a thread-specific key");
}
}
~ThreadLocal() {
pthread_key_delete(key);
}
void set(const T &newValue) {
pthread_setspecific(key, newValue);
}
T get() const {
return reinterpret_cast<T>(pthread_getspecific(key));
}
void operator =(const T &newValue) {
set(newValue);
}
operator T() const {
return get();
}
private:
pthread_key_t key;
};
template <typename T>
class ThreadLocalPtr : public ThreadLocal<T*> {
public:
ThreadLocalPtr(void (*destructor)(void *) = NULL) : ThreadLocal<T*>(destructor) {}
~ThreadLocalPtr() {}
T *operator ->() {
return ThreadLocal<T*>::get();
}
T operator *() {
return *ThreadLocal<T*>::get();
}
void operator =(T *newValue) {
set(newValue);
}
};
template <typename T>
class Atomic {
public:
Atomic() {}
Atomic(const T &initial) {
set(initial);
}
~Atomic() {}
T get() const {
return value;
}
void set(const T &newValue) {
value = newValue;
__sync_synchronize();
}
operator T() const {
return get();
}
void operator =(const T &newValue) {
set(newValue);
}
bool cas(const T &oldValue, const T &newValue) {
return __sync_bool_compare_and_swap(&value, oldValue, newValue);
}
T operator ++() { // prefix
return __sync_add_and_fetch(&value, 1);
}
T operator ++(int ignored) { // postfix
(void)ignored;
return __sync_fetch_and_add(&value, 1);
}
T operator +=(T increment) {
// Returns the new value
return __sync_add_and_fetch(&value, increment);
}
T operator -=(T decrement) {
return __sync_add_and_fetch(&value, -decrement);
}
T incr(const T &increment = 1) {
// Returns the old value
return __sync_fetch_and_add(&value, increment);
}
T swap(const T &newValue) {
T rv;
while (true) {
rv = get();
if (cas(rv, newValue)) {
break;
}
}
return rv;
}
T swapIfNot(const T &badValue, const T &newValue) {
T oldValue;
while (true) {
oldValue = get();
if (oldValue != badValue) {
if (cas(oldValue, newValue)) {
break;
}
} else {
break;
}
}
return oldValue;
}
private:
volatile T value;
};
template <typename T>
class AtomicPtr : public Atomic<T*> {
public:
AtomicPtr(T *initial = NULL) : Atomic<T*>(initial) {}
~AtomicPtr() {}
T *operator ->() {
return Atomic<T*>::get();
}
T operator *() {
return *Atomic<T*>::get();
}
};
template <typename T>
class AtomicQueue {
public:
AtomicQueue() : counter((size_t)0), numItems((size_t)0) {}
~AtomicQueue() {
size_t i;
for (i = 0; i < counter; ++i) {
delete queues[i];
}
}
void push(T value) {
std::queue<T> *q = swapQueue(); // steal our queue
q->push(value);
++numItems;
q = swapQueue(q);
}
void pushQueue(std::queue<T> &inQueue) {
std::queue<T> *q = swapQueue(); // steal our queue
numItems.incr(inQueue.size());
while (!inQueue.empty()) {
q->push(inQueue.front());
inQueue.pop();
}
q = swapQueue(q);
}
void getAll(std::queue<T> &outQueue) {
std::queue<T> *q(swapQueue()); // Grab my own queue
std::queue<T> *newQueue(NULL);
int i(0), count(0);
// Will start empty unless this thread is adding stuff
while (!q->empty()) {
outQueue.push(q->front());
q->pop();
++count;
}
int c = counter;
for (i = 0; i < c; ++i) {
// Swap with another thread
newQueue = queues[i].swapIfNot(NULL, q);
// Empty the queue
if (newQueue != NULL) {
q = newQueue;
while (!q->empty()) {
outQueue.push(q->front());
q->pop();
++count;
}
}
}
q = swapQueue(q);
numItems -= count;
}
size_t getNumQueues() const {
return counter;
}
bool empty() const {
return size() == 0;
}
size_t size() const {
return numItems;
}
private:
AtomicPtr<std::queue<T> > *initialize() {
std::queue<T> *q = new std::queue<T>;
int i = counter++;
queues[i] = q;
threadQueue = &queues[i];
return &queues[i];
}
std::queue<T> *swapQueue(std::queue<T> *newQueue = NULL) {
AtomicPtr<std::queue<T> > *qPtr(threadQueue);
if (qPtr == NULL) {
qPtr = initialize();
}
return qPtr->swap(newQueue);
}
ThreadLocalPtr<AtomicPtr<std::queue<T> > > threadQueue;
AtomicPtr<std::queue<T> > queues[MAX_THREADS];
Atomic<size_t> counter;
Atomic<size_t> numItems;
DISALLOW_COPY_AND_ASSIGN(AtomicQueue);
};
#endif // ATOMIC_HH
<commit_msg>Compile fixes for Linux.<commit_after>#ifndef ATOMIC_HH
#define ATOMIC_HH
#include <pthread.h>
#include <queue>
#include "locks.hh"
#define MAX_THREADS 100
template<typename T>
class ThreadLocal {
public:
ThreadLocal(void (*destructor)(void *) = NULL) {
int rc = pthread_key_create(&key, destructor);
if (rc != 0) {
throw std::runtime_error("Failed to create a thread-specific key");
}
}
~ThreadLocal() {
pthread_key_delete(key);
}
void set(const T &newValue) {
pthread_setspecific(key, newValue);
}
T get() const {
return reinterpret_cast<T>(pthread_getspecific(key));
}
void operator =(const T &newValue) {
set(newValue);
}
operator T() const {
return get();
}
private:
pthread_key_t key;
};
template <typename T>
class ThreadLocalPtr : public ThreadLocal<T*> {
public:
ThreadLocalPtr(void (*destructor)(void *) = NULL) : ThreadLocal<T*>(destructor) {}
~ThreadLocalPtr() {}
T *operator ->() {
return ThreadLocal<T*>::get();
}
T operator *() {
return *ThreadLocal<T*>::get();
}
void operator =(T *newValue) {
set(newValue);
}
};
template <typename T>
class Atomic {
public:
Atomic() {}
Atomic(const T &initial) {
set(initial);
}
~Atomic() {}
T get() const {
return value;
}
void set(const T &newValue) {
value = newValue;
__sync_synchronize();
}
operator T() const {
return get();
}
void operator =(const T &newValue) {
set(newValue);
}
bool cas(const T &oldValue, const T &newValue) {
return __sync_bool_compare_and_swap(&value, oldValue, newValue);
}
T operator ++() { // prefix
return __sync_add_and_fetch(&value, 1);
}
T operator ++(int ignored) { // postfix
(void)ignored;
return __sync_fetch_and_add(&value, 1);
}
T operator +=(T increment) {
// Returns the new value
return __sync_add_and_fetch(&value, increment);
}
T operator -=(T decrement) {
return __sync_add_and_fetch(&value, -decrement);
}
T incr(const T &increment = 1) {
// Returns the old value
return __sync_fetch_and_add(&value, increment);
}
T swap(const T &newValue) {
T rv;
while (true) {
rv = get();
if (cas(rv, newValue)) {
break;
}
}
return rv;
}
T swapIfNot(const T &badValue, const T &newValue) {
T oldValue;
while (true) {
oldValue = get();
if (oldValue != badValue) {
if (cas(oldValue, newValue)) {
break;
}
} else {
break;
}
}
return oldValue;
}
private:
volatile T value;
};
template <typename T>
class AtomicPtr : public Atomic<T*> {
public:
AtomicPtr(T *initial = NULL) : Atomic<T*>(initial) {}
~AtomicPtr() {}
T *operator ->() {
return Atomic<T*>::get();
}
T operator *() {
return *Atomic<T*>::get();
}
};
template <typename T>
class AtomicQueue {
public:
AtomicQueue() : counter((size_t)0), numItems((size_t)0) {}
~AtomicQueue() {
size_t i;
for (i = 0; i < counter; ++i) {
delete queues[i];
}
}
void push(T value) {
std::queue<T> *q = swapQueue(); // steal our queue
q->push(value);
++numItems;
q = swapQueue(q);
}
void pushQueue(std::queue<T> &inQueue) {
std::queue<T> *q = swapQueue(); // steal our queue
numItems.incr(inQueue.size());
while (!inQueue.empty()) {
q->push(inQueue.front());
inQueue.pop();
}
q = swapQueue(q);
}
void getAll(std::queue<T> &outQueue) {
std::queue<T> *q(swapQueue()); // Grab my own queue
std::queue<T> *newQueue(NULL);
int count(0);
// Will start empty unless this thread is adding stuff
while (!q->empty()) {
outQueue.push(q->front());
q->pop();
++count;
}
size_t c(counter);
for (size_t i = 0; i < c; ++i) {
// Swap with another thread
newQueue = queues[i].swapIfNot(NULL, q);
// Empty the queue
if (newQueue != NULL) {
q = newQueue;
while (!q->empty()) {
outQueue.push(q->front());
q->pop();
++count;
}
}
}
q = swapQueue(q);
numItems -= count;
}
size_t getNumQueues() const {
return counter;
}
bool empty() const {
return size() == 0;
}
size_t size() const {
return numItems;
}
private:
AtomicPtr<std::queue<T> > *initialize() {
std::queue<T> *q = new std::queue<T>;
size_t i(counter++);
queues[i] = q;
threadQueue = &queues[i];
return &queues[i];
}
std::queue<T> *swapQueue(std::queue<T> *newQueue = NULL) {
AtomicPtr<std::queue<T> > *qPtr(threadQueue);
if (qPtr == NULL) {
qPtr = initialize();
}
return qPtr->swap(newQueue);
}
ThreadLocalPtr<AtomicPtr<std::queue<T> > > threadQueue;
AtomicPtr<std::queue<T> > queues[MAX_THREADS];
Atomic<size_t> counter;
Atomic<size_t> numItems;
DISALLOW_COPY_AND_ASSIGN(AtomicQueue);
};
#endif // ATOMIC_HH
<|endoftext|> |
<commit_before>#include<iostream>
using namespace std;
int main()
{
int a=2,b=2;
a++;
cout<<a<<endl;
b=++a;
cout<<b<<endl;
return 0;
}
<commit_msg>Update test09.cpp<commit_after>#include<iostream>
using namespace std;
int main()
{
int a=2,b=2;
a++;//a=3
cout<<a<<endl;//3
b=++a;//4
cout<<b<<endl;//4
return 0;
}
<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS TriMeshT
//
//=============================================================================
#ifndef OPENMESH_TRIMESH_HH
#define OPENMESH_TRIMESH_HH
//== INCLUDES =================================================================
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/Mesh/PolyMeshT.hh>
#include <vector>
//== NAMESPACES ===============================================================
namespace OpenMesh {
//== CLASS DEFINITION =========================================================
/** \class TriMeshT TriMeshT.hh <OpenMesh/Mesh/TriMeshT.hh>
Base type for a triangle mesh.
Base type for a triangle mesh, parameterized by a mesh kernel. The
mesh inherits all methods from the kernel class and the
more general polygonal mesh PolyMeshT. Therefore it provides
the same types for items, handles, iterators and so on.
\param Kernel: template argument for the mesh kernel
\note You should use the predefined mesh-kernel combinations in
\ref mesh_types_group
\see \ref mesh_type
\see OpenMesh::PolyMeshT
*/
template <class Kernel>
class TriMeshT : public PolyMeshT<Kernel>
{
public:
// self
typedef TriMeshT<Kernel> This;
typedef PolyMeshT<Kernel> PolyMesh;
//@{
/// Determine whether this is a PolyMeshT or TriMeshT ( This function does not check the per face vertex count! It only checks if the datatype is PolyMeshT or TriMeshT )
enum { IsPolyMesh = 0 };
enum { IsTriMesh = 1 };
static bool is_polymesh() { return false; }
static bool is_trimesh() { return true; }
//@}
//--- items ---
typedef typename PolyMesh::Scalar Scalar;
typedef typename PolyMesh::Point Point;
typedef typename PolyMesh::Normal Normal;
typedef typename PolyMesh::Color Color;
typedef typename PolyMesh::TexCoord1D TexCoord1D;
typedef typename PolyMesh::TexCoord2D TexCoord2D;
typedef typename PolyMesh::TexCoord3D TexCoord3D;
typedef typename PolyMesh::Vertex Vertex;
typedef typename PolyMesh::Halfedge Halfedge;
typedef typename PolyMesh::Edge Edge;
typedef typename PolyMesh::Face Face;
//--- handles ---
typedef typename PolyMesh::VertexHandle VertexHandle;
typedef typename PolyMesh::HalfedgeHandle HalfedgeHandle;
typedef typename PolyMesh::EdgeHandle EdgeHandle;
typedef typename PolyMesh::FaceHandle FaceHandle;
//--- iterators ---
typedef typename PolyMesh::VertexIter VertexIter;
typedef typename PolyMesh::ConstVertexIter ConstVertexIter;
typedef typename PolyMesh::EdgeIter EdgeIter;
typedef typename PolyMesh::ConstEdgeIter ConstEdgeIter;
typedef typename PolyMesh::FaceIter FaceIter;
typedef typename PolyMesh::ConstFaceIter ConstFaceIter;
//--- circulators ---
typedef typename PolyMesh::VertexVertexIter VertexVertexIter;
typedef typename PolyMesh::VertexOHalfedgeIter VertexOHalfedgeIter;
typedef typename PolyMesh::VertexIHalfedgeIter VertexIHalfedgeIter;
typedef typename PolyMesh::VertexEdgeIter VertexEdgeIter;
typedef typename PolyMesh::VertexFaceIter VertexFaceIter;
typedef typename PolyMesh::FaceVertexIter FaceVertexIter;
typedef typename PolyMesh::FaceHalfedgeIter FaceHalfedgeIter;
typedef typename PolyMesh::FaceEdgeIter FaceEdgeIter;
typedef typename PolyMesh::FaceFaceIter FaceFaceIter;
typedef typename PolyMesh::ConstVertexVertexIter ConstVertexVertexIter;
typedef typename PolyMesh::ConstVertexOHalfedgeIter ConstVertexOHalfedgeIter;
typedef typename PolyMesh::ConstVertexIHalfedgeIter ConstVertexIHalfedgeIter;
typedef typename PolyMesh::ConstVertexEdgeIter ConstVertexEdgeIter;
typedef typename PolyMesh::ConstVertexFaceIter ConstVertexFaceIter;
typedef typename PolyMesh::ConstFaceVertexIter ConstFaceVertexIter;
typedef typename PolyMesh::ConstFaceHalfedgeIter ConstFaceHalfedgeIter;
typedef typename PolyMesh::ConstFaceEdgeIter ConstFaceEdgeIter;
typedef typename PolyMesh::ConstFaceFaceIter ConstFaceFaceIter;
// --- constructor/destructor
/// Default constructor
TriMeshT() : PolyMesh() {}
/// Destructor
virtual ~TriMeshT() {}
//--- halfedge collapse / vertex split ---
/** \brief Vertex Split: inverse operation to collapse().
*
* Insert the new vertex at position v0. The vertex will be added
* as the inverse of the vertex split. The faces above the split
* will be correctly attached to the two new edges
*
* Before:
* v_l v0 v_r
* x x x
* \ /
* \ /
* \ /
* \ /
* \ /
* \ /
* x
* v1
*
* After:
* v_l v0 v_r
* x------x------x
* \ | /
* \ | /
* \ | /
* \ | /
* \ | /
* \|/
* x
* v1
*
* @param _v0_point Point position for the new point
* @param _v1 Vertex that will be split
* @param _vl Left vertex handle
* @param _vr Right vertex handle
* @return Newly inserted halfedge
*/
inline HalfedgeHandle vertex_split(Point _v0_point, VertexHandle _v1,
VertexHandle _vl, VertexHandle _vr)
{ return PolyMesh::vertex_split(add_vertex(_v0_point), _v1, _vl, _vr); }
/** \brief Vertex Split: inverse operation to collapse().
*
* Insert the new vertex at position v0. The vertex will be added
* as the inverse of the vertex split. The faces above the split
* will be correctly attached to the two new edges
*
* Before:
* v_l v0 v_r
* x x x
* \ /
* \ /
* \ /
* \ /
* \ /
* \ /
* x
* v1
*
* After:
* v_l v0 v_r
* x------x------x
* \ | /
* \ | /
* \ | /
* \ | /
* \ | /
* \|/
* x
* v1
*
* @param _v0 Vertex handle for the newly inserted point (Input has to be unconnected!)
* @param _v1 Vertex that will be split
* @param _vl Left vertex handle
* @param _vr Right vertex handle
* @return Newly inserted halfedge
*/
inline HalfedgeHandle vertex_split(VertexHandle _v0, VertexHandle _v1,
VertexHandle _vl, VertexHandle _vr)
{ return PolyMesh::vertex_split(_v0, _v1, _vl, _vr); }
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be undefined!
*
*
* @param _eh Edge handle that should be splitted
* @param _p New point position that will be inserted at the edge
* @return Vertex handle of the newly added vertex
*/
inline VertexHandle split(EdgeHandle _eh, const Point& _p)
{
//Do not call PolyMeshT function below as this does the wrong operation
const VertexHandle vh = this->add_vertex(_p); Kernel::split(_eh, vh); return vh;
}
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be adjusted to the properties of the original edge
*
* @param _eh Edge handle that should be splitted
* @param _p New point position that will be inserted at the edge
* @return Vertex handle of the newly added vertex
*/
inline VertexHandle split_copy(EdgeHandle _eh, const Point& _p)
{
//Do not call PolyMeshT function below as this does the wrong operation
const VertexHandle vh = this->add_vertex(_p); Kernel::split_copy(_eh, vh); return vh;
}
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be undefined!
*
* @param _eh Edge handle that should be splitted
* @param _vh Vertex handle that will be inserted at the edge
*/
inline void split(EdgeHandle _eh, VertexHandle _vh)
{
//Do not call PolyMeshT function below as this does the wrong operation
Kernel::split(_eh, _vh);
}
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be adjusted to the properties of the original edge
*
* @param _eh Edge handle that should be splitted
* @param _vh Vertex handle that will be inserted at the edge
*/
inline void split_copy(EdgeHandle _eh, VertexHandle _vh)
{
//Do not call PolyMeshT function below as this does the wrong operation
Kernel::split_copy(_eh, _vh);
}
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be undefined!
*
* @param _fh Face handle that should be splitted
* @param _p New point position that will be inserted in the face
*/
inline void split(FaceHandle _fh, const Point& _p)
{ PolyMesh::split(_fh, _p); }
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be adjusted to the properties of the original face
*
* @param _fh Face handle that should be splitted
* @param _p New point position that will be inserted in the face
*/
inline void split_copy(FaceHandle _fh, const Point& _p)
{ PolyMesh::split_copy(_fh, _p); }
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be undefined!
*
* @param _fh Face handle that should be splitted
* @param _vh Vertex handle that will be inserted at the face
*/
inline void split(FaceHandle _fh, VertexHandle _vh)
{ PolyMesh::split(_fh, _vh); }
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be adjusted to the properties of the original face
*
* @param _fh Face handle that should be splitted
* @param _vh Vertex handle that will be inserted at the face
*/
inline void split_copy(FaceHandle _fh, VertexHandle _vh)
{ PolyMesh::split_copy(_fh, _vh); }
/** \name Normal vector computation
*/
//@{
/** Calculate normal vector for face _fh (specialized for TriMesh). */
Normal calc_face_normal(FaceHandle _fh) const;
//@}
};
//=============================================================================
} // namespace OpenMesh
//=============================================================================
#if defined(OM_INCLUDE_TEMPLATES) && !defined(OPENMESH_TRIMESH_C)
#define OPENMESH_TRIMESH_TEMPLATES
#include "TriMeshT.cc"
#endif
//=============================================================================
#endif // OPENMESH_TRIMESH_HH defined
//=============================================================================
<commit_msg>Return vertex handles of newly added vertices in split and split copy when passing points instead of handles<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS TriMeshT
//
//=============================================================================
#ifndef OPENMESH_TRIMESH_HH
#define OPENMESH_TRIMESH_HH
//== INCLUDES =================================================================
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/Mesh/PolyMeshT.hh>
#include <vector>
//== NAMESPACES ===============================================================
namespace OpenMesh {
//== CLASS DEFINITION =========================================================
/** \class TriMeshT TriMeshT.hh <OpenMesh/Mesh/TriMeshT.hh>
Base type for a triangle mesh.
Base type for a triangle mesh, parameterized by a mesh kernel. The
mesh inherits all methods from the kernel class and the
more general polygonal mesh PolyMeshT. Therefore it provides
the same types for items, handles, iterators and so on.
\param Kernel: template argument for the mesh kernel
\note You should use the predefined mesh-kernel combinations in
\ref mesh_types_group
\see \ref mesh_type
\see OpenMesh::PolyMeshT
*/
template <class Kernel>
class TriMeshT : public PolyMeshT<Kernel>
{
public:
// self
typedef TriMeshT<Kernel> This;
typedef PolyMeshT<Kernel> PolyMesh;
//@{
/// Determine whether this is a PolyMeshT or TriMeshT ( This function does not check the per face vertex count! It only checks if the datatype is PolyMeshT or TriMeshT )
enum { IsPolyMesh = 0 };
enum { IsTriMesh = 1 };
static bool is_polymesh() { return false; }
static bool is_trimesh() { return true; }
//@}
//--- items ---
typedef typename PolyMesh::Scalar Scalar;
typedef typename PolyMesh::Point Point;
typedef typename PolyMesh::Normal Normal;
typedef typename PolyMesh::Color Color;
typedef typename PolyMesh::TexCoord1D TexCoord1D;
typedef typename PolyMesh::TexCoord2D TexCoord2D;
typedef typename PolyMesh::TexCoord3D TexCoord3D;
typedef typename PolyMesh::Vertex Vertex;
typedef typename PolyMesh::Halfedge Halfedge;
typedef typename PolyMesh::Edge Edge;
typedef typename PolyMesh::Face Face;
//--- handles ---
typedef typename PolyMesh::VertexHandle VertexHandle;
typedef typename PolyMesh::HalfedgeHandle HalfedgeHandle;
typedef typename PolyMesh::EdgeHandle EdgeHandle;
typedef typename PolyMesh::FaceHandle FaceHandle;
//--- iterators ---
typedef typename PolyMesh::VertexIter VertexIter;
typedef typename PolyMesh::ConstVertexIter ConstVertexIter;
typedef typename PolyMesh::EdgeIter EdgeIter;
typedef typename PolyMesh::ConstEdgeIter ConstEdgeIter;
typedef typename PolyMesh::FaceIter FaceIter;
typedef typename PolyMesh::ConstFaceIter ConstFaceIter;
//--- circulators ---
typedef typename PolyMesh::VertexVertexIter VertexVertexIter;
typedef typename PolyMesh::VertexOHalfedgeIter VertexOHalfedgeIter;
typedef typename PolyMesh::VertexIHalfedgeIter VertexIHalfedgeIter;
typedef typename PolyMesh::VertexEdgeIter VertexEdgeIter;
typedef typename PolyMesh::VertexFaceIter VertexFaceIter;
typedef typename PolyMesh::FaceVertexIter FaceVertexIter;
typedef typename PolyMesh::FaceHalfedgeIter FaceHalfedgeIter;
typedef typename PolyMesh::FaceEdgeIter FaceEdgeIter;
typedef typename PolyMesh::FaceFaceIter FaceFaceIter;
typedef typename PolyMesh::ConstVertexVertexIter ConstVertexVertexIter;
typedef typename PolyMesh::ConstVertexOHalfedgeIter ConstVertexOHalfedgeIter;
typedef typename PolyMesh::ConstVertexIHalfedgeIter ConstVertexIHalfedgeIter;
typedef typename PolyMesh::ConstVertexEdgeIter ConstVertexEdgeIter;
typedef typename PolyMesh::ConstVertexFaceIter ConstVertexFaceIter;
typedef typename PolyMesh::ConstFaceVertexIter ConstFaceVertexIter;
typedef typename PolyMesh::ConstFaceHalfedgeIter ConstFaceHalfedgeIter;
typedef typename PolyMesh::ConstFaceEdgeIter ConstFaceEdgeIter;
typedef typename PolyMesh::ConstFaceFaceIter ConstFaceFaceIter;
// --- constructor/destructor
/// Default constructor
TriMeshT() : PolyMesh() {}
/// Destructor
virtual ~TriMeshT() {}
//--- halfedge collapse / vertex split ---
/** \brief Vertex Split: inverse operation to collapse().
*
* Insert the new vertex at position v0. The vertex will be added
* as the inverse of the vertex split. The faces above the split
* will be correctly attached to the two new edges
*
* Before:
* v_l v0 v_r
* x x x
* \ /
* \ /
* \ /
* \ /
* \ /
* \ /
* x
* v1
*
* After:
* v_l v0 v_r
* x------x------x
* \ | /
* \ | /
* \ | /
* \ | /
* \ | /
* \|/
* x
* v1
*
* @param _v0_point Point position for the new point
* @param _v1 Vertex that will be split
* @param _vl Left vertex handle
* @param _vr Right vertex handle
* @return Newly inserted halfedge
*/
inline HalfedgeHandle vertex_split(Point _v0_point, VertexHandle _v1,
VertexHandle _vl, VertexHandle _vr)
{ return PolyMesh::vertex_split(add_vertex(_v0_point), _v1, _vl, _vr); }
/** \brief Vertex Split: inverse operation to collapse().
*
* Insert the new vertex at position v0. The vertex will be added
* as the inverse of the vertex split. The faces above the split
* will be correctly attached to the two new edges
*
* Before:
* v_l v0 v_r
* x x x
* \ /
* \ /
* \ /
* \ /
* \ /
* \ /
* x
* v1
*
* After:
* v_l v0 v_r
* x------x------x
* \ | /
* \ | /
* \ | /
* \ | /
* \ | /
* \|/
* x
* v1
*
* @param _v0 Vertex handle for the newly inserted point (Input has to be unconnected!)
* @param _v1 Vertex that will be split
* @param _vl Left vertex handle
* @param _vr Right vertex handle
* @return Newly inserted halfedge
*/
inline HalfedgeHandle vertex_split(VertexHandle _v0, VertexHandle _v1,
VertexHandle _vl, VertexHandle _vr)
{ return PolyMesh::vertex_split(_v0, _v1, _vl, _vr); }
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be undefined!
*
*
* @param _eh Edge handle that should be splitted
* @param _p New point position that will be inserted at the edge
* @return Vertex handle of the newly added vertex
*/
inline VertexHandle split(EdgeHandle _eh, const Point& _p)
{
//Do not call PolyMeshT function below as this does the wrong operation
const VertexHandle vh = this->add_vertex(_p); Kernel::split(_eh, vh); return vh;
}
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be adjusted to the properties of the original edge
*
* @param _eh Edge handle that should be splitted
* @param _p New point position that will be inserted at the edge
* @return Vertex handle of the newly added vertex
*/
inline VertexHandle split_copy(EdgeHandle _eh, const Point& _p)
{
//Do not call PolyMeshT function below as this does the wrong operation
const VertexHandle vh = this->add_vertex(_p); Kernel::split_copy(_eh, vh); return vh;
}
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be undefined!
*
* @param _eh Edge handle that should be splitted
* @param _vh Vertex handle that will be inserted at the edge
*/
inline void split(EdgeHandle _eh, VertexHandle _vh)
{
//Do not call PolyMeshT function below as this does the wrong operation
Kernel::split(_eh, _vh);
}
/** \brief Edge split (= 2-to-4 split)
*
* The properties of the new edges will be adjusted to the properties of the original edge
*
* @param _eh Edge handle that should be splitted
* @param _vh Vertex handle that will be inserted at the edge
*/
inline void split_copy(EdgeHandle _eh, VertexHandle _vh)
{
//Do not call PolyMeshT function below as this does the wrong operation
Kernel::split_copy(_eh, _vh);
}
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be undefined!
*
* @param _fh Face handle that should be splitted
* @param _p New point position that will be inserted in the face
*
* @return Vertex handle of the new vertex
*/
inline VertexHandle split(FaceHandle _fh, const Point& _p)
{ const VertexHandle vh = this->add_vertex(_p); PolyMesh::split(_fh, vh); return vh; }
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be adjusted to the properties of the original face
*
* @param _fh Face handle that should be splitted
* @param _p New point position that will be inserted in the face
*
* @return Vertex handle of the new vertex
*/
inline VertexHandle split_copy(FaceHandle _fh, const Point& _p)
{ const VertexHandle vh = this->add_vertex(_p); PolyMesh::split_copy(_fh, _p); return vh; }
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be undefined!
*
* @param _fh Face handle that should be splitted
* @param _vh Vertex handle that will be inserted at the face
*/
inline void split(FaceHandle _fh, VertexHandle _vh)
{ PolyMesh::split(_fh, _vh); }
/** \brief Face split (= 1-to-3 split, calls corresponding PolyMeshT function).
*
* The properties of the new faces will be adjusted to the properties of the original face
*
* @param _fh Face handle that should be splitted
* @param _vh Vertex handle that will be inserted at the face
*/
inline void split_copy(FaceHandle _fh, VertexHandle _vh)
{ PolyMesh::split_copy(_fh, _vh); }
/** \name Normal vector computation
*/
//@{
/** Calculate normal vector for face _fh (specialized for TriMesh). */
Normal calc_face_normal(FaceHandle _fh) const;
//@}
};
//=============================================================================
} // namespace OpenMesh
//=============================================================================
#if defined(OM_INCLUDE_TEMPLATES) && !defined(OPENMESH_TRIMESH_C)
#define OPENMESH_TRIMESH_TEMPLATES
#include "TriMeshT.cc"
#endif
//=============================================================================
#endif // OPENMESH_TRIMESH_HH defined
//=============================================================================
<|endoftext|> |
<commit_before>/**
* @file server.cpp
* @author shae, CS5201 Section A
* @date Apr 27, 2016
* @brief Description:
* @details Details:
*/
/************************************************************************/
/* PROGRAM NAME: server1.c (works with client.c) */
/* */
/* Server creates a socket to listen for the connection from Client */
/* When the communication established, Server echoes data from Client */
/* and writes them back. */
/* */
/* Using socket() to create an endpoint for communication. It */
/* returns socket descriptor. Stream socket (SOCK_STREAM) is used here*/
/* as opposed to a Datagram Socket (SOCK_DGRAM) */
/* Using bind() to bind/assign a name to an unnamed socket. */
/* Using listen() to listen for connections on a socket. */
/* Using accept() to accept a connection on a socket. It returns */
/* the descriptor for the accepted socket. */
/* */
/* To run this program, first compile the server_ex.c and run it */
/* on a server machine. Then run the client program on another */
/* machine. */
/* */
/* COMPILE: gcc server1.c -o server1 -lnsl */
/* */
/************************************************************************/
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h> /* define socket */
#include <netinet/in.h> /* define internet socket */
#include <netdb.h> /* define internet socket */
#include <pthread.h>
#define SERVER_PORT 9993 /* define a server port number */
#define MAX_CLIENT 100
void *input_thread(void *arg);
void *server_thread(void *arg);
void *main_thread(void* arg);
void *client_messenger(void* arg);
pthread_mutex_t stop_lock;
pthread_mutex_t file_descriptor_lock;
bool stop = false;
int sd, ns, k;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
unsigned int client_len;
char *host;
int file_descriptor_array[MAX_CLIENT]; /* allocate as many file descriptors
as the number of clients */
pthread_t input_handler;
pthread_t client_handler;
pthread_t client_handlers[100];
int counter = 0;
int main()
{
server_addr =
{ AF_INET, htons( SERVER_PORT)};
client_addr =
{ AF_INET};
client_len = sizeof(client_addr);
counter = 0;
if (pthread_create(&input_handler, NULL, input_thread, NULL) != 0)
{
perror("pthread_create() failure.");
exit(1);
}
/* create a stream socket */
if ((sd = socket( AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("server: socket failed");
exit(1);
}
/* bind the socket to an internet port */
if (bind(sd, (struct sockaddr*) &server_addr, sizeof(server_addr)) == -1)
{
perror("server: bind failed");
exit(1);
}
/*
if (pthread_create(&client_handler, NULL, server_thread, NULL) != 0)
{
perror("pthread_create() failure.");
exit(1);
}
*/
if (listen(sd, 10) == -1)
{
perror("server: listen failed");
exit(1);
}
printf("SERVER is listening for clients to establish a connection\n");
while((ns = accept(sd, (struct sockaddr*) &client_addr, &client_len)) > 0)
{
pthread_mutex_lock(&file_descriptor_lock);
file_descriptor_array[counter] = ns; /* first check for room here though */
pthread_mutex_unlock(&file_descriptor_lock);
pthread_create(&client_handlers[counter++], NULL, client_messenger, (void*)&file_descriptor_array[counter]);
counter++;
}
pthread_join(input_handler, NULL);
pthread_join(client_handler, NULL);
//pthread_join(input_handler, NULL);
//pthread_join(client_handler, NULL);
close(sd);
unlink((const char*) &server_addr.sin_addr);
//pthread_exit(&writeThread);
//pthread_exit(&readThread);
//close(ns);
//close(sd);
//unlink((const char*) &server_addr.sin_addr);
return (0);
}
void *input_thread(void *arg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
/* A simple loop with only puts() would allow a thread to write several
lines in a row.
With pthread_yield(), each thread gives another thread a chance before
it writes its next line */
while (1)
{
//puts((char*) arg);
char temp[20] = "";
std::cin >> temp;
std::cout << "you entered " << std::endl;
std::cout << temp;
if (strcmp(temp, "/QUIT") == 0)
{
pthread_mutex_lock(&stop_lock);
stop = true;
pthread_mutex_unlock(&stop_lock);
for (int i = 0; i < counter; i++)
{
pthread_cancel(client_handlers[i]);
}
pthread_exit(0);
}
pthread_yield();
}
}
/*
void *server_thread(void *arg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
while (!pthread_mutex_trylock(&stop_lock) && !stop)
{
//std::cout << (stop ? "TRUE " : "FALSE ") << std::endl;
pthread_mutex_unlock(&stop_lock);
/* listen for clients
if (listen(sd, 4) == -1)
{
perror("server: listen failed");
exit(1);
}
printf("SERVER is listening for clients to establish a connection\n");
if ((ns = accept(sd, (struct sockaddr*) &client_addr, &client_len)) == -1)
{
perror("server: accept failed");
exit(1);
}
printf(
"accept() successful.. a client has connected! waiting for a message\n");
/* data transfer on connected socket ns
while ((k = read(ns, buf, sizeof(buf))) != 0 && !stop)
{
printf("SERVER RECEIVED: %s\n", buf);
write(ns, buf, k);
//write(ns, temp, sizeof(temp));
}
}
}
*/
/*
void *main_thread(void* arg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
if (listen(sd, 10) == -1)
{
perror("server: listen failed");
exit(1);
}
while((ns = accept(sd, (struct sockaddr*) &client_addr, &client_len)) > 0)
{
pthread_mutex_lock(&file_descriptor_lock);
file_descriptor_array[counter++] = ns; /* first check for room here though ///
pthread_mutex_unlock(&file_descriptor_lock);
pthread_create(&client_handlers[counter++], NULL, input_thread, (void*)&file_descriptor_array[counter]);
}
//pthread_join(input_handler, NULL);
//pthread_join(client_handler, NULL);
close(sd);
unlink((const char*) &server_addr.sin_addr);
pthread_exit(0);
}
*/
void *client_messenger(void* arg) /* what does 'bob' do ? */
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
printf("Child accept() successful.. a client has connected to child ! waiting for a message\n");
//this is FD, fd, or file descriptor
char buf[512];
int some_fd = *(int*) arg;
std::cout << some_fd << std::endl;
char host_name[100];
gethostname(host_name, 100);
char client_name[512];
char message_buffer[100 + 512];
char server_message[100];
std::cout << "hello " << std::endl;
while ((k = read(some_fd, buf, sizeof(buf))) != 0)
{
std::cout << "hello" << std::endl;
strcpy(message_buffer, "HELLO ");
strcpy(client_name, buf);
strncat(message_buffer, client_name, 512);
printf("GIVEN MESSAGE: %s\n", buf);
for (int i = 0; i < counter; i++)
{
write(file_descriptor_array[i], message_buffer, k);
}
break;
}
while ((k = read(some_fd, buf, sizeof(buf))) != 0 && !stop)
{
printf("SERVER RECEIVED: %s\n", buf);
strcpy(message_buffer, client_name);
strncat(message_buffer, " says:", 6);
for (int i = 0; i < counter; i++)
{
write(file_descriptor_array[i], message_buffer, k);
}
pthread_mutex_unlock(&file_descriptor_lock);
}
pthread_mutex_lock(&file_descriptor_lock);
int i = 0;
while ((file_descriptor_array[i] != some_fd))
{
i++;
}
counter--;
for (int j = i; j < counter; j++)
{
file_descriptor_array[j] = file_descriptor_array[j - 1];
}
pthread_mutex_unlock(&file_descriptor_lock);
close(some_fd);
pthread_exit(0);
}
<commit_msg>Server Almost Donzo<commit_after>/**
* @file server.cpp
* @author shae, CS5201 Section A
* @date Apr 27, 2016
* @brief Description:
* @details Details:
*/
/************************************************************************/
/* PROGRAM NAME: server1.c (works with client.c) */
/* */
/* Server creates a socket to listen for the connection from Client */
/* When the communication established, Server echoes data from Client */
/* and writes them back. */
/* */
/* Using socket() to create an endpoint for communication. It */
/* returns socket descriptor. Stream socket (SOCK_STREAM) is used here*/
/* as opposed to a Datagram Socket (SOCK_DGRAM) */
/* Using bind() to bind/assign a name to an unnamed socket. */
/* Using listen() to listen for connections on a socket. */
/* Using accept() to accept a connection on a socket. It returns */
/* the descriptor for the accepted socket. */
/* */
/* To run this program, first compile the server_ex.c and run it */
/* on a server machine. Then run the client program on another */
/* machine. */
/* */
/* COMPILE: gcc server1.c -o server1 -lnsl */
/* */
/************************************************************************/
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h> /* define socket */
#include <netinet/in.h> /* define internet socket */
#include <netdb.h> /* define internet socket */
#include <pthread.h>
#include <signal.h>
#define SERVER_PORT 9993 /* define a server port number */
#define MAX_CLIENT 100
void *input_thread(void *arg);
void *server_thread(void *arg);
void *main_thread(void* arg);
void *client_messenger(void* arg);
void cntrlc_signal_handle(int signal);
pthread_mutex_t stop_lock;
pthread_mutex_t file_descriptor_lock;
bool stop = false;
int sd, ns, k;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
unsigned int client_len;
char *host;
int file_descriptor_array[MAX_CLIENT]; /* allocate as many file descriptors
as the number of clients */
pthread_t input_handler;
pthread_t client_handler;
pthread_t client_handlers[100];
int counter;
int main()
{
signal(SIGINT, cntrlc_signal_handle);
server_addr =
{ AF_INET, htons( SERVER_PORT)};
client_addr =
{ AF_INET};
client_len = sizeof(client_addr);
counter = 0;
if (pthread_create(&input_handler, NULL, input_thread, NULL) != 0)
{
perror("pthread_create() failure.");
exit(1);
}
/* create a stream socket */
if ((sd = socket( AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("server: socket failed");
exit(1);
}
int enable = 1;
if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
{
perror("setsockopt(SO_REUSEADDR) failed");
}
/* bind the socket to an internet port */
if (bind(sd, (struct sockaddr*) &server_addr, sizeof(server_addr)) == -1)
{
perror("server: bind failed");
exit(1);
}
/*
if (pthread_create(&client_handler, NULL, server_thread, NULL) != 0)
{
perror("pthread_create() failure.");
exit(1);
}
*/
if (listen(sd, 10) == -1)
{
perror("server: listen failed");
exit(1);
}
printf("SERVER is listening for clients to establish a connection\n");
while (((ns = accept(sd, (struct sockaddr*) &client_addr, &client_len)) > 0)
&& !stop)
{
pthread_mutex_lock(&file_descriptor_lock);
if (counter < 100)
{
file_descriptor_array[counter] = ns; /* first check for room here though */
pthread_create(&client_handlers[counter], NULL, client_messenger,
(void*) &file_descriptor_array[counter]);
pthread_mutex_unlock(&file_descriptor_lock);
counter++;
}
else
{
std::cerr << "Error too many threads" << std::endl;
}
}
//std::cout << "Why are you ending?" << std::endl;
//pthread_join(input_handler, NULL);
//pthread_join(client_handler, NULL);
//pthread_join(input_handler, NULL);
//pthread_join(client_handler, NULL);
close(sd);
unlink((const char*) &server_addr.sin_addr);
//pthread_exit(&writeThread);
//pthread_exit(&readThread);
//close(ns);
//close(sd);
//unlink((const char*) &server_addr.sin_addr);
return (0);
}
void cntrlc_signal_handle(int signal)
{
std::cout << "\nCNTRLC detected" << std::endl;
char message_buffer[512] = "ADVISIO: EL SERVIDOR SE APAGARÀ EN 10 SEGUNDOS\n";
char quit_msg[32] = "/quit";
for (int i = 0; i < counter; i++)
{
//std::cout << "i " << i << std::endl;
//client_handlers[i];
write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));
//std::cout << "i " << i << std::endl;
}
for (int i = 0; i < counter; i++)
{
std::cout << "sending qm" << std::endl;
write(file_descriptor_array[i], quit_msg, sizeof(quit_msg));
}
sleep(10);
pthread_mutex_lock(&stop_lock);
stop = true;
pthread_mutex_unlock(&stop_lock);
//std::cout << "canceling done" << std::endl;
for (int i = 0; i < counter; i++)
{
//std::cout << "canceling i " << i << std::endl;
//std::cout << "i " << i << std::endl;
pthread_cancel(client_handlers[i]);
//std::cout << "i " << i << std::endl;
}
//std::cout << "canceling done" << std::endl;
pthread_cancel(input_handler);
close(sd);
unlink((const char*) &server_addr.sin_addr);
//pthread_yield();
}
void *input_thread(void *arg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
/* A simple loop with only puts() would allow a thread to write several
lines in a row.
With pthread_yield(), each thread gives another thread a chance before
it writes its next line */
while (1)
{
//puts((char*) arg);
char temp[20] = "";
std::cin >> temp;
std::cout << "you entered " << std::endl;
std::cout << temp;
if (strcmp(temp, "/QUIT") == 0)
{
pthread_mutex_lock(&stop_lock);
stop = true;
pthread_mutex_unlock(&stop_lock);
char message_buffer[512] = "/quit";
pthread_mutex_lock(&file_descriptor_lock);
for (int i = 0; i < counter; i++)
{
write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));
}
pthread_mutex_unlock(&file_descriptor_lock);
for (int i = 0; i < counter; i++)
{
std::cout << "canceling i " << i << std::endl;
//std::cout << "i " << i << std::endl;
pthread_cancel(client_handlers[i]);
//std::cout << "i " << i << std::endl;
}
pthread_exit(0);
}
pthread_yield();
}
}
void *client_messenger(void* arg) /* what does 'bob' do ? */
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
printf(
"Child accept() successful.. a client has connected to child ! waiting for a message\n");
//this is FD, fd, or file descriptor
char buf[512];
int some_fd = *(int*) arg;
//std::cout << some_fd << std::endl;
char host_name[100];
gethostname(host_name, 100);
char client_name[512];
char message_buffer[100 + 512];
char server_message[100];
while ((k = read(some_fd, buf, sizeof(buf))) != 0)
{
strcpy(message_buffer, "Hello User ");
strcpy(client_name, buf);
strncat(message_buffer, client_name, 512);
strncat(message_buffer, "\n", 3);
//printf("GIVEN MESSAGE: %s\n", buf);
pthread_mutex_lock(&file_descriptor_lock);
for (int i = 0; i < counter; i++)
{
write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));
}
pthread_mutex_unlock(&file_descriptor_lock);
break;
}
while ((k = read(some_fd, buf, sizeof(buf))) != 0 && !stop)
{
bzero(message_buffer, 512 + 100);
printf("SERVER RECEIVED: %s\n", buf);
if (strcmp(buf, "/quit") == 0)
{
break;
}
strcpy(message_buffer, ">> ");
strncat(message_buffer, client_name, sizeof(client_name));
strncat(message_buffer, ": ", 8);
strncat(message_buffer, buf, 512);
strncat(message_buffer, "\n", 3);
//std::cout << message_buffer << std::endl;
pthread_mutex_lock(&file_descriptor_lock);
//std::cout << "done messaging 1" << std::endl;
for (int i = 0; i < counter; i++)
{
if (file_descriptor_array[i] != some_fd)
{
std::cout << "Messaging user i = " << i << std::endl;
write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));
}
}
//std::cout << "done messaging 3" << std::endl;
pthread_mutex_unlock(&file_descriptor_lock);
pthread_yield();
}
pthread_mutex_lock(&file_descriptor_lock);
bzero(message_buffer, 512 + 100);
strcpy(message_buffer, "User ");
strncat(message_buffer, client_name, sizeof(client_name));
strncat(message_buffer, " has disconnected.", 24);
for (int i = 0; i < counter; i++)
{
if (file_descriptor_array[i] != some_fd)
{
//std::cout << "done messaging 2" << std::endl;
write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));
}
}
int i = 0;
while ((file_descriptor_array[i] != some_fd))
{
i++;
}
counter--;
for (int j = i; j < counter; j++)
{
file_descriptor_array[j] = file_descriptor_array[j - 1];
}
pthread_mutex_unlock(&file_descriptor_lock);
close(some_fd);
std::cout << "EXITING THREAD" << std::endl;
pthread_exit(0);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include <cstring>
#include "sal/types.h"
#include "typelib/typeclass.h"
#include "typelib/typedescription.h"
#include "abi.hxx"
#include "callvirtualmethod.hxx"
// The call instruction within the asm block of callVirtualMethod may throw
// exceptions. At least GCC 4.7.0 with -O0 would create (unnecessary)
// .gcc_exception_table call-site table entries around all other calls in this
// function that can throw, leading to std::terminate if the asm call throws an
// exception and the unwinding C++ personality routine finds the unexpected hole
// in the .gcc_exception_table. Therefore, make sure this function explicitly
// only calls nothrow-functions (so GCC 4.7.0 with -O0 happens to not create a
// .gcc_exception_table section at all for this function). For some reason,
// this also needs to be in a source file of its own.
//
// Also, this file should be compiled with -fnon-call-exceptions, and ideally
// there would be a way to tell the compiler that the asm block contains calls
// to functions that can potentially throw; see the mail thread starting at
// <http://gcc.gnu.org/ml/gcc/2012-03/msg00454.html> "C++: Letting compiler know
// asm block can call function that can throw?"
void CPPU_CURRENT_NAMESPACE::callVirtualMethod(
void * pThis, sal_uInt32 nVtableIndex, void * pRegisterReturn,
typelib_TypeDescriptionReference * pReturnTypeRef, bool bSimpleReturn,
sal_uInt64 *pStack, sal_uInt32 nStack, sal_uInt64 *pGPR, sal_uInt32 nGPR,
double * pFPR, sal_uInt32 nFPR)
{
// Should not happen, but...
if ( nFPR > x86_64::MAX_SSE_REGS )
nFPR = x86_64::MAX_SSE_REGS;
if ( nGPR > x86_64::MAX_GPR_REGS )
nGPR = x86_64::MAX_GPR_REGS;
// Get pointer to method
sal_uInt64 pMethod = *((sal_uInt64 *)pThis);
pMethod += 8 * nVtableIndex;
pMethod = *((sal_uInt64 *)pMethod);
// Load parameters to stack, if necessary
if ( nStack )
{
// 16-bytes aligned
sal_uInt32 nStackBytes = ( ( nStack + 1 ) >> 1 ) * 16;
sal_uInt64 *pCallStack = (sal_uInt64 *) __builtin_alloca( nStackBytes );
std::memcpy( pCallStack, pStack, nStackBytes );
}
// Return values
sal_uInt64 rax;
sal_uInt64 rdx;
double xmm0;
double xmm1;
asm volatile (
// Fill the xmm registers
"movq %6, %%rax\n\t"
"movsd (%%rax), %%xmm0\n\t"
"movsd 8(%%rax), %%xmm1\n\t"
"movsd 16(%%rax), %%xmm2\n\t"
"movsd 24(%%rax), %%xmm3\n\t"
"movsd 32(%%rax), %%xmm4\n\t"
"movsd 40(%%rax), %%xmm5\n\t"
"movsd 48(%%rax), %%xmm6\n\t"
"movsd 56(%%rax), %%xmm7\n\t"
// Fill the general purpose registers
"movq %5, %%rax\n\t"
"movq (%%rax), %%rdi\n\t"
"movq 8(%%rax), %%rsi\n\t"
"movq 16(%%rax), %%rdx\n\t"
"movq 24(%%rax), %%rcx\n\t"
"movq 32(%%rax), %%r8\n\t"
"movq 40(%%rax), %%r9\n\t"
// Perform the call
"movq %4, %%r11\n\t"
"movq %7, %%rax\n\t"
"call *%%r11\n\t"
// Fill the return values
"movq %%rax, %0\n\t"
"movq %%rdx, %1\n\t"
"movsd %%xmm0, %2\n\t"
"movsd %%xmm1, %3\n\t"
: "=m" ( rax ), "=m" ( rdx ), "=m" ( xmm0 ), "=m" ( xmm1 )
: "m" ( pMethod ), "m" ( pGPR ), "m" ( pFPR ), "m" ( nFPR )
: "rax", "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r11"
);
switch (pReturnTypeRef->eTypeClass)
{
case typelib_TypeClass_HYPER:
case typelib_TypeClass_UNSIGNED_HYPER:
*reinterpret_cast<sal_uInt64 *>( pRegisterReturn ) = rax;
break;
case typelib_TypeClass_LONG:
case typelib_TypeClass_UNSIGNED_LONG:
case typelib_TypeClass_ENUM:
*reinterpret_cast<sal_uInt32 *>( pRegisterReturn ) = *reinterpret_cast<sal_uInt32*>( &rax );
break;
case typelib_TypeClass_CHAR:
case typelib_TypeClass_SHORT:
case typelib_TypeClass_UNSIGNED_SHORT:
*reinterpret_cast<sal_uInt16 *>( pRegisterReturn ) = *reinterpret_cast<sal_uInt16*>( &rax );
break;
case typelib_TypeClass_BOOLEAN:
case typelib_TypeClass_BYTE:
*reinterpret_cast<sal_uInt8 *>( pRegisterReturn ) = *reinterpret_cast<sal_uInt8*>( &rax );
break;
case typelib_TypeClass_FLOAT:
case typelib_TypeClass_DOUBLE:
*reinterpret_cast<double *>( pRegisterReturn ) = xmm0;
break;
default:
{
sal_Int32 const nRetSize = pReturnTypeRef->pType->nSize;
if (bSimpleReturn && nRetSize <= 16 && nRetSize > 0)
{
sal_uInt64 longs[2];
longs[0] = rax;
longs[1] = rdx;
double doubles[2];
doubles[0] = xmm0;
doubles[1] = xmm1;
x86_64::fill_struct( pReturnTypeRef, &longs[0], &doubles[0], pRegisterReturn);
}
break;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Mark all registered as clobbered that are not saved across call<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include <cstring>
#include "sal/types.h"
#include "typelib/typeclass.h"
#include "typelib/typedescription.h"
#include "abi.hxx"
#include "callvirtualmethod.hxx"
// The call instruction within the asm block of callVirtualMethod may throw
// exceptions. At least GCC 4.7.0 with -O0 would create (unnecessary)
// .gcc_exception_table call-site table entries around all other calls in this
// function that can throw, leading to std::terminate if the asm call throws an
// exception and the unwinding C++ personality routine finds the unexpected hole
// in the .gcc_exception_table. Therefore, make sure this function explicitly
// only calls nothrow-functions (so GCC 4.7.0 with -O0 happens to not create a
// .gcc_exception_table section at all for this function). For some reason,
// this also needs to be in a source file of its own.
//
// Also, this file should be compiled with -fnon-call-exceptions, and ideally
// there would be a way to tell the compiler that the asm block contains calls
// to functions that can potentially throw; see the mail thread starting at
// <http://gcc.gnu.org/ml/gcc/2012-03/msg00454.html> "C++: Letting compiler know
// asm block can call function that can throw?"
void CPPU_CURRENT_NAMESPACE::callVirtualMethod(
void * pThis, sal_uInt32 nVtableIndex, void * pRegisterReturn,
typelib_TypeDescriptionReference * pReturnTypeRef, bool bSimpleReturn,
sal_uInt64 *pStack, sal_uInt32 nStack, sal_uInt64 *pGPR, sal_uInt32 nGPR,
double * pFPR, sal_uInt32 nFPR)
{
// Should not happen, but...
if ( nFPR > x86_64::MAX_SSE_REGS )
nFPR = x86_64::MAX_SSE_REGS;
if ( nGPR > x86_64::MAX_GPR_REGS )
nGPR = x86_64::MAX_GPR_REGS;
// Get pointer to method
sal_uInt64 pMethod = *((sal_uInt64 *)pThis);
pMethod += 8 * nVtableIndex;
pMethod = *((sal_uInt64 *)pMethod);
// Load parameters to stack, if necessary
if ( nStack )
{
// 16-bytes aligned
sal_uInt32 nStackBytes = ( ( nStack + 1 ) >> 1 ) * 16;
sal_uInt64 *pCallStack = (sal_uInt64 *) __builtin_alloca( nStackBytes );
std::memcpy( pCallStack, pStack, nStackBytes );
}
// Return values
sal_uInt64 rax;
sal_uInt64 rdx;
double xmm0;
double xmm1;
asm volatile (
// Fill the xmm registers
"movq %6, %%rax\n\t"
"movsd (%%rax), %%xmm0\n\t"
"movsd 8(%%rax), %%xmm1\n\t"
"movsd 16(%%rax), %%xmm2\n\t"
"movsd 24(%%rax), %%xmm3\n\t"
"movsd 32(%%rax), %%xmm4\n\t"
"movsd 40(%%rax), %%xmm5\n\t"
"movsd 48(%%rax), %%xmm6\n\t"
"movsd 56(%%rax), %%xmm7\n\t"
// Fill the general purpose registers
"movq %5, %%rax\n\t"
"movq (%%rax), %%rdi\n\t"
"movq 8(%%rax), %%rsi\n\t"
"movq 16(%%rax), %%rdx\n\t"
"movq 24(%%rax), %%rcx\n\t"
"movq 32(%%rax), %%r8\n\t"
"movq 40(%%rax), %%r9\n\t"
// Perform the call
"movq %4, %%r11\n\t"
"movq %7, %%rax\n\t"
"call *%%r11\n\t"
// Fill the return values
"movq %%rax, %0\n\t"
"movq %%rdx, %1\n\t"
"movsd %%xmm0, %2\n\t"
"movsd %%xmm1, %3\n\t"
: "=m" ( rax ), "=m" ( rdx ), "=m" ( xmm0 ), "=m" ( xmm1 )
: "m" ( pMethod ), "m" ( pGPR ), "m" ( pFPR ), "m" ( nFPR )
: "rax", "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11",
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"
);
switch (pReturnTypeRef->eTypeClass)
{
case typelib_TypeClass_HYPER:
case typelib_TypeClass_UNSIGNED_HYPER:
*reinterpret_cast<sal_uInt64 *>( pRegisterReturn ) = rax;
break;
case typelib_TypeClass_LONG:
case typelib_TypeClass_UNSIGNED_LONG:
case typelib_TypeClass_ENUM:
*reinterpret_cast<sal_uInt32 *>( pRegisterReturn ) = *reinterpret_cast<sal_uInt32*>( &rax );
break;
case typelib_TypeClass_CHAR:
case typelib_TypeClass_SHORT:
case typelib_TypeClass_UNSIGNED_SHORT:
*reinterpret_cast<sal_uInt16 *>( pRegisterReturn ) = *reinterpret_cast<sal_uInt16*>( &rax );
break;
case typelib_TypeClass_BOOLEAN:
case typelib_TypeClass_BYTE:
*reinterpret_cast<sal_uInt8 *>( pRegisterReturn ) = *reinterpret_cast<sal_uInt8*>( &rax );
break;
case typelib_TypeClass_FLOAT:
case typelib_TypeClass_DOUBLE:
*reinterpret_cast<double *>( pRegisterReturn ) = xmm0;
break;
default:
{
sal_Int32 const nRetSize = pReturnTypeRef->pType->nSize;
if (bSimpleReturn && nRetSize <= 16 && nRetSize > 0)
{
sal_uInt64 longs[2];
longs[0] = rax;
longs[1] = rdx;
double doubles[2];
doubles[0] = xmm0;
doubles[1] = xmm1;
x86_64::fill_struct( pReturnTypeRef, &longs[0], &doubles[0], pRegisterReturn);
}
break;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fgas/crt/fgas_memory.h"
#define MEMORY_TOOL_REPLACES_ALLOCATOR // Temporary, for CF testing.
#include <algorithm>
#ifdef MEMORY_TOOL_REPLACES_ALLOCATOR
namespace {
class CFX_DefStore : public IFX_MemoryAllocator, public CFX_Target {
public:
CFX_DefStore() {}
~CFX_DefStore() override {}
void* Alloc(size_t size) override { return FX_Alloc(uint8_t, size); }
void Free(void* pBlock) override { FX_Free(pBlock); }
};
} // namespace
IFX_MemoryAllocator* IFX_MemoryAllocator::Create(FX_ALLOCTYPE eType,
size_t chunkSize,
size_t blockSize) {
return new CFX_DefStore();
}
#else // MEMORY_TOOL_REPLACES_ALLOCATOR
namespace {
struct FX_STATICSTORECHUNK {
FX_STATICSTORECHUNK* pNextChunk;
size_t iChunkSize;
size_t iFreeSize;
};
class CFX_StaticStore : public IFX_MemoryAllocator, public CFX_Target {
public:
CFX_StaticStore(size_t iDefChunkSize = 4096);
~CFX_StaticStore() override;
void* Alloc(size_t size) override;
void Free(void* pBlock) override {}
protected:
size_t m_iAllocatedSize;
size_t m_iDefChunkSize;
FX_STATICSTORECHUNK* m_pChunk;
FX_STATICSTORECHUNK* m_pLastChunk;
FX_STATICSTORECHUNK* AllocChunk(size_t size);
FX_STATICSTORECHUNK* FindChunk(size_t size);
};
struct FX_FIXEDSTORECHUNK {
uint8_t* FirstFlag() { return reinterpret_cast<uint8_t*>(this + 1); }
uint8_t* FirstBlock() { return FirstFlag() + iChunkSize; }
FX_FIXEDSTORECHUNK* pNextChunk;
size_t iChunkSize;
size_t iFreeNum;
};
class CFX_FixedStore : public IFX_MemoryAllocator, public CFX_Target {
public:
CFX_FixedStore(size_t iBlockSize, size_t iBlockNumsInChunk);
~CFX_FixedStore() override;
void* Alloc(size_t size) override;
void Free(void* pBlock) override;
protected:
FX_FIXEDSTORECHUNK* AllocChunk();
size_t m_iBlockSize;
size_t m_iDefChunkSize;
FX_FIXEDSTORECHUNK* m_pChunk;
};
} // namespace
#define FX_4BYTEALIGN(size) (((size) + 3) & ~3)
IFX_MemoryAllocator* IFX_MemoryAllocator::Create(FX_ALLOCTYPE eType,
size_t chunkSize,
size_t blockSize) {
switch (eType) {
case FX_ALLOCTYPE_Static:
return new CFX_StaticStore(chunkSize);
case FX_ALLOCTYPE_Fixed:
return new CFX_FixedStore(blockSize, chunkSize);
default:
ASSERT(0);
return nullptr;
}
}
CFX_StaticStore::CFX_StaticStore(size_t iDefChunkSize)
: m_iAllocatedSize(0),
m_iDefChunkSize(iDefChunkSize),
m_pChunk(nullptr),
m_pLastChunk(nullptr) {
ASSERT(m_iDefChunkSize != 0);
}
CFX_StaticStore::~CFX_StaticStore() {
FX_STATICSTORECHUNK* pChunk = m_pChunk;
while (pChunk) {
FX_STATICSTORECHUNK* pNext = pChunk->pNextChunk;
FX_Free(pChunk);
pChunk = pNext;
}
}
FX_STATICSTORECHUNK* CFX_StaticStore::AllocChunk(size_t size) {
ASSERT(size != 0);
FX_STATICSTORECHUNK* pChunk = (FX_STATICSTORECHUNK*)FX_Alloc(
uint8_t, sizeof(FX_STATICSTORECHUNK) + size);
pChunk->iChunkSize = size;
pChunk->iFreeSize = size;
pChunk->pNextChunk = nullptr;
if (!m_pLastChunk) {
m_pChunk = pChunk;
} else {
m_pLastChunk->pNextChunk = pChunk;
}
m_pLastChunk = pChunk;
return pChunk;
}
FX_STATICSTORECHUNK* CFX_StaticStore::FindChunk(size_t size) {
ASSERT(size != 0);
if (!m_pLastChunk || m_pLastChunk->iFreeSize < size) {
return AllocChunk(std::max(m_iDefChunkSize, size));
}
return m_pLastChunk;
}
void* CFX_StaticStore::Alloc(size_t size) {
size = FX_4BYTEALIGN(size);
ASSERT(size != 0);
FX_STATICSTORECHUNK* pChunk = FindChunk(size);
ASSERT(pChunk->iFreeSize >= size);
uint8_t* p = (uint8_t*)pChunk;
p += sizeof(FX_STATICSTORECHUNK) + pChunk->iChunkSize - pChunk->iFreeSize;
pChunk->iFreeSize -= size;
m_iAllocatedSize += size;
return p;
}
size_t CFX_StaticStore::SetDefChunkSize(size_t size) {
ASSERT(size != 0);
size_t v = m_iDefChunkSize;
m_iDefChunkSize = size;
return v;
}
CFX_FixedStore::CFX_FixedStore(size_t iBlockSize, size_t iBlockNumsInChunk)
: m_iBlockSize(FX_4BYTEALIGN(iBlockSize)),
m_iDefChunkSize(FX_4BYTEALIGN(iBlockNumsInChunk)),
m_pChunk(nullptr) {
ASSERT(m_iBlockSize != 0 && m_iDefChunkSize != 0);
}
CFX_FixedStore::~CFX_FixedStore() {
FX_FIXEDSTORECHUNK* pChunk = m_pChunk;
while (pChunk) {
FX_FIXEDSTORECHUNK* pNext = pChunk->pNextChunk;
FX_Free(pChunk);
pChunk = pNext;
}
}
FX_FIXEDSTORECHUNK* CFX_FixedStore::AllocChunk() {
int32_t iTotalSize = sizeof(FX_FIXEDSTORECHUNK) + m_iDefChunkSize +
m_iBlockSize * m_iDefChunkSize;
FX_FIXEDSTORECHUNK* pChunk =
(FX_FIXEDSTORECHUNK*)FX_Alloc(uint8_t, iTotalSize);
if (!pChunk)
return nullptr;
FXSYS_memset(pChunk->FirstFlag(), 0, m_iDefChunkSize);
pChunk->pNextChunk = m_pChunk;
pChunk->iChunkSize = m_iDefChunkSize;
pChunk->iFreeNum = m_iDefChunkSize;
m_pChunk = pChunk;
return pChunk;
}
void* CFX_FixedStore::Alloc(size_t size) {
if (size > m_iBlockSize) {
return nullptr;
}
FX_FIXEDSTORECHUNK* pChunk = m_pChunk;
while (pChunk) {
if (pChunk->iFreeNum > 0) {
break;
}
pChunk = pChunk->pNextChunk;
}
if (!pChunk) {
pChunk = AllocChunk();
}
uint8_t* pFlags = pChunk->FirstFlag();
size_t i = 0;
for (; i < pChunk->iChunkSize; i++)
if (pFlags[i] == 0) {
break;
}
ASSERT(i < pChunk->iChunkSize);
pFlags[i] = 1;
pChunk->iFreeNum--;
return pChunk->FirstBlock() + i * m_iBlockSize;
}
void CFX_FixedStore::Free(void* pBlock) {
FX_FIXEDSTORECHUNK* pPrior = nullptr;
FX_FIXEDSTORECHUNK* pChunk = m_pChunk;
uint8_t* pStart = nullptr;
uint8_t* pEnd;
while (pChunk) {
pStart = pChunk->FirstBlock();
if (pBlock >= pStart) {
pEnd = pStart + m_iBlockSize * pChunk->iChunkSize;
if (pBlock < pEnd) {
break;
}
}
pPrior = pChunk, pChunk = pChunk->pNextChunk;
}
ASSERT(pChunk);
size_t iPos = ((uint8_t*)pBlock - pStart) / m_iBlockSize;
ASSERT(iPos < pChunk->iChunkSize);
uint8_t* pFlags = pChunk->FirstFlag();
if (pFlags[iPos] == 0) {
return;
}
pFlags[iPos] = 0;
pChunk->iFreeNum++;
if (pChunk->iFreeNum == pChunk->iChunkSize) {
if (!pPrior) {
m_pChunk = pChunk->pNextChunk;
} else {
pPrior->pNextChunk = pChunk->pNextChunk;
}
FX_Free(pChunk);
}
}
size_t CFX_FixedStore::SetDefChunkSize(size_t iChunkSize) {
ASSERT(iChunkSize != 0);
size_t v = m_iDefChunkSize;
m_iDefChunkSize = FX_4BYTEALIGN(iChunkSize);
return v;
}
#endif // MEMORY_TOOL_REPLACES_ALLOCATOR
<commit_msg>Only set memory tool define if not set.<commit_after>// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fgas/crt/fgas_memory.h"
#ifndef MEMORY_TOOL_REPLACES_ALLOCATOR
#define MEMORY_TOOL_REPLACES_ALLOCATOR // Temporary, for CF testing.
#endif
#include <algorithm>
#ifdef MEMORY_TOOL_REPLACES_ALLOCATOR
namespace {
class CFX_DefStore : public IFX_MemoryAllocator, public CFX_Target {
public:
CFX_DefStore() {}
~CFX_DefStore() override {}
void* Alloc(size_t size) override { return FX_Alloc(uint8_t, size); }
void Free(void* pBlock) override { FX_Free(pBlock); }
};
} // namespace
IFX_MemoryAllocator* IFX_MemoryAllocator::Create(FX_ALLOCTYPE eType,
size_t chunkSize,
size_t blockSize) {
return new CFX_DefStore();
}
#else // MEMORY_TOOL_REPLACES_ALLOCATOR
namespace {
struct FX_STATICSTORECHUNK {
FX_STATICSTORECHUNK* pNextChunk;
size_t iChunkSize;
size_t iFreeSize;
};
class CFX_StaticStore : public IFX_MemoryAllocator, public CFX_Target {
public:
CFX_StaticStore(size_t iDefChunkSize = 4096);
~CFX_StaticStore() override;
void* Alloc(size_t size) override;
void Free(void* pBlock) override {}
protected:
size_t m_iAllocatedSize;
size_t m_iDefChunkSize;
FX_STATICSTORECHUNK* m_pChunk;
FX_STATICSTORECHUNK* m_pLastChunk;
FX_STATICSTORECHUNK* AllocChunk(size_t size);
FX_STATICSTORECHUNK* FindChunk(size_t size);
};
struct FX_FIXEDSTORECHUNK {
uint8_t* FirstFlag() { return reinterpret_cast<uint8_t*>(this + 1); }
uint8_t* FirstBlock() { return FirstFlag() + iChunkSize; }
FX_FIXEDSTORECHUNK* pNextChunk;
size_t iChunkSize;
size_t iFreeNum;
};
class CFX_FixedStore : public IFX_MemoryAllocator, public CFX_Target {
public:
CFX_FixedStore(size_t iBlockSize, size_t iBlockNumsInChunk);
~CFX_FixedStore() override;
void* Alloc(size_t size) override;
void Free(void* pBlock) override;
protected:
FX_FIXEDSTORECHUNK* AllocChunk();
size_t m_iBlockSize;
size_t m_iDefChunkSize;
FX_FIXEDSTORECHUNK* m_pChunk;
};
} // namespace
#define FX_4BYTEALIGN(size) (((size) + 3) & ~3)
IFX_MemoryAllocator* IFX_MemoryAllocator::Create(FX_ALLOCTYPE eType,
size_t chunkSize,
size_t blockSize) {
switch (eType) {
case FX_ALLOCTYPE_Static:
return new CFX_StaticStore(chunkSize);
case FX_ALLOCTYPE_Fixed:
return new CFX_FixedStore(blockSize, chunkSize);
default:
ASSERT(0);
return nullptr;
}
}
CFX_StaticStore::CFX_StaticStore(size_t iDefChunkSize)
: m_iAllocatedSize(0),
m_iDefChunkSize(iDefChunkSize),
m_pChunk(nullptr),
m_pLastChunk(nullptr) {
ASSERT(m_iDefChunkSize != 0);
}
CFX_StaticStore::~CFX_StaticStore() {
FX_STATICSTORECHUNK* pChunk = m_pChunk;
while (pChunk) {
FX_STATICSTORECHUNK* pNext = pChunk->pNextChunk;
FX_Free(pChunk);
pChunk = pNext;
}
}
FX_STATICSTORECHUNK* CFX_StaticStore::AllocChunk(size_t size) {
ASSERT(size != 0);
FX_STATICSTORECHUNK* pChunk = (FX_STATICSTORECHUNK*)FX_Alloc(
uint8_t, sizeof(FX_STATICSTORECHUNK) + size);
pChunk->iChunkSize = size;
pChunk->iFreeSize = size;
pChunk->pNextChunk = nullptr;
if (!m_pLastChunk) {
m_pChunk = pChunk;
} else {
m_pLastChunk->pNextChunk = pChunk;
}
m_pLastChunk = pChunk;
return pChunk;
}
FX_STATICSTORECHUNK* CFX_StaticStore::FindChunk(size_t size) {
ASSERT(size != 0);
if (!m_pLastChunk || m_pLastChunk->iFreeSize < size) {
return AllocChunk(std::max(m_iDefChunkSize, size));
}
return m_pLastChunk;
}
void* CFX_StaticStore::Alloc(size_t size) {
size = FX_4BYTEALIGN(size);
ASSERT(size != 0);
FX_STATICSTORECHUNK* pChunk = FindChunk(size);
ASSERT(pChunk->iFreeSize >= size);
uint8_t* p = (uint8_t*)pChunk;
p += sizeof(FX_STATICSTORECHUNK) + pChunk->iChunkSize - pChunk->iFreeSize;
pChunk->iFreeSize -= size;
m_iAllocatedSize += size;
return p;
}
size_t CFX_StaticStore::SetDefChunkSize(size_t size) {
ASSERT(size != 0);
size_t v = m_iDefChunkSize;
m_iDefChunkSize = size;
return v;
}
CFX_FixedStore::CFX_FixedStore(size_t iBlockSize, size_t iBlockNumsInChunk)
: m_iBlockSize(FX_4BYTEALIGN(iBlockSize)),
m_iDefChunkSize(FX_4BYTEALIGN(iBlockNumsInChunk)),
m_pChunk(nullptr) {
ASSERT(m_iBlockSize != 0 && m_iDefChunkSize != 0);
}
CFX_FixedStore::~CFX_FixedStore() {
FX_FIXEDSTORECHUNK* pChunk = m_pChunk;
while (pChunk) {
FX_FIXEDSTORECHUNK* pNext = pChunk->pNextChunk;
FX_Free(pChunk);
pChunk = pNext;
}
}
FX_FIXEDSTORECHUNK* CFX_FixedStore::AllocChunk() {
int32_t iTotalSize = sizeof(FX_FIXEDSTORECHUNK) + m_iDefChunkSize +
m_iBlockSize * m_iDefChunkSize;
FX_FIXEDSTORECHUNK* pChunk =
(FX_FIXEDSTORECHUNK*)FX_Alloc(uint8_t, iTotalSize);
if (!pChunk)
return nullptr;
FXSYS_memset(pChunk->FirstFlag(), 0, m_iDefChunkSize);
pChunk->pNextChunk = m_pChunk;
pChunk->iChunkSize = m_iDefChunkSize;
pChunk->iFreeNum = m_iDefChunkSize;
m_pChunk = pChunk;
return pChunk;
}
void* CFX_FixedStore::Alloc(size_t size) {
if (size > m_iBlockSize) {
return nullptr;
}
FX_FIXEDSTORECHUNK* pChunk = m_pChunk;
while (pChunk) {
if (pChunk->iFreeNum > 0) {
break;
}
pChunk = pChunk->pNextChunk;
}
if (!pChunk) {
pChunk = AllocChunk();
}
uint8_t* pFlags = pChunk->FirstFlag();
size_t i = 0;
for (; i < pChunk->iChunkSize; i++)
if (pFlags[i] == 0) {
break;
}
ASSERT(i < pChunk->iChunkSize);
pFlags[i] = 1;
pChunk->iFreeNum--;
return pChunk->FirstBlock() + i * m_iBlockSize;
}
void CFX_FixedStore::Free(void* pBlock) {
FX_FIXEDSTORECHUNK* pPrior = nullptr;
FX_FIXEDSTORECHUNK* pChunk = m_pChunk;
uint8_t* pStart = nullptr;
uint8_t* pEnd;
while (pChunk) {
pStart = pChunk->FirstBlock();
if (pBlock >= pStart) {
pEnd = pStart + m_iBlockSize * pChunk->iChunkSize;
if (pBlock < pEnd) {
break;
}
}
pPrior = pChunk, pChunk = pChunk->pNextChunk;
}
ASSERT(pChunk);
size_t iPos = ((uint8_t*)pBlock - pStart) / m_iBlockSize;
ASSERT(iPos < pChunk->iChunkSize);
uint8_t* pFlags = pChunk->FirstFlag();
if (pFlags[iPos] == 0) {
return;
}
pFlags[iPos] = 0;
pChunk->iFreeNum++;
if (pChunk->iFreeNum == pChunk->iChunkSize) {
if (!pPrior) {
m_pChunk = pChunk->pNextChunk;
} else {
pPrior->pNextChunk = pChunk->pNextChunk;
}
FX_Free(pChunk);
}
}
size_t CFX_FixedStore::SetDefChunkSize(size_t iChunkSize) {
ASSERT(iChunkSize != 0);
size_t v = m_iDefChunkSize;
m_iDefChunkSize = FX_4BYTEALIGN(iChunkSize);
return v;
}
#endif // MEMORY_TOOL_REPLACES_ALLOCATOR
<|endoftext|> |
<commit_before>#include "CorrectionEngine.h"
#include "parser/TaobaoParser.h"
#include "StringUtil.h"
#include "evaluate/EvaluatorFactory.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <knlp/normalize.h>
#include <util/ustring/UString.h>
#include <time.h>
#include <stdlib.h>
#include <ctype.h>
namespace sf1r
{
namespace Recommend
{
static double factorForPinYin(const std::string& self, const std::string& userQuery)
{
izenelib::util::UString uself(self, izenelib::util::UString::UTF_8);
izenelib::util::UString ustr(userQuery, izenelib::util::UString::UTF_8);
double s = 1.0;
if (uself.isAllChineseChar())
{
if (uself.length() != ustr.length())
return 1e-6;
if (2 == uself.length())
{
if (uself[0] != ustr[0])
{
if (uself[1] != ustr[1])
s /= 10;
s /= 2;
}
else
s *= 1.28;
}
if (2 < uself.length())
{
uint32_t n = 0;
for (std::size_t i = 0; i < uself.length(); i++)
{
if (uself[i] == ustr[i])
n++;
}
s *= n;
s /= (uself.length() -n);
}
}
return s;
}
static double factorForPrefix(const std::string& self, const std::string& userQuery)
{
izenelib::util::UString uself(self, izenelib::util::UString::UTF_8);
izenelib::util::UString ustr(userQuery, izenelib::util::UString::UTF_8);
double s = 1.0;
if (PrefixTable::isPrefixEnglish(userQuery))
s *= 20;
// iphone5 => iphone 5
bool selfHasChinese = false;
for (std::size_t i = 0; i < uself.length(); i++)
{
if (uself.isChineseChar(i))
{
selfHasChinese = true;
break;
}
}
if (!selfHasChinese)
{
bool ustrHasChinese = false;
for (std::size_t i = 0; i < ustr.length(); i++)
{
if (ustr.isChineseChar(i))
{
ustrHasChinese = true;
break;
}
}
if (!ustrHasChinese)
{
std::size_t selfL = self.size();
std::size_t userL = userQuery.size();
if (selfL < userL)
{
std::size_t i = 0, j = 0;
while (true)
{
if ((i >= selfL) || (j >= userL))
break;
if (self[i] == userQuery[j])
{
i++;
j++;
}
else if (' ' == self[i])
{
break;
}
else if (' ' == userQuery[j])
{
j++;
}
else
{
break;
}
}
if ((i == selfL) && (j == userL))
s *= 400;
}
}
}
// digit change iphone6 => iphone5
std::size_t selfL = uself.length();
std::size_t ustrL = ustr.length();
std::size_t i = 0;
std::size_t j = 0;
while (true)
{
if ((i >= selfL) || (j >= ustrL))
break;
if (uself[i] == ustr[j])
{
i++;
j++;
}
else if (uself.isSpaceChar(i))
{
i++;
}
else if (ustr.isSpaceChar(j))
{
j++;
}
else if (uself.isDigitChar(i))
{
if (ustr.isDigitChar(j))
s /= 100;
else if (ustr.isChineseChar(j))
s /= 200;
else
s /= 150;
i++;
j++;
}
else if (ustr.isDigitChar(j))
{
if (uself.isDigitChar(i))
s /= 100;
else if (uself.isChineseChar(i))
s /= 200;
else
s /= 150;
i++;
j++;
}
else
{
i++;
j++;
}
}
if ((i < selfL) && (uself.isDigitChar(i)))
s /= 150;
if (selfL >= ustrL)
s /= 1024;
std::size_t nself = 0;
for (i = 0; i < selfL; i++)
{
if (!uself.isSpaceChar(i))
nself++;
}
std::size_t nstr = 0;
for (i = 0; i < ustrL; i++)
{
if (!ustr.isSpaceChar(i))
nstr++;
}
if (nself != nstr)
s /= 1024;
return s;
}
static std::string timestamp = ".CorrectionEngineTimestamp";
CorrectionEngine::CorrectionEngine(const std::string& workdir)
: pinyin_(NULL)
, prefix_(NULL)
, filter_(NULL)
, parsers_(NULL)
, pyConverter_(NULL)
, pyApproximator_(NULL)
, timestamp_(0)
, workdir_(workdir)
{
if (!boost::filesystem::exists(workdir_))
{
boost::filesystem::create_directory(workdir_);
}
pinyin_ = new PinyinTable(workdir_);
prefix_ = new PrefixTable(workdir_);
filter_ = new Filter(workdir_ + "/filter/");
parsers_ = new ParserFactory();
UQCateEngine::workdir = workdir_;
UQCateEngine::getInstance().lock((void*)this);
std::string path = workdir_;
path += "/";
path += timestamp;
std::ifstream in;
in.open(path.c_str(), std::ifstream::in);
in>>timestamp_;
in.close();
}
CorrectionEngine:: ~CorrectionEngine()
{
if (NULL != pinyin_)
{
delete pinyin_;
pinyin_ = NULL;
}
if (NULL != prefix_)
{
delete prefix_;
prefix_ = NULL;
}
if (NULL != filter_)
{
delete filter_;
filter_ = NULL;
}
if (NULL != parsers_)
{
delete parsers_;
parsers_ = NULL;
}
}
void CorrectionEngine::evaluate(const std::string& path, std::string& sResult) const
{
std::string resource;
if (!boost::filesystem::exists(path))
resource = workdir_;
else if(!boost::filesystem::is_directory(path))
resource = workdir_;
else
resource = path;
std::ofstream out;
out.open("errors", std::ofstream::out | std::ofstream::trunc);
boost::filesystem::directory_iterator end;
for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it)
{
const std::string p = it->path().string();
if(boost::filesystem::is_regular_file(p))
{
if (!EvaluatorFactory::isValid(p))
continue;
Evaluator* evaluator = EvaluatorFactory::load(p);
Evaluator::iterator it = evaluator->begin();
for (; it != evaluator->end(); ++it)
{
std::string result;
double freq = 0.0;
correct(it->userQuery(), result, freq);
evaluator->isCorrect(out, result);
}
EvaluatorFactory::destory(evaluator);
}
}
out.close();
Evaluator::toString(sResult);
Evaluator::clear();
}
bool CorrectionEngine::isNeedBuild(const std::string& path) const
{
std::string resource;
if (!boost::filesystem::exists(path))
resource = workdir_;
else if(!boost::filesystem::is_directory(path))
resource = workdir_;
else
resource = path;
boost::filesystem::directory_iterator end;
for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it)
{
const std::string p = it->path().string();
if(boost::filesystem::is_regular_file(p))
{
//std::cout<<p<<"\n";
if (!parsers_->isValid(p))
continue;
std::time_t mt = boost::filesystem::last_write_time(it->path());
if (mt > timestamp_)
return true;
}
}
return filter_->isNeedBuild(path +"/filter/");
}
void CorrectionEngine::buildEngine(const std::string& path)
{
clear();
std::string resource;
if (!boost::filesystem::exists(path))
resource = workdir_;
else if(!boost::filesystem::is_directory(path))
resource = workdir_;
else
resource = path;
boost::filesystem::directory_iterator end;
for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it)
{
const std::string p = it->path().string();
if(boost::filesystem::is_regular_file(p))
{
//std::cout<<p<<"\n";
if (!parsers_->isValid(p))
continue;
Parser* parser = parsers_->load(p);
if (NULL == parser)
continue;
Parser::iterator it = parser->begin();
for (; it != parser->end(); ++it)
{
//std::cout<<it->userQuery()<<" : "<<it->freq()<<"\n";
processQuery(it->userQuery(), it->category(), it->freq());
}
parsers_->destory(parser);
}
}
filter_->buildFilter(path + "/filter/");
timestamp_ = time(NULL);
flush();
}
void CorrectionEngine::processQuery(const std::string& str, const std::string& category, const uint32_t freq)
{
std::string userQuery = str;
try
{
ilplib::knlp::Normalize::normalize(userQuery);
}
catch(...)
{
}
std::vector<std::string> pinyin;
if (NULL != pyConverter_)
{
(*pyConverter_)(userQuery, pinyin);
}
for (std::size_t i = 0; i < pinyin.size(); i++)
{
pinyin_->insert(userQuery, pinyin[i], freq);
}
prefix_->insert(userQuery, freq);
UQCateEngine::getInstance().insert(str, category, freq);
}
void CorrectionEngine::clear()
{
pinyin_->clear();
prefix_->clear();
filter_->clear();
UQCateEngine::getInstance().clear();
}
void CorrectionEngine::flush() const
{
pinyin_->flush();
prefix_->flush();
filter_->flush();
UQCateEngine::getInstance().flush();
std::string path = workdir_;
path += "/";
path += timestamp;
std::ofstream out;
out.open(path.c_str(), std::ofstream::out | std::ofstream::trunc);
out<<timestamp_;
out.close();
}
bool CorrectionEngine::correct(const std::string& str, std::string& results, double& freq) const
{
std::string userQuery = str;
try
{
ilplib::knlp::Normalize::normalize(userQuery);
}
catch(...)
{
}
izenelib::util::UString uself(userQuery, izenelib::util::UString::UTF_8);
if (uself.length() <= 1)
return false;
if (filter_->isFilter(userQuery))
{
return false;
}
std::vector<std::string> pinyin;
bool isUserQueryHasChinese = false;
if (NULL != pyConverter_)
{
isUserQueryHasChinese = (*pyConverter_)(userQuery, pinyin);
}
UserQuery self(userQuery, 0);
FreqStringVector candidates;
// from pinyin
double factor = 100;
boost::unordered_map<std::string, bool> accurate;
for (std::size_t i = 0; i < pinyin.size(); i++)
{
UserQueryList uqList;
pinyin_->search(pinyin[i], uqList);
accurate[pinyin[i]] = true;
//std::cout<<pinyin[i]<<"\t-------------\n";
UserQueryList::iterator it = uqList.begin();
for (; it != uqList.end(); it++)
{
if (it->userQuery() != self.userQuery())
{
if (!UQCateEngine::getInstance().cateEqual(self.userQuery(), it->userQuery(), 10))
continue;
double s = factorForPinYin(self.userQuery(), it->userQuery());
//std::cout<<it->userQuery()<<" : "<<it->freq()<<" : "<<s<<"\n";
candidates.push_back(FreqString(it->userQuery(), it->freq() * factor * s));
}
}
}
// from approximate pinyin
pinyin.clear();
bool isUserQueryPinYin = false;
if ((NULL != pyApproximator_) && (candidates.empty() || (!isUserQueryHasChinese)))
{
isUserQueryPinYin = (*pyApproximator_)(userQuery, pinyin);
factor = 50;
for (std::size_t i = 0; i < pinyin.size(); i++)
{
UserQueryList uqList;
if (accurate.end() != accurate.find(pinyin[i]))
continue;
pinyin_->search(pinyin[i], uqList);
//std::cout<<pinyin[i]<<"\t-------------\n";
UserQueryList::iterator it = uqList.begin();
for (; it != uqList.end(); it++)
{
if (it->userQuery() != self.userQuery())
{
if (!UQCateEngine::getInstance().cateEqual(self.userQuery(), it->userQuery(), 100))
continue;
double s = factorForPinYin(self.userQuery(), it->userQuery());
//std::cout<<it->userQuery()<<" : "<<it->freq()<<" : "<<s<<"\n";
candidates.push_back(FreqString(it->userQuery(), it->freq() * factor * s));
}
}
}
}
pinyin.clear();
accurate.clear();
// from prefix
factor = 1;
UserQueryList uqList;
prefix_->search(userQuery, uqList);
UserQueryList::iterator it = uqList.begin();
//std::cout<<"PREFIX::\t-----------\n";
for (; it != uqList.end(); it++)
{
if (it->userQuery() == self.userQuery())
{
self.setFreq(self.freq() + it->freq());
}
else
{
if (!UQCateEngine::getInstance().cateEqual(self.userQuery(), it->userQuery(), 100))
continue;
double s = factorForPrefix(self.userQuery(), it->userQuery());
//std::cout<<it->userQuery()<<" : "<<s<<"\n";
candidates.push_back(FreqString(it->userQuery(), it->freq() * factor * s));
}
}
if (candidates.empty())
return false;
factor = 1000;
double s = isUserQueryPinYin ? 0.1 : 1;
self.setFreq(self.freq() * factor * s);
if (self.freq() < 1e-2)
{
self.setFreq(100);
}
FreqString max = StringUtil::max(candidates);
const double selfFreq = self.freq();
const double maxFreq = max.getFreq();
//std::cout<<self.freq()<<"\t:\t"<<max.getFreq()<<"\n";
//std::cout<<self.userQuery()<<"\t:\t"<<max.getString()<<"\n";
if (2.4 * selfFreq < maxFreq)
{
results = max.getString();
freq = maxFreq / selfFreq;
return true;
}
return false;
}
}
}
<commit_msg>Remove only one charactor.<commit_after>#include "CorrectionEngine.h"
#include "parser/TaobaoParser.h"
#include "StringUtil.h"
#include "evaluate/EvaluatorFactory.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <knlp/normalize.h>
#include <util/ustring/UString.h>
#include <time.h>
#include <stdlib.h>
#include <ctype.h>
namespace sf1r
{
namespace Recommend
{
static double factorForPinYin(const std::string& self, const std::string& userQuery)
{
izenelib::util::UString uself(self, izenelib::util::UString::UTF_8);
izenelib::util::UString ustr(userQuery, izenelib::util::UString::UTF_8);
double s = 1.0;
if (uself.isAllChineseChar())
{
if (uself.length() != ustr.length())
return 1e-6;
if (2 == uself.length())
{
if (uself[0] != ustr[0])
{
if (uself[1] != ustr[1])
s /= 10;
s /= 2;
}
else
s *= 1.28;
}
if (2 < uself.length())
{
uint32_t n = 0;
for (std::size_t i = 0; i < uself.length(); i++)
{
if (uself[i] == ustr[i])
n++;
}
s *= n;
s /= (uself.length() -n);
}
}
return s;
}
static double factorForPrefix(const std::string& self, const std::string& userQuery)
{
izenelib::util::UString uself(self, izenelib::util::UString::UTF_8);
izenelib::util::UString ustr(userQuery, izenelib::util::UString::UTF_8);
double s = 1.0;
if (PrefixTable::isPrefixEnglish(userQuery))
s *= 20;
// iphone5 => iphone 5
bool selfHasChinese = false;
for (std::size_t i = 0; i < uself.length(); i++)
{
if (uself.isChineseChar(i))
{
selfHasChinese = true;
break;
}
}
if (!selfHasChinese)
{
bool ustrHasChinese = false;
for (std::size_t i = 0; i < ustr.length(); i++)
{
if (ustr.isChineseChar(i))
{
ustrHasChinese = true;
break;
}
}
if (!ustrHasChinese)
{
std::size_t selfL = self.size();
std::size_t userL = userQuery.size();
if (selfL < userL)
{
std::size_t i = 0, j = 0;
while (true)
{
if ((i >= selfL) || (j >= userL))
break;
if (self[i] == userQuery[j])
{
i++;
j++;
}
else if (' ' == self[i])
{
break;
}
else if (' ' == userQuery[j])
{
j++;
}
else
{
break;
}
}
if ((i == selfL) && (j == userL))
s *= 400;
}
}
}
// digit change iphone6 => iphone5
std::size_t selfL = uself.length();
std::size_t ustrL = ustr.length();
std::size_t i = 0;
std::size_t j = 0;
while (true)
{
if ((i >= selfL) || (j >= ustrL))
break;
if (uself[i] == ustr[j])
{
i++;
j++;
}
else if (uself.isSpaceChar(i))
{
i++;
}
else if (ustr.isSpaceChar(j))
{
j++;
}
else if (uself.isDigitChar(i))
{
if (ustr.isDigitChar(j))
s /= 100;
else if (ustr.isChineseChar(j))
s /= 200;
else
s /= 150;
i++;
j++;
}
else if (ustr.isDigitChar(j))
{
if (uself.isDigitChar(i))
s /= 100;
else if (uself.isChineseChar(i))
s /= 200;
else
s /= 150;
i++;
j++;
}
else
{
i++;
j++;
}
}
if ((i < selfL) && (uself.isDigitChar(i)))
s /= 150;
if (selfL >= ustrL)
s /= 1024;
std::size_t nself = 0;
for (i = 0; i < selfL; i++)
{
if (!uself.isSpaceChar(i))
nself++;
}
std::size_t nstr = 0;
for (i = 0; i < ustrL; i++)
{
if (!ustr.isSpaceChar(i))
nstr++;
}
if (nself != nstr)
s /= 1024;
return s;
}
static std::string timestamp = ".CorrectionEngineTimestamp";
CorrectionEngine::CorrectionEngine(const std::string& workdir)
: pinyin_(NULL)
, prefix_(NULL)
, filter_(NULL)
, parsers_(NULL)
, pyConverter_(NULL)
, pyApproximator_(NULL)
, timestamp_(0)
, workdir_(workdir)
{
if (!boost::filesystem::exists(workdir_))
{
boost::filesystem::create_directory(workdir_);
}
pinyin_ = new PinyinTable(workdir_);
prefix_ = new PrefixTable(workdir_);
filter_ = new Filter(workdir_ + "/filter/");
parsers_ = new ParserFactory();
UQCateEngine::workdir = workdir_;
UQCateEngine::getInstance().lock((void*)this);
std::string path = workdir_;
path += "/";
path += timestamp;
std::ifstream in;
in.open(path.c_str(), std::ifstream::in);
in>>timestamp_;
in.close();
}
CorrectionEngine:: ~CorrectionEngine()
{
if (NULL != pinyin_)
{
delete pinyin_;
pinyin_ = NULL;
}
if (NULL != prefix_)
{
delete prefix_;
prefix_ = NULL;
}
if (NULL != filter_)
{
delete filter_;
filter_ = NULL;
}
if (NULL != parsers_)
{
delete parsers_;
parsers_ = NULL;
}
}
void CorrectionEngine::evaluate(const std::string& path, std::string& sResult) const
{
std::string resource;
if (!boost::filesystem::exists(path))
resource = workdir_;
else if(!boost::filesystem::is_directory(path))
resource = workdir_;
else
resource = path;
std::ofstream out;
out.open("errors", std::ofstream::out | std::ofstream::trunc);
boost::filesystem::directory_iterator end;
for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it)
{
const std::string p = it->path().string();
if(boost::filesystem::is_regular_file(p))
{
if (!EvaluatorFactory::isValid(p))
continue;
Evaluator* evaluator = EvaluatorFactory::load(p);
Evaluator::iterator it = evaluator->begin();
for (; it != evaluator->end(); ++it)
{
std::string result;
double freq = 0.0;
correct(it->userQuery(), result, freq);
evaluator->isCorrect(out, result);
}
EvaluatorFactory::destory(evaluator);
}
}
out.close();
Evaluator::toString(sResult);
Evaluator::clear();
}
bool CorrectionEngine::isNeedBuild(const std::string& path) const
{
std::string resource;
if (!boost::filesystem::exists(path))
resource = workdir_;
else if(!boost::filesystem::is_directory(path))
resource = workdir_;
else
resource = path;
boost::filesystem::directory_iterator end;
for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it)
{
const std::string p = it->path().string();
if(boost::filesystem::is_regular_file(p))
{
//std::cout<<p<<"\n";
if (!parsers_->isValid(p))
continue;
std::time_t mt = boost::filesystem::last_write_time(it->path());
if (mt > timestamp_)
return true;
}
}
return filter_->isNeedBuild(path +"/filter/");
}
void CorrectionEngine::buildEngine(const std::string& path)
{
clear();
std::string resource;
if (!boost::filesystem::exists(path))
resource = workdir_;
else if(!boost::filesystem::is_directory(path))
resource = workdir_;
else
resource = path;
boost::filesystem::directory_iterator end;
for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it)
{
const std::string p = it->path().string();
if(boost::filesystem::is_regular_file(p))
{
//std::cout<<p<<"\n";
if (!parsers_->isValid(p))
continue;
Parser* parser = parsers_->load(p);
if (NULL == parser)
continue;
Parser::iterator it = parser->begin();
for (; it != parser->end(); ++it)
{
//std::cout<<it->userQuery()<<" : "<<it->freq()<<"\n";
processQuery(it->userQuery(), it->category(), it->freq());
}
parsers_->destory(parser);
}
}
filter_->buildFilter(path + "/filter/");
timestamp_ = time(NULL);
flush();
}
void CorrectionEngine::processQuery(const std::string& str, const std::string& category, const uint32_t freq)
{
std::string userQuery = str;
try
{
ilplib::knlp::Normalize::normalize(userQuery);
}
catch(...)
{
}
std::vector<std::string> pinyin;
if (NULL != pyConverter_)
{
(*pyConverter_)(userQuery, pinyin);
}
for (std::size_t i = 0; i < pinyin.size(); i++)
{
pinyin_->insert(userQuery, pinyin[i], freq);
}
prefix_->insert(userQuery, freq);
UQCateEngine::getInstance().insert(str, category, freq);
}
void CorrectionEngine::clear()
{
pinyin_->clear();
prefix_->clear();
filter_->clear();
UQCateEngine::getInstance().clear();
}
void CorrectionEngine::flush() const
{
pinyin_->flush();
prefix_->flush();
filter_->flush();
UQCateEngine::getInstance().flush();
std::string path = workdir_;
path += "/";
path += timestamp;
std::ofstream out;
out.open(path.c_str(), std::ofstream::out | std::ofstream::trunc);
out<<timestamp_;
out.close();
}
bool CorrectionEngine::correct(const std::string& str, std::string& results, double& freq) const
{
std::string userQuery = str;
try
{
ilplib::knlp::Normalize::normalize(userQuery);
}
catch(...)
{
}
izenelib::util::UString uself(userQuery, izenelib::util::UString::UTF_8);
if (uself.length() <= 1)
return false;
if (filter_->isFilter(userQuery))
{
return false;
}
std::vector<std::string> pinyin;
bool isUserQueryHasChinese = false;
if (NULL != pyConverter_)
{
isUserQueryHasChinese = (*pyConverter_)(userQuery, pinyin);
}
UserQuery self(userQuery, 0);
FreqStringVector candidates;
// from pinyin
double factor = 100;
boost::unordered_map<std::string, bool> accurate;
for (std::size_t i = 0; i < pinyin.size(); i++)
{
UserQueryList uqList;
pinyin_->search(pinyin[i], uqList);
accurate[pinyin[i]] = true;
//std::cout<<pinyin[i]<<"\t-------------\n";
UserQueryList::iterator it = uqList.begin();
for (; it != uqList.end(); it++)
{
if (it->userQuery() != self.userQuery())
{
if (!UQCateEngine::getInstance().cateEqual(self.userQuery(), it->userQuery(), 10))
continue;
double s = factorForPinYin(self.userQuery(), it->userQuery());
//std::cout<<it->userQuery()<<" : "<<it->freq()<<" : "<<s<<"\n";
candidates.push_back(FreqString(it->userQuery(), it->freq() * factor * s));
}
}
}
// from approximate pinyin
pinyin.clear();
bool isUserQueryPinYin = false;
if ((NULL != pyApproximator_) && (candidates.empty() || (!isUserQueryHasChinese)))
{
isUserQueryPinYin = (*pyApproximator_)(userQuery, pinyin);
factor = 50;
for (std::size_t i = 0; i < pinyin.size(); i++)
{
UserQueryList uqList;
if (accurate.end() != accurate.find(pinyin[i]))
continue;
pinyin_->search(pinyin[i], uqList);
//std::cout<<pinyin[i]<<"\t-------------\n";
UserQueryList::iterator it = uqList.begin();
for (; it != uqList.end(); it++)
{
if (it->userQuery() != self.userQuery())
{
if (!UQCateEngine::getInstance().cateEqual(self.userQuery(), it->userQuery(), 100))
continue;
double s = factorForPinYin(self.userQuery(), it->userQuery());
//std::cout<<it->userQuery()<<" : "<<it->freq()<<" : "<<s<<"\n";
candidates.push_back(FreqString(it->userQuery(), it->freq() * factor * s));
}
}
}
}
pinyin.clear();
accurate.clear();
// from prefix
factor = 1;
UserQueryList uqList;
prefix_->search(userQuery, uqList);
UserQueryList::iterator it = uqList.begin();
//std::cout<<"PREFIX::\t-----------\n";
for (; it != uqList.end(); it++)
{
if (it->userQuery() == self.userQuery())
{
self.setFreq(self.freq() + it->freq());
}
else
{
if (!UQCateEngine::getInstance().cateEqual(self.userQuery(), it->userQuery(), 100))
continue;
double s = factorForPrefix(self.userQuery(), it->userQuery());
//std::cout<<it->userQuery()<<" : "<<s<<"\n";
candidates.push_back(FreqString(it->userQuery(), it->freq() * factor * s));
}
}
if (candidates.empty())
return false;
factor = 1000;
double s = isUserQueryPinYin ? 0.1 : 1;
self.setFreq(self.freq() * factor * s);
if (self.freq() < 1e-2)
{
self.setFreq(100);
}
FreqString max = StringUtil::max(candidates);
const double selfFreq = self.freq();
const double maxFreq = max.getFreq();
izenelib::util::UString umax(max.getString(), izenelib::util::UString::UTF_8);
if (umax.length() <= 1)
return false;
//std::cout<<self.freq()<<"\t:\t"<<max.getFreq()<<"\n";
//std::cout<<self.userQuery()<<"\t:\t"<<max.getString()<<"\n";
if (2.4 * selfFreq < maxFreq)
{
results = max.getString();
freq = maxFreq / selfFreq;
return true;
}
return false;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#include <string.h>
#include <vector>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "build/build_config.h"
#include "chrome/browser/component_updater/component_updater_service.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/widevine_cdm_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/common/pepper_plugin_info.h"
#include "third_party/widevine/cdm/widevine_cdm_common.h"
#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
using content::BrowserThread;
using content::PluginService;
namespace {
// TODO(xhwang): Move duplicate code among all component installer
// implementations to some common place.
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
// CRX hash. The extension id is: pdkaonnflpjcgibpgaanildgengnihcm.
const uint8 kSha2Hash[] = { 0xf3, 0xa0, 0xed, 0xd5, 0xbf, 0x92, 0x68, 0x1f,
0x60, 0x0d, 0x8b, 0x36, 0x4d, 0x6d, 0x87, 0x2c,
0x86, 0x61, 0x12, 0x20, 0x21, 0xf8, 0x94, 0xdd,
0xe1, 0xb6, 0xb4, 0x55, 0x34, 0x8c, 0x2e, 0x20 };
// File name of the Widevine CDM component manifest on different platforms.
const char kWidevineCdmManifestName[] = "WidevineCdm";
// Name of the Widevine CDM OS in the component manifest.
const char kWidevineCdmOperatingSystem[] =
#if defined(OS_MACOSX)
"mac";
#elif defined(OS_WIN)
"win";
#else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?
"linux";
#endif
// Name of the Widevine CDM architecture in the component manifest.
const char kWidevineCdmArch[] =
#if defined(ARCH_CPU_X86)
"ia32";
#elif defined(ARCH_CPU_X86_64)
"x64";
#else // TODO(viettrungluu): Support an ARM check?
"???";
#endif
// If we don't have a Widevine CDM component, this is the version we claim.
const char kNullVersion[] = "0.0.0.0";
// The base directory on Windows looks like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\.
base::FilePath GetWidevineCdmBaseDirectory() {
base::FilePath result;
PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result);
return result;
}
// Widevine CDM has the version encoded in the path so we need to enumerate the
// directories to find the full path.
// On success, |latest_dir| returns something like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\.
// |latest_version| returns the corresponding version number. |older_dirs|
// returns directories of all older versions.
bool GetWidevineCdmDirectory(base::FilePath* latest_dir,
base::Version* latest_version,
std::vector<base::FilePath>* older_dirs) {
base::FilePath base_dir = GetWidevineCdmBaseDirectory();
bool found = false;
file_util::FileEnumerator file_enumerator(
base_dir, false, file_util::FileEnumerator::DIRECTORIES);
for (base::FilePath path = file_enumerator.Next(); !path.value().empty();
path = file_enumerator.Next()) {
base::Version version(path.BaseName().MaybeAsASCII());
if (!version.IsValid())
continue;
if (found) {
if (version.CompareTo(*latest_version) > 0) {
older_dirs->push_back(*latest_dir);
*latest_dir = path;
*latest_version = version;
} else {
older_dirs->push_back(path);
}
} else {
*latest_dir = path;
*latest_version = version;
found = true;
}
}
return found;
}
bool MakeWidevineCdmPluginInfo(const base::FilePath& path,
const base::Version& version,
content::PepperPluginInfo* plugin_info) {
if (!version.IsValid() ||
version.components().size() !=
static_cast<size_t>(kWidevineCdmVersionNumComponents)) {
return false;
}
plugin_info->is_internal = false;
// Widevine CDM must run out of process.
plugin_info->is_out_of_process = true;
plugin_info->path = path;
plugin_info->name = kWidevineCdmDisplayName;
plugin_info->description = kWidevineCdmDescription;
plugin_info->version = version.GetString();
webkit::WebPluginMimeType widevine_cdm_mime_type(
kWidevineCdmPluginMimeType,
kWidevineCdmPluginExtension,
kWidevineCdmPluginMimeTypeDescription);
plugin_info->mime_types.push_back(widevine_cdm_mime_type);
plugin_info->permissions = kWidevineCdmPluginPermissions;
return true;
}
void RegisterWidevineCdmWithChrome(const base::FilePath& path,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
content::PepperPluginInfo plugin_info;
if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))
return;
PluginService::GetInstance()->RegisterInternalPlugin(
plugin_info.ToWebPluginInfo(), true);
PluginService::GetInstance()->RefreshPlugins();
}
// Returns true if this browser is compatible with the given Widevine CDM
// manifest, with the version specified in the manifest in |version_out|.
bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest,
base::Version* version_out) {
std::string name;
manifest.GetStringASCII("name", &name);
if (name != kWidevineCdmManifestName)
return false;
std::string proposed_version;
manifest.GetStringASCII("version", &proposed_version);
base::Version version(proposed_version.c_str());
if (!version.IsValid())
return false;
std::string os;
manifest.GetStringASCII("x-widevine-cdm-os", &os);
if (os != kWidevineCdmOperatingSystem)
return false;
std::string arch;
manifest.GetStringASCII("x-widevine-cdm-arch", &arch);
if (arch != kWidevineCdmArch)
return false;
*version_out = version;
return true;
}
class WidevineCdmComponentInstaller : public ComponentInstaller {
public:
explicit WidevineCdmComponentInstaller(const base::Version& version);
virtual ~WidevineCdmComponentInstaller() {}
virtual void OnUpdateError(int error) OVERRIDE;
virtual bool Install(const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) OVERRIDE;
private:
base::Version current_version_;
};
WidevineCdmComponentInstaller::WidevineCdmComponentInstaller(
const base::Version& version)
: current_version_(version) {
DCHECK(version.IsValid());
}
void WidevineCdmComponentInstaller::OnUpdateError(int error) {
NOTREACHED() << "Widevine CDM update error: " << error;
}
bool WidevineCdmComponentInstaller::Install(
const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) {
base::Version version;
if (!CheckWidevineCdmManifest(manifest, &version))
return false;
if (current_version_.CompareTo(version) > 0)
return false;
if (!file_util::PathExists(unpack_path.AppendASCII(kWidevineCdmFileName)))
return false;
base::FilePath adapter_source_path;
PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path);
if (!file_util::PathExists(adapter_source_path))
return false;
// Passed the basic tests. Time to install it.
base::FilePath install_path =
GetWidevineCdmBaseDirectory().AppendASCII(version.GetString());
if (file_util::PathExists(install_path))
return false;
if (!file_util::Move(unpack_path, install_path))
return false;
base::FilePath adapter_install_path =
install_path.AppendASCII(kWidevineCdmAdapterFileName);
if (!file_util::CopyFile(adapter_source_path, adapter_install_path))
return false;
// Installation is done. Now register the Widevine CDM with chrome.
current_version_ = version;
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
&RegisterWidevineCdmWithChrome, adapter_install_path, version));
return true;
}
void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CrxComponent widevine_cdm;
widevine_cdm.name = "WidevineCdm";
widevine_cdm.installer = new WidevineCdmComponentInstaller(version);
widevine_cdm.version = version;
widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);
if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) {
NOTREACHED() << "Widevine CDM component registration failed.";
return;
}
}
void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::FilePath path = GetWidevineCdmBaseDirectory();
if (!file_util::PathExists(path) && !file_util::CreateDirectory(path)) {
NOTREACHED() << "Could not create Widevine CDM directory.";
return;
}
base::Version version(kNullVersion);
std::vector<base::FilePath> older_dirs;
if (GetWidevineCdmDirectory(&path, &version, &older_dirs)) {
if (file_util::PathExists(path.AppendASCII(kWidevineCdmAdapterFileName)) &&
file_util::PathExists(path.AppendASCII(kWidevineCdmFileName))) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&RegisterWidevineCdmWithChrome, path, version));
} else {
file_util::Delete(path, true);
version = base::Version(kNullVersion);
}
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version));
// Remove older versions of Widevine CDM.
for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();
iter != older_dirs.end(); ++iter) {
file_util::Delete(*iter, true);
}
}
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
} // namespace
void RegisterWidevineCdmComponent(ComponentUpdateService* cus) {
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&StartWidevineCdmUpdateRegistration, cus));
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
}
<commit_msg>Fix Widevine CDM registration path when the component already exists.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#include <string.h>
#include <vector>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "build/build_config.h"
#include "chrome/browser/component_updater/component_updater_service.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/widevine_cdm_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/common/pepper_plugin_info.h"
#include "third_party/widevine/cdm/widevine_cdm_common.h"
#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
using content::BrowserThread;
using content::PluginService;
namespace {
// TODO(xhwang): Move duplicate code among all component installer
// implementations to some common place.
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
// CRX hash. The extension id is: pdkaonnflpjcgibpgaanildgengnihcm.
const uint8 kSha2Hash[] = { 0xf3, 0xa0, 0xed, 0xd5, 0xbf, 0x92, 0x68, 0x1f,
0x60, 0x0d, 0x8b, 0x36, 0x4d, 0x6d, 0x87, 0x2c,
0x86, 0x61, 0x12, 0x20, 0x21, 0xf8, 0x94, 0xdd,
0xe1, 0xb6, 0xb4, 0x55, 0x34, 0x8c, 0x2e, 0x20 };
// File name of the Widevine CDM component manifest on different platforms.
const char kWidevineCdmManifestName[] = "WidevineCdm";
// Name of the Widevine CDM OS in the component manifest.
const char kWidevineCdmOperatingSystem[] =
#if defined(OS_MACOSX)
"mac";
#elif defined(OS_WIN)
"win";
#else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?
"linux";
#endif
// Name of the Widevine CDM architecture in the component manifest.
const char kWidevineCdmArch[] =
#if defined(ARCH_CPU_X86)
"ia32";
#elif defined(ARCH_CPU_X86_64)
"x64";
#else // TODO(viettrungluu): Support an ARM check?
"???";
#endif
// If we don't have a Widevine CDM component, this is the version we claim.
const char kNullVersion[] = "0.0.0.0";
// The base directory on Windows looks like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\.
base::FilePath GetWidevineCdmBaseDirectory() {
base::FilePath result;
PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result);
return result;
}
// Widevine CDM has the version encoded in the path so we need to enumerate the
// directories to find the full path.
// On success, |latest_dir| returns something like:
// <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\.
// |latest_version| returns the corresponding version number. |older_dirs|
// returns directories of all older versions.
bool GetWidevineCdmDirectory(base::FilePath* latest_dir,
base::Version* latest_version,
std::vector<base::FilePath>* older_dirs) {
base::FilePath base_dir = GetWidevineCdmBaseDirectory();
bool found = false;
file_util::FileEnumerator file_enumerator(
base_dir, false, file_util::FileEnumerator::DIRECTORIES);
for (base::FilePath path = file_enumerator.Next(); !path.value().empty();
path = file_enumerator.Next()) {
base::Version version(path.BaseName().MaybeAsASCII());
if (!version.IsValid())
continue;
if (found) {
if (version.CompareTo(*latest_version) > 0) {
older_dirs->push_back(*latest_dir);
*latest_dir = path;
*latest_version = version;
} else {
older_dirs->push_back(path);
}
} else {
*latest_dir = path;
*latest_version = version;
found = true;
}
}
return found;
}
bool MakeWidevineCdmPluginInfo(const base::FilePath& path,
const base::Version& version,
content::PepperPluginInfo* plugin_info) {
if (!version.IsValid() ||
version.components().size() !=
static_cast<size_t>(kWidevineCdmVersionNumComponents)) {
return false;
}
plugin_info->is_internal = false;
// Widevine CDM must run out of process.
plugin_info->is_out_of_process = true;
plugin_info->path = path;
plugin_info->name = kWidevineCdmDisplayName;
plugin_info->description = kWidevineCdmDescription;
plugin_info->version = version.GetString();
webkit::WebPluginMimeType widevine_cdm_mime_type(
kWidevineCdmPluginMimeType,
kWidevineCdmPluginExtension,
kWidevineCdmPluginMimeTypeDescription);
plugin_info->mime_types.push_back(widevine_cdm_mime_type);
plugin_info->permissions = kWidevineCdmPluginPermissions;
return true;
}
void RegisterWidevineCdmWithChrome(const base::FilePath& path,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
content::PepperPluginInfo plugin_info;
if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))
return;
PluginService::GetInstance()->RegisterInternalPlugin(
plugin_info.ToWebPluginInfo(), true);
PluginService::GetInstance()->RefreshPlugins();
}
// Returns true if this browser is compatible with the given Widevine CDM
// manifest, with the version specified in the manifest in |version_out|.
bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest,
base::Version* version_out) {
std::string name;
manifest.GetStringASCII("name", &name);
if (name != kWidevineCdmManifestName)
return false;
std::string proposed_version;
manifest.GetStringASCII("version", &proposed_version);
base::Version version(proposed_version.c_str());
if (!version.IsValid())
return false;
std::string os;
manifest.GetStringASCII("x-widevine-cdm-os", &os);
if (os != kWidevineCdmOperatingSystem)
return false;
std::string arch;
manifest.GetStringASCII("x-widevine-cdm-arch", &arch);
if (arch != kWidevineCdmArch)
return false;
*version_out = version;
return true;
}
class WidevineCdmComponentInstaller : public ComponentInstaller {
public:
explicit WidevineCdmComponentInstaller(const base::Version& version);
virtual ~WidevineCdmComponentInstaller() {}
virtual void OnUpdateError(int error) OVERRIDE;
virtual bool Install(const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) OVERRIDE;
private:
base::Version current_version_;
};
WidevineCdmComponentInstaller::WidevineCdmComponentInstaller(
const base::Version& version)
: current_version_(version) {
DCHECK(version.IsValid());
}
void WidevineCdmComponentInstaller::OnUpdateError(int error) {
NOTREACHED() << "Widevine CDM update error: " << error;
}
bool WidevineCdmComponentInstaller::Install(
const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) {
base::Version version;
if (!CheckWidevineCdmManifest(manifest, &version))
return false;
if (current_version_.CompareTo(version) > 0)
return false;
if (!file_util::PathExists(unpack_path.AppendASCII(kWidevineCdmFileName)))
return false;
base::FilePath adapter_source_path;
PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path);
if (!file_util::PathExists(adapter_source_path))
return false;
// Passed the basic tests. Time to install it.
base::FilePath install_path =
GetWidevineCdmBaseDirectory().AppendASCII(version.GetString());
if (file_util::PathExists(install_path))
return false;
if (!file_util::Move(unpack_path, install_path))
return false;
base::FilePath adapter_install_path =
install_path.AppendASCII(kWidevineCdmAdapterFileName);
if (!file_util::CopyFile(adapter_source_path, adapter_install_path))
return false;
// Installation is done. Now register the Widevine CDM with chrome.
current_version_ = version;
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
&RegisterWidevineCdmWithChrome, adapter_install_path, version));
return true;
}
void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus,
const base::Version& version) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CrxComponent widevine_cdm;
widevine_cdm.name = "WidevineCdm";
widevine_cdm.installer = new WidevineCdmComponentInstaller(version);
widevine_cdm.version = version;
widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);
if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) {
NOTREACHED() << "Widevine CDM component registration failed.";
return;
}
}
void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::FilePath base_dir = GetWidevineCdmBaseDirectory();
if (!file_util::PathExists(base_dir) &&
!file_util::CreateDirectory(base_dir)) {
NOTREACHED() << "Could not create Widevine CDM directory.";
return;
}
base::FilePath latest_dir;
base::Version version(kNullVersion);
std::vector<base::FilePath> older_dirs;
if (GetWidevineCdmDirectory(&latest_dir, &version, &older_dirs)) {
base::FilePath adpater_path =
latest_dir.AppendASCII(kWidevineCdmAdapterFileName);
base::FilePath cdm_path = latest_dir.AppendASCII(kWidevineCdmFileName);
if (file_util::PathExists(adapter_path) &&
file_util::PathExists(cdm_path))) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&RegisterWidevineCdmWithChrome, adpater_path, version));
} else {
file_util::Delete(latest_dir, true);
version = base::Version(kNullVersion);
}
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version));
// Remove older versions of Widevine CDM.
for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();
iter != older_dirs.end(); ++iter) {
file_util::Delete(*iter, true);
}
}
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
} // namespace
void RegisterWidevineCdmComponent(ComponentUpdateService* cus) {
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&StartWidevineCdmUpdateRegistration, cus));
#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)
}
<|endoftext|> |
<commit_before>#include "motorController.h"
#include "time.h"
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <string>
using namespace std;
void printMessageMismatchError() {
}
ros::NodeHandle* n;
void MotorControllerHandler::print(string error) {
bool init = false;
if(!init) {
errorOut = n.advertise<std_msgs::String>("/Error_Log", 100);
init = true;
}
printf("ErrorHandler: %s\n", error.c_str());
std_msgs::String msg;
msg.data = error;
errorOut.publish(msg);
}
MotorControllerHandler::MotorControllerHandler(ros::NodeHandle* nh, const char* Port)
: serialPort(Port) {
n = nh;
awaitingResponce = false;
currentMessage.type = NO_MESSAGE;
gettimeofday(&lastQRCurTime, NULL);
gettimeofday(&lastQLCurTime, NULL);
gettimeofday(&lastQVoltTime, NULL);
gettimeofday(&lastMotorTime, NULL);
rightSpeed = leftSpeed = rightTargetSpeed = leftTargetSpeed = 0;
MaxStep = 20;
name = Port;
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: Failed during initialization\n", name.c_str());
print(string(temp));
bufIndex = 0;
}
void MotorControllerHandler::sendMessage(Message m) {
currentMessage = m;
transmit();
}
int filter(int speed) {
if(speed >= 256)
speed = 255;
if(speed <= -256)
speed = -255;
return speed;
}
void MotorControllerHandler::setMotorSpeed(int right, int left) {
rightTargetSpeed = filter(right);
leftTargetSpeed = filter(left);
printf("setting target speeds to %d %d\n", rightTargetSpeed, leftTargetSpeed);
}
Message createMessageFromSpeed(int rightSpeed, int leftSpeed) {
printf("creating message for %d %d", rightSpeed, leftSpeed);
Message msg;
msg.type = MOTOR_TYPE;
if(leftSpeed > 0) {
msg.DataC[0] = leftSpeed;
msg.DataC[1] = 0;
} else {
int rev = -leftSpeed;
msg.DataC[0] = 0;
msg.DataC[1] = rev;
}
if(rightSpeed > 0) {
msg.DataC[2] = rightSpeed;
msg.DataC[3] = 0;
} else {
int rev = -rightSpeed;
msg.DataC[2] = 0;
msg.DataC[3] = rev;
}
return msg;
}
void MotorControllerHandler::transmit() {
if(currentMessage.type == NO_MESSAGE)
return;
printf("%s: attempting to send message of type %c\n", name.c_str(), currentMessage.type);
gettimeofday(&lastSendTime, NULL);
printf("sending message %c %d %d %d %d\n", currentMessage.type,
currentMessage.DataC[0],
currentMessage.DataC[1],
currentMessage.DataC[2],
currentMessage.DataC[3]);
awaitingResponce = true;
if(!serialPort.IsOpen()) {
printf("%s: port not open attempting to re-open port\n", name.c_str());
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
printf("crap I couldn't open the port\n");
char temp[1000];
sprintf(temp, "%s error: Unable to open port\n", name.c_str());
print(string(temp));
}
}
try {
serialPort.WriteByte('S');
serialPort.WriteByte(currentMessage.type);
for(int i = 0; i < 4; i++) {
serialPort.WriteByte(currentMessage.DataC[i]);
}
serialPort.WriteByte('E');
awaitingResponce = true;
} catch (...) {
printf("crap I couldn't get it to send\n");
char temp[1000];
sprintf(temp, "%s error: Unable to send message\n", name.c_str());
print(string(temp));
}
}
void MotorControllerHandler::processResponce() {
if(buffer[0] != 'S' || buffer[6] != 'E') {
//Misaligned data? throw out bytes until you get it to align correctly
printf("Misaligned data\n");
for(int i = 0; i < 6; i++) {
buffer[i] = buffer[i+1];
bufIndex--;
return;
}
}
bufIndex = 0;
Message responce;
responce.type = buffer[1];
printf("got responce of type %c\n", responce.type);
for(int i = 0; i < 4; i++) {
responce.DataC[i] = buffer[i+2];
}
printf("%s: got a responce of type %c\n", name.c_str(), responce.type);
//printf("got responce %c %c %x %x %x %x %c\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6]);
switch (responce.type) {
case ERROR_TYPE:
char temp[1000];
sprintf(temp, "%s error from controller: %c%c%c%c\n", name.c_str(), buffer[2], buffer[3], buffer[4], buffer[5]);
print(string(temp));
awaitingResponce = false;
break;
case MOTOR_RESPONCE_TYPE:
if(currentMessage.type != MOTOR_TYPE) {
printMessageMismatchError();
break;
}
if(responce.DataC[0])
leftSpeed = responce.DataC[0];
else
leftSpeed = -responce.DataC[1];
if(responce.DataC[2])
rightSpeed = responce.DataC[2];
else
rightSpeed = -responce.DataC[3];
printf("new speeds right=%d(%d) left=%d(%d)\n", rightSpeed, rightTargetSpeed, leftSpeed, leftTargetSpeed);
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case CURRENT_RESPONCE_TYPE:
if(currentMessage.type != CURRENT_TYPE) {
printMessageMismatchError();
break;
}
if(currentMessage.DataC[0] == 'L')
LeftCurrent = responce.DataF;
else
RightCurrent = responce.DataF;
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case VOLTAGE_RESPONCE_TYPE:
if(currentMessage.type != VOLTAGE_TYPE) {
printMessageMismatchError();
break;
}
Voltage = responce.DataF;
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
default:
printf("Unrecognized responce type: %c\n", responce.type);
}
}
void MotorControllerHandler::recieve() {
if(serialPort.IsOpen() && awaitingResponce) {
try {
while(serialPort.IsDataAvailable()) {
unsigned char data = serialPort.ReadByte();
//printf("recieved byte \'%c\'\n", data);
while(bufIndex == 7) {
printf("You are not clearing bufIndex\n");
processResponce();
}
buffer[bufIndex++] = data;
if(bufIndex == 7) {
processResponce();
}
}
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: While attempting to read data\n", name.c_str());
print(string(temp));
}
}
}
int getMilliSecsBetween(timeval& start, timeval& end) {
int millis = (end.tv_sec - start.tv_sec) * 1000;
millis += (end.tv_usec - start.tv_usec) / 1000;
return millis;
}
bool MotorControllerHandler::TransmitTimeout() {
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastSendTime, curTime);
if(elsaped > RESEND_TIMEOUT)
return true;
return false;
}
void MotorControllerHandler::CheckQuery() {
if(awaitingResponce)
return;
timeval curtime;
gettimeofday(&curtime, NULL);
int elsaped = getMilliSecsBetween(lastQRCurTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'R';
sendMessage(query);
gettimeofday(&lastQRCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQLCurTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'L';
sendMessage(query);
gettimeofday(&lastQLCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQVoltTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = VOLTAGE_TYPE;
sendMessage(query);
gettimeofday(&lastQVoltTime, NULL);
return;
}
}
void MotorControllerHandler::CheckMotor() {
if(awaitingResponce)
return;
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastMotorTime, curTime);
if(elsaped < MOTOR_PERIOD)
return;
bool needsSent = false;
int leftSetSpeed = leftSpeed;
int rightSetSpeed = rightSpeed;
if(leftSpeed != leftTargetSpeed) {
int diff = leftTargetSpeed - leftSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
leftSetSpeed += diff;
needsSent=true;
}
if(rightSpeed != rightTargetSpeed) {
int diff = rightTargetSpeed - rightSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
rightSetSpeed += diff;
needsSent=true;
}
if(needsSent) {
sendMessage(createMessageFromSpeed(rightSetSpeed, leftSetSpeed));
gettimeofday(&lastMotorTime, NULL);
}
}
void MotorControllerHandler::spinOnce() {
recieve();
CheckMotor();
CheckQuery();
if(awaitingResponce && TransmitTimeout()) {
transmit();
}
}
<commit_msg>smal fixes<commit_after>#include "motorController.h"
#include "time.h"
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <string>
using namespace std;
void printMessageMismatchError() {
}
ros::NodeHandle* n;
void MotorControllerHandler::print(string error) {
bool init = false;
if(!init) {
errorOut = n->advertise<std_msgs::String>("/Error_Log", 100);
init = true;
}
printf("ErrorHandler: %s\n", error.c_str());
std_msgs::String msg;
msg.data = error;
errorOut.publish(msg);
}
MotorControllerHandler::MotorControllerHandler(ros::NodeHandle* nh, const char* Port)
: serialPort(Port) {
n = nh;
awaitingResponce = false;
currentMessage.type = NO_MESSAGE;
gettimeofday(&lastQRCurTime, NULL);
gettimeofday(&lastQLCurTime, NULL);
gettimeofday(&lastQVoltTime, NULL);
gettimeofday(&lastMotorTime, NULL);
rightSpeed = leftSpeed = rightTargetSpeed = leftTargetSpeed = 0;
MaxStep = 20;
name = Port;
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: Failed during initialization\n", name.c_str());
print(string(temp));
bufIndex = 0;
}
}
void MotorControllerHandler::sendMessage(Message m) {
currentMessage = m;
transmit();
}
int filter(int speed) {
if(speed >= 256)
speed = 255;
if(speed <= -256)
speed = -255;
return speed;
}
void MotorControllerHandler::setMotorSpeed(int right, int left) {
rightTargetSpeed = filter(right);
leftTargetSpeed = filter(left);
printf("setting target speeds to %d %d\n", rightTargetSpeed, leftTargetSpeed);
}
Message createMessageFromSpeed(int rightSpeed, int leftSpeed) {
printf("creating message for %d %d", rightSpeed, leftSpeed);
Message msg;
msg.type = MOTOR_TYPE;
if(leftSpeed > 0) {
msg.DataC[0] = leftSpeed;
msg.DataC[1] = 0;
} else {
int rev = -leftSpeed;
msg.DataC[0] = 0;
msg.DataC[1] = rev;
}
if(rightSpeed > 0) {
msg.DataC[2] = rightSpeed;
msg.DataC[3] = 0;
} else {
int rev = -rightSpeed;
msg.DataC[2] = 0;
msg.DataC[3] = rev;
}
return msg;
}
void MotorControllerHandler::transmit() {
if(currentMessage.type == NO_MESSAGE)
return;
printf("%s: attempting to send message of type %c\n", name.c_str(), currentMessage.type);
gettimeofday(&lastSendTime, NULL);
printf("sending message %c %d %d %d %d\n", currentMessage.type,
currentMessage.DataC[0],
currentMessage.DataC[1],
currentMessage.DataC[2],
currentMessage.DataC[3]);
awaitingResponce = true;
if(!serialPort.IsOpen()) {
printf("%s: port not open attempting to re-open port\n", name.c_str());
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
printf("crap I couldn't open the port\n");
char temp[1000];
sprintf(temp, "%s error: Unable to open port\n", name.c_str());
print(string(temp));
}
}
try {
serialPort.WriteByte('S');
serialPort.WriteByte(currentMessage.type);
for(int i = 0; i < 4; i++) {
serialPort.WriteByte(currentMessage.DataC[i]);
}
serialPort.WriteByte('E');
awaitingResponce = true;
} catch (...) {
printf("crap I couldn't get it to send\n");
char temp[1000];
sprintf(temp, "%s error: Unable to send message\n", name.c_str());
print(string(temp));
}
}
void MotorControllerHandler::processResponce() {
if(buffer[0] != 'S' || buffer[6] != 'E') {
//Misaligned data? throw out bytes until you get it to align correctly
printf("Misaligned data\n");
for(int i = 0; i < 6; i++) {
buffer[i] = buffer[i+1];
bufIndex--;
return;
}
}
bufIndex = 0;
Message responce;
responce.type = buffer[1];
printf("got responce of type %c\n", responce.type);
for(int i = 0; i < 4; i++) {
responce.DataC[i] = buffer[i+2];
}
printf("%s: got a responce of type %c\n", name.c_str(), responce.type);
//printf("got responce %c %c %x %x %x %x %c\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6]);
switch (responce.type) {
case ERROR_TYPE:
char temp[1000];
sprintf(temp, "%s error from controller: %c%c%c%c\n", name.c_str(), buffer[2], buffer[3], buffer[4], buffer[5]);
print(string(temp));
awaitingResponce = false;
break;
case MOTOR_RESPONCE_TYPE:
if(currentMessage.type != MOTOR_TYPE) {
printMessageMismatchError();
break;
}
if(responce.DataC[0])
leftSpeed = responce.DataC[0];
else
leftSpeed = -responce.DataC[1];
if(responce.DataC[2])
rightSpeed = responce.DataC[2];
else
rightSpeed = -responce.DataC[3];
printf("new speeds right=%d(%d) left=%d(%d)\n", rightSpeed, rightTargetSpeed, leftSpeed, leftTargetSpeed);
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case CURRENT_RESPONCE_TYPE:
if(currentMessage.type != CURRENT_TYPE) {
printMessageMismatchError();
break;
}
if(currentMessage.DataC[0] == 'L')
LeftCurrent = responce.DataF;
else
RightCurrent = responce.DataF;
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case VOLTAGE_RESPONCE_TYPE:
if(currentMessage.type != VOLTAGE_TYPE) {
printMessageMismatchError();
break;
}
Voltage = responce.DataF;
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
default:
printf("Unrecognized responce type: %c\n", responce.type);
}
}
void MotorControllerHandler::recieve() {
if(serialPort.IsOpen() && awaitingResponce) {
try {
while(serialPort.IsDataAvailable()) {
unsigned char data = serialPort.ReadByte();
//printf("recieved byte \'%c\'\n", data);
while(bufIndex == 7) {
printf("You are not clearing bufIndex\n");
processResponce();
}
buffer[bufIndex++] = data;
if(bufIndex == 7) {
processResponce();
}
}
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: While attempting to read data\n", name.c_str());
print(string(temp));
}
}
}
int getMilliSecsBetween(timeval& start, timeval& end) {
int millis = (end.tv_sec - start.tv_sec) * 1000;
millis += (end.tv_usec - start.tv_usec) / 1000;
return millis;
}
bool MotorControllerHandler::TransmitTimeout() {
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastSendTime, curTime);
if(elsaped > RESEND_TIMEOUT)
return true;
return false;
}
void MotorControllerHandler::CheckQuery() {
if(awaitingResponce)
return;
timeval curtime;
gettimeofday(&curtime, NULL);
int elsaped = getMilliSecsBetween(lastQRCurTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'R';
sendMessage(query);
gettimeofday(&lastQRCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQLCurTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'L';
sendMessage(query);
gettimeofday(&lastQLCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQVoltTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = VOLTAGE_TYPE;
sendMessage(query);
gettimeofday(&lastQVoltTime, NULL);
return;
}
}
void MotorControllerHandler::CheckMotor() {
if(awaitingResponce)
return;
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastMotorTime, curTime);
if(elsaped < MOTOR_PERIOD)
return;
bool needsSent = false;
int leftSetSpeed = leftSpeed;
int rightSetSpeed = rightSpeed;
if(leftSpeed != leftTargetSpeed) {
int diff = leftTargetSpeed - leftSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
leftSetSpeed += diff;
needsSent=true;
}
if(rightSpeed != rightTargetSpeed) {
int diff = rightTargetSpeed - rightSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
rightSetSpeed += diff;
needsSent=true;
}
if(needsSent) {
sendMessage(createMessageFromSpeed(rightSetSpeed, leftSetSpeed));
gettimeofday(&lastMotorTime, NULL);
}
}
void MotorControllerHandler::spinOnce() {
recieve();
CheckMotor();
CheckQuery();
if(awaitingResponce && TransmitTimeout()) {
transmit();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/printing/print_web_view_helper.h"
#include <memory>
#include "base/logging.h"
#include "chrome/common/print_messages.h"
#include "content/public/renderer/render_thread.h"
#include "printing/metafile_skia_wrapper.h"
#include "printing/page_size_margins.h"
#include "printing/pdf_metafile_skia.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
#include "base/process/process_handle.h"
#else
#include "base/file_descriptor_posix.h"
#endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
namespace printing {
using blink::WebLocalFrame;
bool PrintWebViewHelper::RenderPreviewPage(
int page_number,
const PrintMsg_Print_Params& print_params) {
PrintMsg_PrintPage_Params page_params;
page_params.params = print_params;
page_params.page_number = page_number;
std::unique_ptr<PdfMetafileSkia> draft_metafile;
PdfMetafileSkia* initial_render_metafile = print_preview_context_.metafile();
if (print_preview_context_.IsModifiable() && is_print_ready_metafile_sent_) {
draft_metafile.reset(new PdfMetafileSkia(PDF_SKIA_DOCUMENT_TYPE));
initial_render_metafile = draft_metafile.get();
}
base::TimeTicks begin_time = base::TimeTicks::Now();
PrintPageInternal(page_params,
print_preview_context_.prepared_frame(),
initial_render_metafile);
print_preview_context_.RenderedPreviewPage(
base::TimeTicks::Now() - begin_time);
if (draft_metafile.get()) {
draft_metafile->FinishDocument();
} else if (print_preview_context_.IsModifiable() &&
print_preview_context_.generate_draft_pages()) {
DCHECK(!draft_metafile.get());
draft_metafile =
print_preview_context_.metafile()->GetMetafileForCurrentPage(
PDF_SKIA_DOCUMENT_TYPE);
}
return PreviewPageRendered(page_number, draft_metafile.get());
}
bool PrintWebViewHelper::PrintPagesNative(blink::WebLocalFrame* frame,
int page_count) {
PdfMetafileSkia metafile(PDF_SKIA_DOCUMENT_TYPE);
if (!metafile.Init())
return false;
const PrintMsg_PrintPages_Params& params = *print_pages_params_;
std::vector<int> printed_pages;
if (params.pages.empty()) {
for (int i = 0; i < page_count; ++i) {
printed_pages.push_back(i);
}
} else {
// TODO(vitalybuka): redesign to make more code cross platform.
for (size_t i = 0; i < params.pages.size(); ++i) {
if (params.pages[i] >= 0 && params.pages[i] < page_count) {
printed_pages.push_back(params.pages[i]);
}
}
}
if (printed_pages.empty())
return false;
PrintMsg_PrintPage_Params page_params;
page_params.params = params.params;
for (size_t i = 0; i < printed_pages.size(); ++i) {
page_params.page_number = printed_pages[i];
PrintPageInternal(page_params, frame, &metafile);
}
// blink::printEnd() for PDF should be called before metafile is closed.
FinishFramePrinting();
metafile.FinishDocument();
PrintHostMsg_DidPrintPage_Params printed_page_params;
if (!CopyMetafileDataToSharedMem(
metafile, &printed_page_params.metafile_data_handle)) {
return false;
}
printed_page_params.data_size = metafile.GetDataSize();
printed_page_params.document_cookie = params.params.document_cookie;
for (size_t i = 0; i < printed_pages.size(); ++i) {
printed_page_params.page_number = printed_pages[i];
Send(new PrintHostMsg_DidPrintPage(routing_id(), printed_page_params));
// Send the rest of the pages with an invalid metafile handle.
printed_page_params.metafile_data_handle.fd = -1;
}
return true;
}
void PrintWebViewHelper::PrintPageInternal(
const PrintMsg_PrintPage_Params& params,
WebLocalFrame* frame,
PdfMetafileSkia* metafile) {
PageSizeMargins page_layout_in_points;
double scale_factor = 1.0f;
ComputePageLayoutInPointsForCss(frame, params.page_number, params.params,
ignore_css_margins_, &scale_factor,
&page_layout_in_points);
gfx::Size page_size;
gfx::Rect content_area;
GetPageSizeAndContentAreaFromPageLayout(page_layout_in_points, &page_size,
&content_area);
gfx::Rect canvas_area = content_area;
cc::PaintCanvas* canvas =
metafile->GetVectorCanvasForNewPage(page_size, canvas_area, scale_factor);
if (!canvas)
return;
MetafileSkiaWrapper::SetMetafileOnCanvas(canvas, metafile);
RenderPageContent(frame, params.page_number, canvas_area, content_area,
scale_factor, canvas);
// Done printing. Close the device context to retrieve the compiled metafile.
if (!metafile->FinishPage())
NOTREACHED() << "metafile failed";
}
} // namespace printing
<commit_msg>make base::SharedMemoryHandle a class on POSIX.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/printing/print_web_view_helper.h"
#include <memory>
#include "base/logging.h"
#include "chrome/common/print_messages.h"
#include "content/public/renderer/render_thread.h"
#include "printing/metafile_skia_wrapper.h"
#include "printing/page_size_margins.h"
#include "printing/pdf_metafile_skia.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
#include "base/process/process_handle.h"
#else
#include "base/file_descriptor_posix.h"
#endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
namespace printing {
using blink::WebLocalFrame;
bool PrintWebViewHelper::RenderPreviewPage(
int page_number,
const PrintMsg_Print_Params& print_params) {
PrintMsg_PrintPage_Params page_params;
page_params.params = print_params;
page_params.page_number = page_number;
std::unique_ptr<PdfMetafileSkia> draft_metafile;
PdfMetafileSkia* initial_render_metafile = print_preview_context_.metafile();
if (print_preview_context_.IsModifiable() && is_print_ready_metafile_sent_) {
draft_metafile.reset(new PdfMetafileSkia(PDF_SKIA_DOCUMENT_TYPE));
initial_render_metafile = draft_metafile.get();
}
base::TimeTicks begin_time = base::TimeTicks::Now();
PrintPageInternal(page_params,
print_preview_context_.prepared_frame(),
initial_render_metafile);
print_preview_context_.RenderedPreviewPage(
base::TimeTicks::Now() - begin_time);
if (draft_metafile.get()) {
draft_metafile->FinishDocument();
} else if (print_preview_context_.IsModifiable() &&
print_preview_context_.generate_draft_pages()) {
DCHECK(!draft_metafile.get());
draft_metafile =
print_preview_context_.metafile()->GetMetafileForCurrentPage(
PDF_SKIA_DOCUMENT_TYPE);
}
return PreviewPageRendered(page_number, draft_metafile.get());
}
bool PrintWebViewHelper::PrintPagesNative(blink::WebLocalFrame* frame,
int page_count) {
PdfMetafileSkia metafile(PDF_SKIA_DOCUMENT_TYPE);
if (!metafile.Init())
return false;
const PrintMsg_PrintPages_Params& params = *print_pages_params_;
std::vector<int> printed_pages;
if (params.pages.empty()) {
for (int i = 0; i < page_count; ++i) {
printed_pages.push_back(i);
}
} else {
// TODO(vitalybuka): redesign to make more code cross platform.
for (size_t i = 0; i < params.pages.size(); ++i) {
if (params.pages[i] >= 0 && params.pages[i] < page_count) {
printed_pages.push_back(params.pages[i]);
}
}
}
if (printed_pages.empty())
return false;
PrintMsg_PrintPage_Params page_params;
page_params.params = params.params;
for (size_t i = 0; i < printed_pages.size(); ++i) {
page_params.page_number = printed_pages[i];
PrintPageInternal(page_params, frame, &metafile);
}
// blink::printEnd() for PDF should be called before metafile is closed.
FinishFramePrinting();
metafile.FinishDocument();
PrintHostMsg_DidPrintPage_Params printed_page_params;
if (!CopyMetafileDataToSharedMem(
metafile, &printed_page_params.metafile_data_handle)) {
return false;
}
printed_page_params.data_size = metafile.GetDataSize();
printed_page_params.document_cookie = params.params.document_cookie;
for (size_t i = 0; i < printed_pages.size(); ++i) {
printed_page_params.page_number = printed_pages[i];
Send(new PrintHostMsg_DidPrintPage(routing_id(), printed_page_params));
// Send the rest of the pages with an invalid metafile handle.
printed_page_params.metafile_data_handle.Release();
}
return true;
}
void PrintWebViewHelper::PrintPageInternal(
const PrintMsg_PrintPage_Params& params,
WebLocalFrame* frame,
PdfMetafileSkia* metafile) {
PageSizeMargins page_layout_in_points;
double scale_factor = 1.0f;
ComputePageLayoutInPointsForCss(frame, params.page_number, params.params,
ignore_css_margins_, &scale_factor,
&page_layout_in_points);
gfx::Size page_size;
gfx::Rect content_area;
GetPageSizeAndContentAreaFromPageLayout(page_layout_in_points, &page_size,
&content_area);
gfx::Rect canvas_area = content_area;
cc::PaintCanvas* canvas =
metafile->GetVectorCanvasForNewPage(page_size, canvas_area, scale_factor);
if (!canvas)
return;
MetafileSkiaWrapper::SetMetafileOnCanvas(canvas, metafile);
RenderPageContent(frame, params.page_number, canvas_area, content_area,
scale_factor, canvas);
// Done printing. Close the device context to retrieve the compiled metafile.
if (!metafile->FinishPage())
NOTREACHED() << "metafile failed";
}
} // namespace printing
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2015, University of Colorado, Boulder
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Univ of CO, Boulder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Dave Coleman
Desc: Records a ros_control ControllerState data to CSV for Matlab/etc analysis
*/
#include <ros_control_boilerplate/tools/controller_to_csv.h>
// Basic file operations
#include <iostream>
#include <fstream>
// ROS parameter loading
#include <rosparam_shortcuts/rosparam_shortcuts.h>
namespace ros_control_boilerplate
{
ControllerToCSV::ControllerToCSV(const std::string& topic)
: nh_("~")
, first_update_(true)
, recording_started_(true)
{
// Load rosparams
ros::NodeHandle rpsnh(nh_, name_);
int error = 0;
error += !rosparam_shortcuts::get(name_, rpsnh, "record_hz", record_hz_);
rosparam_shortcuts::shutdownIfError(name_, error);
ROS_INFO_STREAM_NAMED(name_, "Subscribing to " << topic);
// State subscriber
state_sub_ = nh_.subscribe<control_msgs::JointTrajectoryControllerState>(
topic, 1, &ControllerToCSV::stateCB, this);
// Wait for states to populate
waitForSubscriber(state_sub_);
// Alert user to mode
if (recordAll())
{
ROS_INFO_STREAM_NAMED(name_, "Recording all incoming controller state messages");
}
else
{
ROS_INFO_STREAM_NAMED(name_, "Only recording every " << record_hz_ << " hz");
}
ROS_INFO_STREAM_NAMED(name_, "ControllerToCSV Ready.");
}
ControllerToCSV::~ControllerToCSV()
{
stopRecording();
}
bool ControllerToCSV::recordAll()
{
return record_hz_ == 0;
}
void ControllerToCSV::stateCB(const control_msgs::JointTrajectoryControllerState::ConstPtr& state)
{
// Two modes - save all immediately, or only save at certain frequency
if (recordAll())
{
// Record state
states_.push_back(current_state_);
// Record current time
timestamps_.push_back(ros::Time::now());
}
else // only record at freq
{
current_state_ = *state;
}
}
// Start the data collection
void ControllerToCSV::startRecording(const std::string& file_name)
{
ROS_INFO_STREAM_NAMED(name_, "Saving to " << file_name);
file_name_ = file_name;
// Reset data collections
states_.clear();
timestamps_.clear();
recording_started_ = true;
// Start sampling loop
if (!recordAll()) // only record at the specified frequency
{
ros::Duration update_freq = ros::Duration(1.0 / record_hz_);
non_realtime_loop_ = nh_.createTimer(update_freq, &ControllerToCSV::update, this);
}
}
void ControllerToCSV::update(const ros::TimerEvent& event)
{
if (first_update_)
{
// Check if we've recieved any states yet
if (current_state_.joint_names.empty())
{
ROS_WARN_STREAM_THROTTLE_NAMED(2, name_, "No states recieved yet");
return;
}
first_update_ = false;
}
else // if (event.last_real > 0)
{
const double freq = 1.0 / (event.current_real - event.last_real).toSec();
ROS_INFO_STREAM_THROTTLE_NAMED(2, name_, "Updating at " << freq << " hz, total: " << (ros::Time::now() - timestamps_.front()).toSec() << " seconds");
}
// Record state
states_.push_back(current_state_);
// Record current time
timestamps_.push_back(ros::Time::now());
}
void ControllerToCSV::stopRecording()
{
non_realtime_loop_.stop();
writeToFile();
}
bool ControllerToCSV::writeToFile()
{
std::cout << "Writing data to file " << std::endl;
if (!states_.size())
{
std::cout << "No controller states populated" << std::endl;
return false;
}
std::ofstream output_file;
output_file.open(file_name_.c_str());
// Output header -------------------------------------------------------
output_file << "timestamp,";
for (std::size_t j = 0; j < states_[0].joint_names.size(); ++j)
{
output_file << states_[0].joint_names[j] << "_desired_pos,"
<< states_[0].joint_names[j] << "_desired_vel,"
<< states_[0].joint_names[j] << "_actual_pos,"
<< states_[0].joint_names[j] << "_actual_vel,"
<< states_[0].joint_names[j] << "_error_pos,"
<< states_[0].joint_names[j] << "_error_vel,";
}
output_file << std::endl;
// Output data ------------------------------------------------------
// Subtract starting time
// double start_time = states_[0].header.stamp.toSec();
double start_time = timestamps_[0].toSec();
for (std::size_t i = 0; i < states_.size(); ++i)
{
// Timestamp
output_file << timestamps_[i].toSec() - start_time << ",";
// Output entire state of robot to single line
for (std::size_t j = 0; j < states_[i].joint_names.size(); ++j)
{
// Output State
output_file << states_[i].desired.positions[j] << ","
<< states_[i].desired.velocities[j] << ","
<< states_[i].actual.positions[j] << ","
<< states_[i].actual.velocities[j] << ","
<< states_[i].error.positions[j] << ","
<< states_[i].error.velocities[j] << ",";
}
output_file << std::endl;
}
output_file.close();
std::cout << "Wrote to file: " << file_name_ << std::endl;
return true;
}
bool ControllerToCSV::waitForSubscriber(const ros::Subscriber& sub, const double& wait_time)
{
// Benchmark runtime
ros::Time start_time;
start_time = ros::Time::now();
// Will wait at most 1000 ms (1 sec)
ros::Time max_time(ros::Time::now() + ros::Duration(wait_time));
// This is wrong. It returns only the number of subscribers that have already established their
// direct connections to this subscriber
int num_existing_subscribers = sub.getNumPublishers();
// How often to check for subscribers
ros::Rate poll_rate(200);
// Wait for subsriber
while (num_existing_subscribers == 0)
{
// Check if timed out
if (ros::Time::now() > max_time)
{
ROS_WARN_STREAM_NAMED(name_, "Topic '" << sub.getTopic() << "' unable to connect to any publishers within "
<< wait_time << " seconds.");
return false;
}
ros::spinOnce();
// Sleep
poll_rate.sleep();
// Check again
num_existing_subscribers = sub.getNumPublishers();
}
// Benchmark runtime
if (true)
{
double duration = (ros::Time::now() - start_time).toSec();
ROS_DEBUG_STREAM_NAMED(name_, "Topic '" << sub.getTopic() << "' took " << duration
<< " seconds to connect to a subscriber. "
"Connected to " << num_existing_subscribers
<< " total subsribers");
}
return true;
}
} // end namespace
<commit_msg>Delete controller_to_csv.cpp<commit_after><|endoftext|> |
<commit_before><commit_msg><commit_after><|endoftext|> |
<commit_before>#include "servercommand.h"
#include "user_db_editor.h"
#include <sqlite3.h>
#define END 1234
using namespace std ;
ServerCommand::ServerCommand( int sockfd ) :
m_sockfd( sockfd )
{
m_serverpath = "." ;
// m_fd = open( "userdata.dat", O_CREAT | O_RDWR, 0644 ) ;
// if ( -1 == m_fd )
// {
// perror( "open" ) ;
// }
UserData data ;
memset( &data, 0, sizeof(data) ) ;
// while ( read( m_fd, &data, sizeof(data) ) > 0 )
// {
// m_Datas.insert( data ) ;
// }
ude.user_db_editor::DbInitialize();
sqlite3_open("UsersTable.db", &db_user);
}
ServerCommand::~ServerCommand( void )
{
if ( !m_bstart )
{
return ;
}
// close( m_fd ) ;
close( m_sockfd ) ;
sqlite3_close(db_user);
}
// content of client directory
int ServerCommand::LsCommand( void ) const
{
DIR *mydir = NULL ;
int retval = 0 ;
char fileName[SEND_BUF_SIZE] ;
bzero( fileName, sizeof(fileName) ) ;
struct dirent *pdir = NULL ;
if ( !(mydir = opendir( m_userpath.c_str() )) )
{
perror( "opendir" ) ;
goto error ;
}
while ( (pdir = readdir(mydir)) )
{
bzero( fileName, sizeof(fileName) ) ;
// cout << pdir << endl ;
*(int*)fileName = pdir->d_type ;
if ( !memcpy( fileName+sizeof(int), pdir->d_name, strlen(pdir->d_name) ) )
{
perror( "memcpy" ) ;
goto error ;
}
if ( write( m_sockfd, fileName, SEND_BUF_SIZE ) < 0 )
{
perror( "write" ) ;
goto error ;
}
// printf( "while\n" ) ;
}
*(int*)fileName = END ;
if ( write( m_sockfd, fileName, SEND_BUF_SIZE ) < 0 )
{
perror( "write" ) ;
goto error ;
}
done:
closedir( mydir ) ;
// cout << "LsCommand:End" << endl ;
return retval ;
error:
retval = -1 ;
goto done ;
}
//list of message
int ServerCommand::LsmCommand ( ) const
{
// To be done by database
// I guess it's looking into database and get the result
// this class has fields like m_username that might be useful
// you can check the header file
queue<message_t> MQ;
MQ=ude.user_db_editor::DbGetMessageQ(m_username, db_user);
//std::cout<<"MQ"<<(MQ.front()).isRequest<<(MQ.front()).name<<(MQ.front()).message<<std::endl;
return 0;
}
int ServerCommand::LsfCommand ( ) const
{
// see above
queue<string> FQ;
FQ=ude.user_db_editor::DbGetFrQ(m_username, db_user);
return 0;
}
// client out
int ServerCommand::QuitCommand( ) const
{
cout << "One client disconnects" << endl;
return close( m_sockfd ) ;
}
// Download file
int ServerCommand::GetCommand( const char *fileName ) const
{
cout << "GetCommand" << endl ;
string file = m_userpath + "/" + fileName ;
char buffer[SEND_BUF_SIZE] ;
bzero( buffer, sizeof(buffer) ) ;
cout << "[get]" << file << endl ;
int fd = open( file.c_str(), O_RDONLY ) ;
if ( -1 == fd )
{
cerr << "openfile:" << file << endl ;
return -1 ;
}
ssize_t rbyte = 0 ;
while ( (rbyte = read( fd, buffer, sizeof(buffer)) ) >= 0 )
{
if ( (write( m_sockfd, buffer, rbyte) ) < 0 )
{
perror( "write" ) ;
close( fd ) ;
close( m_sockfd ) ;
return -1 ;
}
if ( (rbyte < SEND_BUF_SIZE) )
{
goto done ;
}
}
done:
close( fd ) ;
cout << "GetCommand:End" << endl ;
return 0 ;
}
// upload file
int ServerCommand::PutCommand( const char *fileName ) const
{
char buffer[RECV_BUF_SIZE] ;
bzero( buffer, sizeof(buffer) ) ;
string file = m_userpath + "/" + fileName ;
cout << "[put]" << file << endl ;
int fd = open( file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644 ) ;
if ( -1 == fd )
{
cerr << "openfile:" << file << endl ;
return -1 ;
}
ssize_t rbyte = 0 ;
while ( (rbyte = read( m_sockfd, buffer, RECV_BUF_SIZE )) > 0 )
{
if ( write( fd, buffer, rbyte ) < 0 )
{
perror( "writefile" ) ;
close( fd ) ;
return -1 ;
}
cout << "rbyte:" << rbyte << endl ;
if ( (rbyte < RECV_BUF_SIZE) )
{
goto done ;
}
}
done:
cout << "Done receiving" << endl ;
return close( fd ) ;
}
int ServerCommand::HelpCommand( void ) const
{
cout << "help" << endl ;
return 0 ;
}
// change directories
int ServerCommand::CdCommand( const char *dir )
{
if ( ('/' == dir[0]) )
{
m_userpath = dir ;
}
else
{
m_userpath = m_userpath + "/" + dir ;
}
return 0 ;
}
// login on
int ServerCommand::LoginCommand( void )
{
int retval = 0 ;
UserData user ;
int replay = 0 ;
int trycount = 3 ;
retry:
// set<UserData>::iterator it ;
if ( read( m_sockfd, &user, sizeof(user) ) < 0 )
{
perror( "read" ) ;
goto error ;
}
cout << user.username << endl ;
cout << user.password << endl ;
// it = m_Datas.find( user ) ;
/*if ( m_Datas.end() != it )
{
cout << it->username << endl ;
cout << it->password << endl ;
if ( !strcmp( it->password, user.password ) )
{
replay = 0 ;
}
else
{
replay = -1 ;
}
}
else
{
replay = -1 ;
}
*/
if( ude.user_db_editor::UserDbLogin(user.username , user.password , db_user)) {
replay=0;
}
else {
replay=-1;
}
// result of verification
cout << "replay:" << replay << endl ;
write( m_sockfd, &replay, sizeof(replay) ) ;
if ( -1 == replay && trycount )
{
--trycount ;
goto retry ;
}
else if ( -1 == replay )
{
goto error ;
}
m_username = user.username ;
m_password = user.password ;
m_userpath = m_serverpath + "/" + user.username ;
done:
return retval ;
error:
retval = -1 ;
goto done ;
}
// register
int ServerCommand::LogonCommand( void )
{
int retval = 0 ;
UserData user ;
int replay = 0 ;
int trycount = 3 ;
// set<UserData>::iterator it ;
retry:
if ( read( m_sockfd, &user, sizeof(user) ) < 0 )
{
perror( "read" ) ;
goto error ;
}
cout << user.username << endl ;
cout << user.password << endl ;
// it = m_Datas.find( user ) ;
/*if ( m_Datas.end() == it )
{
m_Datas.insert( user ) ;
replay = 0 ;
}
else
{
replay = -1 ;
}
*/
if (ude.user_db_editor::DbAddUser(user.username , user.password , db_user)){
replay=0;
}
else {
replay=-1;
}
// sending result
cout << "replay:" << replay << endl ;
write( m_sockfd, &replay, sizeof(replay) ) ;
if ( -1 == replay && trycount )
{
--trycount ;
goto retry ;
}
else if ( -1 == replay )
{
goto error ;
}
m_username = user.username ;
m_password = user.password ;
m_userpath = m_serverpath + "/" + user.username ;
cout << "m_userpath" << m_userpath << endl;
if ( -1 == mkdir( m_userpath.c_str(), 0775 ) )
{
perror( "mkdir" ) ;
goto error ;
}
// m_Datas.insert( user ) ;
// if ( write( m_fd, &user, sizeof(user) ) < 0 )
// {
// perror( "m_userfile.write" ) ;
// goto error ;
// }
done:
return retval ;
error:
retval = -1 ;
goto done ;
}
// share
int ServerCommand::ShareCommand( void )
{
cout << "COMMAND_SHARE" << endl;
int retval = 0 ;
char file[256] ;
char user[256] ;
bzero( file, sizeof(file) ) ;
bzero( user, sizeof(user) ) ;
string _newfile ;
string oldfile ;
// obatain file name and username
if ( read( m_sockfd, file, sizeof(file) ) < 0 )
{
perror( "read filename" ) ;
goto error ;
}
if ( read( m_sockfd, user, sizeof(user) ) < 0 )
{
perror( "read username" ) ;
goto error ;
}
cout << file << ":" << user << endl ;
_newfile = m_serverpath + "/" + user + "/" + file ;
oldfile = m_userpath + "/" + file ;
cout << _newfile << endl ;
if ( -1 == link( oldfile.c_str(), _newfile.c_str() ) )
{
perror( "link" ) ;
goto error ;
}
done:
cout << "COMMAND_SHARE END" << endl ;
return retval ;
error:
retval = -1 ;
goto done ;
}
int ServerCommand::SendCommand( void )
{
cout << "COMMAND_SEND" << endl;
int retval = 0 ;
char user[256] ;
char message[MSG_BUF_SIZE];
bzero( user, sizeof(user));
bzero( message, sizeof(message ) );
// get receiver and message
if ( read( m_sockfd, user, sizeof(user)) < 0 )
{
perror("read username" );
goto error;
}
if (read( m_sockfd, message, sizeof(message) ) < 0 )
{
perror( " read message" );
goto error;
}
//
// DATABASE TO BE DONE
//
//
string tousers=touser;
string messages=message;
bool isRequest;
if(strcmp(message,"friend_request")==0){isRequest=1;}
else{isRequest=0;}
ude.DbAddMessage(user, m_username,isRequest, message, db_user);
cout << message << endl;
done:
cout << " COMMAND_SEND END" << endl ;
return retval;
error:
retval = -1 ;
goto done;
}
bool ServerCommand::ApproveAddFriendCommand(std::string Name2){
ude.user_db_editor::DbAddFriend(m_username, Name2, db_user);
ude.user_db_editor::DbAddFriend(Name2, m_username, db_user);
}
bool ServerCommand::RemoveFriendCommand(std::string receiverName){
ude.user_db_editor::DbRmFriend(m_username, receivername, db_user);
ude.user_db_editor::DbRmFriend(receivername,m_username, db_user);
}
int ServerCommand::RmCommand( string filename )
{
string file = m_userpath + "/" + filename ;
cout << "file:" << file << endl ;
return unlink( file.c_str() ) ;
}
bool ServerCommand::FindUser( const string &username ) const
{
UserData user( username ) ;
return m_Datas.end() != m_Datas.find( user ) ;
}
<commit_msg>cout list<commit_after>#include "servercommand.h"
#include "user_db_editor.h"
#include <sqlite3.h>
#define END 1234
using namespace std ;
ServerCommand::ServerCommand( int sockfd ) :
m_sockfd( sockfd )
{
m_serverpath = "." ;
// m_fd = open( "userdata.dat", O_CREAT | O_RDWR, 0644 ) ;
// if ( -1 == m_fd )
// {
// perror( "open" ) ;
// }
UserData data ;
memset( &data, 0, sizeof(data) ) ;
// while ( read( m_fd, &data, sizeof(data) ) > 0 )
// {
// m_Datas.insert( data ) ;
// }
ude.user_db_editor::DbInitialize();
sqlite3_open("UsersTable.db", &db_user);
}
ServerCommand::~ServerCommand( void )
{
if ( !m_bstart )
{
return ;
}
// close( m_fd ) ;
close( m_sockfd ) ;
sqlite3_close(db_user);
}
// content of client directory
int ServerCommand::LsCommand( void ) const
{
DIR *mydir = NULL ;
int retval = 0 ;
char fileName[SEND_BUF_SIZE] ;
bzero( fileName, sizeof(fileName) ) ;
struct dirent *pdir = NULL ;
if ( !(mydir = opendir( m_userpath.c_str() )) )
{
perror( "opendir" ) ;
goto error ;
}
while ( (pdir = readdir(mydir)) )
{
bzero( fileName, sizeof(fileName) ) ;
// cout << pdir << endl ;
*(int*)fileName = pdir->d_type ;
if ( !memcpy( fileName+sizeof(int), pdir->d_name, strlen(pdir->d_name) ) )
{
perror( "memcpy" ) ;
goto error ;
}
if ( write( m_sockfd, fileName, SEND_BUF_SIZE ) < 0 )
{
perror( "write" ) ;
goto error ;
}
// printf( "while\n" ) ;
}
*(int*)fileName = END ;
if ( write( m_sockfd, fileName, SEND_BUF_SIZE ) < 0 )
{
perror( "write" ) ;
goto error ;
}
done:
closedir( mydir ) ;
// cout << "LsCommand:End" << endl ;
return retval ;
error:
retval = -1 ;
goto done ;
}
//list of message
int ServerCommand::LsmCommand ( ) const
{
// To be done by database
// I guess it's looking into database and get the result
// this class has fields like m_username that might be useful
// you can check the header file
queue<message_t> MQ;
MQ=ude.user_db_editor::DbGetMessageQ(m_username, db_user);
//std::cout<<"MQ"<<(MQ.front()).isRequest<<(MQ.front()).name<<(MQ.front()).message<<std::endl;
while(!MQ.empty()){
cout << (MQ.front()).isRequest<<" "<<(MQ.front()).name<<" "<<(MQ.front()).message << endl;
MQ.pop();
}
return 0;
}
int ServerCommand::LsfCommand ( ) const
{
// see above
queue<string> FQ;
FQ=ude.user_db_editor::DbGetFrQ(m_username, db_user);
while(!FQ.empty()){
cout << FQ.front() << endl;
FQ.pop();
}
return 0;
}
// client out
int ServerCommand::QuitCommand( ) const
{
cout << "One client disconnects" << endl;
return close( m_sockfd ) ;
}
// Download file
int ServerCommand::GetCommand( const char *fileName ) const
{
cout << "GetCommand" << endl ;
string file = m_userpath + "/" + fileName ;
char buffer[SEND_BUF_SIZE] ;
bzero( buffer, sizeof(buffer) ) ;
cout << "[get]" << file << endl ;
int fd = open( file.c_str(), O_RDONLY ) ;
if ( -1 == fd )
{
cerr << "openfile:" << file << endl ;
return -1 ;
}
ssize_t rbyte = 0 ;
while ( (rbyte = read( fd, buffer, sizeof(buffer)) ) >= 0 )
{
if ( (write( m_sockfd, buffer, rbyte) ) < 0 )
{
perror( "write" ) ;
close( fd ) ;
close( m_sockfd ) ;
return -1 ;
}
if ( (rbyte < SEND_BUF_SIZE) )
{
goto done ;
}
}
done:
close( fd ) ;
cout << "GetCommand:End" << endl ;
return 0 ;
}
// upload file
int ServerCommand::PutCommand( const char *fileName ) const
{
char buffer[RECV_BUF_SIZE] ;
bzero( buffer, sizeof(buffer) ) ;
string file = m_userpath + "/" + fileName ;
cout << "[put]" << file << endl ;
int fd = open( file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644 ) ;
if ( -1 == fd )
{
cerr << "openfile:" << file << endl ;
return -1 ;
}
ssize_t rbyte = 0 ;
while ( (rbyte = read( m_sockfd, buffer, RECV_BUF_SIZE )) > 0 )
{
if ( write( fd, buffer, rbyte ) < 0 )
{
perror( "writefile" ) ;
close( fd ) ;
return -1 ;
}
cout << "rbyte:" << rbyte << endl ;
if ( (rbyte < RECV_BUF_SIZE) )
{
goto done ;
}
}
done:
cout << "Done receiving" << endl ;
return close( fd ) ;
}
int ServerCommand::HelpCommand( void ) const
{
cout << "help" << endl ;
return 0 ;
}
// change directories
int ServerCommand::CdCommand( const char *dir )
{
if ( ('/' == dir[0]) )
{
m_userpath = dir ;
}
else
{
m_userpath = m_userpath + "/" + dir ;
}
return 0 ;
}
// login on
int ServerCommand::LoginCommand( void )
{
int retval = 0 ;
UserData user ;
int replay = 0 ;
int trycount = 3 ;
retry:
// set<UserData>::iterator it ;
if ( read( m_sockfd, &user, sizeof(user) ) < 0 )
{
perror( "read" ) ;
goto error ;
}
cout << user.username << endl ;
cout << user.password << endl ;
// it = m_Datas.find( user ) ;
/*if ( m_Datas.end() != it )
{
cout << it->username << endl ;
cout << it->password << endl ;
if ( !strcmp( it->password, user.password ) )
{
replay = 0 ;
}
else
{
replay = -1 ;
}
}
else
{
replay = -1 ;
}
*/
if( ude.user_db_editor::UserDbLogin(user.username , user.password , db_user)) {
replay=0;
}
else {
replay=-1;
}
// result of verification
cout << "replay:" << replay << endl ;
write( m_sockfd, &replay, sizeof(replay) ) ;
if ( -1 == replay && trycount )
{
--trycount ;
goto retry ;
}
else if ( -1 == replay )
{
goto error ;
}
m_username = user.username ;
m_password = user.password ;
m_userpath = m_serverpath + "/" + user.username ;
done:
return retval ;
error:
retval = -1 ;
goto done ;
}
// register
int ServerCommand::LogonCommand( void )
{
int retval = 0 ;
UserData user ;
int replay = 0 ;
int trycount = 3 ;
// set<UserData>::iterator it ;
retry:
if ( read( m_sockfd, &user, sizeof(user) ) < 0 )
{
perror( "read" ) ;
goto error ;
}
cout << user.username << endl ;
cout << user.password << endl ;
// it = m_Datas.find( user ) ;
/*if ( m_Datas.end() == it )
{
m_Datas.insert( user ) ;
replay = 0 ;
}
else
{
replay = -1 ;
}
*/
if (ude.user_db_editor::DbAddUser(user.username , user.password , db_user)){
replay=0;
}
else {
replay=-1;
}
// sending result
cout << "replay:" << replay << endl ;
write( m_sockfd, &replay, sizeof(replay) ) ;
if ( -1 == replay && trycount )
{
--trycount ;
goto retry ;
}
else if ( -1 == replay )
{
goto error ;
}
m_username = user.username ;
m_password = user.password ;
m_userpath = m_serverpath + "/" + user.username ;
cout << "m_userpath" << m_userpath << endl;
if ( -1 == mkdir( m_userpath.c_str(), 0775 ) )
{
perror( "mkdir" ) ;
goto error ;
}
// m_Datas.insert( user ) ;
// if ( write( m_fd, &user, sizeof(user) ) < 0 )
// {
// perror( "m_userfile.write" ) ;
// goto error ;
// }
done:
return retval ;
error:
retval = -1 ;
goto done ;
}
// share
int ServerCommand::ShareCommand( void )
{
cout << "COMMAND_SHARE" << endl;
int retval = 0 ;
char file[256] ;
char user[256] ;
bzero( file, sizeof(file) ) ;
bzero( user, sizeof(user) ) ;
string _newfile ;
string oldfile ;
// obatain file name and username
if ( read( m_sockfd, file, sizeof(file) ) < 0 )
{
perror( "read filename" ) ;
goto error ;
}
if ( read( m_sockfd, user, sizeof(user) ) < 0 )
{
perror( "read username" ) ;
goto error ;
}
cout << file << ":" << user << endl ;
_newfile = m_serverpath + "/" + user + "/" + file ;
oldfile = m_userpath + "/" + file ;
cout << _newfile << endl ;
if ( -1 == link( oldfile.c_str(), _newfile.c_str() ) )
{
perror( "link" ) ;
goto error ;
}
done:
cout << "COMMAND_SHARE END" << endl ;
return retval ;
error:
retval = -1 ;
goto done ;
}
int ServerCommand::SendCommand( void )
{
cout << "COMMAND_SEND" << endl;
int retval = 0 ;
char user[256] ;
char message[MSG_BUF_SIZE];
bzero( user, sizeof(user));
bzero( message, sizeof(message ) );
// get receiver and message
if ( read( m_sockfd, user, sizeof(user)) < 0 )
{
perror("read username" );
goto error;
}
if (read( m_sockfd, message, sizeof(message) ) < 0 )
{
perror( " read message" );
goto error;
}
//
// DATABASE TO BE DONE
//
//
string tousers=touser;
string messages=message;
bool isRequest;
if(strcmp(message,"friend_request")==0){isRequest=1;}
else{isRequest=0;}
ude.DbAddMessage(user, m_username,isRequest, message, db_user);
cout << message << endl;
done:
cout << " COMMAND_SEND END" << endl ;
return retval;
error:
retval = -1 ;
goto done;
}
bool ServerCommand::ApproveAddFriendCommand(std::string Name2){
ude.user_db_editor::DbAddFriend(m_username, Name2, db_user);
ude.user_db_editor::DbAddFriend(Name2, m_username, db_user);
}
bool ServerCommand::RemoveFriendCommand(std::string receiverName){
ude.user_db_editor::DbRmFriend(m_username, receivername, db_user);
ude.user_db_editor::DbRmFriend(receivername,m_username, db_user);
}
int ServerCommand::RmCommand( string filename )
{
string file = m_userpath + "/" + filename ;
cout << "file:" << file << endl ;
return unlink( file.c_str() ) ;
}
bool ServerCommand::FindUser( const string &username ) const
{
UserData user( username ) ;
return m_Datas.end() != m_Datas.find( user ) ;
}
<|endoftext|> |
<commit_before>// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <utility>
#ifndef RCLCPP__MACROS_HPP_
#define RCLCPP__MACROS_HPP_
/**
* Disables the copy constructor and operator= for the given class.
*
* Use in the private section of the class.
*/
#define RCLCPP_DISABLE_COPY(...) \
__VA_ARGS__(const __VA_ARGS__ &) = delete; \
__VA_ARGS__ & operator=(const __VA_ARGS__ &) = delete;
/**
* Defines aliases and static functions for using the Class with smart pointers.
*
* Use in the public section of the class.
* Make sure to include `<memory>` in the header when using this.
*/
#define RCLCPP_SMART_PTR_DEFINITIONS(...) \
RCLCPP_SHARED_PTR_DEFINITIONS(__VA_ARGS__) \
RCLCPP_WEAK_PTR_DEFINITIONS(__VA_ARGS__) \
RCLCPP_UNIQUE_PTR_DEFINITIONS(__VA_ARGS__)
/**
* Defines aliases and static functions for using the Class with smart pointers.
*
* Same as RCLCPP_SMART_PTR_DEFINITIONS expect it excludes the static
* Class::make_unique() method definition which does not work on classes which
* are not CopyConstructable.
*
* Use in the public section of the class.
* Make sure to include `<memory>` in the header when using this.
*/
#define RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(...) \
RCLCPP_SHARED_PTR_DEFINITIONS(__VA_ARGS__) \
RCLCPP_WEAK_PTR_DEFINITIONS(__VA_ARGS__) \
__RCLCPP_UNIQUE_PTR_ALIAS(__VA_ARGS__)
/**
* Defines aliases only for using the Class with smart pointers.
*
* Same as RCLCPP_SMART_PTR_DEFINITIONS expect it excludes the static
* method definitions which do not work on pure virtual classes and classes
* which are not CopyConstructable.
*
* Use in the public section of the class.
* Make sure to include `<memory>` in the header when using this.
*/
#define RCLCPP_SMART_PTR_ALIASES_ONLY(...) \
__RCLCPP_SHARED_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_WEAK_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_MAKE_SHARED_DEFINITION(__VA_ARGS__)
#define __RCLCPP_SHARED_PTR_ALIAS(...) \
using SharedPtr = std::shared_ptr<__VA_ARGS__>; \
using ConstSharedPtr = std::shared_ptr<const __VA_ARGS__>;
#define __RCLCPP_MAKE_SHARED_DEFINITION(...) \
template<typename ... Args> \
static std::shared_ptr<__VA_ARGS__> \
make_shared(Args && ... args) \
{ \
return std::make_shared<__VA_ARGS__>(std::forward<Args>(args) ...); \
}
/// Defines aliases and static functions for using the Class with shared_ptrs.
#define RCLCPP_SHARED_PTR_DEFINITIONS(...) \
__RCLCPP_SHARED_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_MAKE_SHARED_DEFINITION(__VA_ARGS__)
#define __RCLCPP_WEAK_PTR_ALIAS(...) \
using WeakPtr = std::weak_ptr<__VA_ARGS__>; \
using ConstWeakPtr = std::weak_ptr<const __VA_ARGS__>;
/// Defines aliases and static functions for using the Class with weak_ptrs.
#define RCLCPP_WEAK_PTR_DEFINITIONS(...) __RCLCPP_WEAK_PTR_ALIAS(__VA_ARGS__)
#define __RCLCPP_UNIQUE_PTR_ALIAS(...) using UniquePtr = std::unique_ptr<__VA_ARGS__>;
#define __RCLCPP_MAKE_UNIQUE_DEFINITION(...) \
template<typename ... Args> \
static std::unique_ptr<__VA_ARGS__> \
make_unique(Args && ... args) \
{ \
return std::unique_ptr<__VA_ARGS__>(new __VA_ARGS__(std::forward<Args>(args) ...)); \
}
/// Defines aliases and static functions for using the Class with unique_ptrs.
#define RCLCPP_UNIQUE_PTR_DEFINITIONS(...) \
__RCLCPP_UNIQUE_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_MAKE_UNIQUE_DEFINITION(__VA_ARGS__)
#define RCLCPP_STRING_JOIN(arg1, arg2) RCLCPP_DO_STRING_JOIN(arg1, arg2)
#define RCLCPP_DO_STRING_JOIN(arg1, arg2) arg1 ## arg2
#define RCLCPP_INFO(Args) std::cout << Args << std::endl;
#endif // RCLCPP__MACROS_HPP_
<commit_msg>macros: fix two minor typos in doxygen. (#386)<commit_after>// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <utility>
#ifndef RCLCPP__MACROS_HPP_
#define RCLCPP__MACROS_HPP_
/**
* Disables the copy constructor and operator= for the given class.
*
* Use in the private section of the class.
*/
#define RCLCPP_DISABLE_COPY(...) \
__VA_ARGS__(const __VA_ARGS__ &) = delete; \
__VA_ARGS__ & operator=(const __VA_ARGS__ &) = delete;
/**
* Defines aliases and static functions for using the Class with smart pointers.
*
* Use in the public section of the class.
* Make sure to include `<memory>` in the header when using this.
*/
#define RCLCPP_SMART_PTR_DEFINITIONS(...) \
RCLCPP_SHARED_PTR_DEFINITIONS(__VA_ARGS__) \
RCLCPP_WEAK_PTR_DEFINITIONS(__VA_ARGS__) \
RCLCPP_UNIQUE_PTR_DEFINITIONS(__VA_ARGS__)
/**
* Defines aliases and static functions for using the Class with smart pointers.
*
* Same as RCLCPP_SMART_PTR_DEFINITIONS except it excludes the static
* Class::make_unique() method definition which does not work on classes which
* are not CopyConstructable.
*
* Use in the public section of the class.
* Make sure to include `<memory>` in the header when using this.
*/
#define RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(...) \
RCLCPP_SHARED_PTR_DEFINITIONS(__VA_ARGS__) \
RCLCPP_WEAK_PTR_DEFINITIONS(__VA_ARGS__) \
__RCLCPP_UNIQUE_PTR_ALIAS(__VA_ARGS__)
/**
* Defines aliases only for using the Class with smart pointers.
*
* Same as RCLCPP_SMART_PTR_DEFINITIONS except it excludes the static
* method definitions which do not work on pure virtual classes and classes
* which are not CopyConstructable.
*
* Use in the public section of the class.
* Make sure to include `<memory>` in the header when using this.
*/
#define RCLCPP_SMART_PTR_ALIASES_ONLY(...) \
__RCLCPP_SHARED_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_WEAK_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_MAKE_SHARED_DEFINITION(__VA_ARGS__)
#define __RCLCPP_SHARED_PTR_ALIAS(...) \
using SharedPtr = std::shared_ptr<__VA_ARGS__>; \
using ConstSharedPtr = std::shared_ptr<const __VA_ARGS__>;
#define __RCLCPP_MAKE_SHARED_DEFINITION(...) \
template<typename ... Args> \
static std::shared_ptr<__VA_ARGS__> \
make_shared(Args && ... args) \
{ \
return std::make_shared<__VA_ARGS__>(std::forward<Args>(args) ...); \
}
/// Defines aliases and static functions for using the Class with shared_ptrs.
#define RCLCPP_SHARED_PTR_DEFINITIONS(...) \
__RCLCPP_SHARED_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_MAKE_SHARED_DEFINITION(__VA_ARGS__)
#define __RCLCPP_WEAK_PTR_ALIAS(...) \
using WeakPtr = std::weak_ptr<__VA_ARGS__>; \
using ConstWeakPtr = std::weak_ptr<const __VA_ARGS__>;
/// Defines aliases and static functions for using the Class with weak_ptrs.
#define RCLCPP_WEAK_PTR_DEFINITIONS(...) __RCLCPP_WEAK_PTR_ALIAS(__VA_ARGS__)
#define __RCLCPP_UNIQUE_PTR_ALIAS(...) using UniquePtr = std::unique_ptr<__VA_ARGS__>;
#define __RCLCPP_MAKE_UNIQUE_DEFINITION(...) \
template<typename ... Args> \
static std::unique_ptr<__VA_ARGS__> \
make_unique(Args && ... args) \
{ \
return std::unique_ptr<__VA_ARGS__>(new __VA_ARGS__(std::forward<Args>(args) ...)); \
}
/// Defines aliases and static functions for using the Class with unique_ptrs.
#define RCLCPP_UNIQUE_PTR_DEFINITIONS(...) \
__RCLCPP_UNIQUE_PTR_ALIAS(__VA_ARGS__) \
__RCLCPP_MAKE_UNIQUE_DEFINITION(__VA_ARGS__)
#define RCLCPP_STRING_JOIN(arg1, arg2) RCLCPP_DO_STRING_JOIN(arg1, arg2)
#define RCLCPP_DO_STRING_JOIN(arg1, arg2) arg1 ## arg2
#define RCLCPP_INFO(Args) std::cout << Args << std::endl;
#endif // RCLCPP__MACROS_HPP_
<|endoftext|> |
<commit_before>//g++-5 --std=c++11 -g -o algo_dp_burst_balloons algo_dp_burst_balloons.cc
/**
* @FILE Burst Balloons
* @brief Given n balloons burst them in right order to maximize profit
*/
// https://leetcode.com/problems/burst-balloons/
#include <iostream> /* std::cout */
#include <algorithm> /* std::max */
#include <vector> /* std::vector */
using namespace std;
/**
* Given n balloons, indexed from 0 to n-1. Each balloon is painted
* with a number on it represented by array nums. You are asked to
* burst all the balloons. If the you burst balloon i you will get
* nums[left] * nums[i] * nums[right] coins. Here left and right
* are adjacent indices of i. After the burst, the left and right
* then becomes adjacent.
* Find the maximum coins you can collect by bursting the balloons wisely.
* Note:
* (1) You may imagine nums[-1] = nums[n] = 1. They are not real
* therefore you can not burst them.
* (2) 0 <= n <= 500, 0 <= nums[i] <= 100
* Example:
* Given [3, 1, 5, 8]
* Return 167
* nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
* coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
*/
/* Top-Down DP approach *
* In each recursive call, left and right are fixed. Calculate *
* maximum value possible within [left, right] and store it. */
int maxCoinsDP(std::vector<int>& nums, int left, int right,
std::vector<std::vector<int>>& dp) {
/* We need atleast 3 balloons to calculate coins */
if(right - left + 1 < 3) return 0;
/* If Top-Down DP has already calculated this value, skip it */
else if(dp[left][right]) return dp[left][right];
/* Try popping all balloons inbetween left and right */
for(int i = left + 1; i < right; ++i) {
/* Calculate the value of the balloon we just popped */
auto cur = nums[left] * nums[i] * nums[right];
/* Calculate value of remaining balloon to left & right */
if(i - left + 1 >= 3) cur += maxCoinsDP(nums, left, i, dp);
if(right- i + 1 >= 3) cur += maxCoinsDP(nums, i, right, dp);
dp[left][right] = std::max(dp[left][right], cur);
}
return dp[left][right];
}
int maxCoins1(std::vector<int>& nums) {
/* Burst every balloon that has a value of 0 */
for(auto it = nums.begin(); it != nums.end();) {
if(*it == 0) nums.erase(it);
else ++it;
}
/* Add a balloon of value 1 to left and right */
nums.push_back(1); nums.insert(nums.begin(), 1);
vector<vector<int>> dp(nums.size(), vector<int>(nums.size(), 0));
return maxCoinsDP(nums, 0, nums.size() - 1, dp);
}
struct test_vector {
std::vector<int> nums;
int exp_profit;
};
const struct test_vector test[3] = {
{ {1,2,3,4}, 40},
{ {3,1,5,8}, 167},
{ {5,0,1,3}, 35},
{ {125,6,5,0,1,3,0,0}, 6140},
};
int main()
{
for(auto tst : test) {
auto ans = maxCoins1(tst.nums);
if(ans != tst.exp_profit) {
cout << "Error:maxCoins1 failed for: ";
for(auto v : tst.nums) cout << v << ",";
cout << endl;
cout << " Exp: " << tst.exp_profit
<< " Got: " << ans << endl;
return -1;
}
}
cout << "Info: All manual testcases passed" << endl;
return 0;
}
<commit_msg>Fix Travis build break -- incorrect #arguments for test-case DP balloons<commit_after>//g++-5 --std=c++11 -g -o algo_dp_burst_balloons algo_dp_burst_balloons.cc
/**
* @FILE Burst Balloons
* @brief Given n balloons burst them in right order to maximize profit
*/
// https://leetcode.com/problems/burst-balloons/
#include <iostream> /* std::cout */
#include <algorithm> /* std::max */
#include <vector> /* std::vector */
using namespace std;
/**
* Given n balloons, indexed from 0 to n-1. Each balloon is painted
* with a number on it represented by array nums. You are asked to
* burst all the balloons. If the you burst balloon i you will get
* nums[left] * nums[i] * nums[right] coins. Here left and right
* are adjacent indices of i. After the burst, the left and right
* then becomes adjacent.
* Find the maximum coins you can collect by bursting the balloons wisely.
* Note:
* (1) You may imagine nums[-1] = nums[n] = 1. They are not real
* therefore you can not burst them.
* (2) 0 <= n <= 500, 0 <= nums[i] <= 100
* Example:
* Given [3, 1, 5, 8]
* Return 167
* nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
* coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
*/
/* Top-Down DP approach *
* In each recursive call, left and right are fixed. Calculate *
* maximum value possible within [left, right] and store it. */
int maxCoinsDP(std::vector<int>& nums, int left, int right,
std::vector<std::vector<int>>& dp) {
/* We need atleast 3 balloons to calculate coins */
if(right - left + 1 < 3) return 0;
/* If Top-Down DP has already calculated this value, skip it */
else if(dp[left][right]) return dp[left][right];
/* Try popping all balloons inbetween left and right */
for(int i = left + 1; i < right; ++i) {
/* Calculate the value of the balloon we just popped */
auto cur = nums[left] * nums[i] * nums[right];
/* Calculate value of remaining balloon to left & right */
if(i - left + 1 >= 3) cur += maxCoinsDP(nums, left, i, dp);
if(right- i + 1 >= 3) cur += maxCoinsDP(nums, i, right, dp);
dp[left][right] = std::max(dp[left][right], cur);
}
return dp[left][right];
}
int maxCoins1(std::vector<int>& nums) {
/* Burst every balloon that has a value of 0 */
for(auto it = nums.begin(); it != nums.end();) {
if(*it == 0) nums.erase(it);
else ++it;
}
/* Add a balloon of value 1 to left and right */
nums.push_back(1); nums.insert(nums.begin(), 1);
vector<vector<int>> dp(nums.size(), vector<int>(nums.size(), 0));
return maxCoinsDP(nums, 0, nums.size() - 1, dp);
}
struct test_vector {
std::vector<int> nums;
int exp_profit;
};
const struct test_vector test[4] = {
{ {1,2,3,4}, 40},
{ {3,1,5,8}, 167},
{ {5,0,1,3}, 35},
{ {125,6,5,0,1,3,0,0}, 6140},
};
int main()
{
for(auto tst : test) {
auto ans = maxCoins1(tst.nums);
if(ans != tst.exp_profit) {
cout << "Error:maxCoins1 failed for: ";
for(auto v : tst.nums) cout << v << ",";
cout << endl;
cout << " Exp: " << tst.exp_profit
<< " Got: " << ans << endl;
return -1;
}
}
cout << "Info: All manual testcases passed" << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <Rcpp.h>
#include <tuple>
#include "craam/fastopt.hpp"
/// Computes the maximum distribution subject to L1 constraints
//[[Rcpp::export]]
Rcpp::List worstcase_l1(Rcpp::NumericVector z, Rcpp::NumericVector q, double t){
// resulting probability
craam::numvec p;
// resulting objective value
double objective;
craam::numvec vz(z.begin(), z.end()), vq(q.begin(), q.end());
std::tie(p,objective) = craam::worstcase_l1(vz,vq,t);
Rcpp::List result;
result["p"] = Rcpp::NumericVector(p.cbegin(), p.cend());
result["obj"] = objective;
return result;
}
<commit_msg>added a space<commit_after>#include <Rcpp.h>
#include <tuple>
#include "craam/fastopt.hpp"
/// Computes the maximum distribution subject to L1 constraints
// [[Rcpp::export]]
Rcpp::List worstcase_l1(Rcpp::NumericVector z, Rcpp::NumericVector q, double t){
// resulting probability
craam::numvec p;
// resulting objective value
double objective;
craam::numvec vz(z.begin(), z.end()), vq(q.begin(), q.end());
std::tie(p,objective) = craam::worstcase_l1(vz,vq,t);
Rcpp::List result;
result["p"] = Rcpp::NumericVector(p.cbegin(), p.cend());
result["obj"] = objective;
return result;
}
<|endoftext|> |
<commit_before>#include "ProcessEvent.h"
#if defined(__linux__) /* Linux 2.6.15+ */
// Linux
#include <linux/netlink.h>
#include <linux/connector.h>
#include <linux/cn_proc.h>
// PDTK
#include <cxxutils/posix_helpers.h>
#include <cxxutils/socket_helpers.h>
#include <cxxutils/vterm.h>
#include <cassert>
// process flags
static constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept
{
return
(flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) |
(flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) |
(flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ;
}
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | // Process called exec*()
(flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | // Process exited
(flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; // Process forked
}
struct ProcessEvent::platform_dependant // process notification (process events connector)
{
posix::fd_t fd;
std::unordered_multimap<pid_t, ProcessEvent::Flags_t> events;
platform_dependant(void) noexcept
: fd(posix::invalid_descriptor)
{
fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector);
flaw(fd == posix::invalid_descriptor,
terminal::warning,,,
"Unable to open a netlink socket for Process Events Connector: %s", std::strerror(errno))
sockaddr_nl sa_nl;
sa_nl.nl_family = PF_NETLINK;
sa_nl.nl_groups = CN_IDX_PROC;
sa_nl.nl_pid = getpid();
flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)),
terminal::warning,,,
"Process Events Connector requires root level access: %s", std::strerror(errno))
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procconn_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_cn_mcast_op operation;
} procconn;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), "compiler needs to pack struct");
std::memset(&procconn, 0, sizeof(procconn));
procconn.header.nlmsg_len = sizeof(procconn);
procconn.header.nlmsg_pid = getpid();
procconn.header.nlmsg_type = NLMSG_DONE;
procconn.message.id.idx = CN_IDX_PROC;
procconn.message.id.val = CN_VAL_PROC;
procconn.message.len = sizeof(proc_cn_mcast_op);
procconn.operation = PROC_CN_MCAST_LISTEN;
flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response,
terminal::warning,,,
"Failed to enable Process Events Connector notifications: %s", std::strerror(errno))
}
~platform_dependant(void) noexcept
{
posix::close(fd);
fd = posix::invalid_descriptor;
}
posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept
{
auto iter = events.emplace(pid, flags);
// add filter installation code here
return iter->first;
}
bool remove(pid_t pid) noexcept
{
if(!events.erase(pid)) // erase all the entries for that PID
return false; // no entries found
// add filter removal code here
return true;
}
proc_event read(posix::fd_t procfd) noexcept
{
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procmsg_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_event event;
} procmsg;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), "compiler needs to pack struct");
pollfd fds = { procfd, POLLIN, 0 };
while(posix::poll(&fds, 1, 0) > 0) // while there are messages
{
if(posix::recv(fd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) // read process event message
return procmsg.event;
}
assert(false);
return {};
}
} ProcessEvent::s_platform;
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
m_fd = s_platform.add(m_pid, m_flags);
EventBackend::add(m_fd, EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{
proc_event data = s_platform.read(lambda_fd);
switch(from_native_flags(data.what))
{
case Flags::Exec:
Object::enqueue(execed,
data.event_data.exec.process_pid);
break;
case Flags::Exit:
Object::enqueue(exited,
data.event_data.exit.process_pid,
*reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code));
break;
case Flags::Fork:
Object::enqueue(forked,
data.event_data.fork.parent_pid,
data.event_data.fork.child_pid);
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags);
assert(s_platform.remove(m_pid));
}
#elif (defined(__APPLE__) && defined(__MACH__)) /* Darwin 7+ */ || \
defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \
defined(__DragonFly__) /* DragonFly BSD */ || \
defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \
defined(__NetBSD__) /* NetBSD 2+ */
#include <sys/event.h> // kqueue
static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept
{ return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }
static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)
{ return (flags & subset) == subset; }
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) |
(flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) |
(flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ;
}
static constexpr ushort extract_filter(native_flags_t flags) noexcept
{ return (flags >> 16) & 0xFFFF; }
static constexpr uint32_t extract_flags(native_flags_t flags) noexcept
{ return flags >> 32; }
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
EventBackend::add(m_pid, to_native_flags(m_flags),
[this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept
{
uint32_t data = extract_flags(lambda_fd);
switch(extract_filter(lambda_fd))
{
case Flags::Exec:
Object::enqueue(execed, m_pid);
break;
case Flags::Exit:
Object::enqueue(exited, m_pid,
*reinterpret_cast<posix::error_t*>(&data));
break;
case Flags::Fork:
Object::enqueue(forked, m_pid,
*reinterpret_cast<pid_t*>(&data));
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_pid, to_native_flags(m_flags)); // disconnect FD with flags from signal
}
#elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos
# error No process event backend code exists in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch!
#elif defined(__minix) // MINIX
# error No process event backend code exists in PDTK for MINIX! Please submit a patch!
#elif defined(__QNX__) // QNX
// QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html
# error No process event backend code exists in PDTK for QNX! Please submit a patch!
#elif defined(__hpux) // HP-UX
# error No process event backend code exists in PDTK for HP-UX! Please submit a patch!
#elif defined(_AIX) // IBM AIX
# error No process event backend code exists in PDTK for IBM AIX! Please submit a patch!
#elif defined(BSD)
# error Unrecognized BSD derivative!
#elif defined(__unix__) || defined(__unix)
# error Unrecognized UNIX variant!
#else
# error This platform is not supported.
#endif
<commit_msg>fixed Linux support<commit_after>#include "ProcessEvent.h"
#include <specialized/eventbackend.h>
#if defined(__linux__)
#include <linux/version.h>
#endif
#if defined(__linux__) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) /* Linux 2.6.15+ */
// Linux
#include <linux/netlink.h>
#include <linux/connector.h>
#include <linux/cn_proc.h>
// PDTK
#include <cxxutils/posix_helpers.h>
#include <cxxutils/socket_helpers.h>
#include <cxxutils/vterm.h>
#include <specialized/procstat.h>
enum {
Read = 0,
Write = 1,
};
struct message_t
{
union {
ProcessEvent::Flags action;
uint32_t : 0;
};
pid_t pid;
};
static_assert(sizeof(message_t) == sizeof(uint64_t), "unexpected struct size");
// process flags
static constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept
{
return
(flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) |
(flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) |
(flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ;
}
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | // Process called exec*()
(flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | // Process exited
(flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; // Process forked
}
struct ProcessEvent::platform_dependant // process notification (process events connector)
{
posix::fd_t fd;
struct eventinfo_t
{
posix::fd_t fd[2];
ProcessEvent::Flags_t flags;
};
std::unordered_map<pid_t, eventinfo_t> events;
platform_dependant(void) noexcept
{
fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector);
flaw(fd == posix::invalid_descriptor,
terminal::warning,,,
"Unable to open a netlink socket for Process Events Connector: %s", std::strerror(errno))
sockaddr_nl sa_nl;
sa_nl.nl_family = PF_NETLINK;
sa_nl.nl_groups = CN_IDX_PROC;
sa_nl.nl_pid = uint32_t(getpid());
flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)),
terminal::warning,,,
"Process Events Connector requires root level access: %s", std::strerror(errno));
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procconn_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_cn_mcast_op operation;
} procconn;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), "compiler needs to pack struct");
std::memset(&procconn, 0, sizeof(procconn));
procconn.header.nlmsg_len = sizeof(procconn);
procconn.header.nlmsg_pid = uint32_t(getpid());
procconn.header.nlmsg_type = NLMSG_DONE;
procconn.message.id.idx = CN_IDX_PROC;
procconn.message.id.val = CN_VAL_PROC;
procconn.message.len = sizeof(proc_cn_mcast_op);
procconn.operation = PROC_CN_MCAST_LISTEN;
flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response,
terminal::warning,,,
"Failed to enable Process Events Connector notifications: %s", std::strerror(errno));
EventBackend::add(fd, EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept { read(lambda_fd); });
std::fprintf(stderr, "%s%s\n", terminal::information, "Process Events Connector active");
}
~platform_dependant(void) noexcept
{
EventBackend::remove(fd, EventBackend::SimplePollReadFlags);
posix::close(fd);
fd = posix::invalid_descriptor;
}
posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept
{
eventinfo_t event;
event.flags = flags;
if(!posix::pipe(event.fd))
return posix::invalid_descriptor;
auto iter = events.emplace(pid, event);
// add filter installation code here
return event.fd[Read];
}
bool remove(pid_t pid) noexcept
{
auto iter = events.find(pid);
if(iter == events.end())
return false;
// add filter removal code here
posix::close(iter->second.fd[Read]);
posix::close(iter->second.fd[Write]);
events.erase(iter);
return true;
}
void read(posix::fd_t procfd) noexcept
{
#pragma pack(push, 1)
struct alignas(NLMSG_ALIGNTO) procmsg_t // 32-bit alignment
{
nlmsghdr header; // 16 bytes
cn_msg message;
proc_event event;
} procmsg;
#pragma pack(pop)
static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), "compiler needs to pack struct");
pollfd fds = { procfd, POLLIN, 0 };
while(posix::poll(&fds, 1, 0) > 0 && // while there are messages AND
posix::recv(procfd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) // read process event message
{
auto iter = events.find(procmsg.event.event_data.id.process_pid);
if(iter != events.end())
posix::write(iter->second.fd[Write], &procmsg.event, sizeof(procmsg.event));
}
}
} ProcessEvent::s_platform;
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
m_fd = s_platform.add(m_pid, m_flags);
EventBackend::add(m_fd, EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{
proc_event data;
pollfd fds = { lambda_fd, POLLIN, 0 };
while(posix::poll(&fds, 1, 0) > 0 &&
posix::read(lambda_fd, &data, sizeof(data)) > 0)
switch(from_native_flags(data.what))
{
case Flags::Exec:
Object::enqueue(execed,
data.event_data.exec.process_pid);
break;
case Flags::Exit:
Object::enqueue(exited,
data.event_data.exit.process_pid,
*reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code));
break;
case Flags::Fork:
Object::enqueue(forked,
data.event_data.fork.parent_pid,
data.event_data.fork.child_pid);
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags);
s_platform.remove(m_pid);
}
#elif (defined(__APPLE__) && defined(__MACH__)) /* Darwin 7+ */ || \
defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \
defined(__DragonFly__) /* DragonFly BSD */ || \
defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \
defined(__NetBSD__) /* NetBSD 2+ */
#include <sys/event.h> // kqueue
static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept
{ return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }
static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)
{ return (flags & subset) == subset; }
static constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept
{
return
(flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) |
(flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) |
(flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ;
}
static constexpr ushort extract_filter(native_flags_t flags) noexcept
{ return (flags >> 16) & 0xFFFF; }
static constexpr uint32_t extract_flags(native_flags_t flags) noexcept
{ return flags >> 32; }
ProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept
: m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)
{
EventBackend::add(m_pid, to_native_flags(m_flags),
[this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept
{
uint32_t data = extract_flags(lambda_fd);
switch(extract_filter(lambda_fd))
{
case Flags::Exec:
Object::enqueue(execed, m_pid);
break;
case Flags::Exit:
Object::enqueue(exited, m_pid,
*reinterpret_cast<posix::error_t*>(&data));
break;
case Flags::Fork:
Object::enqueue(forked, m_pid,
*reinterpret_cast<pid_t*>(&data));
break;
}
});
}
ProcessEvent::~ProcessEvent(void) noexcept
{
EventBackend::remove(m_pid, to_native_flags(m_flags)); // disconnect FD with flags from signal
}
#elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos
# error No process event backend code exists in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch!
#elif defined(__minix) // MINIX
# error No process event backend code exists in PDTK for MINIX! Please submit a patch!
#elif defined(__QNX__) // QNX
// QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html
# error No process event backend code exists in PDTK for QNX! Please submit a patch!
#elif defined(__hpux) // HP-UX
# error No process event backend code exists in PDTK for HP-UX! Please submit a patch!
#elif defined(_AIX) // IBM AIX
# error No process event backend code exists in PDTK for IBM AIX! Please submit a patch!
#elif defined(BSD)
# error Unrecognized BSD derivative!
#elif defined(__unix__) || defined(__unix)
# error Unrecognized UNIX variant!
#else
# error This platform is not supported.
#endif
<|endoftext|> |
<commit_before>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "page_taskmanager.h"
#include "ui_page_taskmanager.h" //auto-generated from the .ui file
#define refreshRate 3000
#define memStyle QString("QLabel{background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:%1p rgb(100,100,200), stop:%2pa rgb(200,100,100), stop:%2pb rgb(200,100,100), stop:%3pa rgb(100,200,100), stop:%3pb rgb(100,200,100), stop:%4pa rgb(230, 230, 230), stop:%4pb rgb(230, 230, 230), stop:%5p white);\nborder: 1px solid black;\nborder-radius: 3px;}")
taskmanager_page::taskmanager_page(QWidget *parent, sysadm_client *core) : PageWidget(parent, core), ui(new Ui::taskmanager_ui){
ui->setupUi(this);
connect(ui->push_kill, SIGNAL(clicked()), this, SLOT(slot_kill_proc()) );
}
taskmanager_page::~taskmanager_page(){
}
//Initialize the CORE <-->Page connections
void taskmanager_page::setupCore(){
connect(CORE, SIGNAL(newReply(QString, QString, QString, QJsonValue)), this, SLOT(ParseReply(QString, QString, QString, QJsonValue)) );
}
//Page embedded, go ahead and startup any core requests
void taskmanager_page::startPage(){
//Let the main window know the name of this page
emit ChangePageTitle( tr("Task Manager") );
//Now run any CORE communications
slotRequestProcInfo();
slotRequestMemInfo();
slotRequestCPUInfo();
slotRequestCPUTempInfo();
qDebug() << "Start page!";
}
// === PRIVATE SLOTS ===
void taskmanager_page::ParseReply(QString id, QString namesp, QString name, QJsonValue args){
if( !id.startsWith("page_task_man_")){ return; }
// qDebug() << "reply" << id;
// Read in the PID list
if ( id == "page_task_man_taskquery")
{
if ( ! args.isObject() )
return;
parsePIDS(args.toObject());
}
else if(id=="page_task_man_mem_check"){
if(name!="error" && namesp!="error"){
if(args.isObject() && args.toObject().contains("memorystats")){
QJsonObject memO = args.toObject().value("memorystats").toObject();
//qDebug() << "Got memory info:" << args << memO;
int active, cache, freeM, inactive, wired; //MB
active = cache = freeM = inactive = wired = 0;
if(memO.contains("active")){ active = memO.value("active").toString().toInt(); }
if(memO.contains("cache")){ cache = memO.value("cache").toString().toInt(); }
if(memO.contains("free")){ freeM = memO.value("free").toString().toInt(); }
if(memO.contains("inactive")){ inactive = memO.value("inactive").toString().toInt(); }
if(memO.contains("wired")){ wired = memO.value("wired").toString().toInt(); }
ShowMemInfo(active, cache, freeM, inactive, wired);
}
}
}else if(id=="page_task_man_cpu_check" && name!="error" && namesp!="error" ){
//CPU usage
qDebug() << "Got CPU Usage:" << args;
}else if(id=="page_task_man_cputemp_check" && name!="error" && namesp!="error" ){
//CPU Temperature
qDebug() << "Got CPU Temps:" << args;
}
}
void taskmanager_page::parsePIDS(QJsonObject jsobj)
{
//ui->taskWidget->clear();
//qDebug() << "KEYS" << jsobj.keys();
QStringList keys = jsobj.keys();
if (keys.contains("message") ) {
qDebug() << "MESSAGE" << jsobj.value("message").toString();
return;
}
// Look for procinfo
QJsonObject procobj = jsobj.value("procinfo").toObject();
QStringList pids = procobj.keys();
int doEvents = 0;
for ( int i=0; i < pids.size(); i++ )
{
doEvents++;
if ( doEvents > 50 ) {
doEvents=0;
QApplication::processEvents();
}
QString PID = pids.at(i);
QJsonObject pidinfo = procobj.value(PID).toObject();
// Check if we have this PID already
QList<QTreeWidgetItem *> foundItems = ui->taskWidget->findItems(PID, Qt::MatchExactly, 0);
if ( ! foundItems.isEmpty() )
{
foundItems.at(0)->setText(1, pidinfo.value("username").toString());
foundItems.at(0)->setText(2, pidinfo.value("thr").toString());
foundItems.at(0)->setText(3, pidinfo.value("pri").toString());
foundItems.at(0)->setText(4, pidinfo.value("nice").toString());
foundItems.at(0)->setText(5, pidinfo.value("size").toString());
foundItems.at(0)->setText(6, pidinfo.value("res").toString());
foundItems.at(0)->setText(7, pidinfo.value("state").toString());
foundItems.at(0)->setText(8, pidinfo.value("cpu").toString());
foundItems.at(0)->setText(9, pidinfo.value("time").toString());
foundItems.at(0)->setText(10, pidinfo.value("wcpu").toString());
foundItems.at(0)->setText(11, pidinfo.value("command").toString());
} else {
// Create the new taskWidget item
new QTreeWidgetItem(ui->taskWidget, QStringList() << PID
<< pidinfo.value("username").toString()
<< pidinfo.value("thr").toString()
<< pidinfo.value("pri").toString()
<< pidinfo.value("nice").toString()
<< pidinfo.value("size").toString()
<< pidinfo.value("res").toString()
<< pidinfo.value("state").toString()
<< pidinfo.value("cpu").toString()
<< pidinfo.value("time").toString()
<< pidinfo.value("wcpu").toString()
<< pidinfo.value("command").toString()
);
}
}
// Now loop through the UI and look for pids to remove
for ( int i=0; i<ui->taskWidget->topLevelItemCount(); i++ ) {
// Check if this item exists in the PID list
if ( ! pids.contains(ui->taskWidget->topLevelItem(i)->text(0)) ) {
// No? Remove it
ui->taskWidget->takeTopLevelItem(i);
}
}
// Resize the widget to the new contents
ui->taskWidget->header()->resizeSections(QHeaderView::ResizeToContents);
ui->taskWidget->sortItems(10, Qt::DescendingOrder);
}
void taskmanager_page::ShowMemInfo(int active, int cache, int freeM, int inactive, int wired){
//assemble the stylesheet
int total = active+cache+freeM+inactive+wired;
QString style = memStyle;
QString TT = tr("Memory Stats (MB)")+"\n";
TT.append( QString(tr(" - Total: %1")).arg(QString::number(total))+"\n");
// Wired memory
double perc = qRound( 10000.0* (wired/( (double) total)) )/10000.0;
double laststop = 0;
TT.append( QString(tr(" - Wired: %1 (%2)")).arg(QString::number(wired), QString::number(perc*100.0)+"%") +"\n");
style.replace("%1p",QString::number(perc)); //placement
style.replace("%2pa",QString::number(perc+0.00001)); //start of next section
laststop = perc+0.00001;
double totperc = perc;
//Active memory
perc = qRound( 10000.0* (active/( (double) total)) )/10000.0;
totperc+=perc;
TT.append( QString(tr(" - Active: %1 (%2)")).arg(QString::number(active), QString::number(perc*100.0)+"%") +"\n");
style.replace("%2pb",QString::number( (totperc>laststop) ? totperc : (laststop+0.000001) ));
style.replace("%3pa",QString::number(totperc+0.00001)); //start of next section
laststop = totperc+0.00001;
//cache memory
perc = qRound( 10000.0* (cache/( (double) total)) )/10000.0;
totperc+=perc;
TT.append( QString(tr(" - Cache: %1 (%2)")).arg(QString::number(cache), QString::number(perc*100.0)+"%")+"\n" );
style.replace("%3pb",QString::number( (totperc>laststop) ? totperc : (laststop+0.000001) ));
style.replace("%4pa",QString::number(totperc+0.0001) ); //start of next section
laststop = totperc+0.0001;
ui->label_mem_stats->setText( QString(tr("Total Memory: %1 MB, Used: %2%")).arg(QString::number(total), QString::number(totperc*100.0)) );
//inactive memory
perc = qRound( 10000.0* (inactive/( (double) total)) )/10000.0;
totperc+=perc;
TT.append( QString(tr(" - Inactive: %1 (%2)")).arg(QString::number(inactive), QString::number(perc*100.0)+"%") +"\n");
style.replace("%4pb",QString::number( (totperc>laststop) ? totperc : (laststop+0.000001) ));
style.replace("%5p",QString::number(totperc+0.00001)); //start of next section
//free memory
TT.append( QString(tr(" - Free: %1 (%2)")).arg(QString::number(freeM), QString::number((1-totperc)*100.0)+"%") );
//Now set the widgets
//qDebug() << "styleSheet:" << style;
ui->label_mem_stats->setToolTip(TT);
ui->label_mem_stats->setStyleSheet(style);
}
void taskmanager_page::slotRequestProcInfo(){
QJsonObject jsobj;
jsobj.insert("action", "procinfo");
CORE->communicate("page_task_man_taskquery", "sysadm", "systemmanager", jsobj);
QTimer::singleShot(refreshRate, this, SLOT(slotRequestProcInfo()) );
}
void taskmanager_page::slotRequestMemInfo(){
QJsonObject jsobj;
jsobj.insert("action", "memorystats");
CORE->communicate("page_task_man_mem_check", "sysadm", "systemmanager", jsobj);
QTimer::singleShot(refreshRate, this, SLOT(slotRequestMemInfo()) );
}
void taskmanager_page::slotRequestCPUInfo(){
QJsonObject jsobj;
jsobj.insert("action", "cpupercentage");
CORE->communicate("page_task_man_cpu_check", "sysadm", "systemmanager", jsobj);
QTimer::singleShot(refreshRate, this, SLOT(slotRequestCPUInfo()) );
}
void taskmanager_page::slotRequestCPUTempInfo(){
QJsonObject jsobj;
jsobj.insert("action", "cputemps");
CORE->communicate("page_task_man_cputemp_check", "sysadm", "systemmanager", jsobj);
QTimer::singleShot(refreshRate, this, SLOT(slotRequestCPUTempInfo()) );
}
void taskmanager_page::slot_kill_proc(){
//get the currently-selected PID
QTreeWidgetItem *tmp = ui->taskWidget->currentItem();
if(tmp==0){ return; }
QString pid = tmp->text(0); //column 0 is the PID
//Now send the request
QJsonObject jsobj;
jsobj.insert("action", "killproc");
jsobj.insert("pid",pid);
jsobj.insert("signal","KILL");
CORE->communicate("page_task_man_kill_proc", "sysadm", "systemmanager", jsobj);
}
<commit_msg>Only start the timers after the previous response has come back. This prevents multiple identical requests being kicked off<commit_after>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "page_taskmanager.h"
#include "ui_page_taskmanager.h" //auto-generated from the .ui file
#define refreshRate 3000
#define memStyle QString("QLabel{background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:%1p rgb(100,100,200), stop:%2pa rgb(200,100,100), stop:%2pb rgb(200,100,100), stop:%3pa rgb(100,200,100), stop:%3pb rgb(100,200,100), stop:%4pa rgb(230, 230, 230), stop:%4pb rgb(230, 230, 230), stop:%5p white);\nborder: 1px solid black;\nborder-radius: 3px;}")
taskmanager_page::taskmanager_page(QWidget *parent, sysadm_client *core) : PageWidget(parent, core), ui(new Ui::taskmanager_ui){
ui->setupUi(this);
connect(ui->push_kill, SIGNAL(clicked()), this, SLOT(slot_kill_proc()) );
}
taskmanager_page::~taskmanager_page(){
}
//Initialize the CORE <-->Page connections
void taskmanager_page::setupCore(){
connect(CORE, SIGNAL(newReply(QString, QString, QString, QJsonValue)), this, SLOT(ParseReply(QString, QString, QString, QJsonValue)) );
}
//Page embedded, go ahead and startup any core requests
void taskmanager_page::startPage(){
//Let the main window know the name of this page
emit ChangePageTitle( tr("Task Manager") );
//Now run any CORE communications
slotRequestProcInfo();
slotRequestMemInfo();
slotRequestCPUInfo();
slotRequestCPUTempInfo();
qDebug() << "Start page!";
}
// === PRIVATE SLOTS ===
void taskmanager_page::ParseReply(QString id, QString namesp, QString name, QJsonValue args){
if( !id.startsWith("page_task_man_")){ return; }
// qDebug() << "reply" << id;
// Read in the PID list
if ( id == "page_task_man_taskquery")
{
if ( ! args.isObject() )
return;
parsePIDS(args.toObject());
QTimer::singleShot(refreshRate, this, SLOT(slotRequestProcInfo()) );
}
else if(id=="page_task_man_mem_check"){
if(name!="error" && namesp!="error"){
if(args.isObject() && args.toObject().contains("memorystats")){
QJsonObject memO = args.toObject().value("memorystats").toObject();
//qDebug() << "Got memory info:" << args << memO;
int active, cache, freeM, inactive, wired; //MB
active = cache = freeM = inactive = wired = 0;
if(memO.contains("active")){ active = memO.value("active").toString().toInt(); }
if(memO.contains("cache")){ cache = memO.value("cache").toString().toInt(); }
if(memO.contains("free")){ freeM = memO.value("free").toString().toInt(); }
if(memO.contains("inactive")){ inactive = memO.value("inactive").toString().toInt(); }
if(memO.contains("wired")){ wired = memO.value("wired").toString().toInt(); }
ShowMemInfo(active, cache, freeM, inactive, wired);
}
}
QTimer::singleShot(refreshRate, this, SLOT(slotRequestMemInfo()) );
}else if(id=="page_task_man_cpu_check" && name!="error" && namesp!="error" ){
//CPU usage
qDebug() << "Got CPU Usage:" << args;
QTimer::singleShot(refreshRate, this, SLOT(slotRequestCPUInfo()) );
}else if(id=="page_task_man_cputemp_check" && name!="error" && namesp!="error" ){
//CPU Temperature
qDebug() << "Got CPU Temps:" << args;
QTimer::singleShot(refreshRate, this, SLOT(slotRequestCPUTempInfo()) );
}
}
void taskmanager_page::parsePIDS(QJsonObject jsobj)
{
//ui->taskWidget->clear();
//qDebug() << "KEYS" << jsobj.keys();
QStringList keys = jsobj.keys();
if (keys.contains("message") ) {
qDebug() << "MESSAGE" << jsobj.value("message").toString();
return;
}
// Look for procinfo
QJsonObject procobj = jsobj.value("procinfo").toObject();
QStringList pids = procobj.keys();
int doEvents = 0;
for ( int i=0; i < pids.size(); i++ )
{
doEvents++;
if ( doEvents > 50 ) {
doEvents=0;
QApplication::processEvents();
}
QString PID = pids.at(i);
QJsonObject pidinfo = procobj.value(PID).toObject();
// Check if we have this PID already
QList<QTreeWidgetItem *> foundItems = ui->taskWidget->findItems(PID, Qt::MatchExactly, 0);
if ( ! foundItems.isEmpty() )
{
foundItems.at(0)->setText(1, pidinfo.value("username").toString());
foundItems.at(0)->setText(2, pidinfo.value("thr").toString());
foundItems.at(0)->setText(3, pidinfo.value("pri").toString());
foundItems.at(0)->setText(4, pidinfo.value("nice").toString());
foundItems.at(0)->setText(5, pidinfo.value("size").toString());
foundItems.at(0)->setText(6, pidinfo.value("res").toString());
foundItems.at(0)->setText(7, pidinfo.value("state").toString());
foundItems.at(0)->setText(8, pidinfo.value("cpu").toString());
foundItems.at(0)->setText(9, pidinfo.value("time").toString());
foundItems.at(0)->setText(10, pidinfo.value("wcpu").toString());
foundItems.at(0)->setText(11, pidinfo.value("command").toString());
} else {
// Create the new taskWidget item
new QTreeWidgetItem(ui->taskWidget, QStringList() << PID
<< pidinfo.value("username").toString()
<< pidinfo.value("thr").toString()
<< pidinfo.value("pri").toString()
<< pidinfo.value("nice").toString()
<< pidinfo.value("size").toString()
<< pidinfo.value("res").toString()
<< pidinfo.value("state").toString()
<< pidinfo.value("cpu").toString()
<< pidinfo.value("time").toString()
<< pidinfo.value("wcpu").toString()
<< pidinfo.value("command").toString()
);
}
}
// Now loop through the UI and look for pids to remove
for ( int i=0; i<ui->taskWidget->topLevelItemCount(); i++ ) {
// Check if this item exists in the PID list
if ( ! pids.contains(ui->taskWidget->topLevelItem(i)->text(0)) ) {
// No? Remove it
ui->taskWidget->takeTopLevelItem(i);
}
}
// Resize the widget to the new contents
ui->taskWidget->header()->resizeSections(QHeaderView::ResizeToContents);
ui->taskWidget->sortItems(10, Qt::DescendingOrder);
}
void taskmanager_page::ShowMemInfo(int active, int cache, int freeM, int inactive, int wired){
//assemble the stylesheet
int total = active+cache+freeM+inactive+wired;
QString style = memStyle;
QString TT = tr("Memory Stats (MB)")+"\n";
TT.append( QString(tr(" - Total: %1")).arg(QString::number(total))+"\n");
// Wired memory
double perc = qRound( 10000.0* (wired/( (double) total)) )/10000.0;
double laststop = 0;
TT.append( QString(tr(" - Wired: %1 (%2)")).arg(QString::number(wired), QString::number(perc*100.0)+"%") +"\n");
style.replace("%1p",QString::number(perc)); //placement
style.replace("%2pa",QString::number(perc+0.00001)); //start of next section
laststop = perc+0.00001;
double totperc = perc;
//Active memory
perc = qRound( 10000.0* (active/( (double) total)) )/10000.0;
totperc+=perc;
TT.append( QString(tr(" - Active: %1 (%2)")).arg(QString::number(active), QString::number(perc*100.0)+"%") +"\n");
style.replace("%2pb",QString::number( (totperc>laststop) ? totperc : (laststop+0.000001) ));
style.replace("%3pa",QString::number(totperc+0.00001)); //start of next section
laststop = totperc+0.00001;
//cache memory
perc = qRound( 10000.0* (cache/( (double) total)) )/10000.0;
totperc+=perc;
TT.append( QString(tr(" - Cache: %1 (%2)")).arg(QString::number(cache), QString::number(perc*100.0)+"%")+"\n" );
style.replace("%3pb",QString::number( (totperc>laststop) ? totperc : (laststop+0.000001) ));
style.replace("%4pa",QString::number(totperc+0.0001) ); //start of next section
laststop = totperc+0.0001;
ui->label_mem_stats->setText( QString(tr("Total Memory: %1 MB, Used: %2%")).arg(QString::number(total), QString::number(totperc*100.0)) );
//inactive memory
perc = qRound( 10000.0* (inactive/( (double) total)) )/10000.0;
totperc+=perc;
TT.append( QString(tr(" - Inactive: %1 (%2)")).arg(QString::number(inactive), QString::number(perc*100.0)+"%") +"\n");
style.replace("%4pb",QString::number( (totperc>laststop) ? totperc : (laststop+0.000001) ));
style.replace("%5p",QString::number(totperc+0.00001)); //start of next section
//free memory
TT.append( QString(tr(" - Free: %1 (%2)")).arg(QString::number(freeM), QString::number((1-totperc)*100.0)+"%") );
//Now set the widgets
//qDebug() << "styleSheet:" << style;
ui->label_mem_stats->setToolTip(TT);
ui->label_mem_stats->setStyleSheet(style);
}
void taskmanager_page::slotRequestProcInfo(){
QJsonObject jsobj;
jsobj.insert("action", "procinfo");
CORE->communicate("page_task_man_taskquery", "sysadm", "systemmanager", jsobj);
}
void taskmanager_page::slotRequestMemInfo(){
QJsonObject jsobj;
jsobj.insert("action", "memorystats");
CORE->communicate("page_task_man_mem_check", "sysadm", "systemmanager", jsobj);
}
void taskmanager_page::slotRequestCPUInfo(){
QJsonObject jsobj;
jsobj.insert("action", "cpupercentage");
CORE->communicate("page_task_man_cpu_check", "sysadm", "systemmanager", jsobj);
}
void taskmanager_page::slotRequestCPUTempInfo(){
QJsonObject jsobj;
jsobj.insert("action", "cputemps");
CORE->communicate("page_task_man_cputemp_check", "sysadm", "systemmanager", jsobj);
}
void taskmanager_page::slot_kill_proc(){
//get the currently-selected PID
QTreeWidgetItem *tmp = ui->taskWidget->currentItem();
if(tmp==0){ return; }
QString pid = tmp->text(0); //column 0 is the PID
//Now send the request
QJsonObject jsobj;
jsobj.insert("action", "killproc");
jsobj.insert("pid",pid);
jsobj.insert("signal","KILL");
CORE->communicate("page_task_man_kill_proc", "sysadm", "systemmanager", jsobj);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: AccessiblePageHeaderArea.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: sab $ $Date: 2002-11-27 14:21:16 $
*
* 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 _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX
#include "AccessiblePageHeaderArea.hxx"
#endif
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#ifndef SC_UNOGUARD_HXX
#include "unoguard.hxx"
#endif
#ifndef SC_EDITSRC_HXX
#include "editsrc.hxx"
#endif
#include "prevwsh.hxx"
#include "prevloc.hxx"
#ifndef SC_SCRESID_HXX
#include "scresid.hxx"
#endif
#ifndef SC_SC_HRC
#include "sc.hrc"
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _EDITOBJ_HXX
#include <svx/editobj.hxx>
#endif
#ifndef _SVX_ACCESSILE_TEXT_HELPER_HXX_
#include <svx/AccessibleTextHelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_CONVERT_HXX_
#include <toolkit/helper/convert.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
//===== internal ========================================================
ScAccessiblePageHeaderArea::ScAccessiblePageHeaderArea(
const uno::Reference<XAccessible>& rxParent,
ScPreviewShell* pViewShell,
const EditTextObject* pEditObj,
sal_Bool bHeader,
SvxAdjust eAdjust)
: ScAccessibleContextBase(rxParent, AccessibleRole::TEXT),
mpEditObj(pEditObj->Clone()),
mpTextHelper(NULL),
mpViewShell(pViewShell),
mbHeader(bHeader),
meAdjust(eAdjust)
{
if (mpViewShell)
mpViewShell->AddAccessibilityObject(*this);
}
ScAccessiblePageHeaderArea::~ScAccessiblePageHeaderArea(void)
{
if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
{
// increment refcount to prevent double call off dtor
osl_incrementInterlockedCount( &m_refCount );
dispose();
}
}
void SAL_CALL ScAccessiblePageHeaderArea::disposing()
{
ScUnoGuard aGuard;
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
if (mpTextHelper)
DELETEZ(mpTextHelper);
if (mpEditObj)
DELETEZ(mpEditObj);
ScAccessibleContextBase::disposing();
}
//===== SfxListener =====================================================
void ScAccessiblePageHeaderArea::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( SfxSimpleHint ) )
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
// only notify if child exist, otherwise it is not necessary
if (rRef.GetId() == SC_HINT_ACC_VISAREACHANGED)
{
if (mpTextHelper)
mpTextHelper->UpdateChildren();
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::ACCESSIBLE_VISIBLE_DATA_EVENT;
aEvent.Source = uno::Reference< XAccessible >(this);
CommitChange(aEvent);
}
}
ScAccessibleContextBase::Notify(rBC, rHint);
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeaderArea::getAccessibleAt(
const awt::Point& rPoint )
throw (uno::RuntimeException)
{
uno::Reference<XAccessible> xRet;
if (contains(rPoint))
{
ScUnoGuard aGuard;
IsObjectValid();
if(!mpTextHelper)
CreateTextHelper();
xRet = mpTextHelper->GetAt(rPoint);
}
return xRet;
}
//===== XAccessibleContext ==============================================
sal_Int32 SAL_CALL
ScAccessiblePageHeaderArea::getAccessibleChildCount(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChildCount();
}
uno::Reference< XAccessible > SAL_CALL
ScAccessiblePageHeaderArea::getAccessibleChild(sal_Int32 nIndex)
throw (uno::RuntimeException,
lang::IndexOutOfBoundsException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChild(nIndex);
}
uno::Reference<XAccessibleStateSet> SAL_CALL
ScAccessiblePageHeaderArea::getAccessibleStateSet(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc())
pStateSet->AddState(AccessibleStateType::DEFUNC);
else
{
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::MULTILINE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
}
return pStateSet;
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
ScAccessiblePageHeaderArea::getImplementationName(void)
throw (uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("ScAccessiblePageHeaderArea"));
}
uno::Sequence< ::rtl::OUString> SAL_CALL
ScAccessiblePageHeaderArea::getSupportedServiceNames(void)
throw (uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("drafts.com.sun.star.sheet.AccessiblePageHeaderFooterAreasView"));
return aSequence;
}
//===== XTypeProvider =======================================================
uno::Sequence<sal_Int8> SAL_CALL
ScAccessiblePageHeaderArea::getImplementationId(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
aId.realloc (16);
rtl_createUuid (reinterpret_cast<sal_uInt8 *>(aId.getArray()), 0, sal_True);
}
return aId;
}
//===== internal ==============================================================
rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleDescription(void)
throw(uno::RuntimeException)
{
rtl::OUString sDesc;
switch (meAdjust)
{
case SVX_ADJUST_LEFT :
sDesc = String(ScResId(STR_ACC_LEFTAREA_DESCR));
break;
case SVX_ADJUST_RIGHT:
sDesc = String(ScResId(STR_ACC_RIGHTAREA_DESCR));
break;
case SVX_ADJUST_CENTER:
sDesc = String(ScResId(STR_ACC_CENTERAREA_DESCR));
break;
default:
DBG_ERRORFILE("wrong adjustment found");
}
return sDesc;
}
rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleName(void)
throw (uno::RuntimeException)
{
rtl::OUString sName;
switch (meAdjust)
{
case SVX_ADJUST_LEFT :
sName = String(ScResId(STR_ACC_LEFTAREA_NAME));
break;
case SVX_ADJUST_RIGHT:
sName = String(ScResId(STR_ACC_RIGHTAREA_NAME));
break;
case SVX_ADJUST_CENTER:
sName = String(ScResId(STR_ACC_CENTERAREA_NAME));
break;
default:
DBG_ERRORFILE("wrong adjustment found");
}
return sName;
}
Rectangle ScAccessiblePageHeaderArea::GetBoundingBoxOnScreen(void) const
throw(::com::sun::star::uno::RuntimeException)
{
Rectangle aRect;
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
if (xComp.is())
{
// has the same size and position on screen like the parent
aRect = Rectangle(VCLPoint(xComp->getLocationOnScreen()), VCLRectangle(xComp->getBounds()).GetSize());
}
}
return aRect;
}
Rectangle ScAccessiblePageHeaderArea::GetBoundingBox(void) const
throw (::com::sun::star::uno::RuntimeException)
{
Rectangle aRect;
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
if (xComp.is())
{
// has the same size and position on screen like the parent and so the pos is (0, 0)
Rectangle aNewRect(Point(0, 0), VCLRectangle(xComp->getBounds()).GetSize());
aRect = aNewRect;
}
}
return aRect;
}
void ScAccessiblePageHeaderArea::CreateTextHelper()
{
if (!mpTextHelper)
{
::std::auto_ptr < ScAccessibleTextData > pAccessibleHeaderTextData
(new ScAccessibleHeaderTextData(mpViewShell, mpEditObj, mbHeader, meAdjust));
::std::auto_ptr< SvxEditSource > pEditSource (new ScAccessibilityEditSource(pAccessibleHeaderTextData));
mpTextHelper = new accessibility::AccessibleTextHelper(pEditSource );
mpTextHelper->SetEventSource(this);
}
}
<commit_msg>INTEGRATION: CWS uaa02 (1.14.128); FILE MERGED 2003/04/22 08:14:50 mt 1.14.128.1: #108656# Moved Accessibility from drafts to final<commit_after>/*************************************************************************
*
* $RCSfile: AccessiblePageHeaderArea.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: vg $ $Date: 2003-04-24 17:11:57 $
*
* 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 _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX
#include "AccessiblePageHeaderArea.hxx"
#endif
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#ifndef SC_UNOGUARD_HXX
#include "unoguard.hxx"
#endif
#ifndef SC_EDITSRC_HXX
#include "editsrc.hxx"
#endif
#include "prevwsh.hxx"
#include "prevloc.hxx"
#ifndef SC_SCRESID_HXX
#include "scresid.hxx"
#endif
#ifndef SC_SC_HRC
#include "sc.hrc"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _EDITOBJ_HXX
#include <svx/editobj.hxx>
#endif
#ifndef _SVX_ACCESSILE_TEXT_HELPER_HXX_
#include <svx/AccessibleTextHelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_CONVERT_HXX_
#include <toolkit/helper/convert.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
//===== internal ========================================================
ScAccessiblePageHeaderArea::ScAccessiblePageHeaderArea(
const uno::Reference<XAccessible>& rxParent,
ScPreviewShell* pViewShell,
const EditTextObject* pEditObj,
sal_Bool bHeader,
SvxAdjust eAdjust)
: ScAccessibleContextBase(rxParent, AccessibleRole::TEXT),
mpEditObj(pEditObj->Clone()),
mpTextHelper(NULL),
mpViewShell(pViewShell),
mbHeader(bHeader),
meAdjust(eAdjust)
{
if (mpViewShell)
mpViewShell->AddAccessibilityObject(*this);
}
ScAccessiblePageHeaderArea::~ScAccessiblePageHeaderArea(void)
{
if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
{
// increment refcount to prevent double call off dtor
osl_incrementInterlockedCount( &m_refCount );
dispose();
}
}
void SAL_CALL ScAccessiblePageHeaderArea::disposing()
{
ScUnoGuard aGuard;
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
if (mpTextHelper)
DELETEZ(mpTextHelper);
if (mpEditObj)
DELETEZ(mpEditObj);
ScAccessibleContextBase::disposing();
}
//===== SfxListener =====================================================
void ScAccessiblePageHeaderArea::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( SfxSimpleHint ) )
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
// only notify if child exist, otherwise it is not necessary
if (rRef.GetId() == SC_HINT_ACC_VISAREACHANGED)
{
if (mpTextHelper)
mpTextHelper->UpdateChildren();
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::VISIBLE_DATA_CHANGED;
aEvent.Source = uno::Reference< XAccessible >(this);
CommitChange(aEvent);
}
}
ScAccessibleContextBase::Notify(rBC, rHint);
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeaderArea::getAccessibleAtPoint(
const awt::Point& rPoint )
throw (uno::RuntimeException)
{
uno::Reference<XAccessible> xRet;
if (containsPoint(rPoint))
{
ScUnoGuard aGuard;
IsObjectValid();
if(!mpTextHelper)
CreateTextHelper();
xRet = mpTextHelper->GetAt(rPoint);
}
return xRet;
}
//===== XAccessibleContext ==============================================
sal_Int32 SAL_CALL
ScAccessiblePageHeaderArea::getAccessibleChildCount(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChildCount();
}
uno::Reference< XAccessible > SAL_CALL
ScAccessiblePageHeaderArea::getAccessibleChild(sal_Int32 nIndex)
throw (uno::RuntimeException,
lang::IndexOutOfBoundsException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChild(nIndex);
}
uno::Reference<XAccessibleStateSet> SAL_CALL
ScAccessiblePageHeaderArea::getAccessibleStateSet(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc())
pStateSet->AddState(AccessibleStateType::DEFUNC);
else
{
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::MULTI_LINE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
}
return pStateSet;
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
ScAccessiblePageHeaderArea::getImplementationName(void)
throw (uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("ScAccessiblePageHeaderArea"));
}
uno::Sequence< ::rtl::OUString> SAL_CALL
ScAccessiblePageHeaderArea::getSupportedServiceNames(void)
throw (uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sheet.AccessiblePageHeaderFooterAreasView"));
return aSequence;
}
//===== XTypeProvider =======================================================
uno::Sequence<sal_Int8> SAL_CALL
ScAccessiblePageHeaderArea::getImplementationId(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
aId.realloc (16);
rtl_createUuid (reinterpret_cast<sal_uInt8 *>(aId.getArray()), 0, sal_True);
}
return aId;
}
//===== internal ==============================================================
rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleDescription(void)
throw(uno::RuntimeException)
{
rtl::OUString sDesc;
switch (meAdjust)
{
case SVX_ADJUST_LEFT :
sDesc = String(ScResId(STR_ACC_LEFTAREA_DESCR));
break;
case SVX_ADJUST_RIGHT:
sDesc = String(ScResId(STR_ACC_RIGHTAREA_DESCR));
break;
case SVX_ADJUST_CENTER:
sDesc = String(ScResId(STR_ACC_CENTERAREA_DESCR));
break;
default:
DBG_ERRORFILE("wrong adjustment found");
}
return sDesc;
}
rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleName(void)
throw (uno::RuntimeException)
{
rtl::OUString sName;
switch (meAdjust)
{
case SVX_ADJUST_LEFT :
sName = String(ScResId(STR_ACC_LEFTAREA_NAME));
break;
case SVX_ADJUST_RIGHT:
sName = String(ScResId(STR_ACC_RIGHTAREA_NAME));
break;
case SVX_ADJUST_CENTER:
sName = String(ScResId(STR_ACC_CENTERAREA_NAME));
break;
default:
DBG_ERRORFILE("wrong adjustment found");
}
return sName;
}
Rectangle ScAccessiblePageHeaderArea::GetBoundingBoxOnScreen(void) const
throw(::com::sun::star::uno::RuntimeException)
{
Rectangle aRect;
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
if (xComp.is())
{
// has the same size and position on screen like the parent
aRect = Rectangle(VCLPoint(xComp->getLocationOnScreen()), VCLRectangle(xComp->getBounds()).GetSize());
}
}
return aRect;
}
Rectangle ScAccessiblePageHeaderArea::GetBoundingBox(void) const
throw (::com::sun::star::uno::RuntimeException)
{
Rectangle aRect;
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
if (xComp.is())
{
// has the same size and position on screen like the parent and so the pos is (0, 0)
Rectangle aNewRect(Point(0, 0), VCLRectangle(xComp->getBounds()).GetSize());
aRect = aNewRect;
}
}
return aRect;
}
void ScAccessiblePageHeaderArea::CreateTextHelper()
{
if (!mpTextHelper)
{
::std::auto_ptr < ScAccessibleTextData > pAccessibleHeaderTextData
(new ScAccessibleHeaderTextData(mpViewShell, mpEditObj, mbHeader, meAdjust));
::std::auto_ptr< SvxEditSource > pEditSource (new ScAccessibilityEditSource(pAccessibleHeaderTextData));
mpTextHelper = new ::accessibility::AccessibleTextHelper(pEditSource );
mpTextHelper->SetEventSource(this);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <cstdlib>
#include <ctime>
#include <rapidjson/document.h>
#include <picojson.h>
#include <rabbit.hpp>
void print(int score, const std::string& title, const std::string& url)
{
std::cerr << "(" << score << ") " << title << " - " << url << std::endl;
}
template <typename Bench>
struct runner
{
Bench bench;
std::string json;
int score;
int try_count;
runner()
: score(0)
, try_count(0)
{
std::ifstream ifs("hot.json");
std::istreambuf_iterator<char> it(ifs), last;
json = std::string(it, last);
}
void run(int n)
{
try
{
std::clock_t t = std::clock();
while (n-- > 0)
bench(json);
score += (std::clock() - t);
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
++try_count;
}
void disp() const
{
std::cout << bench.name() << " " << "score: " << (score / try_count) << std::endl;
}
};
struct rapidjson_bench
{
std::string name() const { return "rapidjson"; }
void operator()(const std::string& json) const
{
rapidjson::Document doc;
if (doc.Parse<0>(json.c_str()).HasParseError())
throw std::runtime_error("parse_error");
const rapidjson::Value& children = doc["data"]["children"];
for (rapidjson::Value::ConstValueIterator it = children.Begin(); it != children.End(); ++it)
{
const rapidjson::Value& data = (*it)["data"];
print(data["score"].GetInt(), data["title"].GetString(), data["url"].GetString());
}
}
};
struct picojson_bench
{
std::string name() const { return "picojson"; }
void operator()(const std::string& json) const
{
picojson::value v;
std::string error;
std::string::const_iterator it = json.begin();
picojson::parse(v, it, json.end(), &error);
if (!error.empty())
throw std::runtime_error(error);
const picojson::array& children = v.get("data").get("children").get<picojson::array>();
for (picojson::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
const picojson::value& data = it->get("data");
print(data.get("score").get<double>(), data.get("title").get<std::string>(), data.get("url").get<std::string>());
}
}
};
struct rabbit_bench
{
std::string name() const { return "rabbit"; }
void operator()(const std::string& json) const
{
rabbit::document doc;
try { doc.parse(json); } catch (...) { throw; }
rabbit::const_array children = doc["data"]["children"];
for (rabbit::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
rabbit::const_object data = it->cat("data");
print(data["score"].as(), data["title"].as(), data["url"].as());
}
}
};
int main(int argc, char** argv)
{
int n = 1000;
int m = 5;
if (argc >= 2) n = std::atoi(argv[1]);
if (argc >= 3) m = std::atoi(argv[2]);
runner<rapidjson_bench> r1;
runner<picojson_bench> r2;
runner<rabbit_bench> r3;
for (int i = 1; i <= m; ++i)
{
std::cout << i << "/" << m << " trying...";
r1.run(n);
r2.run(n);
r3.run(n);
std::cout << "OK" << std::endl;
}
r1.disp();
r2.disp();
r3.disp();
}
<commit_msg>fix bench<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <cstdlib>
#include <ctime>
#include <rapidjson/document.h>
#include <picojson.h>
#include <rabbit.hpp>
void print(int score, const std::string& title, const std::string& url)
{
std::cerr << "(" << score << ") " << title << " - " << url << std::endl;
}
template <typename Bench>
struct runner
{
Bench bench;
std::string json;
int score;
int try_count;
runner(const std::string& json)
: json(json)
, score(0)
, try_count(0)
{}
void run(int n)
{
try
{
std::clock_t t = std::clock();
while (n-- > 0)
bench(json);
score += (std::clock() - t);
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
++try_count;
}
void disp() const
{
std::cout << bench.name() << " " << "score: " << (score / try_count) << std::endl;
}
};
struct rapidjson_bench
{
std::string name() const { return "rapidjson"; }
void operator()(const std::string& json) const
{
rapidjson::Document doc;
if (doc.Parse<0>(json.c_str()).HasParseError())
throw std::runtime_error("parse_error");
const rapidjson::Value& children = doc["data"]["children"];
for (rapidjson::Value::ConstValueIterator it = children.Begin(); it != children.End(); ++it)
{
const rapidjson::Value& data = (*it)["data"];
print(data["score"].GetInt(), data["title"].GetString(), data["url"].GetString());
}
}
};
struct picojson_bench
{
std::string name() const { return "picojson "; }
void operator()(const std::string& json) const
{
picojson::value v;
std::string error;
std::string::const_iterator it = json.begin();
picojson::parse(v, it, json.end(), &error);
if (!error.empty())
throw std::runtime_error(error);
const picojson::array& children = v.get("data").get("children").get<picojson::array>();
for (picojson::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
const picojson::value& data = it->get("data");
print(data.get("score").get<double>(), data.get("title").get<std::string>(), data.get("url").get<std::string>());
}
}
};
struct rabbit_bench
{
std::string name() const { return "rabbit "; }
void operator()(const std::string& json) const
{
rabbit::document doc;
try { doc.parse(json); } catch (...) { throw; }
rabbit::const_array children = doc["data"]["children"];
for (rabbit::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
rabbit::const_object data = it->cat("data");
print(data["score"].as(), data["title"].as(), data["url"].as());
}
}
};
int main(int argc, char** argv)
{
int n = 1000;
if (argc >= 2) n = std::atoi(argv[1]);
std::ifstream ifs("hot.json");
std::istreambuf_iterator<char> it(ifs), last;
std::string json = std::string(it, last);
runner<rapidjson_bench> r1(json);
runner<picojson_bench> r2(json);
runner<rabbit_bench> r3(json);
int i = 1;
while (true)
{
std::cout << i << " trying...";
r1.run(n);
r2.run(n);
r3.run(n);
std::cout << "OK" << std::endl;
r1.disp();
r2.disp();
r3.disp();
std::cout << "---" << std::endl;
++i;
}
}
<|endoftext|> |
<commit_before>#include <set>
#define NOD_ATHENA 1
#include "DNAMP3.hpp"
#include "STRG.hpp"
#include "MLVL.hpp"
#include "CAUD.hpp"
#include "CMDL.hpp"
#include "CHAR.hpp"
#include "MREA.hpp"
#include "MAPA.hpp"
#include "SAVW.hpp"
#include "HINT.hpp"
#include "DataSpec/DNACommon/TXTR.hpp"
#include "DataSpec/DNACommon/FONT.hpp"
#include "DataSpec/DNACommon/FSM2.hpp"
#include "DataSpec/DNACommon/DGRP.hpp"
#include "Runtime/GCNTypes.hpp"
namespace DataSpec::DNAMP3 {
logvisor::Module Log("urde::DNAMP3");
static bool GetNoShare(std::string_view name) {
std::string lowerName(name);
std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), tolower);
if (!lowerName.compare(0, 7, "metroid"))
return false;
return true;
}
PAKBridge::PAKBridge(const nod::Node& node, bool doExtract)
: m_node(node), m_pak(GetNoShare(node.getName())), m_doExtract(doExtract) {
nod::AthenaPartReadStream rs(node.beginReadStream());
m_pak.read(rs);
/* Append Level String */
std::set<hecl::SystemString, hecl::CaseInsensitiveCompare> uniq;
for (auto& ent : m_pak.m_entries) {
PAK::Entry& entry = ent.second;
if (entry.type == FOURCC('MLVL')) {
PAKEntryReadStream rs = entry.beginReadStream(m_node);
MLVL mlvl;
mlvl.read(rs);
const PAK::Entry* nameEnt = m_pak.lookupEntry(mlvl.worldNameId);
if (nameEnt) {
PAKEntryReadStream rs = nameEnt->beginReadStream(m_node);
STRG mlvlName;
mlvlName.read(rs);
uniq.insert(mlvlName.getSystemString(FOURCC('ENGL'), 0));
}
}
}
bool comma = false;
for (const hecl::SystemString& str : uniq) {
if (comma)
m_levelString += _SYS_STR(", ");
comma = true;
m_levelString += str;
}
}
static hecl::SystemString LayerName(std::string_view name) {
hecl::SystemString ret(hecl::SystemStringConv(name).sys_str());
for (auto& ch : ret)
if (ch == _SYS_STR('/') || ch == _SYS_STR('\\'))
ch = _SYS_STR('-');
return ret;
}
void PAKBridge::build() {
/* First pass: build per-area/per-layer dependency map */
for (const auto& ent : m_pak.m_entries) {
const PAK::Entry& entry = ent.second;
if (entry.type == FOURCC('MLVL')) {
Level& level = m_levelDeps[entry.id];
MLVL mlvl;
{
PAKEntryReadStream rs = entry.beginReadStream(m_node);
mlvl.read(rs);
}
std::string catalogueName;
std::string bestName = m_pak.bestEntryName(m_node, entry, catalogueName);
level.name = hecl::SystemStringConv(bestName).sys_str();
level.areas.reserve(mlvl.areaCount);
unsigned layerIdx = 0;
/* Make MAPW available to lookup MAPAs */
const PAK::Entry* worldMapEnt = m_pak.lookupEntry(mlvl.worldMap);
std::vector<UniqueID64> mapw;
if (worldMapEnt) {
PAKEntryReadStream rs = worldMapEnt->beginReadStream(m_node);
rs.seek(8, athena::SeekOrigin::Current);
atUint32 areaCount = rs.readUint32Big();
mapw.reserve(areaCount);
for (atUint32 i = 0; i < areaCount; ++i)
mapw.emplace_back(rs);
}
/* Index areas */
unsigned ai = 0;
auto layerFlagsIt = mlvl.layerFlags.begin();
for (const MLVL::Area& area : mlvl.areas) {
Level::Area& areaDeps = level.areas[area.areaMREAId];
const PAK::Entry* areaNameEnt = m_pak.lookupEntry(area.areaNameId);
if (areaNameEnt) {
STRG areaName;
{
PAKEntryReadStream rs = areaNameEnt->beginReadStream(m_node);
areaName.read(rs);
}
areaDeps.name = areaName.getSystemString(FOURCC('ENGL'), 0);
areaDeps.name = hecl::StringUtils::TrimWhitespace(areaDeps.name);
}
if (areaDeps.name.empty()) {
areaDeps.name = hecl::SystemStringConv(area.internalAreaName).sys_str();
if (areaDeps.name.empty()) {
std::string idStr = area.areaMREAId.toString();
areaDeps.name = hecl::SystemString(_SYS_STR("MREA_")) + hecl::SystemStringConv(idStr).c_str();
}
}
hecl::SystemString num = fmt::format(fmt(_SYS_STR("{:02d} ")), ai);
areaDeps.name = num + areaDeps.name;
const MLVL::LayerFlags& layerFlags = *layerFlagsIt++;
if (layerFlags.layerCount) {
areaDeps.layers.reserve(layerFlags.layerCount);
for (unsigned l = 1; l < layerFlags.layerCount; ++l) {
areaDeps.layers.emplace_back();
Level::Area::Layer& layer = areaDeps.layers.back();
layer.name = LayerName(mlvl.layerNames[layerIdx++]);
layer.active = layerFlags.flags >> (l - 1) & 0x1;
layer.name = hecl::StringUtils::TrimWhitespace(layer.name);
num = fmt::format(fmt(_SYS_STR("{:02d} ")), l - 1);
layer.name = num + layer.name;
}
}
/* Load area DEPS */
const PAK::Entry* areaEntry = m_pak.lookupEntry(area.areaMREAId);
if (areaEntry) {
PAKEntryReadStream ars = areaEntry->beginReadStream(m_node);
MREA::ExtractLayerDeps(ars, areaDeps);
}
areaDeps.resources.emplace(area.areaMREAId);
if (mapw.size() > ai)
areaDeps.resources.emplace(mapw[ai]);
++ai;
}
}
}
/* Second pass: cross-compare uniqueness */
for (auto& entry : m_pak.m_entries) {
entry.second.unique.checkEntry(*this, entry.second);
}
}
void PAKBridge::addCMDLRigPairs(PAKRouter<PAKBridge>& pakRouter, CharacterAssociations<UniqueID64>& charAssoc) const {
for (const std::pair<UniqueID64, PAK::Entry>& entry : m_pak.m_entries) {
if (entry.second.type == FOURCC('CHAR')) {
PAKEntryReadStream rs = entry.second.beginReadStream(m_node);
CHAR aChar;
aChar.read(rs);
const CHAR::CharacterInfo& ci = aChar.characterInfo;
charAssoc.m_cmdlRigs[ci.cmdl] = {ci.cskr, ci.cinf};
charAssoc.m_cskrToCharacter[ci.cskr] =
std::make_pair(entry.second.id, fmt::format(fmt("{}_{}.CSKR"), ci.name, ci.cskr));
for (const CHAR::CharacterInfo::Overlay& overlay : ci.overlays) {
charAssoc.m_cmdlRigs[overlay.cmdl] = {overlay.cskr, ci.cinf};
charAssoc.m_cskrToCharacter[overlay.cskr] =
std::make_pair(entry.second.id, fmt::format(fmt("{}.{}_{}.CSKR"), ci.name, overlay.type, overlay.cskr));
}
}
}
}
static const atVec4f BottomRow = {{0.f, 0.f, 0.f, 1.f}};
void PAKBridge::addMAPATransforms(PAKRouter<PAKBridge>& pakRouter,
std::unordered_map<UniqueID64, zeus::CMatrix4f>& addTo,
std::unordered_map<UniqueID64, hecl::ProjectPath>& pathOverrides) const {
for (const std::pair<UniqueID64, PAK::Entry>& entry : m_pak.m_entries) {
if (entry.second.type == FOURCC('MLVL')) {
MLVL mlvl;
{
PAKEntryReadStream rs = entry.second.beginReadStream(m_node);
mlvl.read(rs);
}
hecl::ProjectPath mlvlDirPath = pakRouter.getWorking(&entry.second).getParentPath();
if (mlvl.worldNameId.isValid())
pathOverrides[mlvl.worldNameId] = hecl::ProjectPath(mlvlDirPath,
fmt::format(fmt(_SYS_STR("!name_{}.yaml")), mlvl.worldNameId));
for (const MLVL::Area& area : mlvl.areas) {
hecl::ProjectPath areaDirPath = pakRouter.getWorking(area.areaMREAId).getParentPath();
if (area.areaNameId.isValid())
pathOverrides[area.areaNameId] = hecl::ProjectPath(areaDirPath,
fmt::format(fmt(_SYS_STR("!name_{}.yaml")), area.areaNameId));
}
if (mlvl.worldMap.isValid()) {
const nod::Node* mapNode;
const PAK::Entry* mapEntry = pakRouter.lookupEntry(mlvl.worldMap, &mapNode);
if (mapEntry) {
PAKEntryReadStream rs = mapEntry->beginReadStream(*mapNode);
u32 magic = rs.readUint32Big();
if (magic == 0xDEADF00D) {
rs.readUint32Big();
u32 count = rs.readUint32Big();
for (u32 i = 0; i < count && i < mlvl.areas.size(); ++i) {
MLVL::Area& areaData = mlvl.areas[i];
UniqueID64 mapaId;
mapaId.read(rs);
addTo[mapaId] = zeus::CMatrix4f(areaData.transformMtx[0], areaData.transformMtx[1],
areaData.transformMtx[2], BottomRow)
.transposed();
}
}
}
}
}
}
}
ResExtractor<PAKBridge> PAKBridge::LookupExtractor(const nod::Node& pakNode, const PAK& pak, const PAK::Entry& entry) {
switch (entry.type.toUint32()) {
case SBIG('CAUD'):
return {CAUD::Extract, {_SYS_STR(".yaml")}};
case SBIG('STRG'):
return {STRG::Extract, {_SYS_STR(".yaml")}};
case SBIG('TXTR'):
return {TXTR::Extract, {_SYS_STR(".png")}};
case SBIG('SAVW'):
return {SAVWCommon::ExtractSAVW<SAVW>, {_SYS_STR(".yaml")}};
case SBIG('HINT'):
return {HINT::Extract, {_SYS_STR(".yaml")}};
// case SBIG('CMDL'):
// return {CMDL::Extract, {_SYS_STR(".blend")}, 1};
// case SBIG('CHAR'):
// return {CHAR::Extract, {_SYS_STR(".yaml"), _SYS_STR(".blend")}, 2};
// case SBIG('MLVL'):
// return {MLVL::Extract, {_SYS_STR(".yaml"), _SYS_STR(".blend")}, 3};
// case SBIG('MREA'):
// return {MREA::Extract, {_SYS_STR(".blend")}, 4};
// case SBIG('MAPA'):
// return {MAPA::Extract, {_SYS_STR(".blend")}, 4};
case SBIG('FSM2'):
return {DNAFSM2::ExtractFSM2<UniqueID64>, {_SYS_STR(".yaml")}};
case SBIG('FONT'):
return {DNAFont::ExtractFONT<UniqueID64>, {_SYS_STR(".yaml")}};
case SBIG('DGRP'):
return {DNADGRP::ExtractDGRP<UniqueID64>, {_SYS_STR(".yaml")}};
}
return {};
}
} // namespace DataSpec::DNAMP3
<commit_msg>DNAMP3: Prevent unnecessary copies<commit_after>#include <set>
#define NOD_ATHENA 1
#include "DNAMP3.hpp"
#include "STRG.hpp"
#include "MLVL.hpp"
#include "CAUD.hpp"
#include "CMDL.hpp"
#include "CHAR.hpp"
#include "MREA.hpp"
#include "MAPA.hpp"
#include "SAVW.hpp"
#include "HINT.hpp"
#include "DataSpec/DNACommon/TXTR.hpp"
#include "DataSpec/DNACommon/FONT.hpp"
#include "DataSpec/DNACommon/FSM2.hpp"
#include "DataSpec/DNACommon/DGRP.hpp"
#include "Runtime/GCNTypes.hpp"
namespace DataSpec::DNAMP3 {
logvisor::Module Log("urde::DNAMP3");
static bool GetNoShare(std::string_view name) {
std::string lowerName(name);
std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), tolower);
if (!lowerName.compare(0, 7, "metroid"))
return false;
return true;
}
PAKBridge::PAKBridge(const nod::Node& node, bool doExtract)
: m_node(node), m_pak(GetNoShare(node.getName())), m_doExtract(doExtract) {
nod::AthenaPartReadStream rs(node.beginReadStream());
m_pak.read(rs);
/* Append Level String */
std::set<hecl::SystemString, hecl::CaseInsensitiveCompare> uniq;
for (auto& ent : m_pak.m_entries) {
PAK::Entry& entry = ent.second;
if (entry.type == FOURCC('MLVL')) {
PAKEntryReadStream rs = entry.beginReadStream(m_node);
MLVL mlvl;
mlvl.read(rs);
const PAK::Entry* nameEnt = m_pak.lookupEntry(mlvl.worldNameId);
if (nameEnt) {
PAKEntryReadStream rs = nameEnt->beginReadStream(m_node);
STRG mlvlName;
mlvlName.read(rs);
uniq.insert(mlvlName.getSystemString(FOURCC('ENGL'), 0));
}
}
}
bool comma = false;
for (const hecl::SystemString& str : uniq) {
if (comma)
m_levelString += _SYS_STR(", ");
comma = true;
m_levelString += str;
}
}
static hecl::SystemString LayerName(std::string_view name) {
hecl::SystemString ret(hecl::SystemStringConv(name).sys_str());
for (auto& ch : ret)
if (ch == _SYS_STR('/') || ch == _SYS_STR('\\'))
ch = _SYS_STR('-');
return ret;
}
void PAKBridge::build() {
/* First pass: build per-area/per-layer dependency map */
for (const auto& ent : m_pak.m_entries) {
const PAK::Entry& entry = ent.second;
if (entry.type == FOURCC('MLVL')) {
Level& level = m_levelDeps[entry.id];
MLVL mlvl;
{
PAKEntryReadStream rs = entry.beginReadStream(m_node);
mlvl.read(rs);
}
std::string catalogueName;
std::string bestName = m_pak.bestEntryName(m_node, entry, catalogueName);
level.name = hecl::SystemStringConv(bestName).sys_str();
level.areas.reserve(mlvl.areaCount);
unsigned layerIdx = 0;
/* Make MAPW available to lookup MAPAs */
const PAK::Entry* worldMapEnt = m_pak.lookupEntry(mlvl.worldMap);
std::vector<UniqueID64> mapw;
if (worldMapEnt) {
PAKEntryReadStream rs = worldMapEnt->beginReadStream(m_node);
rs.seek(8, athena::SeekOrigin::Current);
atUint32 areaCount = rs.readUint32Big();
mapw.reserve(areaCount);
for (atUint32 i = 0; i < areaCount; ++i)
mapw.emplace_back(rs);
}
/* Index areas */
unsigned ai = 0;
auto layerFlagsIt = mlvl.layerFlags.begin();
for (const MLVL::Area& area : mlvl.areas) {
Level::Area& areaDeps = level.areas[area.areaMREAId];
const PAK::Entry* areaNameEnt = m_pak.lookupEntry(area.areaNameId);
if (areaNameEnt) {
STRG areaName;
{
PAKEntryReadStream rs = areaNameEnt->beginReadStream(m_node);
areaName.read(rs);
}
areaDeps.name = areaName.getSystemString(FOURCC('ENGL'), 0);
areaDeps.name = hecl::StringUtils::TrimWhitespace(areaDeps.name);
}
if (areaDeps.name.empty()) {
areaDeps.name = hecl::SystemStringConv(area.internalAreaName).sys_str();
if (areaDeps.name.empty()) {
std::string idStr = area.areaMREAId.toString();
areaDeps.name = hecl::SystemString(_SYS_STR("MREA_")) + hecl::SystemStringConv(idStr).c_str();
}
}
hecl::SystemString num = fmt::format(fmt(_SYS_STR("{:02d} ")), ai);
areaDeps.name = num + areaDeps.name;
const MLVL::LayerFlags& layerFlags = *layerFlagsIt++;
if (layerFlags.layerCount) {
areaDeps.layers.reserve(layerFlags.layerCount);
for (unsigned l = 1; l < layerFlags.layerCount; ++l) {
areaDeps.layers.emplace_back();
Level::Area::Layer& layer = areaDeps.layers.back();
layer.name = LayerName(mlvl.layerNames[layerIdx++]);
layer.active = layerFlags.flags >> (l - 1) & 0x1;
layer.name = hecl::StringUtils::TrimWhitespace(layer.name);
num = fmt::format(fmt(_SYS_STR("{:02d} ")), l - 1);
layer.name = num + layer.name;
}
}
/* Load area DEPS */
const PAK::Entry* areaEntry = m_pak.lookupEntry(area.areaMREAId);
if (areaEntry) {
PAKEntryReadStream ars = areaEntry->beginReadStream(m_node);
MREA::ExtractLayerDeps(ars, areaDeps);
}
areaDeps.resources.emplace(area.areaMREAId);
if (mapw.size() > ai)
areaDeps.resources.emplace(mapw[ai]);
++ai;
}
}
}
/* Second pass: cross-compare uniqueness */
for (auto& entry : m_pak.m_entries) {
entry.second.unique.checkEntry(*this, entry.second);
}
}
void PAKBridge::addCMDLRigPairs(PAKRouter<PAKBridge>& pakRouter, CharacterAssociations<UniqueID64>& charAssoc) const {
for (const auto& entry : m_pak.m_entries) {
if (entry.second.type == FOURCC('CHAR')) {
PAKEntryReadStream rs = entry.second.beginReadStream(m_node);
CHAR aChar;
aChar.read(rs);
const CHAR::CharacterInfo& ci = aChar.characterInfo;
charAssoc.m_cmdlRigs[ci.cmdl] = {ci.cskr, ci.cinf};
charAssoc.m_cskrToCharacter[ci.cskr] =
std::make_pair(entry.second.id, fmt::format(fmt("{}_{}.CSKR"), ci.name, ci.cskr));
for (const CHAR::CharacterInfo::Overlay& overlay : ci.overlays) {
charAssoc.m_cmdlRigs[overlay.cmdl] = {overlay.cskr, ci.cinf};
charAssoc.m_cskrToCharacter[overlay.cskr] =
std::make_pair(entry.second.id, fmt::format(fmt("{}.{}_{}.CSKR"), ci.name, overlay.type, overlay.cskr));
}
}
}
}
static const atVec4f BottomRow = {{0.f, 0.f, 0.f, 1.f}};
void PAKBridge::addMAPATransforms(PAKRouter<PAKBridge>& pakRouter,
std::unordered_map<UniqueID64, zeus::CMatrix4f>& addTo,
std::unordered_map<UniqueID64, hecl::ProjectPath>& pathOverrides) const {
for (const auto& entry : m_pak.m_entries) {
if (entry.second.type == FOURCC('MLVL')) {
MLVL mlvl;
{
PAKEntryReadStream rs = entry.second.beginReadStream(m_node);
mlvl.read(rs);
}
hecl::ProjectPath mlvlDirPath = pakRouter.getWorking(&entry.second).getParentPath();
if (mlvl.worldNameId.isValid())
pathOverrides[mlvl.worldNameId] = hecl::ProjectPath(mlvlDirPath,
fmt::format(fmt(_SYS_STR("!name_{}.yaml")), mlvl.worldNameId));
for (const MLVL::Area& area : mlvl.areas) {
hecl::ProjectPath areaDirPath = pakRouter.getWorking(area.areaMREAId).getParentPath();
if (area.areaNameId.isValid())
pathOverrides[area.areaNameId] = hecl::ProjectPath(areaDirPath,
fmt::format(fmt(_SYS_STR("!name_{}.yaml")), area.areaNameId));
}
if (mlvl.worldMap.isValid()) {
const nod::Node* mapNode;
const PAK::Entry* mapEntry = pakRouter.lookupEntry(mlvl.worldMap, &mapNode);
if (mapEntry) {
PAKEntryReadStream rs = mapEntry->beginReadStream(*mapNode);
u32 magic = rs.readUint32Big();
if (magic == 0xDEADF00D) {
rs.readUint32Big();
u32 count = rs.readUint32Big();
for (u32 i = 0; i < count && i < mlvl.areas.size(); ++i) {
MLVL::Area& areaData = mlvl.areas[i];
UniqueID64 mapaId;
mapaId.read(rs);
addTo[mapaId] = zeus::CMatrix4f(areaData.transformMtx[0], areaData.transformMtx[1],
areaData.transformMtx[2], BottomRow)
.transposed();
}
}
}
}
}
}
}
ResExtractor<PAKBridge> PAKBridge::LookupExtractor(const nod::Node& pakNode, const PAK& pak, const PAK::Entry& entry) {
switch (entry.type.toUint32()) {
case SBIG('CAUD'):
return {CAUD::Extract, {_SYS_STR(".yaml")}};
case SBIG('STRG'):
return {STRG::Extract, {_SYS_STR(".yaml")}};
case SBIG('TXTR'):
return {TXTR::Extract, {_SYS_STR(".png")}};
case SBIG('SAVW'):
return {SAVWCommon::ExtractSAVW<SAVW>, {_SYS_STR(".yaml")}};
case SBIG('HINT'):
return {HINT::Extract, {_SYS_STR(".yaml")}};
// case SBIG('CMDL'):
// return {CMDL::Extract, {_SYS_STR(".blend")}, 1};
// case SBIG('CHAR'):
// return {CHAR::Extract, {_SYS_STR(".yaml"), _SYS_STR(".blend")}, 2};
// case SBIG('MLVL'):
// return {MLVL::Extract, {_SYS_STR(".yaml"), _SYS_STR(".blend")}, 3};
// case SBIG('MREA'):
// return {MREA::Extract, {_SYS_STR(".blend")}, 4};
// case SBIG('MAPA'):
// return {MAPA::Extract, {_SYS_STR(".blend")}, 4};
case SBIG('FSM2'):
return {DNAFSM2::ExtractFSM2<UniqueID64>, {_SYS_STR(".yaml")}};
case SBIG('FONT'):
return {DNAFont::ExtractFONT<UniqueID64>, {_SYS_STR(".yaml")}};
case SBIG('DGRP'):
return {DNADGRP::ExtractDGRP<UniqueID64>, {_SYS_STR(".yaml")}};
}
return {};
}
} // namespace DataSpec::DNAMP3
<|endoftext|> |
<commit_before>//@author A0094446X
#include "stdafx.h"
#include "CppUnitTest.h"
#include "You-GUI\main_window.h"
#include "You-GUI\system_tray_manager.h"
#include "You-QueryEngine\api.h"
#include "You-GUI\task_panel_manager.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using Task = You::Controller::Task;
using TaskList = You::Controller::TaskList;
using Date = boost::gregorian::date;
namespace You {
namespace GUI {
namespace UnitTests {
QApplication *app;
// Simulate running the main() function
// Sets up the logging facility and the Qt event loop
TEST_MODULE_INITIALIZE(ModuleInitialize) {
int argc = 1;
char *argv[] = { "You.exe" };
app = new QApplication(argc, argv);
}
// Cleans up what we set up
TEST_MODULE_CLEANUP(ModuleCleanup) {
app->quit();
delete app;
}
TEST_CLASS(MainWindowTests) {
public:
/// These are generic tests for component visibility/invisibility
TEST_METHOD(visibilityTest) {
MainWindow w;
bool visibilityTest =
w.isVisible() &&
w.ui.centralWidget->isVisible() &&
w.ui.taskTreePanel->isVisible() &&
w.ui.commandEnterButton->isVisible() &&
w.commandTextBox->isVisible() &&
w.ui.statusBar->isVisible() &&
w.ui.statusIcon->isVisible() &&
w.ui.statusMessage->isVisible() &&
!w.ui.mainToolBar->isVisible() &&
!w.ui.menuBar->isVisible();
Assert::IsTrue(visibilityTest);
}
/// Basic task addition test
TEST_METHOD(addSingleTask) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
w.commandEnterPressed();
QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
int column1 = QString::compare(item.text(1), QString("0"));
int column2 = QString::compare(item.text(2), QString("test"));
int column3 = QString::compare(
item.text(3),
QString("Overdue (1999-Nov-01 00:00:00)"));
int column4 = QString::compare(item.text(4), QString("Normal"));
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
(column1 == 0) && (column2 == 0) &&
(column3 == 0) && (column4 == 0));
}
/// Boundary test case for the equivalence partition for the lower
/// bound of the valid zone for testing if a task is due today
TEST_METHOD(testDueToday1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Generic test case for testing if a task is due today (deadline ahead)
TEST_METHOD(testDueToday2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Generic test case for testing if a task is due today (deadline before)
TEST_METHOD(testDueToday3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Generic test case for testing if a task is due
/// tomorrow (deadline after)
TEST_METHOD(testDueTomorrow1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::hours(24);
Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 1));
}
/// Boundary test case for the equivalence partition for the upper
/// bound of the lower invalid zone for testing if a task is overdue
TEST_METHOD(testPastDue1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= boost::posix_time::minutes(1);
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Generic test case for testing if a task is overdue
TEST_METHOD(testPastDue2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, on the same time
TEST_METHOD(testPastDue3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, with deadline 1 minute after
TEST_METHOD(testPastDue4) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Generic task deletion test
TEST_METHOD(deleteSingleTaskCount) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
}
/// Generic task deletion test
TEST_METHOD(deleteSingleTaskFind) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->findItems(
QString("1"), Qt::MatchExactly, 1).size() == 0);
}
TEST_METHOD(editSingleTask) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(
QString("/edit 0 set description abc"));
w.commandEnterButtonClicked();
QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
int column1 = QString::compare(item.text(1), QString("0"));
int column2 = QString::compare(item.text(2), QString("abc"));
int column3 = QString::compare(
item.text(3),
QString("Overdue (1999-Nov-01 00:00:00)"));
int column4 = QString::compare(item.text(4), QString("Normal"));
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
(column1 == 0) && (column2 == 0) &&
(column3 == 0) && (column4 == 0));
}
TEST_METHOD(toggleTrayIcon) {
MainWindow w;
w.clearTasks();
Assert::IsTrue(true);
}
};
} // namespace UnitTests
} // namespace GUI
} // namespace You
<commit_msg>I stayed awake for this single whitespace lint error.<commit_after>//@author A0094446X
#include "stdafx.h"
#include "CppUnitTest.h"
#include "You-GUI\main_window.h"
#include "You-GUI\system_tray_manager.h"
#include "You-QueryEngine\api.h"
#include "You-GUI\task_panel_manager.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using Task = You::Controller::Task;
using TaskList = You::Controller::TaskList;
using Date = boost::gregorian::date;
namespace You {
namespace GUI {
namespace UnitTests {
QApplication *app;
// Simulate running the main() function
// Sets up the logging facility and the Qt event loop
TEST_MODULE_INITIALIZE(ModuleInitialize) {
int argc = 1;
char *argv[] = { "You.exe" };
app = new QApplication(argc, argv);
}
// Cleans up what we set up
TEST_MODULE_CLEANUP(ModuleCleanup) {
app->quit();
delete app;
}
TEST_CLASS(MainWindowTests) {
public:
/// These are generic tests for component visibility/invisibility
TEST_METHOD(visibilityTest) {
MainWindow w;
bool visibilityTest =
w.isVisible() &&
w.ui.centralWidget->isVisible() &&
w.ui.taskTreePanel->isVisible() &&
w.ui.commandEnterButton->isVisible() &&
w.commandTextBox->isVisible() &&
w.ui.statusBar->isVisible() &&
w.ui.statusIcon->isVisible() &&
w.ui.statusMessage->isVisible() &&
!w.ui.mainToolBar->isVisible() &&
!w.ui.menuBar->isVisible();
Assert::IsTrue(visibilityTest);
}
/// Basic task addition test
TEST_METHOD(addSingleTask) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
w.commandEnterPressed();
QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
int column1 = QString::compare(item.text(1), QString("0"));
int column2 = QString::compare(item.text(2), QString("test"));
int column3 = QString::compare(
item.text(3),
QString("Overdue (1999-Nov-01 00:00:00)"));
int column4 = QString::compare(item.text(4), QString("Normal"));
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
(column1 == 0) && (column2 == 0) &&
(column3 == 0) && (column4 == 0));
}
/// Boundary test case for the equivalence partition for the lower
/// bound of the valid zone for testing if a task is due today
TEST_METHOD(testDueToday1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Generic test case for testing if a task is due today (deadline ahead)
TEST_METHOD(testDueToday2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Generic test case for testing if a task is due today (deadline before)
TEST_METHOD(testDueToday3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Generic test case for testing if a task is due
/// tomorrow (deadline after)
TEST_METHOD(testDueTomorrow1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::hours(24);
Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 1));
}
/// Boundary test case for the equivalence partition for the upper
/// bound of the lower invalid zone for testing if a task is overdue
TEST_METHOD(testPastDue1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= boost::posix_time::minutes(1);
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Generic test case for testing if a task is overdue
TEST_METHOD(testPastDue2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, on the same time
TEST_METHOD(testPastDue3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, with deadline 1 minute after
TEST_METHOD(testPastDue4) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Generic task deletion test
TEST_METHOD(deleteSingleTaskCount) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
}
/// Generic task deletion test
TEST_METHOD(deleteSingleTaskFind) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->findItems(
QString("1"), Qt::MatchExactly, 1).size() == 0);
}
TEST_METHOD(editSingleTask) {
MainWindow w;
w.clearTasks();
w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
w.commandEnterPressed();
w.commandTextBox->setPlainText(
QString("/edit 0 set description abc"));
w.commandEnterButtonClicked();
QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
int column1 = QString::compare(item.text(1), QString("0"));
int column2 = QString::compare(item.text(2), QString("abc"));
int column3 = QString::compare(
item.text(3),
QString("Overdue (1999-Nov-01 00:00:00)"));
int column4 = QString::compare(item.text(4), QString("Normal"));
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
(column1 == 0) && (column2 == 0) &&
(column3 == 0) && (column4 == 0));
}
TEST_METHOD(toggleTrayIcon) {
MainWindow w;
w.clearTasks();
Assert::IsTrue(true);
}
};
} // namespace UnitTests
} // namespace GUI
} // namespace You
<|endoftext|> |
<commit_before>#include "libtorrent/lazy_entry.hpp"
#include <boost/lexical_cast.hpp>
#include <iostream>
#include "test.hpp"
#include "libtorrent/time.hpp"
using namespace libtorrent;
int test_main()
{
using namespace libtorrent;
ptime start(time_now());
for (int i = 0; i < 1000000; ++i)
{
char b[] = "d1:ai12453e1:b3:aaa1:c3:bbbe";
lazy_entry e;
int ret = lazy_bdecode(b, b + sizeof(b)-1, e);
}
ptime stop(time_now());
std::cout << "done in " << total_milliseconds(stop - start) / 1000. << " seconds per million message" << std::endl;
return 0;
}
<commit_msg>made test_bdecode_performance run in a more reasonable amount of time<commit_after>#include "libtorrent/lazy_entry.hpp"
#include <boost/lexical_cast.hpp>
#include <iostream>
#include "test.hpp"
#include "libtorrent/time.hpp"
using namespace libtorrent;
int test_main()
{
using namespace libtorrent;
ptime start(time_now());
for (int i = 0; i < 100000; ++i)
{
char b[] = "d1:ai12453e1:b3:aaa1:c3:bbbe";
lazy_entry e;
int ret = lazy_bdecode(b, b + sizeof(b)-1, e);
}
ptime stop(time_now());
std::cout << "done in " << total_milliseconds(stop - start) / 100. << " seconds per million message" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <climits>
#include <array>
#include <elevator/test.h>
#include <elevator/driver.h>
#include <elevator/channels.h>
namespace elevator {
static const int N_FLOORS = 4;
static const int N_BUTTONS = 3;
static const std::array< std::array< int, N_BUTTONS >, N_FLOORS > lampChannelMatrix{ {
{ { LIGHT_UP1, LIGHT_DOWN1, LIGHT_COMMAND1 } },
{ { LIGHT_UP2, LIGHT_DOWN2, LIGHT_COMMAND2 } },
{ { LIGHT_UP3, LIGHT_DOWN3, LIGHT_COMMAND3 } },
{ { LIGHT_UP4, LIGHT_DOWN4, LIGHT_COMMAND4 } },
} };
static const std::array< std::array< int, N_BUTTONS >, N_FLOORS > buttonChannelMatrix{ {
{ { FLOOR_UP1, FLOOR_DOWN1, FLOOR_COMMAND1 } },
{ { FLOOR_UP2, FLOOR_DOWN2, FLOOR_COMMAND2 } },
{ { FLOOR_UP3, FLOOR_DOWN3, FLOOR_COMMAND3 } },
{ { FLOOR_UP4, FLOOR_DOWN4, FLOOR_COMMAND4 } },
} };
int lamp( Button btn ) {
assert_leq( btn.floor(), int( lampChannelMatrix.size() ), "out-of-bounds" );
assert_leq( 1, btn.floor(), "out-of-bounds" );
return lampChannelMatrix[ btn.floor() - 1 ][ int( btn.type() ) ];
}
int button( Button btn ) {
assert_leq( btn.floor(), int( buttonChannelMatrix.size() ), "out-of-bounds" );
assert_leq( 1, btn.floor(), "out-of-bounds" );
return buttonChannelMatrix[ btn.floor() - 1 ][ int( btn.type() ) ];
}
Driver::Driver() : _minFloor( 1 ), _maxFloor( 4 ),
// we don't know what to set yet, just plug in some sensible values
_lastDirection( Direction::Down ), _lastFloor( 1 ), _moving( false )
{
stopElevator(); // for safety reasons
int sensor = getFloor();
if ( sensor != -1 )
_lastFloor = sensor;
}
/** be nicer to elevator
* in case exception is thrown there is chance elevator is running, if
* Driver goes out of scope we want elevator to stop for safety reasons
*/
Driver::~Driver() { stopElevator(); }
void Driver::init() {
for ( int i = _minFloor; i <= _maxFloor; ++i ) {
if ( i != _maxFloor )
setButtonLamp( Button{ ButtonType::CallUp, i }, false );
if ( i != _minFloor )
setButtonLamp( Button{ ButtonType::CallDown, i }, false );
setButtonLamp( Button{ ButtonType::TargetFloor, i }, false );
}
setStopLamp( false );
setDoorOpenLamp( false );
goToBottom();
}
void Driver::shutdown() {
init(); // for now
}
void Driver::setButtonLamp( Button btn, bool state ) {
_lio.io_set_bit( lamp( btn ), state );
}
void Driver::setStopLamp( bool state ) {
_lio.io_set_bit( LIGHT_STOP, state );
}
void Driver::setDoorOpenLamp( bool state ) {
_lio.io_set_bit( DOOR_OPEN, state );
}
void Driver::setFloorIndicator( int floor ) {
assert_leq( _minFloor, floor, "floor out of bounds" );
assert_leq( floor, _maxFloor, "floor out of bounds" );
--floor; // floor numers are from 0 in backend but from 1 in driver and labels
_lio.io_set_bit(FLOOR_IND1, (floor & 0x02) == 0x02 );
_lio.io_set_bit(FLOOR_IND2, (floor & 0x01) == 0x01 );
}
bool Driver::getButtonLamp( Button button ) {
return _lio.io_read_bit( lamp( button ) );
}
bool Driver::getStopLamp() {
return _lio.io_read_bit( LIGHT_STOP );
}
bool Driver::getDoorOpenLamp() {
return _lio.io_read_bit( DOOR_OPEN );
}
int Driver::getFloorIndicator() {
return ((_lio.io_read_bit( FLOOR_IND1 ) << 1) | (_lio.io_read_bit( FLOOR_IND2 ))) + 1;
}
bool Driver::getButtonSignal( Button btn ) {
return _lio.io_read_bit( button( btn ) );
}
void Driver::setMotorSpeed( Direction direction, int speed ) {
assert_lt( 0, speed, "Speed must be positive" );
_lastDirection = direction;
_lio.io_set_bit( MOTORDIR, direction == Direction::Down );
_lio.io_write_analog( MOTOR, 2048 + 4 * speed );
};
void Driver::stopElevator() {
_lio.io_set_bit( MOTORDIR, _lastDirection == Direction::Up ); // reverse direction
_lio.io_write_analog( MOTOR, 0 ); // actually stop
_moving = false;
};
int Driver::getFloor() {
if ( _lio.io_read_bit( SENSOR1 ) )
return 1;
else if ( _lio.io_read_bit( SENSOR2 ) )
return 2;
else if ( _lio.io_read_bit( SENSOR3 ) )
return 3;
else if ( _lio.io_read_bit( SENSOR4 ) )
return 4;
else
return INT_MIN;
};
bool Driver::getStop() { assert_unimplemented(); };
bool Driver::getObstruction() { assert_unimplemented(); };
void Driver::goToFloor( int floor ) {
assert_leq( _minFloor, floor, "floor out of bounds" );
assert_leq( floor, _maxFloor, "floor out of bounds" );
assert( !_moving, "inconsistent state" );
if ( floor == _lastFloor )
return;
if ( floor < _lastFloor )
goDownToFloor( floor );
else
goUpToFloor( floor );
}
void Driver::goUpToFloor( int floor ) {
_goTo( Direction::Up, floor );
}
void Driver::goDownToFloor( int floor ) {
_goTo( Direction::Down, floor );
}
void Driver::goToBottom() { goDownToFloor( _minFloor ); }
void Driver::goToTop() { goUpToFloor( _maxFloor ); }
void Driver::_goTo( Direction dir, int targetFloor ) {
setMotorSpeed( dir, 300 );
int on;
while ( true ) {
on = getFloor();
movingOnFloor( on );
if ( on == targetFloor )
break;
if ( dir == Direction::Up && on == _maxFloor )
break;
if ( dir == Direction::Down && on == _minFloor )
break;
}
stopElevator();
setFloorIndicator( targetFloor );
}
void Driver::movingOnFloor( int floorSensor ) {
if ( floorSensor != INT_MIN ) {
_lastFloor = floorSensor;
setFloorIndicator( floorSensor );
}
_moving = true;
}
bool Driver::alive() {
if ( getStopLamp() )
return true;
setStopLamp( true );
bool val = getStopLamp();
setStopLamp( false );
return val;
}
}
<commit_msg>driver: Implement missing functions.<commit_after>#include <climits>
#include <array>
#include <elevator/test.h>
#include <elevator/driver.h>
#include <elevator/channels.h>
namespace elevator {
static const int N_FLOORS = 4;
static const int N_BUTTONS = 3;
static const std::array< std::array< int, N_BUTTONS >, N_FLOORS > lampChannelMatrix{ {
{ { LIGHT_UP1, LIGHT_DOWN1, LIGHT_COMMAND1 } },
{ { LIGHT_UP2, LIGHT_DOWN2, LIGHT_COMMAND2 } },
{ { LIGHT_UP3, LIGHT_DOWN3, LIGHT_COMMAND3 } },
{ { LIGHT_UP4, LIGHT_DOWN4, LIGHT_COMMAND4 } },
} };
static const std::array< std::array< int, N_BUTTONS >, N_FLOORS > buttonChannelMatrix{ {
{ { FLOOR_UP1, FLOOR_DOWN1, FLOOR_COMMAND1 } },
{ { FLOOR_UP2, FLOOR_DOWN2, FLOOR_COMMAND2 } },
{ { FLOOR_UP3, FLOOR_DOWN3, FLOOR_COMMAND3 } },
{ { FLOOR_UP4, FLOOR_DOWN4, FLOOR_COMMAND4 } },
} };
int lamp( Button btn ) {
assert_leq( btn.floor(), int( lampChannelMatrix.size() ), "out-of-bounds" );
assert_leq( 1, btn.floor(), "out-of-bounds" );
return lampChannelMatrix[ btn.floor() - 1 ][ int( btn.type() ) ];
}
int button( Button btn ) {
assert_leq( btn.floor(), int( buttonChannelMatrix.size() ), "out-of-bounds" );
assert_leq( 1, btn.floor(), "out-of-bounds" );
return buttonChannelMatrix[ btn.floor() - 1 ][ int( btn.type() ) ];
}
Driver::Driver() : _minFloor( 1 ), _maxFloor( 4 ),
// we don't know what to set yet, just plug in some sensible values
_lastDirection( Direction::Down ), _lastFloor( 1 ), _moving( false )
{
stopElevator(); // for safety reasons
int sensor = getFloor();
if ( sensor != -1 )
_lastFloor = sensor;
}
/** be nicer to elevator
* in case exception is thrown there is chance elevator is running, if
* Driver goes out of scope we want elevator to stop for safety reasons
*/
Driver::~Driver() { stopElevator(); }
void Driver::init() {
for ( int i = _minFloor; i <= _maxFloor; ++i ) {
if ( i != _maxFloor )
setButtonLamp( Button{ ButtonType::CallUp, i }, false );
if ( i != _minFloor )
setButtonLamp( Button{ ButtonType::CallDown, i }, false );
setButtonLamp( Button{ ButtonType::TargetFloor, i }, false );
}
setStopLamp( false );
setDoorOpenLamp( false );
goToBottom();
}
void Driver::shutdown() {
init(); // for now
}
void Driver::setButtonLamp( Button btn, bool state ) {
_lio.io_set_bit( lamp( btn ), state );
}
void Driver::setStopLamp( bool state ) {
_lio.io_set_bit( LIGHT_STOP, state );
}
void Driver::setDoorOpenLamp( bool state ) {
_lio.io_set_bit( DOOR_OPEN, state );
}
void Driver::setFloorIndicator( int floor ) {
assert_leq( _minFloor, floor, "floor out of bounds" );
assert_leq( floor, _maxFloor, "floor out of bounds" );
--floor; // floor numers are from 0 in backend but from 1 in driver and labels
_lio.io_set_bit(FLOOR_IND1, (floor & 0x02) == 0x02 );
_lio.io_set_bit(FLOOR_IND2, (floor & 0x01) == 0x01 );
}
bool Driver::getButtonLamp( Button button ) {
return _lio.io_read_bit( lamp( button ) );
}
bool Driver::getStopLamp() {
return _lio.io_read_bit( LIGHT_STOP );
}
bool Driver::getDoorOpenLamp() {
return _lio.io_read_bit( DOOR_OPEN );
}
int Driver::getFloorIndicator() {
return ((_lio.io_read_bit( FLOOR_IND1 ) << 1) | (_lio.io_read_bit( FLOOR_IND2 ))) + 1;
}
bool Driver::getButtonSignal( Button btn ) {
return _lio.io_read_bit( button( btn ) );
}
void Driver::setMotorSpeed( Direction direction, int speed ) {
assert_lt( 0, speed, "Speed must be positive" );
_lastDirection = direction;
_lio.io_set_bit( MOTORDIR, direction == Direction::Down );
_lio.io_write_analog( MOTOR, 2048 + 4 * speed );
};
void Driver::stopElevator() {
_lio.io_set_bit( MOTORDIR, _lastDirection == Direction::Up ); // reverse direction
_lio.io_write_analog( MOTOR, 0 ); // actually stop
_moving = false;
};
int Driver::getFloor() {
if ( _lio.io_read_bit( SENSOR1 ) )
return 1;
else if ( _lio.io_read_bit( SENSOR2 ) )
return 2;
else if ( _lio.io_read_bit( SENSOR3 ) )
return 3;
else if ( _lio.io_read_bit( SENSOR4 ) )
return 4;
else
return INT_MIN;
};
bool Driver::getStop() { return _lio.io_read_bit( STOP );};
bool Driver::getObstruction() { return _lio.io_read_bit( OBSTRUCTION ); };
void Driver::goToFloor( int floor ) {
assert_leq( _minFloor, floor, "floor out of bounds" );
assert_leq( floor, _maxFloor, "floor out of bounds" );
assert( !_moving, "inconsistent state" );
if ( floor == _lastFloor )
return;
if ( floor < _lastFloor )
goDownToFloor( floor );
else
goUpToFloor( floor );
}
void Driver::goUpToFloor( int floor ) {
_goTo( Direction::Up, floor );
}
void Driver::goDownToFloor( int floor ) {
_goTo( Direction::Down, floor );
}
void Driver::goToBottom() { goDownToFloor( _minFloor ); }
void Driver::goToTop() { goUpToFloor( _maxFloor ); }
void Driver::_goTo( Direction dir, int targetFloor ) {
setMotorSpeed( dir, 300 );
int on;
while ( true ) {
on = getFloor();
movingOnFloor( on );
if ( on == targetFloor )
break;
if ( dir == Direction::Up && on == _maxFloor )
break;
if ( dir == Direction::Down && on == _minFloor )
break;
}
stopElevator();
setFloorIndicator( targetFloor );
}
void Driver::movingOnFloor( int floorSensor ) {
if ( floorSensor != INT_MIN ) {
_lastFloor = floorSensor;
setFloorIndicator( floorSensor );
}
_moving = true;
}
bool Driver::alive() {
if ( getStopLamp() )
return true;
setStopLamp( true );
bool val = getStopLamp();
setStopLamp( false );
return val;
}
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
#include "content/browser/device_sensors/data_fetcher_shared_memory.h"
#include "content/browser/device_sensors/device_inertial_sensor_service.h"
#include "content/common/device_sensors/device_light_hardware_buffer.h"
#include "content/common/device_sensors/device_motion_hardware_buffer.h"
#include "content/common/device_sensors/device_orientation_hardware_buffer.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_javascript_dialog_manager.h"
namespace content {
namespace {
class FakeDataFetcher : public DataFetcherSharedMemory {
public:
FakeDataFetcher()
: started_orientation_(false, false),
stopped_orientation_(false, false),
started_motion_(false, false),
stopped_motion_(false, false),
started_light_(false, false),
stopped_light_(false, false),
sensor_data_available_(true) {}
virtual ~FakeDataFetcher() { }
virtual bool Start(ConsumerType consumer_type, void* buffer) override {
EXPECT_TRUE(buffer);
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
{
DeviceMotionHardwareBuffer* motion_buffer =
static_cast<DeviceMotionHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateMotion(motion_buffer);
SetMotionBufferReady(motion_buffer);
started_motion_.Signal();
}
break;
case CONSUMER_TYPE_ORIENTATION:
{
DeviceOrientationHardwareBuffer* orientation_buffer =
static_cast<DeviceOrientationHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateOrientation(orientation_buffer);
SetOrientationBufferReady(orientation_buffer);
started_orientation_.Signal();
}
break;
case CONSUMER_TYPE_LIGHT:
{
DeviceLightHardwareBuffer* light_buffer =
static_cast<DeviceLightHardwareBuffer*>(buffer);
UpdateLight(light_buffer,
sensor_data_available_
? 100
: std::numeric_limits<double>::infinity());
started_light_.Signal();
}
break;
default:
return false;
}
return true;
}
virtual bool Stop(ConsumerType consumer_type) override {
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
stopped_motion_.Signal();
break;
case CONSUMER_TYPE_ORIENTATION:
stopped_orientation_.Signal();
break;
case CONSUMER_TYPE_LIGHT:
stopped_light_.Signal();
break;
default:
return false;
}
return true;
}
virtual void Fetch(unsigned consumer_bitmask) override {
FAIL() << "fetch should not be called";
}
virtual FetcherType GetType() const override {
return FETCHER_TYPE_DEFAULT;
}
void SetSensorDataAvailable(bool available) {
sensor_data_available_ = available;
}
void SetMotionBufferReady(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void SetOrientationBufferReady(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateMotion(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.accelerationX = 1;
buffer->data.hasAccelerationX = true;
buffer->data.accelerationY = 2;
buffer->data.hasAccelerationY = true;
buffer->data.accelerationZ = 3;
buffer->data.hasAccelerationZ = true;
buffer->data.accelerationIncludingGravityX = 4;
buffer->data.hasAccelerationIncludingGravityX = true;
buffer->data.accelerationIncludingGravityY = 5;
buffer->data.hasAccelerationIncludingGravityY = true;
buffer->data.accelerationIncludingGravityZ = 6;
buffer->data.hasAccelerationIncludingGravityZ = true;
buffer->data.rotationRateAlpha = 7;
buffer->data.hasRotationRateAlpha = true;
buffer->data.rotationRateBeta = 8;
buffer->data.hasRotationRateBeta = true;
buffer->data.rotationRateGamma = 9;
buffer->data.hasRotationRateGamma = true;
buffer->data.interval = 100;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateOrientation(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.alpha = 1;
buffer->data.hasAlpha = true;
buffer->data.beta = 2;
buffer->data.hasBeta = true;
buffer->data.gamma = 3;
buffer->data.hasGamma = true;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateLight(DeviceLightHardwareBuffer* buffer, double lux) {
buffer->seqlock.WriteBegin();
buffer->data.value = lux;
buffer->seqlock.WriteEnd();
}
base::WaitableEvent started_orientation_;
base::WaitableEvent stopped_orientation_;
base::WaitableEvent started_motion_;
base::WaitableEvent stopped_motion_;
base::WaitableEvent started_light_;
base::WaitableEvent stopped_light_;
bool sensor_data_available_;
private:
DISALLOW_COPY_AND_ASSIGN(FakeDataFetcher);
};
class DeviceInertialSensorBrowserTest : public ContentBrowserTest {
public:
DeviceInertialSensorBrowserTest()
: fetcher_(NULL),
io_loop_finished_event_(false, false) {
}
virtual void SetUpOnMainThread() override {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&DeviceInertialSensorBrowserTest::SetUpOnIOThread, this));
io_loop_finished_event_.Wait();
}
void SetUpOnIOThread() {
fetcher_ = new FakeDataFetcher();
DeviceInertialSensorService::GetInstance()->
SetDataFetcherForTesting(fetcher_);
io_loop_finished_event_.Signal();
}
void DelayAndQuit(base::TimeDelta delay) {
base::PlatformThread::Sleep(delay);
base::MessageLoop::current()->QuitWhenIdle();
}
void WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta delay) {
ShellJavaScriptDialogManager* dialog_manager=
static_cast<ShellJavaScriptDialogManager*>(
shell()->GetJavaScriptDialogManager());
scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner();
dialog_manager->set_dialog_request_callback(
base::Bind(&DeviceInertialSensorBrowserTest::DelayAndQuit, this,
delay));
runner->Run();
}
FakeDataFetcher* fetcher_;
private:
base::WaitableEvent io_loop_finished_event_;
};
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, OrientationTest) {
// The test page will register an event handler for orientation events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_orientation_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, LightTest) {
// The test page will register an event handler for light events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_light_test.html");
// TODO(riju): remove command line args when the feature goes stable.
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, MotionTest) {
// The test page will register an event handler for motion events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_motion_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
}
// crbug/416406. The test is flaky.
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
DISABLED_LightOneOffInfintyTest) {
// The test page will register an event handler for light events,
// expects to get an event with value equal to Infinity. This tests that the
// one-off infinity event still propagates to window after the alert is
// dismissed and the callback is invoked which navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
// TODO(riju): remove command line args when the feature goes stable.
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_light_infinity_test.html");
shell()->LoadURL(test_url);
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaking in the android try bot. See http://crbug.com/360578.
#if defined(OS_ANDROID)
#define MAYBE_OrientationNullTestWithAlert DISABLED_OrientationNullTestWithAlert
#else
#define MAYBE_OrientationNullTestWithAlert OrientationNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_OrientationNullTestWithAlert) {
// The test page will register an event handler for orientation events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url = GetTestUrl("device_sensors",
"device_orientation_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaking in the android try bot. See http://crbug.com/360578.
#if defined(OS_ANDROID)
#define MAYBE_MotionNullTestWithAlert DISABLED_MotionNullTestWithAlert
#else
#define MAYBE_MotionNullTestWithAlert MotionNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_MotionNullTestWithAlert) {
// The test page will register an event handler for motion events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_motion_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
} // namespace
} // namespace content
<commit_msg>Disable DeviceInertialSensorBrowserTest.MotionNullTestWithAlert on windows<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
#include "content/browser/device_sensors/data_fetcher_shared_memory.h"
#include "content/browser/device_sensors/device_inertial_sensor_service.h"
#include "content/common/device_sensors/device_light_hardware_buffer.h"
#include "content/common/device_sensors/device_motion_hardware_buffer.h"
#include "content/common/device_sensors/device_orientation_hardware_buffer.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_javascript_dialog_manager.h"
namespace content {
namespace {
class FakeDataFetcher : public DataFetcherSharedMemory {
public:
FakeDataFetcher()
: started_orientation_(false, false),
stopped_orientation_(false, false),
started_motion_(false, false),
stopped_motion_(false, false),
started_light_(false, false),
stopped_light_(false, false),
sensor_data_available_(true) {}
virtual ~FakeDataFetcher() { }
virtual bool Start(ConsumerType consumer_type, void* buffer) override {
EXPECT_TRUE(buffer);
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
{
DeviceMotionHardwareBuffer* motion_buffer =
static_cast<DeviceMotionHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateMotion(motion_buffer);
SetMotionBufferReady(motion_buffer);
started_motion_.Signal();
}
break;
case CONSUMER_TYPE_ORIENTATION:
{
DeviceOrientationHardwareBuffer* orientation_buffer =
static_cast<DeviceOrientationHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateOrientation(orientation_buffer);
SetOrientationBufferReady(orientation_buffer);
started_orientation_.Signal();
}
break;
case CONSUMER_TYPE_LIGHT:
{
DeviceLightHardwareBuffer* light_buffer =
static_cast<DeviceLightHardwareBuffer*>(buffer);
UpdateLight(light_buffer,
sensor_data_available_
? 100
: std::numeric_limits<double>::infinity());
started_light_.Signal();
}
break;
default:
return false;
}
return true;
}
virtual bool Stop(ConsumerType consumer_type) override {
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
stopped_motion_.Signal();
break;
case CONSUMER_TYPE_ORIENTATION:
stopped_orientation_.Signal();
break;
case CONSUMER_TYPE_LIGHT:
stopped_light_.Signal();
break;
default:
return false;
}
return true;
}
virtual void Fetch(unsigned consumer_bitmask) override {
FAIL() << "fetch should not be called";
}
virtual FetcherType GetType() const override {
return FETCHER_TYPE_DEFAULT;
}
void SetSensorDataAvailable(bool available) {
sensor_data_available_ = available;
}
void SetMotionBufferReady(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void SetOrientationBufferReady(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateMotion(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.accelerationX = 1;
buffer->data.hasAccelerationX = true;
buffer->data.accelerationY = 2;
buffer->data.hasAccelerationY = true;
buffer->data.accelerationZ = 3;
buffer->data.hasAccelerationZ = true;
buffer->data.accelerationIncludingGravityX = 4;
buffer->data.hasAccelerationIncludingGravityX = true;
buffer->data.accelerationIncludingGravityY = 5;
buffer->data.hasAccelerationIncludingGravityY = true;
buffer->data.accelerationIncludingGravityZ = 6;
buffer->data.hasAccelerationIncludingGravityZ = true;
buffer->data.rotationRateAlpha = 7;
buffer->data.hasRotationRateAlpha = true;
buffer->data.rotationRateBeta = 8;
buffer->data.hasRotationRateBeta = true;
buffer->data.rotationRateGamma = 9;
buffer->data.hasRotationRateGamma = true;
buffer->data.interval = 100;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateOrientation(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.alpha = 1;
buffer->data.hasAlpha = true;
buffer->data.beta = 2;
buffer->data.hasBeta = true;
buffer->data.gamma = 3;
buffer->data.hasGamma = true;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateLight(DeviceLightHardwareBuffer* buffer, double lux) {
buffer->seqlock.WriteBegin();
buffer->data.value = lux;
buffer->seqlock.WriteEnd();
}
base::WaitableEvent started_orientation_;
base::WaitableEvent stopped_orientation_;
base::WaitableEvent started_motion_;
base::WaitableEvent stopped_motion_;
base::WaitableEvent started_light_;
base::WaitableEvent stopped_light_;
bool sensor_data_available_;
private:
DISALLOW_COPY_AND_ASSIGN(FakeDataFetcher);
};
class DeviceInertialSensorBrowserTest : public ContentBrowserTest {
public:
DeviceInertialSensorBrowserTest()
: fetcher_(NULL),
io_loop_finished_event_(false, false) {
}
virtual void SetUpOnMainThread() override {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&DeviceInertialSensorBrowserTest::SetUpOnIOThread, this));
io_loop_finished_event_.Wait();
}
void SetUpOnIOThread() {
fetcher_ = new FakeDataFetcher();
DeviceInertialSensorService::GetInstance()->
SetDataFetcherForTesting(fetcher_);
io_loop_finished_event_.Signal();
}
void DelayAndQuit(base::TimeDelta delay) {
base::PlatformThread::Sleep(delay);
base::MessageLoop::current()->QuitWhenIdle();
}
void WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta delay) {
ShellJavaScriptDialogManager* dialog_manager=
static_cast<ShellJavaScriptDialogManager*>(
shell()->GetJavaScriptDialogManager());
scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner();
dialog_manager->set_dialog_request_callback(
base::Bind(&DeviceInertialSensorBrowserTest::DelayAndQuit, this,
delay));
runner->Run();
}
FakeDataFetcher* fetcher_;
private:
base::WaitableEvent io_loop_finished_event_;
};
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, OrientationTest) {
// The test page will register an event handler for orientation events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_orientation_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, LightTest) {
// The test page will register an event handler for light events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_light_test.html");
// TODO(riju): remove command line args when the feature goes stable.
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, MotionTest) {
// The test page will register an event handler for motion events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_motion_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
}
// crbug/416406. The test is flaky.
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
DISABLED_LightOneOffInfintyTest) {
// The test page will register an event handler for light events,
// expects to get an event with value equal to Infinity. This tests that the
// one-off infinity event still propagates to window after the alert is
// dismissed and the callback is invoked which navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
// TODO(riju): remove command line args when the feature goes stable.
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_light_infinity_test.html");
shell()->LoadURL(test_url);
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaking in the android try bot. See http://crbug.com/360578.
#if defined(OS_ANDROID)
#define MAYBE_OrientationNullTestWithAlert DISABLED_OrientationNullTestWithAlert
#else
#define MAYBE_OrientationNullTestWithAlert OrientationNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_OrientationNullTestWithAlert) {
// The test page will register an event handler for orientation events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url = GetTestUrl("device_sensors",
"device_orientation_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaking in the android try bot. See http://crbug.com/360578.
#if defined(OS_ANDROID) || defined(OS_WIN)
#define MAYBE_MotionNullTestWithAlert DISABLED_MotionNullTestWithAlert
#else
#define MAYBE_MotionNullTestWithAlert MotionNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_MotionNullTestWithAlert) {
// The test page will register an event handler for motion events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_motion_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
} // namespace
} // namespace content
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/configuration_policy_provider.h"
#include "base/values.h"
#include "chrome/common/policy_constants.h"
#include "chrome/common/notification_service.h"
namespace {
// TODO(avi): Use this mapping to auto-generate MCX manifests and Windows
// ADM/ADMX files. http://crbug.com/49316
struct InternalPolicyValueMapEntry {
ConfigurationPolicyStore::PolicyType policy_type;
Value::ValueType value_type;
const char* name;
};
const InternalPolicyValueMapEntry kPolicyValueMap[] = {
{ ConfigurationPolicyStore::kPolicyHomePage,
Value::TYPE_STRING, policy::key::kHomepageLocation },
{ ConfigurationPolicyStore::kPolicyHomepageIsNewTabPage,
Value::TYPE_BOOLEAN, policy::key::kHomepageIsNewTabPage },
{ ConfigurationPolicyStore::kPolicyRestoreOnStartup,
Value::TYPE_INTEGER, policy::key::kRestoreOnStartup },
{ ConfigurationPolicyStore::kPolicyURLsToRestoreOnStartup,
Value::TYPE_LIST, policy::key::kURLsToRestoreOnStartup },
{ ConfigurationPolicyStore::kPolicyProxyServerMode,
Value::TYPE_INTEGER, policy::key::kProxyServerMode },
{ ConfigurationPolicyStore::kPolicyProxyServer,
Value::TYPE_STRING, policy::key::kProxyServer },
{ ConfigurationPolicyStore::kPolicyProxyPacUrl,
Value::TYPE_STRING, policy::key::kProxyPacUrl },
{ ConfigurationPolicyStore::kPolicyProxyBypassList,
Value::TYPE_STRING, policy::key::kProxyBypassList },
{ ConfigurationPolicyStore::kPolicyAlternateErrorPagesEnabled,
Value::TYPE_BOOLEAN, policy::key::kAlternateErrorPagesEnabled },
{ ConfigurationPolicyStore::kPolicySearchSuggestEnabled,
Value::TYPE_BOOLEAN, policy::key::kSearchSuggestEnabled },
{ ConfigurationPolicyStore::kPolicyDnsPrefetchingEnabled,
Value::TYPE_BOOLEAN, policy::key::kDnsPrefetchingEnabled },
{ ConfigurationPolicyStore::kPolicySafeBrowsingEnabled,
Value::TYPE_BOOLEAN, policy::key::kSafeBrowsingEnabled },
{ ConfigurationPolicyStore::kPolicyMetricsReportingEnabled,
Value::TYPE_BOOLEAN, policy::key::kMetricsReportingEnabled },
{ ConfigurationPolicyStore::kPolicyPasswordManagerEnabled,
Value::TYPE_BOOLEAN, policy::key::kPasswordManagerEnabled },
{ ConfigurationPolicyStore::kPolicyPasswordManagerAllowShowPasswords,
Value::TYPE_BOOLEAN, policy::key::kPasswordManagerAllowShowPasswords },
{ ConfigurationPolicyStore::kPolicyAutoFillEnabled,
Value::TYPE_BOOLEAN, policy::key::kAutoFillEnabled },
{ ConfigurationPolicyStore::kPolicyDisabledPlugins,
Value::TYPE_LIST, policy::key::kDisabledPlugins },
{ ConfigurationPolicyStore::kPolicyApplicationLocale,
Value::TYPE_STRING, policy::key::kApplicationLocaleValue },
{ ConfigurationPolicyStore::kPolicySyncDisabled,
Value::TYPE_BOOLEAN, policy::key::kSyncDisabled },
{ ConfigurationPolicyStore::kPolicyExtensionInstallAllowList,
Value::TYPE_LIST, policy::key::kExtensionInstallAllowList },
{ ConfigurationPolicyStore::kPolicyExtensionInstallDenyList,
Value::TYPE_LIST, policy::key::kExtensionInstallDenyList },
{ ConfigurationPolicyStore::kPolicyShowHomeButton,
Value::TYPE_BOOLEAN, policy::key::kShowHomeButton },
};
} // namespace
/* static */
const ConfigurationPolicyProvider::PolicyValueMap*
ConfigurationPolicyProvider::PolicyValueMapping() {
static PolicyValueMap* mapping;
if (!mapping) {
mapping = new PolicyValueMap();
for (size_t i = 0; i < arraysize(kPolicyValueMap); ++i) {
const InternalPolicyValueMapEntry& internal_entry = kPolicyValueMap[i];
PolicyValueMapEntry entry;
entry.policy_type = internal_entry.policy_type;
entry.value_type = internal_entry.value_type;
entry.name = std::string(internal_entry.name);
mapping->push_back(entry);
}
}
return mapping;
}
void ConfigurationPolicyProvider::NotifyStoreOfPolicyChange() {
NotificationService::current()->Notify(
NotificationType::POLICY_CHANGED,
Source<ConfigurationPolicyProvider>(this),
NotificationService::NoDetails());
}
<commit_msg>Update bug reference.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/configuration_policy_provider.h"
#include "base/values.h"
#include "chrome/common/policy_constants.h"
#include "chrome/common/notification_service.h"
namespace {
// TODO(avi): Generate this mapping from the template metafile
// (chrome/app/policy/policy_templates.json). http://crbug.com/54711
struct InternalPolicyValueMapEntry {
ConfigurationPolicyStore::PolicyType policy_type;
Value::ValueType value_type;
const char* name;
};
const InternalPolicyValueMapEntry kPolicyValueMap[] = {
{ ConfigurationPolicyStore::kPolicyHomePage,
Value::TYPE_STRING, policy::key::kHomepageLocation },
{ ConfigurationPolicyStore::kPolicyHomepageIsNewTabPage,
Value::TYPE_BOOLEAN, policy::key::kHomepageIsNewTabPage },
{ ConfigurationPolicyStore::kPolicyRestoreOnStartup,
Value::TYPE_INTEGER, policy::key::kRestoreOnStartup },
{ ConfigurationPolicyStore::kPolicyURLsToRestoreOnStartup,
Value::TYPE_LIST, policy::key::kURLsToRestoreOnStartup },
{ ConfigurationPolicyStore::kPolicyProxyServerMode,
Value::TYPE_INTEGER, policy::key::kProxyServerMode },
{ ConfigurationPolicyStore::kPolicyProxyServer,
Value::TYPE_STRING, policy::key::kProxyServer },
{ ConfigurationPolicyStore::kPolicyProxyPacUrl,
Value::TYPE_STRING, policy::key::kProxyPacUrl },
{ ConfigurationPolicyStore::kPolicyProxyBypassList,
Value::TYPE_STRING, policy::key::kProxyBypassList },
{ ConfigurationPolicyStore::kPolicyAlternateErrorPagesEnabled,
Value::TYPE_BOOLEAN, policy::key::kAlternateErrorPagesEnabled },
{ ConfigurationPolicyStore::kPolicySearchSuggestEnabled,
Value::TYPE_BOOLEAN, policy::key::kSearchSuggestEnabled },
{ ConfigurationPolicyStore::kPolicyDnsPrefetchingEnabled,
Value::TYPE_BOOLEAN, policy::key::kDnsPrefetchingEnabled },
{ ConfigurationPolicyStore::kPolicySafeBrowsingEnabled,
Value::TYPE_BOOLEAN, policy::key::kSafeBrowsingEnabled },
{ ConfigurationPolicyStore::kPolicyMetricsReportingEnabled,
Value::TYPE_BOOLEAN, policy::key::kMetricsReportingEnabled },
{ ConfigurationPolicyStore::kPolicyPasswordManagerEnabled,
Value::TYPE_BOOLEAN, policy::key::kPasswordManagerEnabled },
{ ConfigurationPolicyStore::kPolicyPasswordManagerAllowShowPasswords,
Value::TYPE_BOOLEAN, policy::key::kPasswordManagerAllowShowPasswords },
{ ConfigurationPolicyStore::kPolicyAutoFillEnabled,
Value::TYPE_BOOLEAN, policy::key::kAutoFillEnabled },
{ ConfigurationPolicyStore::kPolicyDisabledPlugins,
Value::TYPE_LIST, policy::key::kDisabledPlugins },
{ ConfigurationPolicyStore::kPolicyApplicationLocale,
Value::TYPE_STRING, policy::key::kApplicationLocaleValue },
{ ConfigurationPolicyStore::kPolicySyncDisabled,
Value::TYPE_BOOLEAN, policy::key::kSyncDisabled },
{ ConfigurationPolicyStore::kPolicyExtensionInstallAllowList,
Value::TYPE_LIST, policy::key::kExtensionInstallAllowList },
{ ConfigurationPolicyStore::kPolicyExtensionInstallDenyList,
Value::TYPE_LIST, policy::key::kExtensionInstallDenyList },
{ ConfigurationPolicyStore::kPolicyShowHomeButton,
Value::TYPE_BOOLEAN, policy::key::kShowHomeButton },
};
} // namespace
/* static */
const ConfigurationPolicyProvider::PolicyValueMap*
ConfigurationPolicyProvider::PolicyValueMapping() {
static PolicyValueMap* mapping;
if (!mapping) {
mapping = new PolicyValueMap();
for (size_t i = 0; i < arraysize(kPolicyValueMap); ++i) {
const InternalPolicyValueMapEntry& internal_entry = kPolicyValueMap[i];
PolicyValueMapEntry entry;
entry.policy_type = internal_entry.policy_type;
entry.value_type = internal_entry.value_type;
entry.name = std::string(internal_entry.name);
mapping->push_back(entry);
}
}
return mapping;
}
void ConfigurationPolicyProvider::NotifyStoreOfPolicyChange() {
NotificationService::current()->Notify(
NotificationType::POLICY_CHANGED,
Source<ConfigurationPolicyProvider>(this),
NotificationService::NoDetails());
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>
#include <cstdlib>
#include <cstring>
#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "terminate_message.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"
using namespace std;
//TODO:
//MANAGE CLIENT CONNECTION
//MANAGE SERVER CONNECTION
//DATABASE
//ROUND ROBIN
static map<procedure_signature, list<server_info *>, ps_compare> procLocDict;
static list<server_function_info *> roundRobinList;
static list<server_info *> serverList;
static bool onSwitch = true;
/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/
void mapPrint(){
cout << "procLocDict size: "<<procLocDict.size() << endl;
cout << "Map Print: ";
for(map<procedure_signature, list<server_info *>, ps_compare> ::const_iterator it = procLocDict.begin();
it != procLocDict.end(); it++){
cout << it->first.name << ", " ;
}
cout << endl;
}
void roundRobinPrint(){
cout << "roundRobin Print: ";
for(list<server_function_info *> ::const_iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
cout <<(*it)->si->server_identifier << ", "<<(*it)->si->port << ", "<<(*it)->ps->name << endl;
}
}
void serverListPrint(){
cout << "serverList Print: " << endl;
for(list<server_info *> ::const_iterator it = serverList.begin(); it != serverList.end(); it++){
cout << (*it)->server_identifier << ", " << (*it)->port << ", " << (*it)->socket<< endl;
}
}
void registration_request_handler(RegisterRequestMessage * message, int sock){
const char * name = message->getName().c_str();
int * argTypes = message->getArgTypes();
string server_identifier = message->getServerIdentifier();
int port = message->getPort();
cout << "We are trying to register: " << name << ", " << server_identifier << ", " << port << endl;
procedure_signature key(name, argTypes);
int status = 0;
//if 'key' dosnt exist in map, add it to the map and round robin
if (procLocDict.find(key) == procLocDict.end()) {
//The purpose of this function is so we can have copy of the argTypes that not the original
int *memArgTypes = copyArgTypes(argTypes);
key = procedure_signature(name, memArgTypes);
procLocDict[key] = list<server_info *>();
//This is bad we shouldn't need a newKey and we should be able to use the key above
//due to &* reasones I made a variable newKey for the 'info' object
procedure_signature * newKey = new procedure_signature(name, memArgTypes);
server_info * entry = new server_info(server_identifier, port, sock);
server_function_info * info = new server_function_info(entry, newKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
//if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
if( (*it)->port == entry->port && (*it)->socket == entry->socket){
cout << "entry->port" << entry->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if(!serverExist){
cout << "why doesnt this work" << endl;
serverList.push_back(entry);
}
} else {
bool sameLoc = false;
list<server_info *> hostList = procLocDict[key];
for (list<server_info *>::iterator it = hostList.begin(); it != hostList.end(); it++) {
if((*it)->server_identifier == server_identifier && (*it)->port == port && (*it)->socket == sock){
//If they have the same socket, then must be same server_address/port
//The same procedure signature already exists on the same location
//TODO: Move to end of round robin or something, maybe we should keep
cout << "Exact same proc and loc" << endl;
sameLoc = true;
}
}
if(!sameLoc){ //same procedure different socket
cout << "same proc different loc" << endl;
server_info * new_msg_loc = new server_info(server_identifier, port, sock);
hostList.push_back(new_msg_loc);
int *newArgTypes = copyArgTypes(argTypes);
procedure_signature * useFulKey = new procedure_signature(name, newArgTypes);
server_function_info * info = new server_function_info(new_msg_loc, useFulKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
//if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
if( (*it)->port == new_msg_loc->port && (*it)->socket == new_msg_loc->socket){
cout << "new_msg_loc->port" << new_msg_loc->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if(!serverExist){
cout << "why doesnt this work" << endl;
serverList.push_back(new_msg_loc);
}
}
}
//mapPrint();
//roundRobinPrint();
serverListPrint();
RegisterSuccessMessage regSuccessMsg = RegisterSuccessMessage(status);
Segment regSuccessSeg = Segment(regSuccessMsg.getLength(), MSG_TYPE_REGISTER_SUCCESS, ®SuccessMsg);
regSuccessSeg.send(sock);
cout << "sock: " << sock << endl;
}
/*
TODO:
USE ROUND ROBIN TO ACCESS THE CORRECT SERVER/FUNCTION FOR THE CLIENT
*/
void location_request_handler(LocRequestMessage * message, int sock){
bool exist = false;
string serverIdToPushBack;
int portToPushBack;
int socketToPushBack;
//cout << "Hunted name names: " << message->getName() << endl;
for (list<server_function_info *>::iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
//If the name are the same and argTypes
//cout << "Iterator names: " << (*it)->ps->name << endl;
if((*it)->ps->name == message->getName() && compareArr((*it)->ps->argTypes, message->getArgTypes() )){
exist = true;
cout << "Sending to server: " << (*it)->si->server_identifier << ", "<< (*it)->si->port<< endl;
serverIdToPushBack = (*it)->si->server_identifier;
portToPushBack = (*it)->si->port;
socketToPushBack = (*it)->si->socket;
LocSuccessMessage locSuccessMsg = LocSuccessMessage((*it)->si->server_identifier.c_str(), (*it)->si->port);
Segment locSuccessSeg = Segment(locSuccessMsg.getLength(), MSG_TYPE_LOC_SUCCESS, &locSuccessMsg);
locSuccessSeg.send(sock);
//When we have identified the correct procedure_signature use splice and move that service to the end
//roundRobinList.splice(roundRobinList.end(), roundRobinList, it);
break;
}
}
if(exist){
list<server_function_info *>::iterator i = roundRobinList.begin();
list<server_function_info *> tempList;
while (i != roundRobinList.end()){
//bool isActive = (*i)->update();
//if((*it)->si->server_identifier == serverIdToPushBack && (*it)->si->port == portToPushBack && (*it)->si->socket == socketToPushBack){
if ((*i)->si->port == portToPushBack && (*i)->si->socket == socketToPushBack){
tempList.push_back(*i);
roundRobinList.erase(i++); // alternatively, i = items.erase(i);
}else{
++i;
}
}
roundRobinList.splice(roundRobinList.end(), tempList);
roundRobinPrint();
}else {
int reasoncode = -5; // Need actual reasoncode
LocFailureMessage locFailMsg = LocFailureMessage(reasoncode);
Segment locFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
locFailSeg.send(sock);
}
}
void binder_terminate_handler() {
cout << "Binder set to execute" << endl;
for (list<server_info *>::const_iterator it = serverList.begin(); it != serverList.end(); it++) {
cout << "Terminating server: " << (*it)->server_identifier << ", " << (*it)->port << ", " << (*it)->socket<< endl;
TerminateMessage termMsg = TerminateMessage();
Segment termSeg = Segment(termMsg.getLength(), MSG_TYPE_TERMINATE, &termMsg);
termSeg.send((*it)->socket);
sleep(1);
}
onSwitch = false;
}
int request_handler(Segment * segment, int sock){
int retval = 0;
if(segment->getType() == MSG_TYPE_REGISTER_REQUEST){
Message * cast1 = segment->getMessage();
RegisterRequestMessage * rrm = dynamic_cast<RegisterRequestMessage*>(cast1);
registration_request_handler(rrm, sock);
}else if (segment->getType() == MSG_TYPE_LOC_REQUEST){
//cout << "Loc Request" << endl;
Message * cast2 = segment->getMessage();
LocRequestMessage * lqm = dynamic_cast<LocRequestMessage*>(cast2);
location_request_handler(lqm, sock);
}else if (segment->getType() == MSG_TYPE_TERMINATE){
cout << "Terminate Request" <<endl;
binder_terminate_handler();
}
return retval;
}
//TODO:
//Create helper functions that can be used for rpcServer.cc
int main() {
fd_set allSockets;
fd_set readSockets;
/*
* Clears all entries from the all sockets set and the read
* sockets set
*/
FD_ZERO(&allSockets);
FD_ZERO(&readSockets);
/*
* Creates the welcome socket, adds it to the all sockets set and
* sets it as the maximum socket so far
*/
int welcomeSocket = createSocket();
int status = setUpToListen(welcomeSocket);
FD_SET(welcomeSocket, &allSockets);
int maxSocket = welcomeSocket;
/*
* Prints the binder address and the binder port on the binder's
* standard output
*/
cout << "BINDER_ADDRESS " << getHostAddress() << endl;
cout << "BINDER_PORT " << getSocketPort(welcomeSocket) << endl;
while (onSwitch) {
readSockets = allSockets;
// Checks if some of the sockets are ready to be read from
int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
if (result < 0) {
continue;
}
for (int i = 0; i <= maxSocket; i++) {
if (!FD_ISSET(i, &readSockets)) {
continue;
}
if (i == welcomeSocket) {
/*
* Creates the connection socket when a connection is made
* to the welcome socket
*/
int connectionSocket = acceptConnection(i);
if (connectionSocket < 0) {
continue;
}
//cout << "WE heard from connectionSocket: " << connectionSocket << endl;
// Adds the connection socket to the all sockets set
FD_SET(connectionSocket, &allSockets);
/*
* Sets the connection socket as the maximum socket so far
* if necessary
*/
if (connectionSocket > maxSocket) {
maxSocket = connectionSocket;
}
} else {
/*
* Creates a segment to receive data from the client/server and
* reads into it from the connection socket
*/
Segment *segment = 0;
result = 0;
result = Segment::receive(i, segment);
if (result < 0) {
/*
* Closes the connection socket and removes it from the
* all sockets set
*/
destroySocket(i);
FD_CLR(i, &allSockets);
continue;
}
request_handler(segment, i);
}
}
}
// Destroys the welcome socket
destroySocket(welcomeSocket);
}
<commit_msg>still doesnt work<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>
#include <cstdlib>
#include <cstring>
#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "terminate_message.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"
using namespace std;
//TODO:
//MANAGE CLIENT CONNECTION
//MANAGE SERVER CONNECTION
//DATABASE
//ROUND ROBIN
static map<procedure_signature, list<server_info *>, ps_compare> procLocDict;
static list<server_function_info *> roundRobinList;
static list<server_info *> serverList;
static bool onSwitch = true;
/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/
void mapPrint(){
cout << "procLocDict size: "<<procLocDict.size() << endl;
cout << "Map Print: ";
for(map<procedure_signature, list<server_info *>, ps_compare> ::const_iterator it = procLocDict.begin();
it != procLocDict.end(); it++){
cout << it->first.name << ", " ;
}
cout << endl;
}
void roundRobinPrint(){
cout << "roundRobin Print: ";
for(list<server_function_info *> ::const_iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
cout <<(*it)->si->server_identifier << ", "<<(*it)->si->port << ", "<<(*it)->ps->name << endl;
}
}
void serverListPrint(){
cout << "serverList Print: " << endl;
for(list<server_info *> ::const_iterator it = serverList.begin(); it != serverList.end(); it++){
cout << (*it)->server_identifier << ", " << (*it)->port << ", " << (*it)->socket<< endl;
}
}
void registration_request_handler(RegisterRequestMessage * message, int sock){
const char * name = message->getName().c_str();
int * argTypes = message->getArgTypes();
string server_identifier = message->getServerIdentifier();
int port = message->getPort();
cout << "We are trying to register: " << name << ", " << server_identifier << ", " << port << endl;
procedure_signature key(name, argTypes);
int status = 0;
//if 'key' dosnt exist in map, add it to the map and round robin
if (procLocDict.find(key) == procLocDict.end()) {
//The purpose of this function is so we can have copy of the argTypes that not the original
int *memArgTypes = copyArgTypes(argTypes);
key = procedure_signature(name, memArgTypes);
procLocDict[key] = list<server_info *>();
//This is bad we shouldn't need a newKey and we should be able to use the key above
//due to &* reasones I made a variable newKey for the 'info' object
procedure_signature * newKey = new procedure_signature(name, memArgTypes);
server_info * entry = new server_info(server_identifier, port, sock);
server_function_info * info = new server_function_info(entry, newKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
//if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
if( (*it)->port == entry->port && (*it)->socket == entry->socket){
cout << "entry->port" << entry->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if(!serverExist){
cout << "why doesnt this work" << endl;
serverList.push_back(entry);
}
} else {
bool sameLoc = false;
list<server_info *> hostList = procLocDict[key];
for (list<server_info *>::iterator it = hostList.begin(); it != hostList.end(); it++) {
if((*it)->server_identifier == server_identifier && (*it)->port == port && (*it)->socket == sock){
//If they have the same socket, then must be same server_address/port
//The same procedure signature already exists on the same location
//TODO: Move to end of round robin or something, maybe we should keep
cout << "Exact same proc and loc" << endl;
sameLoc = true;
}
}
if(!sameLoc){ //same procedure different socket
cout << "same proc different loc" << endl;
server_info * new_msg_loc = new server_info(server_identifier, port, sock);
hostList.push_back(new_msg_loc);
int *newArgTypes = copyArgTypes(argTypes);
procedure_signature * useFulKey = new procedure_signature(name, newArgTypes);
server_function_info * info = new server_function_info(new_msg_loc, useFulKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
//if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
if( (*it)->port == new_msg_loc->port && (*it)->socket == new_msg_loc->socket){
cout << "new_msg_loc->port" << new_msg_loc->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if(!serverExist){
cout << "why doesnt this work" << endl;
serverList.push_back(new_msg_loc);
}
}
}
//mapPrint();
//roundRobinPrint();
serverListPrint();
RegisterSuccessMessage regSuccessMsg = RegisterSuccessMessage(status);
Segment regSuccessSeg = Segment(regSuccessMsg.getLength(), MSG_TYPE_REGISTER_SUCCESS, ®SuccessMsg);
regSuccessSeg.send(sock);
cout << "sock: " << sock << endl;
}
/*
TODO:
USE ROUND ROBIN TO ACCESS THE CORRECT SERVER/FUNCTION FOR THE CLIENT
*/
void location_request_handler(LocRequestMessage * message, int sock){
bool exist = false;
string serverIdToPushBack;
int portToPushBack;
int socketToPushBack;
//cout << "Hunted name names: " << message->getName() << endl;
for (list<server_function_info *>::iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
//If the name are the same and argTypes
//cout << "Iterator names: " << (*it)->ps->name << endl;
if((*it)->ps->name == message->getName() && compareArr((*it)->ps->argTypes, message->getArgTypes() )){
exist = true;
cout << "Sending to server: " << (*it)->si->server_identifier << ", "<< (*it)->si->port<< endl;
serverIdToPushBack = (*it)->si->server_identifier;
portToPushBack = (*it)->si->port;
socketToPushBack = (*it)->si->socket;
LocSuccessMessage locSuccessMsg = LocSuccessMessage((*it)->si->server_identifier.c_str(), (*it)->si->port);
Segment locSuccessSeg = Segment(locSuccessMsg.getLength(), MSG_TYPE_LOC_SUCCESS, &locSuccessMsg);
locSuccessSeg.send(sock);
//When we have identified the correct procedure_signature use splice and move that service to the end
//roundRobinList.splice(roundRobinList.end(), roundRobinList, it);
break;
}
}
if(exist){
list<server_function_info *>::iterator i = roundRobinList.begin();
list<server_function_info *> tempList;
while (i != roundRobinList.end()){
//bool isActive = (*i)->update();
//if((*it)->si->server_identifier == serverIdToPushBack && (*it)->si->port == portToPushBack && (*it)->si->socket == socketToPushBack){
if ((*i)->si->port == portToPushBack && (*i)->si->socket == socketToPushBack){
tempList.push_back(*i);
roundRobinList.erase(i++); // alternatively, i = items.erase(i);
}else{
++i;
}
}
roundRobinList.splice(roundRobinList.end(), tempList);
roundRobinPrint();
}else {
int reasoncode = -5; // Need actual reasoncode
LocFailureMessage locFailMsg = LocFailureMessage(reasoncode);
Segment locFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
locFailSeg.send(sock);
}
}
void binder_terminate_handler() {
cout << "Binder set to execute" << endl;
for (list<server_info *>::const_iterator it = serverList.begin(); it != serverList.end(); it++) {
cout << "Terminating server: " << (*it)->server_identifier << ", " << (*it)->port << ", " << (*it)->socket<< endl;
TerminateMessage termMsg = TerminateMessage();
Segment termSeg = Segment(termMsg.getLength(), MSG_TYPE_TERMINATE, &termMsg);
termSeg.send((*it)->socket);
sleep(1);
}
onSwitch = false;
}
int request_handler(Segment * segment, int sock){
int retval = 0;
if(segment->getType() == MSG_TYPE_REGISTER_REQUEST){
Message * cast1 = segment->getMessage();
RegisterRequestMessage * rrm = dynamic_cast<RegisterRequestMessage*>(cast1);
registration_request_handler(rrm, sock);
}else if (segment->getType() == MSG_TYPE_LOC_REQUEST){
//cout << "Loc Request" << endl;
Message * cast2 = segment->getMessage();
LocRequestMessage * lqm = dynamic_cast<LocRequestMessage*>(cast2);
location_request_handler(lqm, sock);
}else if (segment->getType() == MSG_TYPE_TERMINATE){
cout << "Terminate Request" <<endl;
binder_terminate_handler();
}
return retval;
}
//TODO:
//Create helper functions that can be used for rpcServer.cc
int main() {
fd_set allSockets;
fd_set readSockets;
/*
* Clears all entries from the all sockets set and the read
* sockets set
*/
FD_ZERO(&allSockets);
FD_ZERO(&readSockets);
/*
* Creates the welcome socket, adds it to the all sockets set and
* sets it as the maximum socket so far
*/
int welcomeSocket = createSocket();
int status = setUpToListen(welcomeSocket);
FD_SET(welcomeSocket, &allSockets);
int maxSocket = welcomeSocket;
/*
* Prints the binder address and the binder port on the binder's
* standard output
*/
cout << "BINDER_ADDRESS " << getHostAddress() << endl;
cout << "BINDER_PORT " << getSocketPort(welcomeSocket) << endl;
while (onSwitch) {
readSockets = allSockets;
// Checks if some of the sockets are ready to be read from
int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
if (result < 0) {
continue;
}
for (int i = 0; i <= maxSocket; i++) {
if (!FD_ISSET(i, &readSockets)) {
continue;
}
if (i == welcomeSocket) {
/*
* Creates the connection socket when a connection is made
* to the welcome socket
*/
int connectionSocket = acceptConnection(i);
if (connectionSocket < 0) {
continue;
}
//cout << "WE heard from connectionSocket: " << connectionSocket << endl;
// Adds the connection socket to the all sockets set
FD_SET(connectionSocket, &allSockets);
/*
* Sets the connection socket as the maximum socket so far
* if necessary
*/
if (connectionSocket > maxSocket) {
maxSocket = connectionSocket;
}
} else {
/*
* Creates a segment to receive data from the client/server and
* reads into it from the connection socket
*/
Segment *segment = 0;
result = 0;
result = Segment::receive(i, segment);
if (result < 0) {
/*
* Closes the connection socket and removes it from the
* all sockets set
*/
destroySocket(i);
FD_CLR(i, &allSockets);
continue;
}
request_handler(segment, i);
}
}
}
// Destroys the welcome socket
destroySocket(welcomeSocket);
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <string>
#include <list>
#include <map>
#include <iostream>
#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "terminate_message.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"
using namespace std;
// Global variables for binder
static map<procedure_signature, list<server_info *>, ps_compare> procLocDict;
static list<server_function_info *> roundRobinList;
static list<server_info *> serverList;
static bool isTerminated = false;
/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/
void mapPrint(){
cout << "procLocDict size: "<<procLocDict.size() << endl;
cout << "Map Print: ";
for(map<procedure_signature, list<server_info *>, ps_compare> ::const_iterator it = procLocDict.begin();
it != procLocDict.end(); it++){
cout << it->first.name << ", " ;
}
cout << endl;
}
void roundRobinPrint(){
cout << "roundRobin Print: ";
for(list<server_function_info *> ::const_iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
cout <<(*it)->si->server_identifier << ", "<<(*it)->si->port << ", "<<(*it)->ps->name << endl;
}
}
void serverListPrint(){
cout << "serverList Print: " << endl;
for(list<server_info *> ::const_iterator it = serverList.begin(); it != serverList.end(); it++){
cout << (*it)->server_identifier << ", " << (*it)->port << ", " << (*it)->socket<< endl;
}
}
// Handles a registration request from the server
void handleRegistrationRequest(RegisterRequestMessage *message, int sock) {
const char * name = message->getName().c_str();
int * argTypes = message->getArgTypes();
string server_identifier = message->getServerIdentifier();
int port = message->getPort();
cout << "We are trying to register: " << name << ", " << server_identifier << ", " << port << endl;
procedure_signature key(name, argTypes);
int status = 0;
//if 'key' dosnt exist in map, add it to the map and round robin
if (procLocDict.find(key) == procLocDict.end()) {
//The purpose of this function is so we can have copy of the argTypes that not the original
int *memArgTypes = copyArgTypes(argTypes);
key = procedure_signature(name, memArgTypes);
procLocDict[key] = list<server_info *>();
//This is bad we shouldn't need a newKey and we should be able to use the key above
//due to &* reasones I made a variable newKey for the 'info' object
procedure_signature * newKey = new procedure_signature(name, memArgTypes);
server_info * entry = new server_info(server_identifier, port, sock);
server_function_info * info = new server_function_info(entry, newKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
cout << "(*it)->server_identifier" << (*it)->server_identifier << endl;
cout << "entry->server_identifier" << entry->server_identifier << endl;
if ((*it)->server_identifier == entry->server_identifier){
cout << "The same " << endl;
} else {
cout << "is different" << endl;
}
if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
//if( (*it)->port == entry->port && (*it)->socket == entry->socket){
cout << "entry->port" << entry->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if (!serverExist) {
serverList.push_back(entry);
}
} else {
bool sameLoc = false;
list<server_info *> hostList = procLocDict[key];
for (list<server_info *>::iterator it = hostList.begin(); it != hostList.end(); it++) {
if((*it)->server_identifier == server_identifier && (*it)->port == port && (*it)->socket == sock){
//if((*it)->port == port && (*it)->socket == sock){
//If they have the same socket, then must be same server_address/port
//The same procedure signature already exists on the same location
//TODO: Move to end of round robin or something, maybe we should keep
cout << "Exact same proc and loc" << endl;
sameLoc = true;
}
}
if (!sameLoc) { //same procedure different socket
cout << "same proc different loc" << endl;
server_info * new_msg_loc = new server_info(server_identifier, port, sock);
hostList.push_back(new_msg_loc);
int *newArgTypes = copyArgTypes(argTypes);
procedure_signature * useFulKey = new procedure_signature(name, newArgTypes);
server_function_info * info = new server_function_info(new_msg_loc, useFulKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
//if( (*it)->port == new_msg_loc->port && (*it)->socket == new_msg_loc->socket){
cout << "new_msg_loc->port" << new_msg_loc->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if (!serverExist) {
serverList.push_back(new_msg_loc);
}
}
}
serverListPrint();
RegisterSuccessMessage regSuccessMsg = RegisterSuccessMessage(status);
Segment regSuccessSeg = Segment(regSuccessMsg.getLength(), MSG_TYPE_REGISTER_SUCCESS, ®SuccessMsg);
regSuccessSeg.send(sock);
cout << "sock: " << sock << endl;
}
// Handles a location request from the client
void handleLocationRequest(LocRequestMessage *message, int sock) {
bool exist = false;
string serverIdToPushBack;
int portToPushBack;
int socketToPushBack;
for (list<server_function_info *>::iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
//If the name are the same and argTypes
if((*it)->ps->name == message->getName() && compareArr((*it)->ps->argTypes, message->getArgTypes() )){
exist = true;
cout << "Sending to server: " << (*it)->si->server_identifier << ", "<< (*it)->si->port<< endl;
serverIdToPushBack = (*it)->si->server_identifier;
portToPushBack = (*it)->si->port;
socketToPushBack = (*it)->si->socket;
LocSuccessMessage locSuccessMsg = LocSuccessMessage((*it)->si->server_identifier.c_str(), (*it)->si->port);
Segment locSuccessSeg = Segment(locSuccessMsg.getLength(), MSG_TYPE_LOC_SUCCESS, &locSuccessMsg);
locSuccessSeg.send(sock);
break;
}
}
if (exist) {
list<server_function_info *>::iterator i = roundRobinList.begin();
list<server_function_info *> tempList;
while (i != roundRobinList.end()){
//bool isActive = (*i)->update();
if((*i)->si->server_identifier == serverIdToPushBack && (*i)->si->port == portToPushBack && (*i)->si->socket == socketToPushBack){
//if ((*i)->si->port == portToPushBack && (*i)->si->socket == socketToPushBack){
tempList.push_back(*i);
roundRobinList.erase(i++); // alternatively, i = items.erase(i);
}else{
++i;
}
}
roundRobinList.splice(roundRobinList.end(), tempList);
roundRobinPrint();
} else {
LocFailureMessage locFailMsg =
LocFailureMessage(ERROR_CODE_PROCEDURE_NOT_FOUND);
Segment locFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
locFailSeg.send(sock);
}
}
// Handles a termination request from the client
void handleTerminationRequest() {
// Informs all the servers to terminate
for (list<server_info *>::const_iterator it = serverList.begin(); it != serverList.end(); it++) {
cout << "Terminating server: " << (*it)->server_identifier;
cout << ", " << (*it)->port;
cout << ", " << (*it)->socket << endl;
TerminateMessage messageToServer = TerminateMessage();
Segment segmentToServer =
Segment(messageToServer.getLength(), MSG_TYPE_TERMINATE,
&messageToServer);
segmentToServer.send((*it)->socket);
}
// Signals the binder to terminate
isTerminated = true;
}
// Handles a request from the client/server
void handleRequest(Segment *segment, int socket) {
switch (segment->getType()) {
case MSG_TYPE_REGISTER_REQUEST: {
RegisterRequestMessage *messageFromServer =
dynamic_cast<RegisterRequestMessage *>(segment->getMessage());
handleRegistrationRequest(messageFromServer, socket);
break;
}
case MSG_TYPE_LOC_REQUEST: {
LocRequestMessage *messageFromClient =
dynamic_cast<LocRequestMessage *>(segment->getMessage());
handleLocationRequest(messageFromClient, socket);
break;
}
case MSG_TYPE_TERMINATE: {
handleTerminationRequest();
break;
}
}
}
int main() {
fd_set allSockets;
fd_set readSockets;
/*
* Clears all entries from the all sockets set and the read
* sockets set
*/
FD_ZERO(&allSockets);
FD_ZERO(&readSockets);
/*
* Creates the welcome socket, adds it to the all sockets set and
* sets it as the maximum socket so far
*/
int welcomeSocket = createSocket();
if (welcomeSocket < 0) {
return welcomeSocket;
}
int result = setUpToListen(welcomeSocket);
if (result < 0) {
return result;
}
FD_SET(welcomeSocket, &allSockets);
int maxSocket = welcomeSocket;
/*
* Prints the binder address and the binder port on the binder's
* standard output
*/
string binderIdentifier = getHostAddress();
if (binderIdentifier == "") {
return ERROR_CODE_HOST_ADDRESS_NOT_FOUND;
}
int port = getSocketPort(welcomeSocket);
if (port < 0) {
return port;
}
cout << "BINDER_ADDRESS " << binderIdentifier << endl;
cout << "BINDER_PORT " << port << endl;
while (!isTerminated) {
readSockets = allSockets;
// Checks if some of the sockets are ready to be read from
int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
if (result < 0) {
continue;
}
for (int i = 0; i <= maxSocket; i++) {
if (!FD_ISSET(i, &readSockets)) {
continue;
}
if (i == welcomeSocket) {
/*
* Creates the connection socket when a connection is made
* to the welcome socket
*/
int connectionSocket = acceptConnection(i);
if (connectionSocket < 0) {
continue;
}
// Adds the connection socket to the all sockets set
FD_SET(connectionSocket, &allSockets);
/*
* Sets the connection socket as the maximum socket so far
* if necessary
*/
if (connectionSocket > maxSocket) {
maxSocket = connectionSocket;
}
} else {
/*
* Creates a segment to receive data from the client/server and
* reads into it from the connection socket
*/
Segment *segment = 0;
result = 0;
result = Segment::receive(i, segment);
if (result < 0) {
/*
* Closes the connection socket and removes it from the
* all sockets set
*/
destroySocket(i);
FD_CLR(i, &allSockets);
continue;
}
// Handles a request from the client/server
handleRequest(segment, i);
}
}
}
// Destroys the welcome socket
destroySocket(welcomeSocket);
return SUCCESS_CODE;
}
<commit_msg>cleaning up<commit_after>#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <string>
#include <list>
#include <map>
#include <iostream>
#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "terminate_message.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"
using namespace std;
// Global variables for binder
static map<procedure_signature, list<server_info *>, ps_compare> procLocDict;
static list<server_function_info *> roundRobinList;
static list<server_info *> serverList;
static bool isTerminated = false;
/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/
void mapPrint(){
cout << "procLocDict size: "<<procLocDict.size() << endl;
cout << "Map Print: ";
for(map<procedure_signature, list<server_info *>, ps_compare> ::const_iterator it = procLocDict.begin();
it != procLocDict.end(); it++){
cout << it->first.name << ", " ;
}
cout << endl;
}
void roundRobinPrint(){
cout << "roundRobin Print: ";
for(list<server_function_info *> ::const_iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
cout <<(*it)->si->server_identifier << ", "<<(*it)->si->port << ", "<<(*it)->ps->name << endl;
}
}
void serverListPrint(){
cout << "serverList Print: " << endl;
for(list<server_info *> ::const_iterator it = serverList.begin(); it != serverList.end(); it++){
cout << (*it)->server_identifier << ", " << (*it)->port << ", " << (*it)->socket<< endl;
}
}
// Handles a registration request from the server
void handleRegistrationRequest(RegisterRequestMessage *message, int sock) {
const char * name = message->getName().c_str();
int * argTypes = message->getArgTypes();
string server_identifier = message->getServerIdentifier();
int port = message->getPort();
cout << "We are trying to register: " << name << ", " << server_identifier << ", " << port << endl;
procedure_signature key(name, argTypes);
int status = 0;
//if 'key' dosnt exist in map, add it to the map and round robin
if (procLocDict.find(key) == procLocDict.end()) {
//The purpose of this function is so we can have copy of the argTypes that not the original
int *memArgTypes = copyArgTypes(argTypes);
key = procedure_signature(name, memArgTypes);
procLocDict[key] = list<server_info *>();
//This is bad we shouldn't need a newKey and we should be able to use the key above
//due to &* reasones I made a variable newKey for the 'info' object
procedure_signature * newKey = new procedure_signature(name, memArgTypes);
server_info * entry = new server_info(server_identifier, port, sock);
server_function_info * info = new server_function_info(entry, newKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
cout << "(*it)->server_identifier" << (*it)->server_identifier << endl;
cout << "entry->server_identifier" << entry->server_identifier << endl;
if ((*it)->server_identifier == entry->server_identifier){
cout << "The same " << endl;
} else {
cout << "is different" << endl;
}
if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
//if( (*it)->port == entry->port && (*it)->socket == entry->socket){
cout << "entry->port" << entry->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if (!serverExist) {
serverList.push_back(entry);
}
} else {
bool sameLoc = false;
list<server_info *> hostList = procLocDict[key];
for (list<server_info *>::iterator it = hostList.begin(); it != hostList.end(); it++) {
if((*it)->server_identifier == server_identifier && (*it)->port == port && (*it)->socket == sock){
//if((*it)->port == port && (*it)->socket == sock){
//If they have the same socket, then must be same server_address/port
//The same procedure signature already exists on the same location
//TODO: Move to end of round robin or something, maybe we should keep
cout << "Exact same proc and loc" << endl;
sameLoc = true;
}
}
if (!sameLoc) { //same procedure different socket
cout << "same proc different loc" << endl;
server_info * new_msg_loc = new server_info(server_identifier, port, sock);
hostList.push_back(new_msg_loc);
int *newArgTypes = copyArgTypes(argTypes);
procedure_signature * useFulKey = new procedure_signature(name, newArgTypes);
server_function_info * info = new server_function_info(new_msg_loc, useFulKey);
//Adding to roundRobinList if server is not found
roundRobinList.push_back(info);
//Adding to serverList if server is not found
bool serverExist = false;
for (list<server_info *>::iterator it = serverList.begin(); it != serverList.end(); it++) {
if( (*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket){
//if( (*it)->port == new_msg_loc->port && (*it)->socket == new_msg_loc->socket){
cout << "new_msg_loc->port" << new_msg_loc->port << ", " << (*it)->port << endl;
serverExist = true;
break;
}
}
if (!serverExist) {
serverList.push_back(new_msg_loc);
}
}
}
//serverListPrint();
RegisterSuccessMessage regSuccessMsg = RegisterSuccessMessage(status);
Segment regSuccessSeg = Segment(regSuccessMsg.getLength(), MSG_TYPE_REGISTER_SUCCESS, ®SuccessMsg);
regSuccessSeg.send(sock);
cout << "sock: " << sock << endl;
}
// Handles a location request from the client
void handleLocationRequest(LocRequestMessage *message, int sock) {
bool exist = false;
string serverIdToPushBack;
int portToPushBack;
int socketToPushBack;
for (list<server_function_info *>::iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
//If the name are the same and argTypes
if((*it)->ps->name == message->getName() && compareArr((*it)->ps->argTypes, message->getArgTypes() )){
exist = true;
cout << "Sending to server: " << (*it)->si->server_identifier << ", "<< (*it)->si->port<< endl;
serverIdToPushBack = (*it)->si->server_identifier;
portToPushBack = (*it)->si->port;
socketToPushBack = (*it)->si->socket;
LocSuccessMessage locSuccessMsg = LocSuccessMessage((*it)->si->server_identifier.c_str(), (*it)->si->port);
Segment locSuccessSeg = Segment(locSuccessMsg.getLength(), MSG_TYPE_LOC_SUCCESS, &locSuccessMsg);
locSuccessSeg.send(sock);
break;
}
}
if (exist) {
list<server_function_info *>::iterator i = roundRobinList.begin();
list<server_function_info *> tempList;
while (i != roundRobinList.end()){
//bool isActive = (*i)->update();
if((*i)->si->server_identifier == serverIdToPushBack && (*i)->si->port == portToPushBack && (*i)->si->socket == socketToPushBack){
//if ((*i)->si->port == portToPushBack && (*i)->si->socket == socketToPushBack){
tempList.push_back(*i);
roundRobinList.erase(i++); // alternatively, i = items.erase(i);
}else{
++i;
}
}
roundRobinList.splice(roundRobinList.end(), tempList);
//roundRobinPrint();
} else {
LocFailureMessage locFailMsg =
LocFailureMessage(ERROR_CODE_PROCEDURE_NOT_FOUND);
Segment locFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
locFailSeg.send(sock);
}
}
// Handles a termination request from the client
void handleTerminationRequest() {
// Informs all the servers to terminate
for (list<server_info *>::const_iterator it = serverList.begin(); it != serverList.end(); it++) {
cout << "Terminating server: " << (*it)->server_identifier;
cout << ", " << (*it)->port;
cout << ", " << (*it)->socket << endl;
TerminateMessage messageToServer = TerminateMessage();
Segment segmentToServer =
Segment(messageToServer.getLength(), MSG_TYPE_TERMINATE,
&messageToServer);
segmentToServer.send((*it)->socket);
}
// Signals the binder to terminate
isTerminated = true;
}
// Handles a request from the client/server
void handleRequest(Segment *segment, int socket) {
switch (segment->getType()) {
case MSG_TYPE_REGISTER_REQUEST: {
RegisterRequestMessage *messageFromServer =
dynamic_cast<RegisterRequestMessage *>(segment->getMessage());
handleRegistrationRequest(messageFromServer, socket);
break;
}
case MSG_TYPE_LOC_REQUEST: {
LocRequestMessage *messageFromClient =
dynamic_cast<LocRequestMessage *>(segment->getMessage());
handleLocationRequest(messageFromClient, socket);
break;
}
case MSG_TYPE_TERMINATE: {
handleTerminationRequest();
break;
}
}
}
int main() {
fd_set allSockets;
fd_set readSockets;
/*
* Clears all entries from the all sockets set and the read
* sockets set
*/
FD_ZERO(&allSockets);
FD_ZERO(&readSockets);
/*
* Creates the welcome socket, adds it to the all sockets set and
* sets it as the maximum socket so far
*/
int welcomeSocket = createSocket();
if (welcomeSocket < 0) {
return welcomeSocket;
}
int result = setUpToListen(welcomeSocket);
if (result < 0) {
return result;
}
FD_SET(welcomeSocket, &allSockets);
int maxSocket = welcomeSocket;
/*
* Prints the binder address and the binder port on the binder's
* standard output
*/
string binderIdentifier = getHostAddress();
if (binderIdentifier == "") {
return ERROR_CODE_HOST_ADDRESS_NOT_FOUND;
}
int port = getSocketPort(welcomeSocket);
if (port < 0) {
return port;
}
cout << "BINDER_ADDRESS " << binderIdentifier << endl;
cout << "BINDER_PORT " << port << endl;
while (!isTerminated) {
readSockets = allSockets;
// Checks if some of the sockets are ready to be read from
int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
if (result < 0) {
continue;
}
for (int i = 0; i <= maxSocket; i++) {
if (!FD_ISSET(i, &readSockets)) {
continue;
}
if (i == welcomeSocket) {
/*
* Creates the connection socket when a connection is made
* to the welcome socket
*/
int connectionSocket = acceptConnection(i);
if (connectionSocket < 0) {
continue;
}
// Adds the connection socket to the all sockets set
FD_SET(connectionSocket, &allSockets);
/*
* Sets the connection socket as the maximum socket so far
* if necessary
*/
if (connectionSocket > maxSocket) {
maxSocket = connectionSocket;
}
} else {
/*
* Creates a segment to receive data from the client/server and
* reads into it from the connection socket
*/
Segment *segment = 0;
result = 0;
result = Segment::receive(i, segment);
if (result < 0) {
/*
* Closes the connection socket and removes it from the
* all sockets set
*/
destroySocket(i);
FD_CLR(i, &allSockets);
continue;
}
// Handles a request from the client/server
handleRequest(segment, i);
}
}
}
// Destroys the welcome socket
destroySocket(welcomeSocket);
return SUCCESS_CODE;
}
<|endoftext|> |
<commit_before>/**
Copyright (c) 2013, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _MAIKEN_APP_HPP_
#define _MAIKEN_APP_HPP_
#include "kul/os.hpp"
#include "kul/cli.hpp"
#include "kul/log.hpp"
#include "kul/scm.hpp"
#include "kul/proc.hpp"
#include "kul/threads.hpp"
#include "kul/code/compilers.hpp"
#include "maiken/project.hpp"
namespace maiken{
class Exception : public kul::Exception{
public:
Exception(const char*f, const uint16_t& l, const std::string& s) : kul::Exception(f, l, s){}
};
class AppVars{
private:
bool b = 0, c = 0, d = 0, f = 0, g = 0, l = 0, p = 0, r = 0, s = 0, sh = 0, st = 0, t = 0, u = 0;
uint16_t dl = 0;
uint16_t ts = 1;
std::string aa;
std::string la;
kul::hash::map::S2S jas, pks;
AppVars(){
pks["OS"] = KTOSTRING(__KUL_OS__);
pks["HOME"] = kul::user::home().path();
if(Settings::INSTANCE().root()[LOCAL] && Settings::INSTANCE().root()[LOCAL][REPO])
pks["MKN_REPO"] = Settings::INSTANCE().root()[LOCAL][REPO].Scalar();
else
pks["MKN_REPO"] = kul::user::home(MAIKEN).path();
}
public:
const std::string& args() const { return aa;}
void args(const std::string& aa) { this->aa = aa;}
const kul::hash::map::S2S& jargs() const { return jas;}
void jargs(const std::string& a, const std::string& b) { this->jas.insert(a, b);}
const std::string& linker() const { return la;}
void linker(const std::string& la) { this->la = la;}
const bool& build() const { return this->b;}
void build(const bool& b) { this->b = b;}
const bool& clean() const { return this->c;}
void clean(const bool& c) { this->c = c;}
const bool& compile() const { return this->p;}
void compile(const bool& p) { this->p = p;}
const bool& dbg() const { return this->g;}
void dbg(const bool& g) { this->g = g;}
const bool& debug() const { return this->d;}
void debug(const bool& d) { this->d = d;}
const bool& fupdate() const { return this->f;}
void fupdate(const bool& f) { this->f = f;}
const bool& link() const { return this->l;}
void link(const bool& l) { this->l = l;}
const bool& run() const { return this->r;}
void run(const bool& r) { this->r = r;}
const bool& show() const { return this->s;}
void show(const bool& s){ this->s = s;}
const bool& shar() const { return this->sh;}
void shar(const bool& sh){ this->sh = sh;}
const bool& trim() const { return this->t;}
void trim(const bool& t) { this->t = t;}
const bool& update() const { return this->u;}
void update(const bool& u) { this->u = u;}
const bool& stat() const { return this->st;}
void stat(const bool& st){ this->st = st;}
const uint16_t& dependencyLevel() const { return dl;}
void dependencyLevel(const uint16_t& dl) { this->dl = dl;}
const uint16_t& threads() const { return ts;}
void threads(const uint16_t& t) { this->ts = t;}
const kul::hash::map::S2S& properkeys() const { return pks;}
static AppVars& INSTANCE(){
static AppVars instance;
return instance;
}
};
class ThreadingCompiler;
class Application : public Constants{
protected:
bool ig = 1;
const Application* par = 0;
kul::code::Mode m;
std::string arg, main, lang;
const std::string p;
kul::Dir bd, inst;
maiken::Project proj;
kul::hash::map::S2T<kul::hash::map::S2S> fs;
std::vector<std::string> libs;
std::vector<std::pair<std::string, bool> > srcs;
std::vector<std::pair<std::string, bool> > incs;
std::vector<std::string> paths;
kul::hash::map::S2S ps;
kul::hash::map::S2T<kul::hash::set::String> args;
kul::hash::map::S2T<uint16_t> stss;
kul::hash::map::S2S itss;
kul::hash::map::S2S includeStamps;
std::vector<kul::cli::EnvVar> evs;
std::vector<Application> deps;
std::string scr;
const kul::SCM* scm = 0;
Application(const maiken::Project& proj, const std::string profile) : m(kul::code::Mode::NONE), p(profile), proj(proj){}
Application(const maiken::Project& proj) : m(kul::code::Mode::NONE), proj(proj){}
void buildDepVec(const std::string* depVal);
void buildDepVecRec(std::vector<Application*>& dePs, int16_t i, const kul::hash::set::String& inc);
void buildExecutable(const std::vector<std::string>& objects);
void buildLibrary(const std::vector<std::string>& objects);
void checkErrors(const kul::code::CompilerProcessCapture& cpc) throw(kul::Exception);
void populateMaps(const YAML::Node& n);
void populateMapsFromDependencies();
void populateDependencies(const YAML::Node& n) throw(kul::Exception);
void preSetupValidation() throw(Exception);
void postSetupValidation() throw(Exception);
void resolveProperties();
void build() throw(kul::Exception);
void link() throw(kul::Exception);
void run(bool dbg);
void trim();
void trim(const kul::File& f);
void scmStatus(const bool& deps = false) throw(kul::scm::Exception);
void scmUpdate(const bool& f) throw(kul::scm::Exception);
void scmUpdate(const bool& f, const kul::SCM* scm, const std::string& repo) throw(kul::scm::Exception);
void setup();
void showConfig(bool force = 0);
void cyclicCheck(const std::vector<std::pair<std::string, std::string>>& apps) const throw(kul::Exception);
void showProfiles();
void loadTimeStamps() throw (kul::StringException);
bool incSrc(const kul::File& f);
std::string resolveFromProperties(const std::string& s) const;
kul::Dir resolveDependencyDirectory(const YAML::Node& d);
kul::hash::map::S2T<kul::hash::map::S2T<kul::hash::set::String> > sourceMap();
std::vector<std::string> compile() throw(kul::Exception);
kul::hash::set::String inactiveMains();
void addSourceLine (const std::string& o) throw (kul::StringException);
void addIncludeLine(const std::string& o) throw (kul::StringException);
static void showHelp();
public:
static Application CREATE(int16_t argc, char *argv[]) throw(kul::Exception);
virtual void process() throw(kul::Exception);
const kul::Dir& buildDir() const { return bd; }
const std::string& profile() const { return p; }
const maiken::Project& project() const { return proj;}
const std::vector<Application>& dependencies() const { return deps; }
const std::vector<kul::cli::EnvVar>& envVars() const { return evs; }
const kul::hash::map::S2T<kul::hash::map::S2S>& files() const { return fs; }
const std::vector<std::string>& libraries() const { return libs;}
const std::vector<std::pair<std::string, bool> >& sources() const { return srcs;}
const std::vector<std::pair<std::string, bool> >& includes() const { return incs;}
const std::vector<std::string>& libraryPaths() const { return paths;}
const kul::hash::map::S2S& properties() const { return ps;}
const kul::hash::map::S2T<kul::hash::set::String>& arguments() const { return args; }
friend class ThreadingCompiler;
};
class ThreadingCompiler : public Constants{
private:
bool f;
kul::Mutex compile;
kul::Mutex push;
maiken::Application& app;
std::queue<std::pair<std::string, std::string> >& sources;
std::vector<kul::code::CompilerProcessCapture> cpcs;
std::vector<std::string> incs;
public:
ThreadingCompiler(maiken::Application& app, std::queue<std::pair<std::string, std::string> >& sources)
: f(0), app(app), sources(sources){
for(const auto& s : app.includes()){
kul::Dir d(s.first);
const std::string& m(d.escm());
if(!m.empty()) incs.push_back(m);
else incs.push_back(".");
}
}
void operator()() throw(kul::Exception){
std::pair<std::string, std::string> p;
{
kul::ScopeLock lock(compile);
p = sources.front();
sources.pop();
}
const std::string src(p.first);
const std::string obj(p.second);
if(!f){
const std::string& fileType = src.substr(src.rfind(".") + 1);
const std::string& compiler = (*(*app.files().find(fileType)).second.find(COMPILER)).second;
std::vector<std::string> args;
if(app.arguments().count(fileType) > 0)
for(const std::string& o : (*app.arguments().find(fileType)).second)
for(const auto& s : kul::cli::asArgs(o))
args.push_back(s);
for(const auto& s : kul::cli::asArgs(app.arg)) args.push_back(s);
std::string cmd = compiler + " " + AppVars::INSTANCE().args();
if(AppVars::INSTANCE().jargs().count(fileType) > 0)
cmd += " " + (*AppVars::INSTANCE().jargs().find(fileType)).second;
// WE CHECK BEFORE USING THIS THAT A COMPILER EXISTS FOR EVERY FILE
if(kul::LogMan::INSTANCE().inf() && !kul::LogMan::INSTANCE().dbg())
KOUT(NON) << compiler << " : " << src;
const kul::code::CompilerProcessCapture& cpc = kul::code::Compilers::INSTANCE().get(compiler)->compileSource(cmd, args, incs, src, obj, app.m);
kul::ScopeLock lock(push);
cpcs.push_back(cpc);
if(cpc.exception()) f = 1;
}
}
const std::vector<kul::code::CompilerProcessCapture>& processCaptures(){return cpcs;}
};
class SCMGetter{
private:
kul::hash::map::S2S valids;
static bool IS_SOLID(const std::string& r){
return r.find("://") != std::string::npos || r.find("@") != std::string::npos;
}
static SCMGetter& INSTANCE(){
static SCMGetter s;
return s;
}
static const kul::SCM* GET_SCM(const kul::Dir& d, const std::string& r){
std::vector<std::string> repos;
if(IS_SOLID(r)) repos.push_back(r);
else
for(const std::string& s : Settings::INSTANCE().remoteRepos()) repos.push_back(s + r);
for(const auto& repo : repos){
try{
kul::Process g("git");
kul::ProcessCapture gp(g);
std::string r1(repo);
if(repo.find("http") != std::string::npos && repo.find("@") == std::string::npos)
r1 = repo.substr(0, repo.find("//") + 2) + "u:p@" + repo.substr(repo.find("//") + 2);
g.arg("ls-remote").arg(r1).start();
if(!gp.errs().size()) {
INSTANCE().valids.insert(d.path(), repo);
return &kul::scm::Manager::INSTANCE().get("git");
}
}catch(const kul::proc::ExitException& e){}
try{
kul::Process s("svn");
kul::ProcessCapture sp(s);
s.arg("ls").arg(repo).start();
if(!sp.errs().size()) {
INSTANCE().valids.insert(d.path(), repo);
return &kul::scm::Manager::INSTANCE().get("svn");
}
}catch(const kul::proc::ExitException& e){}
}
std::stringstream ss;
for(const auto& s : repos) ss << s << "\n";
KEXCEPT(Exception, "SCM not found or not supported type(git/svn) for repo(s)\n"+ss.str()+"project:"+d.path());
}
public:
static const std::string REPO(const kul::Dir& d, const std::string& r){
if(INSTANCE().valids.count(d.path())) return (*INSTANCE().valids.find(d.path())).second;
if(IS_SOLID(r)) INSTANCE().valids.insert(d.path(), r);
else GET_SCM(d, r);
if(INSTANCE().valids.count(d.path())) return (*INSTANCE().valids.find(d.path())).second;
KEXCEPT(Exception, "SCM not discovered for project: "+d.path());
}
static bool HAS(const kul::Dir& d){
return (kul::Dir(d.join(".git")) || kul::Dir(d.join(".svn")));
}
static const kul::SCM* GET(const kul::Dir& d, const std::string& r){
if(IS_SOLID(r)) INSTANCE().valids.insert(d.path(), r);
if(kul::Dir(d.join(".git"))) return &kul::scm::Manager::INSTANCE().get("git");
if(kul::Dir(d.join(".svn"))) return &kul::scm::Manager::INSTANCE().get("svn");
return r.size() ? GET_SCM(d, r) : 0;
}
};
}
#endif /* _MAIKEN_APP_HPP_ */
<commit_msg>constants inherited<commit_after>/**
Copyright (c) 2013, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _MAIKEN_APP_HPP_
#define _MAIKEN_APP_HPP_
#include "kul/os.hpp"
#include "kul/cli.hpp"
#include "kul/log.hpp"
#include "kul/scm.hpp"
#include "kul/proc.hpp"
#include "kul/threads.hpp"
#include "kul/code/compilers.hpp"
#include "maiken/project.hpp"
namespace maiken{
class Exception : public kul::Exception{
public:
Exception(const char*f, const uint16_t& l, const std::string& s) : kul::Exception(f, l, s){}
};
class AppVars : public Constants{
private:
bool b = 0, c = 0, d = 0, f = 0, g = 0, l = 0, p = 0, r = 0, s = 0, sh = 0, st = 0, t = 0, u = 0;
uint16_t dl = 0;
uint16_t ts = 1;
std::string aa;
std::string la;
kul::hash::map::S2S jas, pks;
AppVars(){
pks["OS"] = KTOSTRING(__KUL_OS__);
pks["HOME"] = kul::user::home().path();
if(Settings::INSTANCE().root()[LOCAL] && Settings::INSTANCE().root()[LOCAL][REPO])
pks["MKN_REPO"] = Settings::INSTANCE().root()[LOCAL][REPO].Scalar();
else
pks["MKN_REPO"] = kul::user::home(MAIKEN).path();
}
public:
const std::string& args() const { return aa;}
void args(const std::string& aa) { this->aa = aa;}
const kul::hash::map::S2S& jargs() const { return jas;}
void jargs(const std::string& a, const std::string& b) { this->jas.insert(a, b);}
const std::string& linker() const { return la;}
void linker(const std::string& la) { this->la = la;}
const bool& build() const { return this->b;}
void build(const bool& b) { this->b = b;}
const bool& clean() const { return this->c;}
void clean(const bool& c) { this->c = c;}
const bool& compile() const { return this->p;}
void compile(const bool& p) { this->p = p;}
const bool& dbg() const { return this->g;}
void dbg(const bool& g) { this->g = g;}
const bool& debug() const { return this->d;}
void debug(const bool& d) { this->d = d;}
const bool& fupdate() const { return this->f;}
void fupdate(const bool& f) { this->f = f;}
const bool& link() const { return this->l;}
void link(const bool& l) { this->l = l;}
const bool& run() const { return this->r;}
void run(const bool& r) { this->r = r;}
const bool& show() const { return this->s;}
void show(const bool& s){ this->s = s;}
const bool& shar() const { return this->sh;}
void shar(const bool& sh){ this->sh = sh;}
const bool& trim() const { return this->t;}
void trim(const bool& t) { this->t = t;}
const bool& update() const { return this->u;}
void update(const bool& u) { this->u = u;}
const bool& stat() const { return this->st;}
void stat(const bool& st){ this->st = st;}
const uint16_t& dependencyLevel() const { return dl;}
void dependencyLevel(const uint16_t& dl) { this->dl = dl;}
const uint16_t& threads() const { return ts;}
void threads(const uint16_t& t) { this->ts = t;}
const kul::hash::map::S2S& properkeys() const { return pks;}
static AppVars& INSTANCE(){
static AppVars instance;
return instance;
}
};
class ThreadingCompiler;
class Application : public Constants{
protected:
bool ig = 1;
const Application* par = 0;
kul::code::Mode m;
std::string arg, main, lang;
const std::string p;
kul::Dir bd, inst;
maiken::Project proj;
kul::hash::map::S2T<kul::hash::map::S2S> fs;
std::vector<std::string> libs;
std::vector<std::pair<std::string, bool> > srcs;
std::vector<std::pair<std::string, bool> > incs;
std::vector<std::string> paths;
kul::hash::map::S2S ps;
kul::hash::map::S2T<kul::hash::set::String> args;
kul::hash::map::S2T<uint16_t> stss;
kul::hash::map::S2S itss;
kul::hash::map::S2S includeStamps;
std::vector<kul::cli::EnvVar> evs;
std::vector<Application> deps;
std::string scr;
const kul::SCM* scm = 0;
Application(const maiken::Project& proj, const std::string profile) : m(kul::code::Mode::NONE), p(profile), proj(proj){}
Application(const maiken::Project& proj) : m(kul::code::Mode::NONE), proj(proj){}
void buildDepVec(const std::string* depVal);
void buildDepVecRec(std::vector<Application*>& dePs, int16_t i, const kul::hash::set::String& inc);
void buildExecutable(const std::vector<std::string>& objects);
void buildLibrary(const std::vector<std::string>& objects);
void checkErrors(const kul::code::CompilerProcessCapture& cpc) throw(kul::Exception);
void populateMaps(const YAML::Node& n);
void populateMapsFromDependencies();
void populateDependencies(const YAML::Node& n) throw(kul::Exception);
void preSetupValidation() throw(Exception);
void postSetupValidation() throw(Exception);
void resolveProperties();
void build() throw(kul::Exception);
void link() throw(kul::Exception);
void run(bool dbg);
void trim();
void trim(const kul::File& f);
void scmStatus(const bool& deps = false) throw(kul::scm::Exception);
void scmUpdate(const bool& f) throw(kul::scm::Exception);
void scmUpdate(const bool& f, const kul::SCM* scm, const std::string& repo) throw(kul::scm::Exception);
void setup();
void showConfig(bool force = 0);
void cyclicCheck(const std::vector<std::pair<std::string, std::string>>& apps) const throw(kul::Exception);
void showProfiles();
void loadTimeStamps() throw (kul::StringException);
bool incSrc(const kul::File& f);
std::string resolveFromProperties(const std::string& s) const;
kul::Dir resolveDependencyDirectory(const YAML::Node& d);
kul::hash::map::S2T<kul::hash::map::S2T<kul::hash::set::String> > sourceMap();
std::vector<std::string> compile() throw(kul::Exception);
kul::hash::set::String inactiveMains();
void addSourceLine (const std::string& o) throw (kul::StringException);
void addIncludeLine(const std::string& o) throw (kul::StringException);
static void showHelp();
public:
static Application CREATE(int16_t argc, char *argv[]) throw(kul::Exception);
virtual void process() throw(kul::Exception);
const kul::Dir& buildDir() const { return bd; }
const std::string& profile() const { return p; }
const maiken::Project& project() const { return proj;}
const std::vector<Application>& dependencies() const { return deps; }
const std::vector<kul::cli::EnvVar>& envVars() const { return evs; }
const kul::hash::map::S2T<kul::hash::map::S2S>& files() const { return fs; }
const std::vector<std::string>& libraries() const { return libs;}
const std::vector<std::pair<std::string, bool> >& sources() const { return srcs;}
const std::vector<std::pair<std::string, bool> >& includes() const { return incs;}
const std::vector<std::string>& libraryPaths() const { return paths;}
const kul::hash::map::S2S& properties() const { return ps;}
const kul::hash::map::S2T<kul::hash::set::String>& arguments() const { return args; }
friend class ThreadingCompiler;
};
class ThreadingCompiler : public Constants{
private:
bool f;
kul::Mutex compile;
kul::Mutex push;
maiken::Application& app;
std::queue<std::pair<std::string, std::string> >& sources;
std::vector<kul::code::CompilerProcessCapture> cpcs;
std::vector<std::string> incs;
public:
ThreadingCompiler(maiken::Application& app, std::queue<std::pair<std::string, std::string> >& sources)
: f(0), app(app), sources(sources){
for(const auto& s : app.includes()){
kul::Dir d(s.first);
const std::string& m(d.escm());
if(!m.empty()) incs.push_back(m);
else incs.push_back(".");
}
}
void operator()() throw(kul::Exception){
std::pair<std::string, std::string> p;
{
kul::ScopeLock lock(compile);
p = sources.front();
sources.pop();
}
const std::string src(p.first);
const std::string obj(p.second);
if(!f){
const std::string& fileType = src.substr(src.rfind(".") + 1);
const std::string& compiler = (*(*app.files().find(fileType)).second.find(COMPILER)).second;
std::vector<std::string> args;
if(app.arguments().count(fileType) > 0)
for(const std::string& o : (*app.arguments().find(fileType)).second)
for(const auto& s : kul::cli::asArgs(o))
args.push_back(s);
for(const auto& s : kul::cli::asArgs(app.arg)) args.push_back(s);
std::string cmd = compiler + " " + AppVars::INSTANCE().args();
if(AppVars::INSTANCE().jargs().count(fileType) > 0)
cmd += " " + (*AppVars::INSTANCE().jargs().find(fileType)).second;
// WE CHECK BEFORE USING THIS THAT A COMPILER EXISTS FOR EVERY FILE
if(kul::LogMan::INSTANCE().inf() && !kul::LogMan::INSTANCE().dbg())
KOUT(NON) << compiler << " : " << src;
const kul::code::CompilerProcessCapture& cpc = kul::code::Compilers::INSTANCE().get(compiler)->compileSource(cmd, args, incs, src, obj, app.m);
kul::ScopeLock lock(push);
cpcs.push_back(cpc);
if(cpc.exception()) f = 1;
}
}
const std::vector<kul::code::CompilerProcessCapture>& processCaptures(){return cpcs;}
};
class SCMGetter{
private:
kul::hash::map::S2S valids;
static bool IS_SOLID(const std::string& r){
return r.find("://") != std::string::npos || r.find("@") != std::string::npos;
}
static SCMGetter& INSTANCE(){
static SCMGetter s;
return s;
}
static const kul::SCM* GET_SCM(const kul::Dir& d, const std::string& r){
std::vector<std::string> repos;
if(IS_SOLID(r)) repos.push_back(r);
else
for(const std::string& s : Settings::INSTANCE().remoteRepos()) repos.push_back(s + r);
for(const auto& repo : repos){
try{
kul::Process g("git");
kul::ProcessCapture gp(g);
std::string r1(repo);
if(repo.find("http") != std::string::npos && repo.find("@") == std::string::npos)
r1 = repo.substr(0, repo.find("//") + 2) + "u:p@" + repo.substr(repo.find("//") + 2);
g.arg("ls-remote").arg(r1).start();
if(!gp.errs().size()) {
INSTANCE().valids.insert(d.path(), repo);
return &kul::scm::Manager::INSTANCE().get("git");
}
}catch(const kul::proc::ExitException& e){}
try{
kul::Process s("svn");
kul::ProcessCapture sp(s);
s.arg("ls").arg(repo).start();
if(!sp.errs().size()) {
INSTANCE().valids.insert(d.path(), repo);
return &kul::scm::Manager::INSTANCE().get("svn");
}
}catch(const kul::proc::ExitException& e){}
}
std::stringstream ss;
for(const auto& s : repos) ss << s << "\n";
KEXCEPT(Exception, "SCM not found or not supported type(git/svn) for repo(s)\n"+ss.str()+"project:"+d.path());
}
public:
static const std::string REPO(const kul::Dir& d, const std::string& r){
if(INSTANCE().valids.count(d.path())) return (*INSTANCE().valids.find(d.path())).second;
if(IS_SOLID(r)) INSTANCE().valids.insert(d.path(), r);
else GET_SCM(d, r);
if(INSTANCE().valids.count(d.path())) return (*INSTANCE().valids.find(d.path())).second;
KEXCEPT(Exception, "SCM not discovered for project: "+d.path());
}
static bool HAS(const kul::Dir& d){
return (kul::Dir(d.join(".git")) || kul::Dir(d.join(".svn")));
}
static const kul::SCM* GET(const kul::Dir& d, const std::string& r){
if(IS_SOLID(r)) INSTANCE().valids.insert(d.path(), r);
if(kul::Dir(d.join(".git"))) return &kul::scm::Manager::INSTANCE().get("git");
if(kul::Dir(d.join(".svn"))) return &kul::scm::Manager::INSTANCE().get("svn");
return r.size() ? GET_SCM(d, r) : 0;
}
};
}
#endif /* _MAIKEN_APP_HPP_ */
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/session_manager.h"
#include <algorithm>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stl_util-inl.h"
#include "media/base/data_buffer.h"
#include "remoting/base/protocol_decoder.h"
#include "remoting/host/client_connection.h"
#include "remoting/host/encoder.h"
namespace remoting {
// By default we capture 20 times a second. This number is obtained by
// experiment to provide good latency.
static const double kDefaultCaptureRate = 20.0;
// Interval that we perform rate regulation.
static const base::TimeDelta kRateControlInterval =
base::TimeDelta::FromSeconds(1);
// We divide the pending update stream number by this value to determine the
// rate divider.
static const int kSlowDownFactor = 10;
// A list of dividers used to divide the max rate to determine the current
// capture rate.
static const int kRateDividers[] = {1, 2, 4, 8, 16};
SessionManager::SessionManager(
MessageLoop* capture_loop,
MessageLoop* encode_loop,
MessageLoop* network_loop,
Capturer* capturer,
Encoder* encoder)
: capture_loop_(capture_loop),
encode_loop_(encode_loop),
network_loop_(network_loop),
capturer_(capturer),
encoder_(encoder),
rate_(kDefaultCaptureRate),
started_(false),
recordings_(0),
max_rate_(kDefaultCaptureRate),
rate_control_started_(false) {
DCHECK(capture_loop_);
DCHECK(encode_loop_);
DCHECK(network_loop_);
}
SessionManager::~SessionManager() {
clients_.clear();
}
void SessionManager::Start() {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoStart));
}
void SessionManager::DoStart() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (started_) {
NOTREACHED() << "Record session already started";
return;
}
started_ = true;
DoCapture();
// Starts the rate regulation.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoStartRateControl));
}
void SessionManager::DoStartRateControl() {
DCHECK_EQ(network_loop_, MessageLoop::current());
if (rate_control_started_) {
NOTREACHED() << "Rate regulation already started";
return;
}
rate_control_started_ = true;
ScheduleNextRateControl();
}
void SessionManager::Pause() {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoPause));
}
void SessionManager::DoPause() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (!started_) {
NOTREACHED() << "Record session not started";
return;
}
started_ = false;
// Pause the rate regulation.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoPauseRateControl));
}
void SessionManager::DoPauseRateControl() {
DCHECK_EQ(network_loop_, MessageLoop::current());
if (!rate_control_started_) {
NOTREACHED() << "Rate regulation not started";
return;
}
rate_control_started_ = false;
}
void SessionManager::SetMaxRate(double rate) {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSetMaxRate, rate));
}
void SessionManager::AddClient(scoped_refptr<ClientConnection> client) {
// Gets the init information for the client.
capture_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoGetInitInfo, client));
}
void SessionManager::RemoveClient(scoped_refptr<ClientConnection> client) {
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoRemoveClient, client));
}
void SessionManager::DoCapture() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// Make sure we have at most two oustanding recordings. We can simply return
// if we can't make a capture now, the next capture will be started by the
// end of an encode operation.
if (recordings_ >= 2 || !started_)
return;
base::Time now = base::Time::Now();
base::TimeDelta interval = base::TimeDelta::FromMilliseconds(
static_cast<int>(base::Time::kMillisecondsPerSecond / rate_));
base::TimeDelta elapsed = now - last_capture_time_;
// If this method is called sonner than the required interval we return
// immediately
if (elapsed < interval)
return;
// At this point we are going to perform one capture so save the current time.
last_capture_time_ = now;
++recordings_;
// Before we actually do a capture, schedule the next one.
ScheduleNextCapture();
// And finally perform one capture.
DCHECK(capturer_.get());
capturer_->CaptureDirtyRects(
NewRunnableMethod(this, &SessionManager::CaptureDoneTask));
}
void SessionManager::DoFinishEncode() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// Decrement the number of recording in process since we have completed
// one cycle.
--recordings_;
// Try to do a capture again. Note that the following method may do nothing
// if it is too early to perform a capture.
if (rate_ > 0)
DoCapture();
}
void SessionManager::DoEncode(const CaptureData *capture_data) {
// Take ownership of capture_data.
scoped_ptr<const CaptureData> capture_data_owner(capture_data);
DCHECK_EQ(encode_loop_, MessageLoop::current());
DCHECK(encoder_.get());
// TODO(hclam): Enable |force_refresh| if a new client was
// added.
encoder_->SetSize(capture_data->width_, capture_data->height_);
encoder_->SetPixelFormat(capture_data->pixel_format_);
encoder_->Encode(
capture_data->dirty_rects_,
capture_data->data_,
capture_data->data_strides_,
false,
NewCallback(this, &SessionManager::EncodeDataAvailableTask));
}
void SessionManager::DoSendUpdate(const UpdateStreamPacketHeader* header,
const scoped_refptr<media::DataBuffer> data,
Encoder::EncodingState state) {
// Take ownership of header.
scoped_ptr<const UpdateStreamPacketHeader> header_owner(header);
DCHECK_EQ(network_loop_, MessageLoop::current());
for (size_t i = 0; i < clients_.size(); ++i) {
if (state & Encoder::EncodingStarting) {
clients_[i]->SendBeginUpdateStreamMessage();
}
clients_[i]->SendUpdateStreamPacketMessage(header, data);
if (state & Encoder::EncodingEnded) {
clients_[i]->SendEndUpdateStreamMessage();
}
}
delete header;
}
void SessionManager::DoSendInit(scoped_refptr<ClientConnection> client,
int width, int height) {
DCHECK_EQ(network_loop_, MessageLoop::current());
// Sends the client init information.
client->SendInitClientMessage(width, height);
}
void SessionManager::DoGetInitInfo(scoped_refptr<ClientConnection> client) {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// Sends the init message to the cleint.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoSendInit, client,
capturer_->GetWidth(), capturer_->GetHeight()));
// And then add the client to the list so it can receive update stream.
// It is important we do so in such order or the client will receive
// update stream before init message.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoAddClient, client));
}
void SessionManager::DoSetRate(double rate) {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (rate == rate_)
return;
// Change the current capture rate.
rate_ = rate;
// If we have already started then schedule the next capture with the new
// rate.
if (started_)
ScheduleNextCapture();
}
void SessionManager::DoSetMaxRate(double max_rate) {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// TODO(hclam): Should also check for small epsilon.
if (max_rate != 0) {
max_rate_ = max_rate;
DoSetRate(max_rate);
} else {
NOTREACHED() << "Rate is too small.";
}
}
void SessionManager::DoAddClient(scoped_refptr<ClientConnection> client) {
DCHECK_EQ(network_loop_, MessageLoop::current());
// TODO(hclam): Force a full frame for next encode.
clients_.push_back(client);
}
void SessionManager::DoRemoveClient(scoped_refptr<ClientConnection> client) {
DCHECK_EQ(network_loop_, MessageLoop::current());
// TODO(hclam): Is it correct to do to a scoped_refptr?
ClientConnectionList::iterator it
= std::find(clients_.begin(), clients_.end(), client);
if (it != clients_.end())
clients_.erase(it);
}
void SessionManager::DoRateControl() {
DCHECK_EQ(network_loop_, MessageLoop::current());
// If we have been paused then shutdown the rate regulation loop.
if (!rate_control_started_)
return;
int max_pending_update_streams = 0;
for (size_t i = 0; i < clients_.size(); ++i) {
max_pending_update_streams =
std::max(max_pending_update_streams,
clients_[i]->GetPendingUpdateStreamMessages());
}
// If |slow_down| equals zero, we have no slow down.
size_t slow_down = max_pending_update_streams / kSlowDownFactor;
// Set new_rate to -1 for checking later.
double new_rate = -1;
// If the slow down is too large.
if (slow_down >= arraysize(kRateDividers)) {
// Then we stop the capture completely.
new_rate = 0;
} else {
// Slow down the capture rate using the divider.
new_rate = max_rate_ / kRateDividers[slow_down];
}
DCHECK_NE(new_rate, -1.0);
// Then set the rate.
capture_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoSetRate, new_rate));
ScheduleNextRateControl();
}
void SessionManager::ScheduleNextCapture() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (rate_ == 0)
return;
base::TimeDelta interval = base::TimeDelta::FromMilliseconds(
static_cast<int>(base::Time::kMillisecondsPerSecond / rate_));
capture_loop_->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoCapture),
interval.InMilliseconds());
}
void SessionManager::ScheduleNextRateControl() {
network_loop_->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoRateControl),
kRateControlInterval.InMilliseconds());
}
void SessionManager::CaptureDoneTask() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
scoped_ptr<CaptureData> data(new CaptureData);
// Save results of the capture.
capturer_->GetData(data->data_);
capturer_->GetDataStride(data->data_strides_);
capturer_->GetDirtyRects(&data->dirty_rects_);
data->pixel_format_ = capturer_->GetPixelFormat();
data->width_ = capturer_->GetWidth();
data->height_ = capturer_->GetHeight();
encode_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoEncode, data.release()));
}
void SessionManager::EncodeDataAvailableTask(
const UpdateStreamPacketHeader *header,
const scoped_refptr<media::DataBuffer>& data,
Encoder::EncodingState state) {
DCHECK_EQ(encode_loop_, MessageLoop::current());
// Before a new encode task starts, notify clients a new update
// stream is coming.
// Notify this will keep a reference to the DataBuffer in the
// task. The ownership will eventually pass to the ClientConnections.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&SessionManager::DoSendUpdate,
header,
data,
state));
if (state == Encoder::EncodingEnded) {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoFinishEncode));
}
}
} // namespace remoting
<commit_msg>Fix double deletion in SessionManager<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/session_manager.h"
#include <algorithm>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stl_util-inl.h"
#include "media/base/data_buffer.h"
#include "remoting/base/protocol_decoder.h"
#include "remoting/host/client_connection.h"
#include "remoting/host/encoder.h"
namespace remoting {
// By default we capture 20 times a second. This number is obtained by
// experiment to provide good latency.
static const double kDefaultCaptureRate = 20.0;
// Interval that we perform rate regulation.
static const base::TimeDelta kRateControlInterval =
base::TimeDelta::FromSeconds(1);
// We divide the pending update stream number by this value to determine the
// rate divider.
static const int kSlowDownFactor = 10;
// A list of dividers used to divide the max rate to determine the current
// capture rate.
static const int kRateDividers[] = {1, 2, 4, 8, 16};
SessionManager::SessionManager(
MessageLoop* capture_loop,
MessageLoop* encode_loop,
MessageLoop* network_loop,
Capturer* capturer,
Encoder* encoder)
: capture_loop_(capture_loop),
encode_loop_(encode_loop),
network_loop_(network_loop),
capturer_(capturer),
encoder_(encoder),
rate_(kDefaultCaptureRate),
started_(false),
recordings_(0),
max_rate_(kDefaultCaptureRate),
rate_control_started_(false) {
DCHECK(capture_loop_);
DCHECK(encode_loop_);
DCHECK(network_loop_);
}
SessionManager::~SessionManager() {
clients_.clear();
}
void SessionManager::Start() {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoStart));
}
void SessionManager::DoStart() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (started_) {
NOTREACHED() << "Record session already started";
return;
}
started_ = true;
DoCapture();
// Starts the rate regulation.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoStartRateControl));
}
void SessionManager::DoStartRateControl() {
DCHECK_EQ(network_loop_, MessageLoop::current());
if (rate_control_started_) {
NOTREACHED() << "Rate regulation already started";
return;
}
rate_control_started_ = true;
ScheduleNextRateControl();
}
void SessionManager::Pause() {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoPause));
}
void SessionManager::DoPause() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (!started_) {
NOTREACHED() << "Record session not started";
return;
}
started_ = false;
// Pause the rate regulation.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoPauseRateControl));
}
void SessionManager::DoPauseRateControl() {
DCHECK_EQ(network_loop_, MessageLoop::current());
if (!rate_control_started_) {
NOTREACHED() << "Rate regulation not started";
return;
}
rate_control_started_ = false;
}
void SessionManager::SetMaxRate(double rate) {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSetMaxRate, rate));
}
void SessionManager::AddClient(scoped_refptr<ClientConnection> client) {
// Gets the init information for the client.
capture_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoGetInitInfo, client));
}
void SessionManager::RemoveClient(scoped_refptr<ClientConnection> client) {
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoRemoveClient, client));
}
void SessionManager::DoCapture() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// Make sure we have at most two oustanding recordings. We can simply return
// if we can't make a capture now, the next capture will be started by the
// end of an encode operation.
if (recordings_ >= 2 || !started_)
return;
base::Time now = base::Time::Now();
base::TimeDelta interval = base::TimeDelta::FromMilliseconds(
static_cast<int>(base::Time::kMillisecondsPerSecond / rate_));
base::TimeDelta elapsed = now - last_capture_time_;
// If this method is called sonner than the required interval we return
// immediately
if (elapsed < interval)
return;
// At this point we are going to perform one capture so save the current time.
last_capture_time_ = now;
++recordings_;
// Before we actually do a capture, schedule the next one.
ScheduleNextCapture();
// And finally perform one capture.
DCHECK(capturer_.get());
capturer_->CaptureDirtyRects(
NewRunnableMethod(this, &SessionManager::CaptureDoneTask));
}
void SessionManager::DoFinishEncode() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// Decrement the number of recording in process since we have completed
// one cycle.
--recordings_;
// Try to do a capture again. Note that the following method may do nothing
// if it is too early to perform a capture.
if (rate_ > 0)
DoCapture();
}
void SessionManager::DoEncode(const CaptureData *capture_data) {
// Take ownership of capture_data.
scoped_ptr<const CaptureData> capture_data_owner(capture_data);
DCHECK_EQ(encode_loop_, MessageLoop::current());
DCHECK(encoder_.get());
// TODO(hclam): Enable |force_refresh| if a new client was
// added.
encoder_->SetSize(capture_data->width_, capture_data->height_);
encoder_->SetPixelFormat(capture_data->pixel_format_);
encoder_->Encode(
capture_data->dirty_rects_,
capture_data->data_,
capture_data->data_strides_,
false,
NewCallback(this, &SessionManager::EncodeDataAvailableTask));
}
void SessionManager::DoSendUpdate(const UpdateStreamPacketHeader* header,
const scoped_refptr<media::DataBuffer> data,
Encoder::EncodingState state) {
// Take ownership of header.
scoped_ptr<const UpdateStreamPacketHeader> header_owner(header);
DCHECK_EQ(network_loop_, MessageLoop::current());
for (size_t i = 0; i < clients_.size(); ++i) {
if (state & Encoder::EncodingStarting) {
clients_[i]->SendBeginUpdateStreamMessage();
}
clients_[i]->SendUpdateStreamPacketMessage(header, data);
if (state & Encoder::EncodingEnded) {
clients_[i]->SendEndUpdateStreamMessage();
}
}
}
void SessionManager::DoSendInit(scoped_refptr<ClientConnection> client,
int width, int height) {
DCHECK_EQ(network_loop_, MessageLoop::current());
// Sends the client init information.
client->SendInitClientMessage(width, height);
}
void SessionManager::DoGetInitInfo(scoped_refptr<ClientConnection> client) {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// Sends the init message to the cleint.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoSendInit, client,
capturer_->GetWidth(), capturer_->GetHeight()));
// And then add the client to the list so it can receive update stream.
// It is important we do so in such order or the client will receive
// update stream before init message.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoAddClient, client));
}
void SessionManager::DoSetRate(double rate) {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (rate == rate_)
return;
// Change the current capture rate.
rate_ = rate;
// If we have already started then schedule the next capture with the new
// rate.
if (started_)
ScheduleNextCapture();
}
void SessionManager::DoSetMaxRate(double max_rate) {
DCHECK_EQ(capture_loop_, MessageLoop::current());
// TODO(hclam): Should also check for small epsilon.
if (max_rate != 0) {
max_rate_ = max_rate;
DoSetRate(max_rate);
} else {
NOTREACHED() << "Rate is too small.";
}
}
void SessionManager::DoAddClient(scoped_refptr<ClientConnection> client) {
DCHECK_EQ(network_loop_, MessageLoop::current());
// TODO(hclam): Force a full frame for next encode.
clients_.push_back(client);
}
void SessionManager::DoRemoveClient(scoped_refptr<ClientConnection> client) {
DCHECK_EQ(network_loop_, MessageLoop::current());
// TODO(hclam): Is it correct to do to a scoped_refptr?
ClientConnectionList::iterator it
= std::find(clients_.begin(), clients_.end(), client);
if (it != clients_.end())
clients_.erase(it);
}
void SessionManager::DoRateControl() {
DCHECK_EQ(network_loop_, MessageLoop::current());
// If we have been paused then shutdown the rate regulation loop.
if (!rate_control_started_)
return;
int max_pending_update_streams = 0;
for (size_t i = 0; i < clients_.size(); ++i) {
max_pending_update_streams =
std::max(max_pending_update_streams,
clients_[i]->GetPendingUpdateStreamMessages());
}
// If |slow_down| equals zero, we have no slow down.
size_t slow_down = max_pending_update_streams / kSlowDownFactor;
// Set new_rate to -1 for checking later.
double new_rate = -1;
// If the slow down is too large.
if (slow_down >= arraysize(kRateDividers)) {
// Then we stop the capture completely.
new_rate = 0;
} else {
// Slow down the capture rate using the divider.
new_rate = max_rate_ / kRateDividers[slow_down];
}
DCHECK_NE(new_rate, -1.0);
// Then set the rate.
capture_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoSetRate, new_rate));
ScheduleNextRateControl();
}
void SessionManager::ScheduleNextCapture() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
if (rate_ == 0)
return;
base::TimeDelta interval = base::TimeDelta::FromMilliseconds(
static_cast<int>(base::Time::kMillisecondsPerSecond / rate_));
capture_loop_->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoCapture),
interval.InMilliseconds());
}
void SessionManager::ScheduleNextRateControl() {
network_loop_->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoRateControl),
kRateControlInterval.InMilliseconds());
}
void SessionManager::CaptureDoneTask() {
DCHECK_EQ(capture_loop_, MessageLoop::current());
scoped_ptr<CaptureData> data(new CaptureData);
// Save results of the capture.
capturer_->GetData(data->data_);
capturer_->GetDataStride(data->data_strides_);
capturer_->GetDirtyRects(&data->dirty_rects_);
data->pixel_format_ = capturer_->GetPixelFormat();
data->width_ = capturer_->GetWidth();
data->height_ = capturer_->GetHeight();
encode_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &SessionManager::DoEncode, data.release()));
}
void SessionManager::EncodeDataAvailableTask(
const UpdateStreamPacketHeader *header,
const scoped_refptr<media::DataBuffer>& data,
Encoder::EncodingState state) {
DCHECK_EQ(encode_loop_, MessageLoop::current());
// Before a new encode task starts, notify clients a new update
// stream is coming.
// Notify this will keep a reference to the DataBuffer in the
// task. The ownership will eventually pass to the ClientConnections.
network_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this,
&SessionManager::DoSendUpdate,
header,
data,
state));
if (state == Encoder::EncodingEnded) {
capture_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &SessionManager::DoFinishEncode));
}
}
} // namespace remoting
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
#include <string.h>
#include "webrtc/base/checks.h"
namespace webrtc {
AudioEncoderCopyRed::AudioEncoderCopyRed(const Config& config)
: speech_encoder_(config.speech_encoder),
red_payload_type_(config.payload_type) {
CHECK(speech_encoder_) << "Speech encoder not provided.";
}
AudioEncoderCopyRed::~AudioEncoderCopyRed() {
}
int AudioEncoderCopyRed::SampleRateHz() const {
return speech_encoder_->SampleRateHz();
}
int AudioEncoderCopyRed::RtpTimestampRateHz() const {
return speech_encoder_->RtpTimestampRateHz();
}
int AudioEncoderCopyRed::NumChannels() const {
return speech_encoder_->NumChannels();
}
size_t AudioEncoderCopyRed::MaxEncodedBytes() const {
return 2 * speech_encoder_->MaxEncodedBytes();
}
size_t AudioEncoderCopyRed::Num10MsFramesInNextPacket() const {
return speech_encoder_->Num10MsFramesInNextPacket();
}
size_t AudioEncoderCopyRed::Max10MsFramesInAPacket() const {
return speech_encoder_->Max10MsFramesInAPacket();
}
int AudioEncoderCopyRed::GetTargetBitrate() const {
return speech_encoder_->GetTargetBitrate();
}
void AudioEncoderCopyRed::SetTargetBitrate(int bits_per_second) {
speech_encoder_->SetTargetBitrate(bits_per_second);
}
void AudioEncoderCopyRed::SetProjectedPacketLossRate(double fraction) {
DCHECK_GE(fraction, 0.0);
DCHECK_LE(fraction, 1.0);
speech_encoder_->SetProjectedPacketLossRate(fraction);
}
AudioEncoder::EncodedInfo AudioEncoderCopyRed::EncodeInternal(
uint32_t rtp_timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded) {
EncodedInfo info = speech_encoder_->Encode(
rtp_timestamp, audio, static_cast<size_t>(SampleRateHz() / 100),
max_encoded_bytes, encoded);
CHECK_GE(max_encoded_bytes,
info.encoded_bytes + secondary_info_.encoded_bytes);
CHECK(info.redundant.empty()) << "Cannot use nested redundant encoders.";
if (info.encoded_bytes > 0) {
// |info| will be implicitly cast to an EncodedInfoLeaf struct, effectively
// discarding the (empty) vector of redundant information. This is
// intentional.
info.redundant.push_back(info);
DCHECK_EQ(info.redundant.size(), 1u);
if (secondary_info_.encoded_bytes > 0) {
memcpy(&encoded[info.encoded_bytes], secondary_encoded_.data(),
secondary_info_.encoded_bytes);
info.redundant.push_back(secondary_info_);
DCHECK_EQ(info.redundant.size(), 2u);
}
// Save primary to secondary.
secondary_encoded_.SetSize(info.encoded_bytes);
memcpy(secondary_encoded_.data(), encoded, info.encoded_bytes);
secondary_info_ = info;
DCHECK_EQ(info.speech, info.redundant[0].speech);
}
// Update main EncodedInfo.
info.payload_type = red_payload_type_;
info.encoded_bytes = 0;
for (std::vector<EncodedInfoLeaf>::const_iterator it = info.redundant.begin();
it != info.redundant.end(); ++it) {
info.encoded_bytes += it->encoded_bytes;
}
return info;
}
} // namespace webrtc
<commit_msg>copy-red: Fill an rtc::Buffer with bytes the easy way<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
#include <string.h>
#include "webrtc/base/checks.h"
namespace webrtc {
AudioEncoderCopyRed::AudioEncoderCopyRed(const Config& config)
: speech_encoder_(config.speech_encoder),
red_payload_type_(config.payload_type) {
CHECK(speech_encoder_) << "Speech encoder not provided.";
}
AudioEncoderCopyRed::~AudioEncoderCopyRed() {
}
int AudioEncoderCopyRed::SampleRateHz() const {
return speech_encoder_->SampleRateHz();
}
int AudioEncoderCopyRed::RtpTimestampRateHz() const {
return speech_encoder_->RtpTimestampRateHz();
}
int AudioEncoderCopyRed::NumChannels() const {
return speech_encoder_->NumChannels();
}
size_t AudioEncoderCopyRed::MaxEncodedBytes() const {
return 2 * speech_encoder_->MaxEncodedBytes();
}
size_t AudioEncoderCopyRed::Num10MsFramesInNextPacket() const {
return speech_encoder_->Num10MsFramesInNextPacket();
}
size_t AudioEncoderCopyRed::Max10MsFramesInAPacket() const {
return speech_encoder_->Max10MsFramesInAPacket();
}
int AudioEncoderCopyRed::GetTargetBitrate() const {
return speech_encoder_->GetTargetBitrate();
}
void AudioEncoderCopyRed::SetTargetBitrate(int bits_per_second) {
speech_encoder_->SetTargetBitrate(bits_per_second);
}
void AudioEncoderCopyRed::SetProjectedPacketLossRate(double fraction) {
DCHECK_GE(fraction, 0.0);
DCHECK_LE(fraction, 1.0);
speech_encoder_->SetProjectedPacketLossRate(fraction);
}
AudioEncoder::EncodedInfo AudioEncoderCopyRed::EncodeInternal(
uint32_t rtp_timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded) {
EncodedInfo info = speech_encoder_->Encode(
rtp_timestamp, audio, static_cast<size_t>(SampleRateHz() / 100),
max_encoded_bytes, encoded);
CHECK_GE(max_encoded_bytes,
info.encoded_bytes + secondary_info_.encoded_bytes);
CHECK(info.redundant.empty()) << "Cannot use nested redundant encoders.";
if (info.encoded_bytes > 0) {
// |info| will be implicitly cast to an EncodedInfoLeaf struct, effectively
// discarding the (empty) vector of redundant information. This is
// intentional.
info.redundant.push_back(info);
DCHECK_EQ(info.redundant.size(), 1u);
if (secondary_info_.encoded_bytes > 0) {
memcpy(&encoded[info.encoded_bytes], secondary_encoded_.data(),
secondary_info_.encoded_bytes);
info.redundant.push_back(secondary_info_);
DCHECK_EQ(info.redundant.size(), 2u);
}
// Save primary to secondary.
secondary_encoded_.SetData(encoded, info.encoded_bytes);
secondary_info_ = info;
DCHECK_EQ(info.speech, info.redundant[0].speech);
}
// Update main EncodedInfo.
info.payload_type = red_payload_type_;
info.encoded_bytes = 0;
for (std::vector<EncodedInfoLeaf>::const_iterator it = info.redundant.begin();
it != info.redundant.end(); ++it) {
info.encoded_bytes += it->encoded_bytes;
}
return info;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 VOCA AS / Harald Nkland
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef __ZMQ_ADDON_HPP_INCLUDED__
#define __ZMQ_ADDON_HPP_INCLUDED__
#include <zmq.hpp>
#include <deque>
#include <iomanip>
#include <sstream>
namespace zmq {
#ifdef ZMQ_HAS_RVALUE_REFS
/*
This class handles multipart messaging. It is the C++ equivalent of zmsg.h,
which is part of CZMQ (the high-level C binding). Furthermore, it is a major
improvement compared to zmsg.hpp, which is part of the examples in the MQ
Guide. Unnecessary copying is avoided by using move semantics to efficiently
add/remove parts.
*/
class multipart_t
{
private:
std::deque<message_t> m_parts;
public:
multipart_t()
{}
multipart_t(socket_t& socket)
{
recv(socket);
}
multipart_t(const void *src, size_t size)
{
addmem(src, size);
}
multipart_t(const std::string& string)
{
addstr(string);
}
multipart_t(message_t&& message)
{
add(std::move(message));
}
multipart_t(multipart_t&& other)
{
std::swap(m_parts, other.m_parts);
}
multipart_t& operator=(multipart_t&& other)
{
std::swap(m_parts, other.m_parts);
return *this;
}
virtual ~multipart_t()
{
clear();
}
void clear()
{
m_parts.clear();
}
size_t size() const
{
return m_parts.size();
}
bool empty() const
{
return m_parts.empty();
}
bool recv(socket_t& socket)
{
clear();
bool more = true;
while (more)
{
message_t message;
if (!socket.recv(&message))
return false;
more = message.more();
add(std::move(message));
}
return true;
}
bool send(socket_t& socket)
{
bool more = size() > 0;
while (more)
{
message_t message = pop();
more = size() > 0;
if (!socket.send(message, more ? ZMQ_SNDMORE : 0))
return false;
}
clear();
return true;
}
void prepend(multipart_t&& other)
{
while (!other.empty())
push(other.remove());
}
void append(multipart_t&& other)
{
while (!other.empty())
add(other.pop());
}
void pushmem(const void *src, size_t size)
{
m_parts.push_front(message_t(src, size));
}
void addmem(const void *src, size_t size)
{
m_parts.push_back(message_t(src, size));
}
void pushstr(const std::string& string)
{
m_parts.push_front(message_t(string.data(), string.size()));
}
void addstr(const std::string& string)
{
m_parts.push_back(message_t(string.data(), string.size()));
}
template<typename T>
void pushtyp(const T& type)
{
m_parts.push_front(message_t(&type, sizeof(type)));
}
template<typename T>
void addtyp(const T& type)
{
m_parts.push_back(message_t(&type, sizeof(type)));
}
void push(message_t&& message)
{
m_parts.push_front(std::move(message));
}
void add(message_t&& message)
{
m_parts.push_back(std::move(message));
}
std::string popstr()
{
if (m_parts.empty())
return "";
std::string string(m_parts.front().data<char>(), m_parts.front().size());
m_parts.pop_front();
return string;
}
template<typename T>
T poptyp()
{
if (m_parts.empty())
return T();
T type = *m_parts.front().data<T>();
m_parts.pop_front();
return type;
}
message_t pop()
{
if (m_parts.empty())
return message_t(0);
message_t message = std::move(m_parts.front());
m_parts.pop_front();
return message;
}
message_t remove()
{
if (m_parts.empty())
return message_t(0);
message_t message = std::move(m_parts.back());
m_parts.pop_back();
return message;
}
const message_t* peek(size_t index) const
{
if (index >= size())
return nullptr;
return &m_parts[index];
}
template<typename T>
static multipart_t create(const T& type)
{
multipart_t multipart;
multipart.addtyp(type);
return multipart;
}
multipart_t clone() const
{
multipart_t multipart;
for (size_t i = 0; i < size(); i++)
multipart.addmem(m_parts[i].data(), m_parts[i].size());
return multipart;
}
std::string str() const
{
std::stringstream ss;
for (size_t i = 0; i < m_parts.size(); i++)
{
const unsigned char* data = m_parts[i].data<unsigned char>();
size_t size = m_parts[i].size();
// Dump the message as text or binary
bool isText = true;
for (size_t j = 0; j < size; j++)
{
if (data[j] < 32 || data[j] > 127)
{
isText = false;
break;
}
}
ss << "\n[" << std::dec << std::setw(3) << std::setfill('0') << size << "] ";
if (size >= 1000)
{
ss << "... (to big to print)";
continue;
}
for (size_t j = 0; j < size; j++)
{
if (isText)
ss << static_cast<char>(data[j]);
else
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<short>(data[j]);
}
}
return ss.str();
}
bool equal(const multipart_t* other) const
{
if (size() != other->size())
return false;
for (size_t i = 0; i < size(); i++)
if (!peek(i)->equal(other->peek(i)))
return false;
return true;
}
static int test()
{
bool ok = true;
float num = 0;
std::string str = "";
message_t msg;
// Create two PAIR sockets and connect over inproc
context_t context(1);
socket_t output(context, ZMQ_PAIR);
socket_t input(context, ZMQ_PAIR);
output.bind("inproc://multipart.test");
input.connect("inproc://multipart.test");
// Test send and receive of single-frame message
multipart_t multipart;
assert(multipart.empty());
multipart.push(message_t("Hello", 5));
assert(multipart.size() == 1);
ok = multipart.send(output);
assert(multipart.empty());
assert(ok);
ok = multipart.recv(input);
assert(multipart.size() == 1);
assert(ok);
msg = multipart.pop();
assert(multipart.empty());
assert(std::string(msg.data<char>(), msg.size()) == "Hello");
// Test send and receive of multi-frame message
multipart.addstr("A");
multipart.addstr("BB");
multipart.addstr("CCC");
assert(multipart.size() == 3);
multipart_t copy = multipart.clone();
assert(copy.size() == 3);
ok = copy.send(output);
assert(copy.empty());
assert(ok);
ok = copy.recv(input);
assert(copy.size() == 3);
assert(ok);
assert(copy.equal(&multipart));
multipart.clear();
assert(multipart.empty());
// Test message frame manipulation
multipart.add(message_t("Frame5", 6));
multipart.addstr("Frame6");
multipart.addstr("Frame7");
multipart.addtyp(8.0f);
multipart.addmem("Frame9", 6);
multipart.push(message_t("Frame4", 6));
multipart.pushstr("Frame3");
multipart.pushstr("Frame2");
multipart.pushtyp(1.0f);
multipart.pushmem("Frame0", 6);
assert(multipart.size() == 10);
msg = multipart.remove();
assert(multipart.size() == 9);
assert(std::string(msg.data<char>(), msg.size()) == "Frame9");
msg = multipart.pop();
assert(multipart.size() == 8);
assert(std::string(msg.data<char>(), msg.size()) == "Frame0");
num = multipart.poptyp<float>();
assert(multipart.size() == 7);
assert(num == 1.0f);
str = multipart.popstr();
assert(multipart.size() == 6);
assert(str == "Frame2");
str = multipart.popstr();
assert(multipart.size() == 5);
assert(str == "Frame3");
str = multipart.popstr();
assert(multipart.size() == 4);
assert(str == "Frame4");
str = multipart.popstr();
assert(multipart.size() == 3);
assert(str == "Frame5");
str = multipart.popstr();
assert(multipart.size() == 2);
assert(str == "Frame6");
str = multipart.popstr();
assert(multipart.size() == 1);
assert(str == "Frame7");
num = multipart.poptyp<float>();
assert(multipart.empty());
assert(num == 8.0f);
// Test message constructors and concatenation
multipart_t head("One", 3);
head.addstr("Two");
assert(head.size() == 2);
multipart_t tail("One-hundred");
tail.pushstr("Ninety-nine");
assert(tail.size() == 2);
multipart_t tmp(message_t("Fifty", 5));
assert(tmp.size() == 1);
multipart_t mid = multipart_t::create(49.0f);
mid.append(std::move(tmp));
assert(mid.size() == 2);
assert(tmp.empty());
multipart_t merged(std::move(mid));
merged.prepend(std::move(head));
merged.append(std::move(tail));
assert(merged.size() == 6);
assert(head.empty());
assert(tail.empty());
ok = merged.send(output);
assert(merged.empty());
assert(ok);
multipart_t received(input);
assert(received.size() == 6);
str = received.popstr();
assert(received.size() == 5);
assert(str == "One");
str = received.popstr();
assert(received.size() == 4);
assert(str == "Two");
num = received.poptyp<float>();
assert(received.size() == 3);
assert(num == 49.0f);
str = received.popstr();
assert(received.size() == 2);
assert(str == "Fifty");
str = received.popstr();
assert(received.size() == 1);
assert(str == "Ninety-nine");
str = received.popstr();
assert(received.empty());
assert(str == "One-hundred");
return 0;
}
private:
// Disable implicit copying (moving is more efficient)
multipart_t(const multipart_t& other) ZMQ_DELETED_FUNCTION;
void operator=(const multipart_t& other) ZMQ_DELETED_FUNCTION;
};
#endif
}
#endif
<commit_msg>Enable passing flags in to `send()` and `recv()`<commit_after>/*
Copyright (c) 2016 VOCA AS / Harald Nkland
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef __ZMQ_ADDON_HPP_INCLUDED__
#define __ZMQ_ADDON_HPP_INCLUDED__
#include <zmq.hpp>
#include <deque>
#include <iomanip>
#include <sstream>
namespace zmq {
#ifdef ZMQ_HAS_RVALUE_REFS
/*
This class handles multipart messaging. It is the C++ equivalent of zmsg.h,
which is part of CZMQ (the high-level C binding). Furthermore, it is a major
improvement compared to zmsg.hpp, which is part of the examples in the MQ
Guide. Unnecessary copying is avoided by using move semantics to efficiently
add/remove parts.
*/
class multipart_t
{
private:
std::deque<message_t> m_parts;
public:
multipart_t()
{}
multipart_t(socket_t& socket)
{
recv(socket);
}
multipart_t(const void *src, size_t size)
{
addmem(src, size);
}
multipart_t(const std::string& string)
{
addstr(string);
}
multipart_t(message_t&& message)
{
add(std::move(message));
}
multipart_t(multipart_t&& other)
{
std::swap(m_parts, other.m_parts);
}
multipart_t& operator=(multipart_t&& other)
{
std::swap(m_parts, other.m_parts);
return *this;
}
virtual ~multipart_t()
{
clear();
}
void clear()
{
m_parts.clear();
}
size_t size() const
{
return m_parts.size();
}
bool empty() const
{
return m_parts.empty();
}
bool recv(socket_t& socket, int flags = 0)
{
clear();
bool more = true;
while (more)
{
message_t message;
if (!socket.recv(&message, flags))
return false;
more = message.more();
add(std::move(message));
}
return true;
}
bool send(socket_t& socket, int flags = 0)
{
flags &= ~(ZMQ_SNDMORE);
bool more = size() > 0;
while (more)
{
message_t message = pop();
more = size() > 0;
if (!socket.send(message, (more ? ZMQ_SNDMORE : 0) | flags))
return false;
}
clear();
return true;
}
void prepend(multipart_t&& other)
{
while (!other.empty())
push(other.remove());
}
void append(multipart_t&& other)
{
while (!other.empty())
add(other.pop());
}
void pushmem(const void *src, size_t size)
{
m_parts.push_front(message_t(src, size));
}
void addmem(const void *src, size_t size)
{
m_parts.push_back(message_t(src, size));
}
void pushstr(const std::string& string)
{
m_parts.push_front(message_t(string.data(), string.size()));
}
void addstr(const std::string& string)
{
m_parts.push_back(message_t(string.data(), string.size()));
}
template<typename T>
void pushtyp(const T& type)
{
m_parts.push_front(message_t(&type, sizeof(type)));
}
template<typename T>
void addtyp(const T& type)
{
m_parts.push_back(message_t(&type, sizeof(type)));
}
void push(message_t&& message)
{
m_parts.push_front(std::move(message));
}
void add(message_t&& message)
{
m_parts.push_back(std::move(message));
}
std::string popstr()
{
if (m_parts.empty())
return "";
std::string string(m_parts.front().data<char>(), m_parts.front().size());
m_parts.pop_front();
return string;
}
template<typename T>
T poptyp()
{
if (m_parts.empty())
return T();
T type = *m_parts.front().data<T>();
m_parts.pop_front();
return type;
}
message_t pop()
{
if (m_parts.empty())
return message_t(0);
message_t message = std::move(m_parts.front());
m_parts.pop_front();
return message;
}
message_t remove()
{
if (m_parts.empty())
return message_t(0);
message_t message = std::move(m_parts.back());
m_parts.pop_back();
return message;
}
const message_t* peek(size_t index) const
{
if (index >= size())
return nullptr;
return &m_parts[index];
}
template<typename T>
static multipart_t create(const T& type)
{
multipart_t multipart;
multipart.addtyp(type);
return multipart;
}
multipart_t clone() const
{
multipart_t multipart;
for (size_t i = 0; i < size(); i++)
multipart.addmem(m_parts[i].data(), m_parts[i].size());
return multipart;
}
std::string str() const
{
std::stringstream ss;
for (size_t i = 0; i < m_parts.size(); i++)
{
const unsigned char* data = m_parts[i].data<unsigned char>();
size_t size = m_parts[i].size();
// Dump the message as text or binary
bool isText = true;
for (size_t j = 0; j < size; j++)
{
if (data[j] < 32 || data[j] > 127)
{
isText = false;
break;
}
}
ss << "\n[" << std::dec << std::setw(3) << std::setfill('0') << size << "] ";
if (size >= 1000)
{
ss << "... (to big to print)";
continue;
}
for (size_t j = 0; j < size; j++)
{
if (isText)
ss << static_cast<char>(data[j]);
else
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<short>(data[j]);
}
}
return ss.str();
}
bool equal(const multipart_t* other) const
{
if (size() != other->size())
return false;
for (size_t i = 0; i < size(); i++)
if (!peek(i)->equal(other->peek(i)))
return false;
return true;
}
static int test()
{
bool ok = true;
float num = 0;
std::string str = "";
message_t msg;
// Create two PAIR sockets and connect over inproc
context_t context(1);
socket_t output(context, ZMQ_PAIR);
socket_t input(context, ZMQ_PAIR);
output.bind("inproc://multipart.test");
input.connect("inproc://multipart.test");
// Test send and receive of single-frame message
multipart_t multipart;
assert(multipart.empty());
multipart.push(message_t("Hello", 5));
assert(multipart.size() == 1);
ok = multipart.send(output);
assert(multipart.empty());
assert(ok);
ok = multipart.recv(input);
assert(multipart.size() == 1);
assert(ok);
msg = multipart.pop();
assert(multipart.empty());
assert(std::string(msg.data<char>(), msg.size()) == "Hello");
// Test send and receive of multi-frame message
multipart.addstr("A");
multipart.addstr("BB");
multipart.addstr("CCC");
assert(multipart.size() == 3);
multipart_t copy = multipart.clone();
assert(copy.size() == 3);
ok = copy.send(output);
assert(copy.empty());
assert(ok);
ok = copy.recv(input);
assert(copy.size() == 3);
assert(ok);
assert(copy.equal(&multipart));
multipart.clear();
assert(multipart.empty());
// Test message frame manipulation
multipart.add(message_t("Frame5", 6));
multipart.addstr("Frame6");
multipart.addstr("Frame7");
multipart.addtyp(8.0f);
multipart.addmem("Frame9", 6);
multipart.push(message_t("Frame4", 6));
multipart.pushstr("Frame3");
multipart.pushstr("Frame2");
multipart.pushtyp(1.0f);
multipart.pushmem("Frame0", 6);
assert(multipart.size() == 10);
msg = multipart.remove();
assert(multipart.size() == 9);
assert(std::string(msg.data<char>(), msg.size()) == "Frame9");
msg = multipart.pop();
assert(multipart.size() == 8);
assert(std::string(msg.data<char>(), msg.size()) == "Frame0");
num = multipart.poptyp<float>();
assert(multipart.size() == 7);
assert(num == 1.0f);
str = multipart.popstr();
assert(multipart.size() == 6);
assert(str == "Frame2");
str = multipart.popstr();
assert(multipart.size() == 5);
assert(str == "Frame3");
str = multipart.popstr();
assert(multipart.size() == 4);
assert(str == "Frame4");
str = multipart.popstr();
assert(multipart.size() == 3);
assert(str == "Frame5");
str = multipart.popstr();
assert(multipart.size() == 2);
assert(str == "Frame6");
str = multipart.popstr();
assert(multipart.size() == 1);
assert(str == "Frame7");
num = multipart.poptyp<float>();
assert(multipart.empty());
assert(num == 8.0f);
// Test message constructors and concatenation
multipart_t head("One", 3);
head.addstr("Two");
assert(head.size() == 2);
multipart_t tail("One-hundred");
tail.pushstr("Ninety-nine");
assert(tail.size() == 2);
multipart_t tmp(message_t("Fifty", 5));
assert(tmp.size() == 1);
multipart_t mid = multipart_t::create(49.0f);
mid.append(std::move(tmp));
assert(mid.size() == 2);
assert(tmp.empty());
multipart_t merged(std::move(mid));
merged.prepend(std::move(head));
merged.append(std::move(tail));
assert(merged.size() == 6);
assert(head.empty());
assert(tail.empty());
ok = merged.send(output);
assert(merged.empty());
assert(ok);
multipart_t received(input);
assert(received.size() == 6);
str = received.popstr();
assert(received.size() == 5);
assert(str == "One");
str = received.popstr();
assert(received.size() == 4);
assert(str == "Two");
num = received.poptyp<float>();
assert(received.size() == 3);
assert(num == 49.0f);
str = received.popstr();
assert(received.size() == 2);
assert(str == "Fifty");
str = received.popstr();
assert(received.size() == 1);
assert(str == "Ninety-nine");
str = received.popstr();
assert(received.empty());
assert(str == "One-hundred");
return 0;
}
private:
// Disable implicit copying (moving is more efficient)
multipart_t(const multipart_t& other) ZMQ_DELETED_FUNCTION;
void operator=(const multipart_t& other) ZMQ_DELETED_FUNCTION;
};
#endif
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2018, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <net/if.h>
#include <benchmark/benchmark.h>
#include <quant/quant.h>
#include <warpcore/warpcore.h>
extern "C" {
#include "pkt.h"
#include "quic.h"
#include "tls.h" // IWYU pragma: keep
}
static struct q_conn * c;
static struct w_engine * w;
static void BM_quic_encryption(benchmark::State & state)
{
const auto len = uint16_t(state.range(0));
const auto pne = uint16_t(state.range(1));
struct w_iov * const v = q_alloc_iov(w, len, 0);
struct w_iov * const x = q_alloc_iov(w, MAX_PKT_LEN, 0);
meta(v).hdr.type = F_LH_INIT;
meta(v).hdr.flags = F_LONG_HDR | meta(v).hdr.type;
meta(v).hdr.hdr_len = 16;
for (auto _ : state)
benchmark::DoNotOptimize(enc_aead(c, v, x, pne * 16));
state.SetBytesProcessed(int64_t(state.iterations() * len)); // NOLINT
q_free_iov(x);
q_free_iov(v);
}
BENCHMARK(BM_quic_encryption)
->RangeMultiplier(2)
->Ranges({{16, MAX_PKT_LEN}, {0, 1}})
->Complexity();
// BENCHMARK_MAIN()
int main(int argc, char ** argv)
{
char i[IFNAMSIZ] = "lo"
#ifndef __linux__
"0"
#endif
;
benchmark::Initialize(&argc, argv);
#ifndef NDEBUG
util_dlevel = INF;
#endif
w = q_init(i, nullptr, nullptr, nullptr, nullptr); // NOLINT
c = q_bind(w, 55555);
init_tls(c);
init_hshk_prot(c);
benchmark::RunSpecifiedBenchmarks();
q_cleanup(w);
}
<commit_msg>Randomize buffer before benchmark<commit_after>// Copyright (c) 2014-2018, NetApp, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <net/if.h>
#include <benchmark/benchmark.h>
#include <quant/quant.h>
#include <warpcore/warpcore.h>
extern "C" {
#include "pkt.h"
#include "quic.h"
#include "tls.h" // IWYU pragma: keep
}
static struct q_conn * c;
static struct w_engine * w;
static void BM_quic_encryption(benchmark::State & state)
{
const auto len = uint16_t(state.range(0));
const auto pne = uint16_t(state.range(1));
struct w_iov * const v = q_alloc_iov(w, len, 0);
struct w_iov * const x = q_alloc_iov(w, MAX_PKT_LEN, 0);
arc4random_buf(v->buf, len);
meta(v).hdr.type = F_LH_INIT;
meta(v).hdr.flags = F_LONG_HDR | meta(v).hdr.type;
meta(v).hdr.hdr_len = 16;
for (auto _ : state)
benchmark::DoNotOptimize(enc_aead(c, v, x, pne * 16));
state.SetBytesProcessed(int64_t(state.iterations() * len)); // NOLINT
q_free_iov(x);
q_free_iov(v);
}
BENCHMARK(BM_quic_encryption)
->RangeMultiplier(2)
->Ranges({{16, MAX_PKT_LEN}, {0, 1}})
// ->MinTime(3)
// ->UseRealTime()
;
// BENCHMARK_MAIN()
int main(int argc, char ** argv)
{
char i[IFNAMSIZ] = "lo"
#ifndef __linux__
"0"
#endif
;
benchmark::Initialize(&argc, argv);
#ifndef NDEBUG
util_dlevel = INF;
#endif
w = q_init(i, nullptr, nullptr, nullptr, nullptr); // NOLINT
c = q_bind(w, 55555);
init_tls(c);
init_hshk_prot(c);
benchmark::RunSpecifiedBenchmarks();
q_cleanup(w);
}
<|endoftext|> |
<commit_before>#pragma once
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/not_null.hpp"
#include "geometry/rotation.hpp"
#include "geometry/orthogonal_map.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/part.hpp"
#include "ksp_plugin/vessel.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "serialization/ksp_plugin.pb.h"
namespace principia {
using base::not_null;
using geometry::OrthogonalMap;
using physics::DegreesOfFreedom;
using physics::RelativeDegreesOfFreedom;
namespace ksp_plugin {
class PhysicsBubble {
public:
using BarycentricToWorldSun = geometry::OrthogonalMap<Barycentric, WorldSun>;
PhysicsBubble();
~PhysicsBubble() = default;
// Creates |next_| if it is null. Adds the |vessel| to |next_->vessels| with
// a list of pointers to the Parts in |parts|. Merges |parts| into
// |next_->parts|. The |vessel| must not already be in |next_->vessels|.
// |parts| must not contain a |PartId| already in |next_->parts|.
void AddVesselToNext(not_null<Vessel*> const vessel,
std::vector<IdAndOwnedPart> parts);
// If |next_| is not null, computes the world centre of mass, trajectory
// (including intrinsic acceleration) of |*next_|. Moves |next_| into
// |current_|. The trajectory of the centre of mass is reset to a single
// point at |current_time| if the composition of the bubble changes.
// TODO(phl): Document the parameters!
void Prepare(BarycentricToWorldSun const& barycentric_to_world_sun,
Instant const& current_time,
Instant const& next_time);
// Computes and returns |current_->displacement_correction|. This is the
// |World| shift to be applied to the bubble in order for it to be in the
// correct position.
Displacement<World> DisplacementCorrection(
BarycentricToWorldSun const& barycentric_to_world_sun,
Celestial const& reference_celestial,
Position<World> const& reference_celestial_world_position) const;
// Computes and returns |current_->velocity_correction|. This is the |World|
// shift to be applied to the physics bubble in order for it to have the
// correct velocity.
Velocity<World> VelocityCorrection(
BarycentricToWorldSun const& barycentric_to_world_sun,
Celestial const& reference_celestial) const;
// Returns |current_ == nullptr|.
bool empty() const;
// Returns 0 if |empty()|, 1 otherwise.
std::size_t size() const;
// Returns |current_->vessels.size()|, or 0 if |empty()|.
std::size_t number_of_vessels() const;
// Returns true if, and only if, |vessel| is in |current_->vessels|.
// |current_| may be null, in that case, returns false.
bool contains(not_null<Vessel*> const vessel) const;
// Selectors for the data in |current_|.
std::vector<not_null<Vessel*>> vessels() const;
RelativeDegreesOfFreedom<Barycentric> const& from_centre_of_mass(
not_null<Vessel const*> const vessel) const;
Trajectory<Barycentric> const& centre_of_mass_trajectory() const;
not_null<Trajectory<Barycentric>*> mutable_centre_of_mass_trajectory() const;
void WriteToMessage(
std::function<std::string(not_null<Vessel const*>)> const guid,
not_null<serialization::PhysicsBubble*> const message) const;
static std::unique_ptr<PhysicsBubble> ReadFromMessage(
std::function<not_null<Vessel*>(std::string)> const vessel,
serialization::PhysicsBubble const& message);
private:
using PartCorrespondence = std::pair<not_null<Part<World>*>,
not_null<Part<World>*>>;
struct PreliminaryState {
PreliminaryState();
std::map<not_null<Vessel*> const,
std::vector<not_null<Part<World>*> const>> vessels;
PartIdToOwnedPart parts;
};
struct FullState : public PreliminaryState {
explicit FullState(
PreliminaryState&& preliminary_state); // NOLINT(build/c++11)
// TODO(egg): these fields should be |std::optional| when that becomes a
// thing.
std::unique_ptr<DegreesOfFreedom<World>> centre_of_mass;
std::unique_ptr<Trajectory<Barycentric>> centre_of_mass_trajectory;
std::unique_ptr<std::map<not_null<Vessel const*> const,
RelativeDegreesOfFreedom<Barycentric>>>
from_centre_of_mass;
std::unique_ptr<Displacement<World>> displacement_correction;
std::unique_ptr<Velocity<World>> velocity_correction;
};
// Computes the world degrees of freedom of the centre of mass of
// |next| using the contents of |next->parts|.
void ComputeNextCentreOfMassWorldDegreesOfFreedom(
not_null<FullState*> const next);
// Computes |next->displacements_from_centre_of_mass| and
// |next->velocities_from_centre_of_mass|.
void ComputeNextVesselOffsets(
BarycentricToWorldSun const& barycentric_to_world_sun,
not_null<FullState*> const next);
// Creates |next->centre_of_mass_trajectory| and appends to it the barycentre
// of the degrees of freedom of the vessels in |next->vessels|. There is no
// intrinsic acceleration.
void RestartNext(Instant const& current_time,
not_null<FullState*> const next);
// Returns the parts common to |current_| and |next|. The returned vector
// contains pair of pointers to parts (current_part, next_part) for all parts
// common to the two bubbles
std::vector<PhysicsBubble::PartCorrespondence> ComputeCommonParts(
FullState const& next);
// Returns the intrinsic acceleration measured on the parts that are common to
// the current and next bubbles.
Vector<Acceleration, World> IntrinsicAcceleration(
Instant const& current_time,
Instant const& next_time,
std::vector<PartCorrespondence>const& common_parts);
// Given the vector of common parts, constructs
// |next->centre_of_mass_trajectory| and appends degrees of freedom at
// |current_time| that conserve the degrees of freedom of the centre of mass
// of the parts in |common_parts|.
void Shift(BarycentricToWorldSun const& barycentric_to_world_sun,
Instant const& current_time,
std::vector<PartCorrespondence> const& common_parts,
not_null<FullState*> const next);
std::unique_ptr<FullState> current_;
// The following member is only accessed by |AddVesselToNext| and at the
// beginning of |Prepare|.
std::unique_ptr<PreliminaryState> next_;
MasslessBody const body_;
};
} // namespace ksp_plugin
} // namespace principia
<commit_msg>Aphlabetize.<commit_after>#pragma once
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/not_null.hpp"
#include "geometry/orthogonal_map.hpp"
#include "geometry/rotation.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/part.hpp"
#include "ksp_plugin/vessel.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "serialization/ksp_plugin.pb.h"
namespace principia {
using base::not_null;
using geometry::OrthogonalMap;
using physics::DegreesOfFreedom;
using physics::RelativeDegreesOfFreedom;
namespace ksp_plugin {
class PhysicsBubble {
public:
using BarycentricToWorldSun = geometry::OrthogonalMap<Barycentric, WorldSun>;
PhysicsBubble();
~PhysicsBubble() = default;
// Creates |next_| if it is null. Adds the |vessel| to |next_->vessels| with
// a list of pointers to the Parts in |parts|. Merges |parts| into
// |next_->parts|. The |vessel| must not already be in |next_->vessels|.
// |parts| must not contain a |PartId| already in |next_->parts|.
void AddVesselToNext(not_null<Vessel*> const vessel,
std::vector<IdAndOwnedPart> parts);
// If |next_| is not null, computes the world centre of mass, trajectory
// (including intrinsic acceleration) of |*next_|. Moves |next_| into
// |current_|. The trajectory of the centre of mass is reset to a single
// point at |current_time| if the composition of the bubble changes.
// TODO(phl): Document the parameters!
void Prepare(BarycentricToWorldSun const& barycentric_to_world_sun,
Instant const& current_time,
Instant const& next_time);
// Computes and returns |current_->displacement_correction|. This is the
// |World| shift to be applied to the bubble in order for it to be in the
// correct position.
Displacement<World> DisplacementCorrection(
BarycentricToWorldSun const& barycentric_to_world_sun,
Celestial const& reference_celestial,
Position<World> const& reference_celestial_world_position) const;
// Computes and returns |current_->velocity_correction|. This is the |World|
// shift to be applied to the physics bubble in order for it to have the
// correct velocity.
Velocity<World> VelocityCorrection(
BarycentricToWorldSun const& barycentric_to_world_sun,
Celestial const& reference_celestial) const;
// Returns |current_ == nullptr|.
bool empty() const;
// Returns 0 if |empty()|, 1 otherwise.
std::size_t size() const;
// Returns |current_->vessels.size()|, or 0 if |empty()|.
std::size_t number_of_vessels() const;
// Returns true if, and only if, |vessel| is in |current_->vessels|.
// |current_| may be null, in that case, returns false.
bool contains(not_null<Vessel*> const vessel) const;
// Selectors for the data in |current_|.
std::vector<not_null<Vessel*>> vessels() const;
RelativeDegreesOfFreedom<Barycentric> const& from_centre_of_mass(
not_null<Vessel const*> const vessel) const;
Trajectory<Barycentric> const& centre_of_mass_trajectory() const;
not_null<Trajectory<Barycentric>*> mutable_centre_of_mass_trajectory() const;
void WriteToMessage(
std::function<std::string(not_null<Vessel const*>)> const guid,
not_null<serialization::PhysicsBubble*> const message) const;
static std::unique_ptr<PhysicsBubble> ReadFromMessage(
std::function<not_null<Vessel*>(std::string)> const vessel,
serialization::PhysicsBubble const& message);
private:
using PartCorrespondence = std::pair<not_null<Part<World>*>,
not_null<Part<World>*>>;
struct PreliminaryState {
PreliminaryState();
std::map<not_null<Vessel*> const,
std::vector<not_null<Part<World>*> const>> vessels;
PartIdToOwnedPart parts;
};
struct FullState : public PreliminaryState {
explicit FullState(
PreliminaryState&& preliminary_state); // NOLINT(build/c++11)
// TODO(egg): these fields should be |std::optional| when that becomes a
// thing.
std::unique_ptr<DegreesOfFreedom<World>> centre_of_mass;
std::unique_ptr<Trajectory<Barycentric>> centre_of_mass_trajectory;
std::unique_ptr<std::map<not_null<Vessel const*> const,
RelativeDegreesOfFreedom<Barycentric>>>
from_centre_of_mass;
std::unique_ptr<Displacement<World>> displacement_correction;
std::unique_ptr<Velocity<World>> velocity_correction;
};
// Computes the world degrees of freedom of the centre of mass of
// |next| using the contents of |next->parts|.
void ComputeNextCentreOfMassWorldDegreesOfFreedom(
not_null<FullState*> const next);
// Computes |next->displacements_from_centre_of_mass| and
// |next->velocities_from_centre_of_mass|.
void ComputeNextVesselOffsets(
BarycentricToWorldSun const& barycentric_to_world_sun,
not_null<FullState*> const next);
// Creates |next->centre_of_mass_trajectory| and appends to it the barycentre
// of the degrees of freedom of the vessels in |next->vessels|. There is no
// intrinsic acceleration.
void RestartNext(Instant const& current_time,
not_null<FullState*> const next);
// Returns the parts common to |current_| and |next|. The returned vector
// contains pair of pointers to parts (current_part, next_part) for all parts
// common to the two bubbles
std::vector<PhysicsBubble::PartCorrespondence> ComputeCommonParts(
FullState const& next);
// Returns the intrinsic acceleration measured on the parts that are common to
// the current and next bubbles.
Vector<Acceleration, World> IntrinsicAcceleration(
Instant const& current_time,
Instant const& next_time,
std::vector<PartCorrespondence>const& common_parts);
// Given the vector of common parts, constructs
// |next->centre_of_mass_trajectory| and appends degrees of freedom at
// |current_time| that conserve the degrees of freedom of the centre of mass
// of the parts in |common_parts|.
void Shift(BarycentricToWorldSun const& barycentric_to_world_sun,
Instant const& current_time,
std::vector<PartCorrespondence> const& common_parts,
not_null<FullState*> const next);
std::unique_ptr<FullState> current_;
// The following member is only accessed by |AddVesselToNext| and at the
// beginning of |Prepare|.
std::unique_ptr<PreliminaryState> next_;
MasslessBody const body_;
};
} // namespace ksp_plugin
} // namespace principia
<|endoftext|> |
<commit_before>#include "GolfBall.hpp"
#include "../Resources.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.geom.hpp"
#include "Default3D.frag.hpp"
#include "glm/gtc/constants.hpp"
#include "../Util/Log.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
GolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"),
"Resources/Models/GolfBall/Diffuse.png",
"Resources/Models/GolfBall/Normal.png",
"Resources/Models/GolfBall/Specular.png") {
active = false;
restitution = ballType == TWOPIECE ? 0.78f : 0.68f;
this->terrain = terrain;
groundLevel = this->terrain->Position().y;
origin = glm::vec3(1.f, 0.f, 1.f);
/// @todo Mass based on explosive material.
mass = 0.0459f;
this->ballType = ballType;
sphere.position = Position();
SetRadius(0.0214f);
}
GolfBall::~GolfBall() {
Resources().FreeOBJModel(modelGeometry);
}
void GolfBall::Reset(){
active = false;
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
SetPosition(origin);
sphere.position = Position();
orientation = glm::quat();
}
void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) {
if (active) {
Move(static_cast<float>(time)* velocity);
sphere.position = Position();
if (glm::length(angularVelocity) > 0.0001f) {
glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity));
orientation = deltaQuat * orientation;
}
glm::vec3 dragForce, magnusForce = glm::vec3(0.f, 0.f, 0.f);
// Check for collision
groundLevel = terrain->GetY(Position().x, Position().z);
if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){
float vCritical = 0.3f;
float e = 0.35f;
float muSliding = 0.51f;
float muRolling = 0.096f;
SetPosition(Position().x, groundLevel + sphere.radius, Position().z);
sphere.position = Position();
//glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f));
glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().z);
glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh;
glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f);
if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f){
eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity);
}
float vRoh = glm::dot(velocity, eRoh);
float deltaU = -(e + 1.f) * vRoh;
glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity));
float w = glm::dot(angularVelocity, angularDirection);
if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) {
if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) {
// Sliding.
velocity = tangentialVelocity - static_cast<float>(time)* (eFriction * muSliding * 9.82f*eRoh.y);
angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * angularDirection;
} else {
// Rolling.
velocity = tangentialVelocity - static_cast<float>(time)* (glm::normalize(tangentialVelocity) * muRolling * 9.82f*eRoh.y);
float tangentialVelocityAfter = glm::length(velocity - glm::dot(velocity, eRoh) * eRoh);
angularVelocity = (glm::length(tangentialVelocityAfter) / sphere.radius) * angularDirection;
// Stopped.
if (glm::length(velocity) < 0.005f) {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
} else {
float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f;
float velocityRoh = glm::dot(velocity, eRoh);
float velocityNormal = glm::dot(velocity, eFriction);
float uRoh = -e*velocityRoh;
float deltauRoh = uRoh - (velocityRoh);
float deltaUn = muSliding*deltauRoh;
float rollUn = (5.f / 7.f)*velocityNormal;
float slideUn = velocityNormal - deltaUn;
if (velocityNormal > rollUn){
velocity = uRoh*eRoh + rollUn*eFriction;
angularVelocity += muRolling * (deltaU + 9.82f*eRoh.y * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
} else {
velocity = uRoh*eRoh + slideUn*eFriction;
angularVelocity += muSliding * (deltaU + 9.82f *eRoh.y* deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
}
}
} else {
// Calculate magnus force.
float v = glm::length(velocity);
float u = glm::length(velocity - wind);
float w = glm::length(angularVelocity);
glm::vec3 eU = (velocity - wind) / u;
magnusForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f && v > 0.f && w > 0.f) {
float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f;
float Fm = 0.5f * Cm * 1.23f * area * u * u;
magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity));
}
// Calculate drag force.
float cD;
if (ballType == TWOPIECE)
cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;
else
cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;
dragForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f)
dragForce = -0.5f * 1.23f * area * cD * u * u * eU;
}
// Calculate gravitational force.
glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);
// Get acceleration from total force.
glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) / mass;
velocity += acceleration * static_cast<float>(time);
}
}
void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{
ModelObject::Render(camera, screenSize, clippingPlane);
}
void GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){
//@TODO: Set mass equivalent depending on material used.
float equivalenceFactor = 1.0f;
float massEquivalent = mass*equivalenceFactor;
for (auto &player : players){
glm::vec3 distanceV = (Position() - player.Position());
float distance = glm::length(distanceV);
//pow(meq, 1.f/3.f) => cube root of meq
float z = distance / (pow(massEquivalent, 1.f / 3.f));
float alpha = 1 + pow((z / 4.5f), 2.f);
float beta = 1 + pow((z / 0.048f), 2.f);
float gamma = 1 + pow((z / 1.35f), 2.f);
float delta = 1 + pow((z / 0.32f), 2.f);
float Pf = 8.08f*pow(10.f, 7.f)*alpha;
Pf = Pf / sqrt(beta*gamma*delta);
player.TakeDamage(Pf);
}
origin = players[playerIndex].Position();
Reset();
}
void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) {
active = true;
// Club velocity in strike plane.
float v = glm::length(clubVelocity);
if (v > 0.f)
{
float sinLoft = sin(club.loft);
float cosLoft = cos(club.loft);
// Ball velocity.
float massCoefficient = club.mass / (club.mass + mass);
float Up = (1.f + restitution) * massCoefficient * v * cosLoft;
float Un = (2.f / 7.f) * massCoefficient * v * sinLoft;
// Go back from strike plane to 3D.
glm::vec3 forward = clubVelocity / v;
glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward));
glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up);
glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up);
// Total velocity.
velocity = Up * ep + Un * en;
angularVelocity = -Un / sphere.radius * glm::cross(ep, en);
} else {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
void GolfBall::SetRadius(float radius) {
sphere.radius = radius;
SetScale(glm::vec3(radius, radius, radius));
area = glm::pi<float>() * radius * radius;
}
glm::mat4 GolfBall::Orientation() const {
return glm::toMat4(orientation);
}
<commit_msg>Changed minimum velocity to stop the ball.<commit_after>#include "GolfBall.hpp"
#include "../Resources.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.geom.hpp"
#include "Default3D.frag.hpp"
#include "glm/gtc/constants.hpp"
#include "../Util/Log.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
GolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"),
"Resources/Models/GolfBall/Diffuse.png",
"Resources/Models/GolfBall/Normal.png",
"Resources/Models/GolfBall/Specular.png") {
active = false;
restitution = ballType == TWOPIECE ? 0.78f : 0.68f;
this->terrain = terrain;
groundLevel = this->terrain->Position().y;
origin = glm::vec3(1.f, 0.f, 1.f);
/// @todo Mass based on explosive material.
mass = 0.0459f;
this->ballType = ballType;
sphere.position = Position();
SetRadius(0.0214f);
}
GolfBall::~GolfBall() {
Resources().FreeOBJModel(modelGeometry);
}
void GolfBall::Reset(){
active = false;
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
SetPosition(origin);
sphere.position = Position();
orientation = glm::quat();
}
void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) {
if (active) {
Move(static_cast<float>(time)* velocity);
sphere.position = Position();
if (glm::length(angularVelocity) > 0.0001f) {
glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity));
orientation = deltaQuat * orientation;
}
glm::vec3 dragForce, magnusForce = glm::vec3(0.f, 0.f, 0.f);
// Check for collision
groundLevel = terrain->GetY(Position().x, Position().z);
if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){
float vCritical = 0.3f;
float e = 0.35f;
float muSliding = 0.51f;
float muRolling = 0.096f;
SetPosition(Position().x, groundLevel + sphere.radius, Position().z);
sphere.position = Position();
//glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f));
glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().z);
glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh;
glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f);
if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f){
eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity);
}
float vRoh = glm::dot(velocity, eRoh);
float deltaU = -(e + 1.f) * vRoh;
glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity));
float w = glm::dot(angularVelocity, angularDirection);
if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) {
if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) {
// Sliding.
velocity = tangentialVelocity - static_cast<float>(time)* (eFriction * muSliding * 9.82f*eRoh.y);
angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * angularDirection;
} else {
// Rolling.
velocity = tangentialVelocity - static_cast<float>(time)* (glm::normalize(tangentialVelocity) * muRolling * 9.82f*eRoh.y);
float tangentialVelocityAfter = glm::length(velocity - glm::dot(velocity, eRoh) * eRoh);
angularVelocity = (glm::length(tangentialVelocityAfter) / sphere.radius) * angularDirection;
// Stopped.
if (glm::length(velocity) < 0.2f) {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
} else {
float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f;
float velocityRoh = glm::dot(velocity, eRoh);
float velocityNormal = glm::dot(velocity, eFriction);
float uRoh = -e*velocityRoh;
float deltauRoh = uRoh - (velocityRoh);
float deltaUn = muSliding*deltauRoh;
float rollUn = (5.f / 7.f)*velocityNormal;
float slideUn = velocityNormal - deltaUn;
if (velocityNormal > rollUn){
velocity = uRoh*eRoh + rollUn*eFriction;
angularVelocity += muRolling * (deltaU + 9.82f*eRoh.y * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
} else {
velocity = uRoh*eRoh + slideUn*eFriction;
angularVelocity += muSliding * (deltaU + 9.82f *eRoh.y* deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
}
}
} else {
// Calculate magnus force.
float v = glm::length(velocity);
float u = glm::length(velocity - wind);
float w = glm::length(angularVelocity);
glm::vec3 eU = (velocity - wind) / u;
magnusForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f && v > 0.f && w > 0.f) {
float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f;
float Fm = 0.5f * Cm * 1.23f * area * u * u;
magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity));
}
// Calculate drag force.
float cD;
if (ballType == TWOPIECE)
cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;
else
cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;
dragForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f)
dragForce = -0.5f * 1.23f * area * cD * u * u * eU;
}
// Calculate gravitational force.
glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);
// Get acceleration from total force.
glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) / mass;
velocity += acceleration * static_cast<float>(time);
}
}
void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{
ModelObject::Render(camera, screenSize, clippingPlane);
}
void GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){
//@TODO: Set mass equivalent depending on material used.
float equivalenceFactor = 1.0f;
float massEquivalent = mass*equivalenceFactor;
for (auto &player : players){
glm::vec3 distanceV = (Position() - player.Position());
float distance = glm::length(distanceV);
//pow(meq, 1.f/3.f) => cube root of meq
float z = distance / (pow(massEquivalent, 1.f / 3.f));
float alpha = 1 + pow((z / 4.5f), 2.f);
float beta = 1 + pow((z / 0.048f), 2.f);
float gamma = 1 + pow((z / 1.35f), 2.f);
float delta = 1 + pow((z / 0.32f), 2.f);
float Pf = 8.08f*pow(10.f, 7.f)*alpha;
Pf = Pf / sqrt(beta*gamma*delta);
player.TakeDamage(Pf);
}
origin = players[playerIndex].Position();
Reset();
}
void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) {
active = true;
// Club velocity in strike plane.
float v = glm::length(clubVelocity);
if (v > 0.f)
{
float sinLoft = sin(club.loft);
float cosLoft = cos(club.loft);
// Ball velocity.
float massCoefficient = club.mass / (club.mass + mass);
float Up = (1.f + restitution) * massCoefficient * v * cosLoft;
float Un = (2.f / 7.f) * massCoefficient * v * sinLoft;
// Go back from strike plane to 3D.
glm::vec3 forward = clubVelocity / v;
glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward));
glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up);
glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up);
// Total velocity.
velocity = Up * ep + Un * en;
angularVelocity = -Un / sphere.radius * glm::cross(ep, en);
} else {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
void GolfBall::SetRadius(float radius) {
sphere.radius = radius;
SetScale(glm::vec3(radius, radius, radius));
area = glm::pi<float>() * radius * radius;
}
glm::mat4 GolfBall::Orientation() const {
return glm::toMat4(orientation);
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2003-2008 Grame
Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
[email protected]
This file is provided as an example of the MusicXML Library use.
*/
#ifdef WIN32
# pragma warning (disable : 4786)
#endif
#include <stdlib.h>
#include <iostream>
#include "libmusicxml.h"
using namespace std;
using namespace MusicXML2;
//_______________________________________________________________________________
int main(int argc, char *argv[])
{
cout << "libmusicxml version " << musicxmllibVersionStr() << endl;
cout << "libmusicxml to guido converter version " << musicxml2guidoVersionStr() << endl;
cout << "libmusicxml to lilypond converter version " << musicxml2lilypondVersionStr() << endl;
return 0;
}
<commit_msg>output change<commit_after>/*
Copyright (C) 2003-2008 Grame
Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
[email protected]
This file is provided as an example of the MusicXML Library use.
*/
#ifdef WIN32
# pragma warning (disable : 4786)
#endif
#include <stdlib.h>
#include <iostream>
#include "libmusicxml.h"
using namespace std;
using namespace MusicXML2;
//_______________________________________________________________________________
int main(int argc, char *argv[])
{
cout << "libmusicxml version " << musicxmllibVersionStr() << endl;
cout << "musicxml to guido converter version " << musicxml2guidoVersionStr() << endl;
cout << "musicxml to lilypond converter version " << musicxml2lilypondVersionStr() << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* sig_demo.C
* Ignore ^C, catch and respond to ^| and USR1 signal.
*
* Bryan Clair, 2002
*/
#include <iostream>
#include <unistd.h>
#include <signal.h>
using namespace std;
//
// handle_signal
// Called asynchronously when signals are received.
// It's not generally safe to use cout in a signal handler.
//
// int the_sig is the type of signal received.
//
void handle_signal(int the_sig)
{
switch(the_sig) {
case SIGQUIT:
cout << "Caught SIGQUIT.\n";
break;
case SIGUSR1:
cout << "Caught SIGUSR1.\n";
break;
}
}
main()
{
int i;
// set ^C to be ignored
signal(SIGINT,SIG_IGN);
// set handler to catch ^| and USR1 signal
signal(SIGQUIT,handle_signal);
signal(SIGUSR1,handle_signal);
// count for a while
for (i=0; ;i++) {
cout << i << endl;
sleep(1);
}
}
<commit_msg>check return value from sleep.<commit_after>/*
* sig_demo.C
* Ignore ^C, catch and respond to ^| and USR1 signal.
*
* Bryan Clair, 2002-2015
*/
#include <iostream>
#include <unistd.h>
#include <signal.h>
using namespace std;
//
// handle_signal
// Called asynchronously when signals are received.
// It's not generally safe to use cout in a signal handler.
//
// int the_sig is the type of signal received.
//
void handle_signal(int the_sig)
{
switch(the_sig) {
case SIGQUIT:
cout << "Caught SIGQUIT.\n";
break;
case SIGUSR1:
cout << "Caught SIGUSR1.\n";
break;
}
}
main()
{
// set ^C to be ignored
signal(SIGINT,SIG_IGN);
// set handler to catch ^| and USR1 signal
signal(SIGQUIT,handle_signal);
signal(SIGUSR1,handle_signal);
// count for a while
int i, timeleft;
for (i=0; ;i++) {
cout << i << endl;
timeleft = sleep(1);
if (timeleft != 0)
cout << "woke with " << timeleft << " second left" << endl;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
class Fracao {
private:
int num;
int den;
public:
void imprimir( void ) {
std::cout << getNum() << "/" << getDen() << '\n';
}
void setNum( const int num ) {
this->num = num;
}
void setDen( const int den ) {
if( den != 0 ) {
this->den = den;
} else {
std::cout << "Erro denominador" << '\n';
this->den = 0;
}
}
int getNum( void ) const {
return num;
}
int getDen( void ) const {
return den;
}
Fracao( const int num, const int den ) {
setNum( num );
setDen( den );
imprimir();
}
~Fracao( void ) {
std::cout << "Destrutor: ";
imprimir();
std::cout << '\n';
}
};
Fracao operator*( const Fracao &a, const Fracao &b ) {
Fracao resultado( a.getNum() * b.getNum(), a.getDen() * b.getDen() );
return resultado;
}
int main( void ) {
Fracao a( 1, 2 );
Fracao b( 2, 4 );
a.imprimir();
b.imprimir();
Fracao resultado = a * b;
resultado.imprimir();
return 0;
}
<commit_msg>Correção da multiplicação<commit_after>#include <iostream>
class Fracao {
private:
int num;
int den;
public:
void imprimir( void ) const {
std::cout << getNum() << "/" << getDen() << '\n';
}
void setNum( const int num ) {
this->num = num;
}
void setDen( const int den ) {
if( den != 0 ) {
this->den = den;
} else {
std::cout << "Erro denominador" << '\n';
this->den = 0;
}
}
int getNum( void ) const {
return num;
}
int getDen( void ) const {
return den;
}
Fracao( const int num, const int den ) {
setNum( num );
setDen( den );
imprimir();
}
~Fracao( void ) {
std::cout << "Destrutor: ";
imprimir();
std::cout << '\n';
}
Fracao operator*( const Fracao &b ) const {
Fracao resultado( this->getNum() * b.getNum(), this->getDen() * b.getDen() );
return resultado;
}
};
int main( void ) {
Fracao a( 1, 2 );
Fracao b( 2, 4 );
a.imprimir();
b.imprimir();
Fracao resultado = a * b;
resultado.imprimir();
return 0;
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
/// \file es/storage.hpp
/// \brief The entity/component data store
//
// Copyright 2013, [email protected] Released under the MIT License.
//---------------------------------------------------------------------------
#pragma once
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#include <unordered_map>
#include "component.hpp"
#include "entity.hpp"
#include "traits.hpp"
namespace es {
/** A storage ties entities and components together.
* Storage associates two other bits of data with every entity:
* - A 64-bit mask that keeps track of which components are defined
* - A vector of bytes, holding the actual data
*
* The vector of bytes tries to pack the component data as tightly as
* possible. It is really fast for plain old datatypes, but it also
* handles nontrivial types safely. It packs a virtual table and a
* pointer to some heap space in the vector, and calls the constructor
* and destructor as needed.
*/
class storage
{
// It is assumed the first few components will be accessed the
// most often. We keep a cache of the first 12.
static constexpr uint32_t cache_size = 12;
static constexpr uint32_t cache_mask = (1 << cache_size) - 1;
/** This data gets associated with every entity. */
struct elem
{
/** Bitmask to keep track of which components are held in \a data. */
std::bitset<64> components;
/** Component data for this entity. */
std::vector<char> data;
};
typedef component::placeholder placeholder;
/** Data types that do not have a flat memory layout are kept in the
** elem::data buffer in a placeholder object. */
template <typename t>
class holder : public placeholder
{
public:
holder () { }
holder (t init) : held_(std::move(init)) { }
const t& held() const { return held_; }
t& held() { return held_; }
placeholder* clone() const { return new holder<t>(held_); }
private:
t held_;
};
typedef std::unordered_map<uint32_t, elem> stor_impl;
public:
typedef uint8_t component_id;
typedef stor_impl::iterator iterator;
typedef stor_impl::const_iterator const_iterator;
public:
/** Variable references are used by systems to access an entity's data.
* It keeps track of the elem::data buffer and the offset inside that
* buffer. */
template <typename type>
class var_ref
{
friend class storage;
type& get()
{
if (is_flat<type>::value)
return *reinterpret_cast<type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
public:
operator const type& () const
{
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<const holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
var_ref& operator= (type assign)
{
if (is_flat<type>::value)
{
new (&*e_.data.begin() + offset_) type(std::move(assign));
}
else
{
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
new (ptr) holder<type>(std::move(assign));
}
return *this;
}
template <typename s>
var_ref& operator+= (s val)
{ get() += val; return *this; }
template <typename s>
var_ref& operator-= (s val)
{ get() -= val; return *this; }
template <typename s>
var_ref& operator*= (s val)
{ get() *= val; return *this; }
template <typename s>
var_ref& operator/= (s val)
{ get() /= val; return *this; }
protected:
var_ref (size_t offset, elem& e)
: offset_(offset), e_(e)
{ }
private:
size_t offset_;
elem& e_;
};
public:
storage()
: next_id_(0)
{
component_offsets_.push_back(0);
}
template <typename type>
component_id register_component (std::string name)
{
size_t size;
if (is_flat<type>::value)
{
size = sizeof(type);
components_.emplace_back(name, size, nullptr);
}
else
{
flat_mask_.set(components_.size());
size = sizeof(holder<type>);
components_.emplace_back(name, size,
std::unique_ptr<placeholder>(new holder<type>()));
}
if (components_.size() < cache_size)
{
size_t i (component_offsets_.size());
component_offsets_.resize(i * 2);
for (size_t j (i); j != i * 2; ++j)
component_offsets_[j] = component_offsets_[j-i] + size;
}
return components_.size() - 1;
}
component_id find_component (const std::string& name) const
{
auto found (std::find(components_.begin(), components_.end(), name));
if (found == components_.end())
throw std::logic_error("component does not exist");
return std::distance(components_.begin(), found);
}
const component& operator[] (component_id id) const
{ return components_[id]; }
const std::vector<component>& components() const
{ return components_; }
public:
entity new_entity()
{
entities_[next_id_++];
return next_id_ - 1;
}
/** Create a whole bunch of empty entities in one go.
* @param count The number of entities to create
* @return The range of entities created */
std::pair<entity, entity> new_entities (size_t count)
{
auto range_begin (next_id_);
for (; count > 0; --count)
entities_[next_id_++];
return std::make_pair(range_begin, next_id_);
}
entity clone_entity (iterator f)
{
elem& e (f->second);
entities_[next_id_++] = e;
// Quick check if we need to make deep copies
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
{
if (e.components[c_id])
{
if (!components_[c_id].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr = ptr->clone();
}
off += components_[c_id].size();
}
}
}
return next_id_ - 1;
}
iterator find (entity en)
{
auto found (entities_.find(en.id()));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
const_iterator find (entity en) const
{
auto found (entities_.find(en.id()));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
void delete_entity (entity en)
{ delete_entity(find(en)); }
void delete_entity (iterator f)
{
elem& e (f->second);
// Quick check if we'll have to call any destructors.
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int search (0); search < 64 && off < e.data.size(); ++search)
{
if (e.components[search])
{
if (!components_[search].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
off += components_[search].size();
}
}
}
entities_.erase(f);
}
void remove_component_from_entity (iterator en, component_id c)
{
auto& e (en->second);
if (!e.components[c])
return;
size_t off (offset(e, c));
auto& comp_info (components_[c]);
if (!comp_info.is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
auto o (e.data.begin() + off);
e.data.erase(o, o + comp_info.size());
e.components.reset(c);
}
/** Call a function for every entity that has a given component.
* The callee can then query and change the value of the component through
* a var_ref object, or remove the entity.
* @param c The component to look for.
* @param func The function to call. This function will be passed an
* iterator to the current entity, and a var_ref corresponding
* to the component value in this entity. */
template <typename t>
void for_each (component_id c, std::function<void(iterator, var_ref<t>)> func)
{
std::bitset<64> mask;
mask.set(c);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
func(i, var_ref<t>(offset(e, c), e));
i = next;
}
}
template <typename t1, typename t2>
void for_each (component_id c1, component_id c2,
std::function<void(iterator, var_ref<t1>, var_ref<t2>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
for (auto i (entities_.begin()); i != entities_.end(); ++i)
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e));
}
i = next;
}
}
template <typename t1, typename t2, typename t3>
void for_each (component_id c1, component_id c2, component_id c3,
std::function<void(iterator, var_ref<t1>, var_ref<t2>, var_ref<t3>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
mask.set(c3);
for (auto i (entities_.begin()); i != entities_.end(); ++i)
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e),
var_ref<t3>(offset(e, c3), e));
}
i = next;
}
}
bool exists (entity en) const
{ return entities_.count(en.id()); }
template <typename type>
void set (entity en, component_id c_id, type val)
{ return set<type>(find(en), c_id, std::move(val)); }
template <typename type>
void set (iterator en, component_id c_id, type val)
{
const component& c (components_[c_id]);
elem& e (en->second);
size_t off (offset(e, c_id));
if (!e.components[c_id])
{
if (e.data.size() < off)
e.data.resize(off + c.size());
else
e.data.insert(e.data.begin() + off, c.size(), 0);
e.components.set(c_id);
}
if (is_flat<type>::value)
{
assert(e.data.size() >= off + sizeof(type));
new (&*e.data.begin() + off) type(std::move(val));
}
else
{
assert(e.data.size() >= off + sizeof(holder<type>));
auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off));
new (ptr) holder<type>(std::move(val));
}
}
template <typename type>
const type& get (entity en, component_id c_id) const
{ return get<type>(find(en), c_id); }
template <typename type>
const type& get (const_iterator en, component_id c_id) const
{
auto& e (en->second);
if (!e.components[c_id])
throw std::logic_error("entity does not have component");
return get<type>(e, c_id);
}
private:
template <typename type>
const type& get (const elem& e, component_id c_id) const
{
size_t off (offset(e, c_id));
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e.data.begin() + off);
auto ptr (reinterpret_cast<const holder<type>*>(&*e.data.begin() + off));
return ptr->held();
}
size_t offset (const elem& e, component_id c) const
{
assert(c < components_.size());
assert((c & cache_mask) < component_offsets_.size());
size_t result (component_offsets_[c & cache_mask]);
for (component_id search (cache_size); search < c; ++search)
{
if (e.components[search])
result += components_[search].size();
}
return result;
}
private:
/** Keeps track of entity IDs to give out. */
uint32_t next_id_;
/** The list of registered components. */
std::vector<component> components_;
/** Mapping entity IDs to their data. */
std::unordered_map<uint32_t, elem> entities_;
/** A lookup table for the data offsets of components.
* The index is the bitmask as used in elem::components. */
std::vector<size_t> component_offsets_;
/** A bitmask to quickly determine whether a certain combination of
** components has a flat memory layout or not. */
std::bitset<64> flat_mask_;
};
} // namespace es
<commit_msg>Bugfix in for_each<commit_after>//---------------------------------------------------------------------------
/// \file es/storage.hpp
/// \brief The entity/component data store
//
// Copyright 2013, [email protected] Released under the MIT License.
//---------------------------------------------------------------------------
#pragma once
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#include <unordered_map>
#include "component.hpp"
#include "entity.hpp"
#include "traits.hpp"
namespace es {
/** A storage ties entities and components together.
* Storage associates two other bits of data with every entity:
* - A 64-bit mask that keeps track of which components are defined
* - A vector of bytes, holding the actual data
*
* The vector of bytes tries to pack the component data as tightly as
* possible. It is really fast for plain old datatypes, but it also
* handles nontrivial types safely. It packs a virtual table and a
* pointer to some heap space in the vector, and calls the constructor
* and destructor as needed.
*/
class storage
{
// It is assumed the first few components will be accessed the
// most often. We keep a cache of the first 12.
static constexpr uint32_t cache_size = 12;
static constexpr uint32_t cache_mask = (1 << cache_size) - 1;
/** This data gets associated with every entity. */
struct elem
{
/** Bitmask to keep track of which components are held in \a data. */
std::bitset<64> components;
/** Component data for this entity. */
std::vector<char> data;
};
typedef component::placeholder placeholder;
/** Data types that do not have a flat memory layout are kept in the
** elem::data buffer in a placeholder object. */
template <typename t>
class holder : public placeholder
{
public:
holder () { }
holder (t init) : held_(std::move(init)) { }
const t& held() const { return held_; }
t& held() { return held_; }
placeholder* clone() const { return new holder<t>(held_); }
private:
t held_;
};
typedef std::unordered_map<uint32_t, elem> stor_impl;
public:
typedef uint8_t component_id;
typedef stor_impl::iterator iterator;
typedef stor_impl::const_iterator const_iterator;
public:
/** Variable references are used by systems to access an entity's data.
* It keeps track of the elem::data buffer and the offset inside that
* buffer. */
template <typename type>
class var_ref
{
friend class storage;
type& get()
{
if (is_flat<type>::value)
return *reinterpret_cast<type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
public:
operator const type& () const
{
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<const holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
var_ref& operator= (type assign)
{
if (is_flat<type>::value)
{
new (&*e_.data.begin() + offset_) type(std::move(assign));
}
else
{
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
new (ptr) holder<type>(std::move(assign));
}
return *this;
}
template <typename s>
var_ref& operator+= (s val)
{ get() += val; return *this; }
template <typename s>
var_ref& operator-= (s val)
{ get() -= val; return *this; }
template <typename s>
var_ref& operator*= (s val)
{ get() *= val; return *this; }
template <typename s>
var_ref& operator/= (s val)
{ get() /= val; return *this; }
protected:
var_ref (size_t offset, elem& e)
: offset_(offset), e_(e)
{ }
private:
size_t offset_;
elem& e_;
};
public:
storage()
: next_id_(0)
{
component_offsets_.push_back(0);
}
template <typename type>
component_id register_component (std::string name)
{
size_t size;
if (is_flat<type>::value)
{
size = sizeof(type);
components_.emplace_back(name, size, nullptr);
}
else
{
flat_mask_.set(components_.size());
size = sizeof(holder<type>);
components_.emplace_back(name, size,
std::unique_ptr<placeholder>(new holder<type>()));
}
if (components_.size() < cache_size)
{
size_t i (component_offsets_.size());
component_offsets_.resize(i * 2);
for (size_t j (i); j != i * 2; ++j)
component_offsets_[j] = component_offsets_[j-i] + size;
}
return components_.size() - 1;
}
component_id find_component (const std::string& name) const
{
auto found (std::find(components_.begin(), components_.end(), name));
if (found == components_.end())
throw std::logic_error("component does not exist");
return std::distance(components_.begin(), found);
}
const component& operator[] (component_id id) const
{ return components_[id]; }
const std::vector<component>& components() const
{ return components_; }
public:
entity new_entity()
{
entities_[next_id_++];
return next_id_ - 1;
}
/** Create a whole bunch of empty entities in one go.
* @param count The number of entities to create
* @return The range of entities created */
std::pair<entity, entity> new_entities (size_t count)
{
auto range_begin (next_id_);
for (; count > 0; --count)
entities_[next_id_++];
return std::make_pair(range_begin, next_id_);
}
entity clone_entity (iterator f)
{
elem& e (f->second);
entities_[next_id_++] = e;
// Quick check if we need to make deep copies
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
{
if (e.components[c_id])
{
if (!components_[c_id].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr = ptr->clone();
}
off += components_[c_id].size();
}
}
}
return next_id_ - 1;
}
iterator find (entity en)
{
auto found (entities_.find(en.id()));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
const_iterator find (entity en) const
{
auto found (entities_.find(en.id()));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
void delete_entity (entity en)
{ delete_entity(find(en)); }
void delete_entity (iterator f)
{
elem& e (f->second);
// Quick check if we'll have to call any destructors.
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int search (0); search < 64 && off < e.data.size(); ++search)
{
if (e.components[search])
{
if (!components_[search].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
off += components_[search].size();
}
}
}
entities_.erase(f);
}
void remove_component_from_entity (iterator en, component_id c)
{
auto& e (en->second);
if (!e.components[c])
return;
size_t off (offset(e, c));
auto& comp_info (components_[c]);
if (!comp_info.is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
auto o (e.data.begin() + off);
e.data.erase(o, o + comp_info.size());
e.components.reset(c);
}
/** Call a function for every entity that has a given component.
* The callee can then query and change the value of the component through
* a var_ref object, or remove the entity.
* @param c The component to look for.
* @param func The function to call. This function will be passed an
* iterator to the current entity, and a var_ref corresponding
* to the component value in this entity. */
template <typename t>
void for_each (component_id c, std::function<void(iterator, var_ref<t>)> func)
{
std::bitset<64> mask;
mask.set(c);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
func(i, var_ref<t>(offset(e, c), e));
i = next;
}
}
template <typename t1, typename t2>
void for_each (component_id c1, component_id c2,
std::function<void(iterator, var_ref<t1>, var_ref<t2>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e));
}
i = next;
}
}
template <typename t1, typename t2, typename t3>
void for_each (component_id c1, component_id c2, component_id c3,
std::function<void(iterator, var_ref<t1>, var_ref<t2>, var_ref<t3>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
mask.set(c3);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e),
var_ref<t3>(offset(e, c3), e));
}
i = next;
}
}
bool exists (entity en) const
{ return entities_.count(en.id()); }
template <typename type>
void set (entity en, component_id c_id, type val)
{ return set<type>(find(en), c_id, std::move(val)); }
template <typename type>
void set (iterator en, component_id c_id, type val)
{
const component& c (components_[c_id]);
elem& e (en->second);
size_t off (offset(e, c_id));
if (!e.components[c_id])
{
if (e.data.size() < off)
e.data.resize(off + c.size());
else
e.data.insert(e.data.begin() + off, c.size(), 0);
e.components.set(c_id);
}
if (is_flat<type>::value)
{
assert(e.data.size() >= off + sizeof(type));
new (&*e.data.begin() + off) type(std::move(val));
}
else
{
assert(e.data.size() >= off + sizeof(holder<type>));
auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off));
new (ptr) holder<type>(std::move(val));
}
}
template <typename type>
const type& get (entity en, component_id c_id) const
{ return get<type>(find(en), c_id); }
template <typename type>
const type& get (const_iterator en, component_id c_id) const
{
auto& e (en->second);
if (!e.components[c_id])
throw std::logic_error("entity does not have component");
return get<type>(e, c_id);
}
private:
template <typename type>
const type& get (const elem& e, component_id c_id) const
{
size_t off (offset(e, c_id));
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e.data.begin() + off);
auto ptr (reinterpret_cast<const holder<type>*>(&*e.data.begin() + off));
return ptr->held();
}
size_t offset (const elem& e, component_id c) const
{
assert(c < components_.size());
assert((c & cache_mask) < component_offsets_.size());
size_t result (component_offsets_[c & cache_mask]);
for (component_id search (cache_size); search < c; ++search)
{
if (e.components[search])
result += components_[search].size();
}
return result;
}
private:
/** Keeps track of entity IDs to give out. */
uint32_t next_id_;
/** The list of registered components. */
std::vector<component> components_;
/** Mapping entity IDs to their data. */
std::unordered_map<uint32_t, elem> entities_;
/** A lookup table for the data offsets of components.
* The index is the bitmask as used in elem::components. */
std::vector<size_t> component_offsets_;
/** A bitmask to quickly determine whether a certain combination of
** components has a flat memory layout or not. */
std::bitset<64> flat_mask_;
};
} // namespace es
<|endoftext|> |
<commit_before>#include "errors.h"
#include <sstream>
#include <string.h>
using namespace es3;
extern ES3LIB_PUBLIC const die_t es3::die=die_t();
extern ES3LIB_PUBLIC const libc_die_t es3::libc_die=libc_die_t();
extern ES3LIB_PUBLIC const result_code_t es3::sok=result_code_t();
es3_exception::es3_exception(const result_code_t &code) : code_(code)
{
std::stringstream s;
s<<("Error code: ")<<code.code()<<", description: "<<code.desc();
what_=s.str();
}
int es3::operator | (const int res, const libc_die_t &)
{
if (res>=0)
return res;
char buf[1024]={0};
strerror_r(errno, buf, 1023);
err(errFatal) << "Got error: " << buf;
//Unreachable
}
<commit_msg>Backtrace hack<commit_after>#include "errors.h"
#include <sstream>
#include <string.h>
using namespace es3;
extern ES3LIB_PUBLIC const die_t es3::die=die_t();
extern ES3LIB_PUBLIC const libc_die_t es3::libc_die=libc_die_t();
extern ES3LIB_PUBLIC const result_code_t es3::sok=result_code_t();
es3_exception::es3_exception(const result_code_t &code) : code_(code)
{
std::stringstream s;
backtrace_it();
s<<("Error code: ")<<code.code()<<", description: "<<code.desc();
what_=s.str();
}
int es3::operator | (const int res, const libc_die_t &)
{
if (res>=0)
return res;
char buf[1024]={0};
strerror_r(errno, buf, 1023);
err(errFatal) << "Got error: " << buf;
//Unreachable
}
<|endoftext|> |
<commit_before>#pragma once
#include <agency/detail/config.hpp>
#include <agency/cuda/detail/allocator.hpp>
#include <agency/detail/index_cast.hpp>
#include <agency/detail/shape_cast.hpp>
#include <thrust/detail/swap.h>
namespace agency
{
namespace cuda
{
namespace detail
{
template<class T, class Shape = size_t, class Index = Shape>
class array
{
public:
using value_type = T;
using pointer = value_type*;
using const_pointer = const value_type*;
using shape_type = Shape;
using index_type = Index;
__host__ __device__
array() : shape_{}, data_(nullptr) {}
__host__ __device__
array(const shape_type& shape)
: shape_(shape)
{
allocator<value_type> alloc;
data_ = alloc.allocate(size());
}
__host__ __device__
array(const array& other)
: array(other.shape())
{
auto iter = other.begin();
auto result = begin();
for(; iter != other.end(); ++iter, ++result)
{
*result = *iter;
}
}
__host__ __device__
array(array&& other)
: shape_{}, data_{}
{
thrust::swap(shape_, other.shape_);
thrust::swap(data_, other.data_);
}
__host__ __device__
~array()
{
allocator<value_type> alloc;
alloc.deallocate(data_, size());
}
__host__ __device__
value_type& operator[](index_type idx)
{
std::size_t idx_1d = agency::detail::index_cast<std::size_t>(idx, shape(), size());
return data_[idx_1d];
}
__host__ __device__
shape_type shape() const
{
return shape_;
}
__host__ __device__
std::size_t size() const
{
return agency::detail::shape_cast<std::size_t>(shape_);
}
__host__ __device__
pointer data()
{
return data_;
}
__host__ __device__
const_pointer data() const
{
return data_;
}
__host__ __device__
pointer begin()
{
return data();
}
__host__ __device__
pointer end()
{
return begin() + size();
}
__host__ __device__
const_pointer begin() const
{
return data();
}
__host__ __device__
const_pointer end() const
{
return begin() + size();
}
__agency_hd_warning_disable__
template<class Range>
__host__ __device__
bool operator==(const Range& rhs) const
{
auto i = begin();
auto j = rhs.begin();
for(; i != end(); ++i, ++j)
{
if(*i != *j)
{
return false;
}
}
return true;
}
private:
shape_type shape_;
pointer data_;
};
} // end detail
} // end cuda
} // end agency
<commit_msg>Give cuda::detail::array a fill constructor<commit_after>#pragma once
#include <agency/detail/config.hpp>
#include <agency/cuda/detail/allocator.hpp>
#include <agency/detail/index_cast.hpp>
#include <agency/detail/shape_cast.hpp>
#include <thrust/detail/swap.h>
namespace agency
{
namespace cuda
{
namespace detail
{
template<class T, class Shape = size_t, class Index = Shape>
class array
{
public:
using value_type = T;
using pointer = value_type*;
using const_pointer = const value_type*;
using shape_type = Shape;
using index_type = Index;
__host__ __device__
array() : shape_{}, data_(nullptr) {}
__host__ __device__
array(const shape_type& shape)
: shape_(shape)
{
allocator<value_type> alloc;
data_ = alloc.allocate(size());
}
__host__ __device__
array(const shape_type& shape, const T& val)
: array(shape)
{
for(auto& x : *this)
{
x = val;
}
}
__host__ __device__
array(const array& other)
: array(other.shape())
{
auto iter = other.begin();
auto result = begin();
for(; iter != other.end(); ++iter, ++result)
{
*result = *iter;
}
}
__host__ __device__
array(array&& other)
: shape_{}, data_{}
{
thrust::swap(shape_, other.shape_);
thrust::swap(data_, other.data_);
}
__host__ __device__
~array()
{
allocator<value_type> alloc;
alloc.deallocate(data_, size());
}
__host__ __device__
value_type& operator[](index_type idx)
{
std::size_t idx_1d = agency::detail::index_cast<std::size_t>(idx, shape(), size());
return data_[idx_1d];
}
__host__ __device__
shape_type shape() const
{
return shape_;
}
__host__ __device__
std::size_t size() const
{
return agency::detail::shape_cast<std::size_t>(shape_);
}
__host__ __device__
pointer data()
{
return data_;
}
__host__ __device__
const_pointer data() const
{
return data_;
}
__host__ __device__
pointer begin()
{
return data();
}
__host__ __device__
pointer end()
{
return begin() + size();
}
__host__ __device__
const_pointer begin() const
{
return data();
}
__host__ __device__
const_pointer end() const
{
return begin() + size();
}
__agency_hd_warning_disable__
template<class Range>
__host__ __device__
bool operator==(const Range& rhs) const
{
auto i = begin();
auto j = rhs.begin();
for(; i != end(); ++i, ++j)
{
if(*i != *j)
{
return false;
}
}
return true;
}
private:
shape_type shape_;
pointer data_;
};
} // end detail
} // end cuda
} // end agency
<|endoftext|> |
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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.
#pragma once
struct Options {
// Debug mode
bool debug;
// Print messages to standard output
bool print;
// Use subband dedispersion
bool subbandDedispersion;
// Compact the triggered events in time and DM dimensions
bool compactResults;
// Threshold for triggering
float threshold;
};
struct DeviceOptions {
// OpenCL platform ID
unsigned int platformID;
// OpenCL device ID
unsigned int deviceID;
// OpenCL device name
std::string deviceName;
// Padding of OpenCL devices
AstroData::paddingConf padding;
};
struct DataOptions {
// Use LOFAR file as input
bool dataLOFAR;
// Use SIGPROC file as input
bool dataSIGPROC;
// Use PSRDADA buffer as input
bool dataPSRDADA;
// Limit the number of batches processed from a LOFAR file
bool limit;
// Size (in bytes) of the SIGPROC file header
unsigned int headerSizeSIGPROC;
// Name of the input file
std::string dataFile;
// Name of the LOFAR header file
std::string headerFile;
// Basename for the output files
std::string outputFile;
// Name of the file containing the zapped channels
std::string channelsFile;
// Name of the file containing the integration steps
std::string integrationFile;
#ifdef HAVE_PSRDADA
// PSRDADA buffer key
key_t dadaKey;
#endif // HAVE_PSRDADA
};
struct GeneratorOptions {
// Use random numbers in generated data
bool random;
// Width of random generated pulse
unsigned int width;
// DM of random generated pulse
float DM;
};
struct HostMemory {
// Input data
std::vector<std::vector<std::vector<inputDataType> *> *> input;
// Zapped channels
std::vector<unsigned int> zappedChannels;
// Integration steps
std::set<unsigned int> integrationSteps;
// Map to create synthesized beams
std::vector<unsigned int> beamMapping;
// Dispersed data
std::vector<inputDataType> dispersedData;
// Subbanded data
std::vector<outputDataType> subbandedData;
// Dedispersed data
std::vector<outputDataType> dedispersedData;
// Integrated data
std::vector<outputDataType> integratedData;
// SNR data
std::vector<float> snrData;
// Index of the sample with highest SNR value
std::vector<unsigned int> snrSamples;
// Shifts single step dedispersion
std::vector<float> * shiftsSingleStep;
// Shifts step one subbanding dedispersion
std::vector<float> * shiftsStepOne;
// Shifts step two subbanding dedispersion
std::vector<float> * shiftsStepTwo;
#ifdef HAVE_PSRDADA
// PSRDADA ring buffer
dada_hdu_t * ringBuffer;
// Input data
std::vector<std::vector<inputDataType> *> inputDADA;
#endif // HAVE_PSRDADA
};
struct DeviceMemory {
// Shifts single step dedispersion
cl::Buffer shiftsSingleStep;
// Shifts step one subbanding dedispersion
cl::Buffer shiftsStepOne;
// Shifts step two subbanding dedispersion
cl::Buffer shiftsStepTwo;
// Zapped channels
cl::Buffer zappedChannels;
// Map to create synthesized beams
cl::Buffer beamMapping;
// Dispersed dada
cl::Buffer dispersedData;
// Subbanded data
cl::Buffer subbandedData;
// Dedispersed data
cl::Buffer dedispersedData;
// Integrated data
cl::Buffer integratedData;
// SNR data
cl::Buffer snrData;
// Index of the sample with highest SNR value
cl::Buffer snrSamples;
};
struct KernelConfigurations {
// Configuration of single step dedispersion kernel
Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters;
// Configuration of subband dedispersion kernel, step one
Dedispersion::tunedDedispersionConf dedispersionStepOneParameters;
// Configuration of subband dedispersion kernel, step two
Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters;
// Configuration of integration kernel
Integration::tunedIntegrationConf integrationParameters;
// Configuration of SNR kernel
SNR::tunedSNRConf snrParameters;
};
struct Kernels {
// Single step dedispersion kernel
cl::Kernel * dedispersionSingleStep;
// Step one subbanding dedispersion kernel
cl::Kernel * dedispersionStepOne;
// Step two subbanding dedispersion kernel
cl::Kernel * dedispersionStepTwo;
// Integration kernels, one for each integration step
std::vector<cl::Kernel *> integration;
// SNR kernels, one for the original data and one for each integration step
std::vector<cl::Kernel *> snr;
};
struct KernelRunTimeConfigurations {
// Global NDrange for single step dedispersion
cl::NDRange dedispersionSingleStepGlobal;
// Local NDRange for single step dedispersion
cl::NDRange dedispersionSingleStepLocal;
// Global NDRange for subbanding dedispersion step one
cl::NDRange dedispersionStepOneGlobal;
// Local NDRange for subbanding dedispersion step one
cl::NDRange dedispersionStepOneLocal;
// Global NDRange for subbanding dedispersion step two
cl::NDRange dedispersionStepTwoGlobal;
// Local NDRange for subbanding dedispersion step two
cl::NDRange dedispersionStepTwoLocal;
// Global NDRange for integration
std::vector<cl::NDRange> integrationGlobal;
// Local NDRange for integration
std::vector<cl::NDRange> integrationLocal;
// Global NDRange for SNR
std::vector<cl::NDRange> snrGlobal;
// Local NDRange for SNR
std::vector<cl::NDRange> snrLocal;
};
struct Timers {
isa::utils::Timer inputLoad;
isa::utils::Timer search;
isa::utils::Timer inputHandling;
isa::utils::Timer inputCopy;
isa::utils::Timer dedispersionSingleStep;
isa::utils::Timer dedispersionStepOne;
isa::utils::Timer dedispersionStepTwo;
isa::utils::Timer integration;
isa::utils::Timer snr;
isa::utils::Timer outputCopy;
isa::utils::Timer trigger;
};
struct TriggeredEvent {
unsigned int beam = 0;
unsigned int sample = 0;
unsigned int integration = 0;
float DM = 0.0f;
float SNR = 0.0f;
};
struct CompactedEvent : TriggeredEvent {
unsigned int compactedIntegration = 1;
unsigned int compactedDMs = 1;
};
using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>;
using CompactedEvents = std::vector<std::vector<CompactedEvent>>;
struct OpenCLRunTime {
cl::Context * clContext;
std::vector<cl::Platform> * clPlatforms;
std::vector<cl::Device> * clDevices;
std::vector<std::vector<cl::CommandQueue>> * clQueues;
};
<commit_msg>Changing the names.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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.
#pragma once
struct Options {
// Debug mode
bool debug;
// Print messages to standard output
bool print;
// Use subband dedispersion
bool subbandDedispersion;
// Compact the triggered events in time and DM dimensions
bool compactResults;
// Threshold for triggering
float threshold;
};
struct DeviceOptions {
// OpenCL platform ID
unsigned int platformID;
// OpenCL device ID
unsigned int deviceID;
// OpenCL device name
std::string deviceName;
// Padding of OpenCL devices
AstroData::paddingConf padding;
};
struct DataOptions {
// Use LOFAR file as input
bool dataLOFAR;
// Use SIGPROC file as input
bool dataSIGPROC;
// Use PSRDADA buffer as input
bool dataPSRDADA;
// Limit the number of batches processed from a LOFAR file
bool limit;
// Size (in bytes) of the SIGPROC file header
unsigned int headerSizeSIGPROC;
// Name of the input file
std::string dataFile;
// Name of the LOFAR header file
std::string headerFile;
// Basename for the output files
std::string outputFile;
// Name of the file containing the zapped channels
std::string channelsFile;
// Name of the file containing the integration steps
std::string integrationFile;
#ifdef HAVE_PSRDADA
// PSRDADA buffer key
key_t dadaKey;
#endif // HAVE_PSRDADA
};
struct GeneratorOptions {
// Use random numbers in generated data
bool random;
// Width of random generated pulse
unsigned int width;
// DM of random generated pulse
float DM;
};
struct HostMemory {
// Input data
std::vector<std::vector<std::vector<inputDataType> *> *> input;
// Zapped channels
std::vector<unsigned int> zappedChannels;
// Integration steps
std::set<unsigned int> integrationSteps;
// Map to create synthesized beams
std::vector<unsigned int> beamMapping;
// Dispersed data
std::vector<inputDataType> dispersedData;
// Subbanded data
std::vector<outputDataType> subbandedData;
// Dedispersed data
std::vector<outputDataType> dedispersedData;
// Integrated data
std::vector<outputDataType> integratedData;
// SNR data
std::vector<float> snrData;
// Index of the sample with highest SNR value
std::vector<unsigned int> snrSamples;
// Shifts single step dedispersion
std::vector<float> * shiftsSingleStep;
// Shifts step one subbanding dedispersion
std::vector<float> * shiftsStepOne;
// Shifts step two subbanding dedispersion
std::vector<float> * shiftsStepTwo;
#ifdef HAVE_PSRDADA
// PSRDADA ring buffer
dada_hdu_t * ringBuffer;
// Input data
std::vector<std::vector<inputDataType> *> inputDADA;
#endif // HAVE_PSRDADA
};
struct DeviceMemory {
// Shifts single step dedispersion
cl::Buffer shiftsSingleStep;
// Shifts step one subbanding dedispersion
cl::Buffer shiftsStepOne;
// Shifts step two subbanding dedispersion
cl::Buffer shiftsStepTwo;
// Zapped channels
cl::Buffer zappedChannels;
// Map to create synthesized beams
cl::Buffer beamMapping;
// Dispersed dada
cl::Buffer dispersedData;
// Subbanded data
cl::Buffer subbandedData;
// Dedispersed data
cl::Buffer dedispersedData;
// Integrated data
cl::Buffer integratedData;
// SNR data
cl::Buffer snrData;
// Index of the sample with highest SNR value
cl::Buffer snrSamples;
};
struct KernelConfigurations {
// Configuration of single step dedispersion kernel
Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters;
// Configuration of subband dedispersion kernel, step one
Dedispersion::tunedDedispersionConf dedispersionStepOneParameters;
// Configuration of subband dedispersion kernel, step two
Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters;
// Configuration of integration kernel
Integration::tunedIntegrationConf integrationParameters;
// Configuration of SNR kernel
SNR::tunedSNRConf snrParameters;
};
struct Kernels {
// Single step dedispersion kernel
cl::Kernel * dedispersionSingleStep;
// Step one subbanding dedispersion kernel
cl::Kernel * dedispersionStepOne;
// Step two subbanding dedispersion kernel
cl::Kernel * dedispersionStepTwo;
// Integration kernels, one for each integration step
std::vector<cl::Kernel *> integration;
// SNR kernels, one for the original data and one for each integration step
std::vector<cl::Kernel *> snr;
};
struct KernelRunTimeConfigurations {
// Global NDrange for single step dedispersion
cl::NDRange dedispersionSingleStepGlobal;
// Local NDRange for single step dedispersion
cl::NDRange dedispersionSingleStepLocal;
// Global NDRange for subbanding dedispersion step one
cl::NDRange dedispersionStepOneGlobal;
// Local NDRange for subbanding dedispersion step one
cl::NDRange dedispersionStepOneLocal;
// Global NDRange for subbanding dedispersion step two
cl::NDRange dedispersionStepTwoGlobal;
// Local NDRange for subbanding dedispersion step two
cl::NDRange dedispersionStepTwoLocal;
// Global NDRange for integration
std::vector<cl::NDRange> integrationGlobal;
// Local NDRange for integration
std::vector<cl::NDRange> integrationLocal;
// Global NDRange for SNR
std::vector<cl::NDRange> snrGlobal;
// Local NDRange for SNR
std::vector<cl::NDRange> snrLocal;
};
struct Timers {
isa::utils::Timer inputLoad;
isa::utils::Timer search;
isa::utils::Timer inputHandling;
isa::utils::Timer inputCopy;
isa::utils::Timer dedispersionSingleStep;
isa::utils::Timer dedispersionStepOne;
isa::utils::Timer dedispersionStepTwo;
isa::utils::Timer integration;
isa::utils::Timer snr;
isa::utils::Timer outputCopy;
isa::utils::Timer trigger;
};
struct TriggeredEvent {
unsigned int beam = 0;
unsigned int sample = 0;
unsigned int integration = 0;
float DM = 0.0f;
float SNR = 0.0f;
};
struct CompactedEvent : TriggeredEvent {
unsigned int compactedIntegration = 1;
unsigned int compactedDMs = 1;
};
using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>;
using CompactedEvents = std::vector<std::vector<CompactedEvent>>;
struct OpenCLRunTime {
cl::Context * context;
std::vector<cl::Platform> * platforms;
std::vector<cl::Device> * devices;
std::vector<std::vector<cl::CommandQueue>> * queues;
};
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef VARIABLES_H
#define VARIABLES_H
#include <string>
#include <map>
#include "Types.hpp"
#include "ByteCodeFileWriter.hpp"
namespace eddic {
class Variable {
private:
std::string m_name;
Type m_type;
int m_index;
public:
Variable(const std::string& name, Type type, int index) : m_name(name), m_type(type), m_index(index) {}
std::string name() {
return m_name;
}
int index() {
return m_index;
}
Type type() {
return m_type;
}
};
class Variables {
private:
std::map<std::string, Variable*> variables;
unsigned int currentVariable;
public:
Variables() {
currentVariable = 0;
};
~Variables();
bool exists(const std::string& variable) const;
unsigned int index(const std::string& variable) const;
Variable* create(const std::string& variable, Type type);
Variable* find(const std::string& variable);
void write(ByteCodeFileWriter& writer);
};
} //end of eddic
#endif
<commit_msg>Enforce constness of Variable members and functions<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef VARIABLES_H
#define VARIABLES_H
#include <string>
#include <map>
#include "Types.hpp"
#include "ByteCodeFileWriter.hpp"
namespace eddic {
class Variable {
private:
const std::string m_name;
const Type m_type;
const int m_index;
public:
Variable(const std::string& name, Type type, int index) : m_name(name), m_type(type), m_index(index) {}
std::string name() const {
return m_name;
}
int index() const {
return m_index;
}
Type type() const {
return m_type;
}
};
class Variables {
private:
std::map<std::string, Variable*> variables;
unsigned int currentVariable;
public:
Variables() {
currentVariable = 0;
};
~Variables();
bool exists(const std::string& variable) const;
unsigned int index(const std::string& variable) const;
Variable* create(const std::string& variable, Type type);
Variable* find(const std::string& variable);
void write(ByteCodeFileWriter& writer);
};
} //end of eddic
#endif
<|endoftext|> |
<commit_before>#ifndef WLWalker_HPP_
#define WLWalker_HPP_
#include "WL_Window.hpp"
#include "MC_Walker.hpp"
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
struct WL_State
{
int ibin;
double Sval;
void copy(const WL_State& orig) { ibin=orig.ibin; Sval=orig.Sval; }
void operator=(const WL_State& orig) { copy(orig); }
};
// Expands an MCWalker to include Wang-Landau information
template<typename Config, typename Observables>
class WL_Walker : public MC_Walker<Config,Observables>
{
public:
typedef MC_Walker<Config,Observables> BASE;
double wlgamma; // Wang-Landau gamma = ln(f)
WL_State wl_now,wl_old; // Wang-Landau information
WL_Window window; // Wang-Landau Window provides limits and binning
std::vector<double> S; // Entropy = log-density-of-states
std::vector<double> Sfixed; // Changes only very slowly
std::vector<double> h; // Visit histogram
// The sampling window might be smaller than the energy window
double WEmin,WEmax;
// Combined WL-Transition Matrix: RG Ghulghazaryan, S. Hayryan, CK Hu, J Comp Chem 28, 715-726 (2007)
// wleta comes from Eq. (24) S_WL[I] <- (1-wleta)*S_WL[I] + wleta*S_TM[I]
std::vector<double> Sittm; // A local version of the Infinite-temperature transition matrix result
std::vector<double> Vittm; // A local version of the Vittm error matrix
double EStepSum; // Statistics of how big a MC step is
long long EStepCnt;
public:
// Clear the visit histogram
void clear_histogram()
{
if( h.size()!=window.NBin ) h.resize(window.NBin);
fill(h.begin(),h.end(),0);
}
// Clear the estimated entropy
void clear_entropy()
{
S.resize(window.NBin);
fill(S.begin(),S.end(),0);
Sfixed.resize(window.NBin);
fill(Sfixed.begin(),Sfixed.end(),0);
}
// Set values of member array. Window must already be set
void set_values(const std::vector<double>& E, const std::vector<double>& y, std::vector<double>& seq)
{
const int nread = E.size();
if( E.size()<2 )
{
std::cout << __FILE__ << ":" << __LINE__ << " Energy array is length " << nread << std::endl;
int nbin = window.NBin;
seq.resize(nbin);
for(int i=0; i<nbin; i++) seq[i] = 0;
return;
}
if( y.size()<nread ) std::cout << __FILE__ << ":" << __LINE__ << " array y is too small" << std::endl;
int iread = 0;
int nbin = window.NBin;
seq.resize(nbin);
for(int ibin=0; ibin<nbin; ibin++)
{
double Eset = window.unbin(ibin);
while( iread<nread && E[iread]<Eset ) iread++;
if(iread>=nread) iread = nread-1;
if(iread<1) iread = 1;
double E0 = E[iread];
double y0 = y[iread];
double E1 = E[iread-1];
double y1 = y[iread-1];
double slope = (y1-y0)/(E1-E0);
seq[ibin] = y0 + slope*(Eset-E0);
}
}
void set_fixed(const std::vector<double>& E, const std::vector<double>& y)
{
this->set_values(E,y,this->Sfixed);
}
// Deep copy of the walker
void copy(const WL_Walker<Config,Observables>& orig)
{
this->BASE::copy(orig);
wlgamma = orig.wlgamma;
wl_now = orig.wl_now;
wl_old = orig.wl_old;
window = orig.window;
S = orig.S;
Sfixed = orig.Sfixed;
Sittm = orig.Sittm;
Vittm = orig.Vittm;
h = orig.h;
EStepSum = orig.EStepSum;
EStepCnt = orig.EStepCnt;
}
WL_Walker()
{
}
WL_Walker(const WL_Walker& orig)
{
this->copy(orig);
}
// Use this to find the current bin of the walker
int bin() { return wl_now.ibin = window.bin(BASE::now.E); }
// Estimate Entropy/lndos using linear interpolation
double get_lndos(double E, bool LinearInterp=true)
{
int ibin = window.bin(E);
double E0 = window.unbin(ibin);
double S0 = S[ibin] + Sfixed[ibin];
if( !LinearInterp ) return S0;
double S1,E1;
if( E<E0 )
{
// look left
if( ibin==0 )
{
// Interpolate to edge half a bin away. Force WL portion to zero
E1 = window.Elo;
S1 = S[ibin]+Sfixed[ibin] - 0.5*( Sfixed[ibin+1]-Sfixed[ibin] );
}
else
{
E1 = window.unbin(ibin-1);
S1 = S[ibin-1] + Sfixed[ibin-1];
}
}
else
{
// look right
if( ibin==(window.NBin-1) )
{
E1 = window.Ehi;
S1 = S[ibin]+Sfixed[ibin] + 0.5*( Sfixed[ibin]-Sfixed[ibin-1] );
}
else
{
E1 = window.unbin(ibin+1);
S1 = S[ibin+1] + Sfixed[ibin+1];
}
}
double slope = (S1-S0)/(E1-E0);
double SE = S0 + slope*(E-E0);
return SE;
}
float flatness() const
{
// Find the prefactor that normalizes histogram such that
// h_ibin = 1 for perfectly flat histogram (divide by mean h_ibin)
long long htot = 0;
int hbin = 0;
for(int i=0; i<this->window.NBin; i++)
{
if(h[i]>0)
{
htot += h[i];
hbin++;
}
}
double hnorm = static_cast<double>(hbin)/static_cast<double>(htot);
// Calculate the flatness for the frozen entropy
// Q = (1/nbin) \sum_ibin (h_ibin-1)^2
double Q = 0;
for(int i=0; i<window.NBin; i++)
{
if( h[i]>0 )
{
double Qi=(hnorm*h[i]-1);
Q+=Qi*Qi;
}
}
if( hbin<10 ) Q=1.e+6; // Not flat if trapped
return Q;
}
/*
bool move_walls(double qflat=0.1)
{
//if( move_walls_pileup() ) return true;
// Calculate the flatness from high energy down
int ilft = window.bin(WEmin);
int irgt = window.bin(WEmax);
const int mincts = 500; // Minimum vists before move wall past a bin
int jmax = irgt;
long long htot = 0;
int hbin = 0;
int jbin=jmax;
for(int kbin=jmax; kbin>0 && kbin>(jmax-5); kbin--)
if( h[kbin]>1000000 ) jbin=kbin;
bool flat = true;
while( jbin>=0 && (flat || h[jbin]>1000000) )
{
if( h[jbin]>mincts )
{
htot += h[jbin];
hbin++;
double hnorm = static_cast<double>(hbin)/static_cast<double>(htot);
double Q = 0;
for(int i=jbin; i<=jmax; i++)
{
double Q1 = hnorm*h[i]-1;
Q += Q1*Q1;
}
if(hbin>1) Q /= static_cast<double>(hbin);
flat = (Q<=qflat);
jbin--;
}
else
{
flat = false;
}
}
jmax = jbin;
// Cacluate the flatness from low energy up
int jmin = ilft;
htot = 0;
hbin = 0;
jbin = jmin;
if( jbin<(window.NBin-1) && h[jbin+1]>1000000 ) jbin++;
flat = true;
while( jbin<window.NBin && (flat || h[jbin]>1000000) )
{
if( h[jbin]>mincts )
{
htot += h[jbin];
hbin++;
double hnorm = static_cast<double>(hbin)/static_cast<double>(htot);
double Q = 0;
for(int i=jmin; i<=jbin; i++)
{
double Q1 = hnorm*h[i]-1;
Q += Q1*Q1;
}
if(hbin>1) Q /= static_cast<double>(hbin);
flat = (Q<=qflat);
jbin++;
}
else
{
flat = false;
}
}
const int overlap = 5;
jmin = jbin;
flat = (jmin>jmax);
jmax += overlap;
if(jmax<irgt) irgt=jmax;
jmin -= overlap;
if(jmin>ilft) ilft=jmin;
WEmin = window.unbin(ilft);
WEmax = window.unbin(irgt);
return flat;
}
*/
public:
void save_initial()
{
BASE::save_initial();
wl_old = wl_now;
}
void restore_initial()
{
wl_now = wl_old;
BASE::restore_initial();
}
};
// Return integer index of wlgamma assuming wlgamma_i+1 = wlgamma_i/2
int igamma(double wlgamma)
{
int p2 = static_cast<int>(-std::log(wlgamma)/std::log(2.)+0.01);
return p2;
}
#endif // WLWalker_HPP_
<commit_msg>Addes Slast<commit_after>#ifndef WLWalker_HPP_
#define WLWalker_HPP_
#include "WL_Window.hpp"
#include "MC_Walker.hpp"
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
struct WL_State
{
int ibin;
double Sval;
void copy(const WL_State& orig) { ibin=orig.ibin; Sval=orig.Sval; }
void operator=(const WL_State& orig) { copy(orig); }
};
// Expands an MCWalker to include Wang-Landau information
template<typename Config, typename Observables>
class WL_Walker : public MC_Walker<Config,Observables>
{
public:
typedef MC_Walker<Config,Observables> BASE;
double wlgamma; // Wang-Landau gamma = ln(f)
WL_State wl_now,wl_old; // Wang-Landau information
WL_Window window; // Wang-Landau Window provides limits and binning
std::vector<double> S; // Entropy = log-density-of-states
std::vector<double> Slast; // Last set of values, used to check convergence
std::vector<double> Sfixed; // Changes only very slowly
std::vector<double> h; // Visit histogram
// The sampling window might be smaller than the energy window
double WEmin,WEmax;
// Combined WL-Transition Matrix: RG Ghulghazaryan, S. Hayryan, CK Hu, J Comp Chem 28, 715-726 (2007)
// wleta comes from Eq. (24) S_WL[I] <- (1-wleta)*S_WL[I] + wleta*S_TM[I]
std::vector<double> Sittm; // A local version of the Infinite-temperature transition matrix result
std::vector<double> Vittm; // A local version of the Vittm error matrix
double EStepSum; // Statistics of how big a MC step is
long long EStepCnt;
public:
// Clear the visit histogram
void clear_histogram()
{
if( h.size()!=window.NBin ) h.resize(window.NBin);
fill(h.begin(),h.end(),0);
}
// Clear the estimated entropy
void clear_entropy()
{
S.resize(window.NBin);
fill(S.begin(),S.end(),0);
Sfixed.resize(window.NBin);
fill(Sfixed.begin(),Sfixed.end(),0);
}
// Set values of member array. Window must already be set
void set_values(const std::vector<double>& E, const std::vector<double>& y, std::vector<double>& seq)
{
const int nread = E.size();
if( E.size()<2 )
{
std::cout << __FILE__ << ":" << __LINE__ << " Energy array is length " << nread << std::endl;
int nbin = window.NBin;
seq.resize(nbin);
for(int i=0; i<nbin; i++) seq[i] = 0;
return;
}
if( y.size()<nread ) std::cout << __FILE__ << ":" << __LINE__ << " array y is too small" << std::endl;
int iread = 0;
int nbin = window.NBin;
seq.resize(nbin);
for(int ibin=0; ibin<nbin; ibin++)
{
double Eset = window.unbin(ibin);
while( iread<nread && E[iread]<Eset ) iread++;
if(iread>=nread) iread = nread-1;
if(iread<1) iread = 1;
double E0 = E[iread];
double y0 = y[iread];
double E1 = E[iread-1];
double y1 = y[iread-1];
double slope = (y1-y0)/(E1-E0);
seq[ibin] = y0 + slope*(Eset-E0);
}
}
void set_fixed(const std::vector<double>& E, const std::vector<double>& y)
{
this->set_values(E,y,this->Sfixed);
}
// Deep copy of the walker
void copy(const WL_Walker<Config,Observables>& orig)
{
this->BASE::copy(orig);
wlgamma = orig.wlgamma;
wl_now = orig.wl_now;
wl_old = orig.wl_old;
window = orig.window;
S = orig.S;
Sfixed = orig.Sfixed;
Sittm = orig.Sittm;
Vittm = orig.Vittm;
h = orig.h;
EStepSum = orig.EStepSum;
EStepCnt = orig.EStepCnt;
}
WL_Walker()
{
}
WL_Walker(const WL_Walker& orig)
{
this->copy(orig);
}
// Use this to find the current bin of the walker
int bin() { return wl_now.ibin = window.bin(BASE::now.E); }
// Estimate Entropy/lndos using linear interpolation
double get_lndos(double E, bool LinearInterp=true)
{
int ibin = window.bin(E);
double E0 = window.unbin(ibin);
double S0 = S[ibin] + Sfixed[ibin];
if( !LinearInterp ) return S0;
double S1,E1;
if( E<E0 )
{
// look left
if( ibin==0 )
{
// Interpolate to edge half a bin away. Force WL portion to zero
E1 = window.Elo;
S1 = S[ibin]+Sfixed[ibin] - 0.5*( Sfixed[ibin+1]-Sfixed[ibin] );
}
else
{
E1 = window.unbin(ibin-1);
S1 = S[ibin-1] + Sfixed[ibin-1];
}
}
else
{
// look right
if( ibin==(window.NBin-1) )
{
E1 = window.Ehi;
S1 = S[ibin]+Sfixed[ibin] + 0.5*( Sfixed[ibin]-Sfixed[ibin-1] );
}
else
{
E1 = window.unbin(ibin+1);
S1 = S[ibin+1] + Sfixed[ibin+1];
}
}
double slope = (S1-S0)/(E1-E0);
double SE = S0 + slope*(E-E0);
return SE;
}
float flatness() const
{
// Find the prefactor that normalizes histogram such that
// h_ibin = 1 for perfectly flat histogram (divide by mean h_ibin)
long long htot = 0;
int hbin = 0;
for(int i=0; i<this->window.NBin; i++)
{
if(h[i]>0)
{
htot += h[i];
hbin++;
}
}
double hnorm = static_cast<double>(hbin)/static_cast<double>(htot);
// Calculate the flatness for the frozen entropy
// Q = (1/nbin) \sum_ibin (h_ibin-1)^2
double Q = 0;
for(int i=0; i<window.NBin; i++)
{
if( h[i]>0 )
{
double Qi=(hnorm*h[i]-1);
Q+=Qi*Qi;
}
}
if( hbin<10 ) Q=1.e+6; // Not flat if trapped
return Q;
}
/*
bool move_walls(double qflat=0.1)
{
//if( move_walls_pileup() ) return true;
// Calculate the flatness from high energy down
int ilft = window.bin(WEmin);
int irgt = window.bin(WEmax);
const int mincts = 500; // Minimum vists before move wall past a bin
int jmax = irgt;
long long htot = 0;
int hbin = 0;
int jbin=jmax;
for(int kbin=jmax; kbin>0 && kbin>(jmax-5); kbin--)
if( h[kbin]>1000000 ) jbin=kbin;
bool flat = true;
while( jbin>=0 && (flat || h[jbin]>1000000) )
{
if( h[jbin]>mincts )
{
htot += h[jbin];
hbin++;
double hnorm = static_cast<double>(hbin)/static_cast<double>(htot);
double Q = 0;
for(int i=jbin; i<=jmax; i++)
{
double Q1 = hnorm*h[i]-1;
Q += Q1*Q1;
}
if(hbin>1) Q /= static_cast<double>(hbin);
flat = (Q<=qflat);
jbin--;
}
else
{
flat = false;
}
}
jmax = jbin;
// Cacluate the flatness from low energy up
int jmin = ilft;
htot = 0;
hbin = 0;
jbin = jmin;
if( jbin<(window.NBin-1) && h[jbin+1]>1000000 ) jbin++;
flat = true;
while( jbin<window.NBin && (flat || h[jbin]>1000000) )
{
if( h[jbin]>mincts )
{
htot += h[jbin];
hbin++;
double hnorm = static_cast<double>(hbin)/static_cast<double>(htot);
double Q = 0;
for(int i=jmin; i<=jbin; i++)
{
double Q1 = hnorm*h[i]-1;
Q += Q1*Q1;
}
if(hbin>1) Q /= static_cast<double>(hbin);
flat = (Q<=qflat);
jbin++;
}
else
{
flat = false;
}
}
const int overlap = 5;
jmin = jbin;
flat = (jmin>jmax);
jmax += overlap;
if(jmax<irgt) irgt=jmax;
jmin -= overlap;
if(jmin>ilft) ilft=jmin;
WEmin = window.unbin(ilft);
WEmax = window.unbin(irgt);
return flat;
}
*/
public:
void save_initial()
{
BASE::save_initial();
wl_old = wl_now;
}
void restore_initial()
{
wl_now = wl_old;
BASE::restore_initial();
}
};
// Return integer index of wlgamma assuming wlgamma_i+1 = wlgamma_i/2
int igamma(double wlgamma)
{
int p2 = static_cast<int>(-std::log(wlgamma)/std::log(2.)+0.01);
return p2;
}
#endif // WLWalker_HPP_
<|endoftext|> |
<commit_before>#pragma once
#include <any.hpp>
namespace shadow
{
class object
{
public:
private:
any value_;
};
}
<commit_msg>Add class type_tag with some member functions. modified: include/api_types.hpp<commit_after>#pragma once
#include <string>
#include <cstddef>
#include <any.hpp>
#include <reflection_info.hpp>
namespace shadow
{
class type_tag
{
public:
std::string name() const;
std::size_t size() const;
private:
const type_info* info_ptr_;
};
class object
{
public:
private:
any value_;
};
}
namespace shadow
{
inline std::string
type_tag::name() const
{
return std::string(info_ptr_->name);
}
inline std::size_t
type_tag::size() const
{
return info_ptr_->size;
}
}
<|endoftext|> |
<commit_before>#ifndef APOLLO_GC_HPP_INCLUDED
#define APOLLO_GC_HPP_INCLUDED APOLLO_GC_HPP_INCLUDED
#include <lua.hpp>
#include <type_traits>
#include <boost/assert.hpp>
#include <apollo/detail/meta_util.hpp>
namespace apollo {
template <typename T>
int gc_object(lua_State* L) BOOST_NOEXCEPT
{
BOOST_ASSERT(lua_type(L, 1) == LUA_TUSERDATA);
static_cast<T*>(lua_touserdata(L, 1))->~T();
return 0;
}
template <typename T>
typename detail::remove_qualifiers<T>::type*
push_gc_object(lua_State* L, T&& o)
{
using obj_t = typename detail::remove_qualifiers<T>::type;
void* uf = lua_newuserdata(L, sizeof(obj_t));
try {
new(uf) obj_t(std::forward<T>(o));
} catch (...) {
lua_pop(L, 1);
throw;
}
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable:4127) // Conditional expression is constant.
#endif
if (!std::is_trivially_destructible<obj_t>::value) {
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
lua_createtable(L, 0, 1);
lua_pushcfunction(L, &gc_object<obj_t>);
lua_setfield(L, -2, "__gc");
lua_setmetatable(L, -2);
}
return static_cast<obj_t*>(uf);
}
} // namespace apollo
#endif // APOLLO_GC_HPP_INCLUDED
<commit_msg>gc: Include missing header.<commit_after>#ifndef APOLLO_GC_HPP_INCLUDED
#define APOLLO_GC_HPP_INCLUDED APOLLO_GC_HPP_INCLUDED
#include <lua.hpp>
#include <type_traits>
#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <apollo/detail/meta_util.hpp>
namespace apollo {
template <typename T>
int gc_object(lua_State* L) BOOST_NOEXCEPT
{
BOOST_ASSERT(lua_type(L, 1) == LUA_TUSERDATA);
static_cast<T*>(lua_touserdata(L, 1))->~T();
return 0;
}
template <typename T>
typename detail::remove_qualifiers<T>::type*
push_gc_object(lua_State* L, T&& o)
{
using obj_t = typename detail::remove_qualifiers<T>::type;
void* uf = lua_newuserdata(L, sizeof(obj_t));
try {
new(uf) obj_t(std::forward<T>(o));
} catch (...) {
lua_pop(L, 1);
throw;
}
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable:4127) // Conditional expression is constant.
#endif
if (!std::is_trivially_destructible<obj_t>::value) {
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
lua_createtable(L, 0, 1);
lua_pushcfunction(L, &gc_object<obj_t>);
lua_setfield(L, -2, "__gc");
lua_setmetatable(L, -2);
}
return static_cast<obj_t*>(uf);
}
} // namespace apollo
#endif // APOLLO_GC_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Michael Tesch
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Michael Tesch nor the names of other
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
https://github.com/tesch1/qt-google-analytics-collector
*/
#include <unistd.h>
#include <map>
#include <QCoreApplication>
#include <QSettings>
#ifdef QT_GUI_LIB
#include <QApplication>
#include <QDesktopWidget>
#endif
#include <QUuid>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QDebug>
/*!
* send google tracking data according to
* https://developers.google.com/analytics/devguides/collection/protocol/v1/reference
*/
class GAnalytics : public QObject {
Q_OBJECT
private:
typedef std::map<QNetworkReply *, bool> reply_map;
public:
GAnalytics(QCoreApplication * parent,
QString trackingID,
QString clientID = "",
bool useGET = false)
: QObject(parent), _qnam(this), _trackingID(trackingID), _clientID(clientID), _useGET(useGET), _isFail(false)
{
if (parent) {
setAppName(parent->applicationName());
setAppVersion(parent->applicationVersion());
#ifdef QT_GUI_LIB
parent->dumpObjectTree();
#endif
}
if (!_clientID.size()) {
// load client id from settings
QSettings settings;
if (!settings.contains("GAnalytics-cid")) {
settings.setValue("GAnalytics-cid", QUuid::createUuid().toString());
}
_clientID = settings.value("GAnalytics-cid").toString();
}
connect(&_qnam, SIGNAL(finished(QNetworkReply *)), this, SLOT(postFinished(QNetworkReply *)));
if (!_qnam.networkAccessible())
qDebug() << "error: network inaccessible\n";
}
~GAnalytics() {
// wait up to half a second to let replies finish up
// this generally happens after the event-loop is done, so no more network processing
#if 1 // not sure if this is necessary? does ~_qnam() delete all its replies? i guess it should
for (reply_map::iterator it = _replies.begin(); it != _replies.end(); it++) {
QNetworkReply * reply = it->first;
if (reply->isRunning())
qDebug() << "~GAnalytics, request still running: " << reply->url().toString() << ", aborting.";
//reply->deleteLater();
}
#endif
}
// manual ip and user agent
void setClientID(QString clientID) { _clientID = clientID; }
void setUserIPAddr(QString userIPAddr) { _userIPAddr = userIPAddr; }
void setUserAgent(QString userAgent) { _userAgent = userAgent; }
void setAppName(QString appName) { _appName = appName; }
void setAppVersion(QString appVersion) { _appVersion = appVersion; }
void setScreenResolution(QString screenResolution) { _screenResolution = screenResolution; }
void setViewportSize(QString viewportSize) { _viewportSize = viewportSize; }
void setUserLanguage(QString userLanguage) { _userLanguage = userLanguage; }
QString getClientID() const { return _clientID; }
//
// hit types
//
// - https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
//
public Q_SLOTS:
// pageview
void sendPageview(QString docHostname, QString page, QString title) const {
QUrl params = build_metric("pageview");
params.addQueryItem("dh", docHostname); // document hostname
params.addQueryItem("dp", page); // page
params.addQueryItem("dt", title); // title
send_metric(params);
}
// event
void sendEvent(QString eventCategory = "", QString eventAction = "",
QString eventLabel = "", int eventValue = 0) const {
QUrl params = build_metric("event");
if (_appName.size()) params.addQueryItem("an", _appName); // mobile event app tracking
if (_appVersion.size()) params.addQueryItem("av", _appVersion); // mobile event app tracking
if (eventCategory.size()) params.addQueryItem("ec", eventCategory);
if (eventAction.size()) params.addQueryItem("ea", eventAction);
if (eventLabel.size()) params.addQueryItem("el", eventLabel);
if (eventValue) params.addQueryItem("ev", QString::number(eventValue));
send_metric(params);
}
// transaction
void sendTransaction(QString transactionID, QString transactionAffiliation = "" /*...todo...*/) const {
QUrl params = build_metric("transaction");
params.addQueryItem("ti", transactionID);
if (transactionAffiliation.size()) params.addQueryItem("ta", transactionAffiliation);
send_metric(params);
}
// item
void sendItem(QString itemName) const {
QUrl params = build_metric("item");
params.addQueryItem("in", itemName);
//if (appName.size()) params.addQueryItem("an", appName);
send_metric(params);
}
// social
void sendSocial(QString socialNetwork, QString socialAction, QString socialActionTarget) const {
QUrl params = build_metric("social");
params.addQueryItem("sn", socialNetwork);
params.addQueryItem("sa", socialAction);
params.addQueryItem("st", socialActionTarget);
send_metric(params);
}
// exception
void sendException(QString exceptionDescription, bool exceptionFatal = true) const {
QUrl params = build_metric("exception");
if (exceptionDescription.size()) params.addQueryItem("exd", exceptionDescription);
if (!exceptionFatal) params.addQueryItem("exf", "0");
send_metric(params);
}
// timing
void sendTiming(/* todo */) const {
QUrl params = build_metric("timing");
//if (appName.size()) params.addQueryItem("an", appName);
send_metric(params);
}
// appview
void sendAppview(QString appName, QString appVersion = "", QString screenName = "") const {
QUrl params = build_metric("appview");
if (_appName.size()) params.addQueryItem("an", _appName);
else if (appName.size()) params.addQueryItem("an", appName);
if (_appVersion.size()) params.addQueryItem("av", _appVersion);
else if (appVersion.size()) params.addQueryItem("av", appVersion);
if (screenName.size()) params.addQueryItem("cd", screenName);
send_metric(params);
}
// custom dimensions / metrics
// todo
// experiment id / variant
// todo
//void startSession();
void endSession() const {
QUrl params = build_metric("event");
params.addQueryItem("sc", "end");
send_metric(params);
}
public:
void generateUserAgentEtc() {
QString locale = QLocale::system().name().toLower().replace("_", "-");
#if __APPLE__
QString machine = "Macintosh; Intel Mac OS X 10.9; ";
#endif
#if __linux__
QString machine = "X11; ";
#endif
_userAgent = "Mozilla/5.0 (" + machine + "N; " + locale + ")";
QNetworkRequest req;
qDebug() << "User-Agent:" << req.rawHeader("User-Agent").constData() << "->" << _userAgent;
#ifdef QT_GUI_LIB
QString geom = QString::number(QApplication::desktop()->screenGeometry().width())
+ "x" + QString::number(QApplication::desktop()->screenGeometry().height());
_screenResolution = geom;
//qDebug() << "screen resolution:" << _screenResolution;
setUserLanguage(locale);
#endif
}
private Q_SLOTS:
void postFinished(QNetworkReply * reply) {
//qDebug() << "reply:" << reply->readAll().toHex();
if (QNetworkReply::NoError != reply->error()) {
qDebug() << "postFinished error: " << reply->errorString() << "\n";
}
else {
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
//qDebug() << "http response code: " << httpStatus;
if (httpStatus < 200 || httpStatus > 299) {
_isFail = true;
}
}
_replies.erase(reply);
reply->deleteLater();
}
void postError(QNetworkReply::NetworkError code) {
qDebug() << "network error signal: " << code << "\n";
}
private:
GAnalytics(const GAnalytics &); // disable copy const constructor
QUrl build_metric(QString hitType) const {
QUrl params;
// required in v1
params.addQueryItem("v", "1" ); // version
params.addQueryItem("tid", _trackingID);
params.addQueryItem("cid", _clientID);
params.addQueryItem("t", hitType);
if (_userIPAddr.size())
params.addQueryItem("uip", _userIPAddr);
if (_screenResolution.size())
params.addQueryItem("sr", _screenResolution);
if (_viewportSize.size())
params.addQueryItem("vp", _viewportSize);
if (_userLanguage.size())
params.addQueryItem("ul", _userLanguage);
//if (_userAgent.size())
// params.addQueryItem("ua", _userAgent);
return params;
}
void send_metric(QUrl & params) const {
// when google has err'd us, then stop sending events!
if (_isFail)
return;
QUrl collect_url("http://www.google-analytics.com/collect");
QNetworkRequest request;
if (_userAgent.size())
request.setRawHeader("User-Agent", _userAgent.toUtf8());
QNetworkReply * reply;
if (_useGET) {
// add cache-buster "z" to params
//params.addQueryItem("z", QString::number(qrand()) );
collect_url.setQueryItems(params.queryItems());
request.setUrl(collect_url);
reply = _qnam.get(request);
}
else {
request.setUrl(collect_url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
reply = _qnam.post(request, params.encodedQuery());
}
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(postError(QNetworkReply::NetworkError)));
_replies[reply] = true;
}
mutable QNetworkAccessManager _qnam;
QString _trackingID;
QString _clientID;
bool _useGET; // true=GET, false=POST
QString _userID;
// various parameters:
bool _anonymizeIP;
bool _cacheBust;
//
QString _userIPAddr;
QString _userAgent;
QString _appName;
QString _appVersion;
#if 0 // todo
// traffic sources
QString _documentReferrer;
QString _campaignName;
QString _campaignSource;
QString _campaignMedium;
QString _campaignKeyword;
QString _campaignContent;
QString _campaignID;
QString _adwordsID;
QString _displayAdsID;
#endif
// system info
QString _screenResolution;
QString _viewportSize;
QString _userLanguage;
// etc...
// internal
bool _isFail;
mutable reply_map _replies;
};
<commit_msg>better machine and os<commit_after>/*
Copyright (c) 2014, Michael Tesch
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Michael Tesch nor the names of other
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
https://github.com/tesch1/qt-google-analytics-collector
*/
#include <unistd.h>
#include <map>
#include <QCoreApplication>
#include <QSettings>
#ifdef QT_GUI_LIB
#include <QApplication>
#include <QDesktopWidget>
#endif
#include <QUuid>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QDebug>
/*!
* send google tracking data according to
* https://developers.google.com/analytics/devguides/collection/protocol/v1/reference
*/
class GAnalytics : public QObject {
Q_OBJECT
private:
typedef std::map<QNetworkReply *, bool> reply_map;
public:
GAnalytics(QCoreApplication * parent,
QString trackingID,
QString clientID = "",
bool useGET = false)
: QObject(parent), _qnam(this), _trackingID(trackingID), _clientID(clientID), _useGET(useGET), _isFail(false)
{
if (parent) {
setAppName(parent->applicationName());
setAppVersion(parent->applicationVersion());
#ifdef QT_GUI_LIB
parent->dumpObjectTree();
#endif
}
if (!_clientID.size()) {
// load client id from settings
QSettings settings;
if (!settings.contains("GAnalytics-cid")) {
settings.setValue("GAnalytics-cid", QUuid::createUuid().toString());
}
_clientID = settings.value("GAnalytics-cid").toString();
}
connect(&_qnam, SIGNAL(finished(QNetworkReply *)), this, SLOT(postFinished(QNetworkReply *)));
if (!_qnam.networkAccessible())
qDebug() << "error: network inaccessible\n";
}
~GAnalytics() {
// wait up to half a second to let replies finish up
// this generally happens after the event-loop is done, so no more network processing
#if 1 // not sure if this is necessary? does ~_qnam() delete all its replies? i guess it should
for (reply_map::iterator it = _replies.begin(); it != _replies.end(); it++) {
QNetworkReply * reply = it->first;
if (reply->isRunning())
qDebug() << "~GAnalytics, request still running: " << reply->url().toString() << ", aborting.";
//reply->deleteLater();
}
#endif
}
// manual ip and user agent
void setClientID(QString clientID) { _clientID = clientID; }
void setUserIPAddr(QString userIPAddr) { _userIPAddr = userIPAddr; }
void setUserAgent(QString userAgent) { _userAgent = userAgent; }
void setAppName(QString appName) { _appName = appName; }
void setAppVersion(QString appVersion) { _appVersion = appVersion; }
void setScreenResolution(QString screenResolution) { _screenResolution = screenResolution; }
void setViewportSize(QString viewportSize) { _viewportSize = viewportSize; }
void setUserLanguage(QString userLanguage) { _userLanguage = userLanguage; }
QString getClientID() const { return _clientID; }
//
// hit types
//
// - https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
//
public Q_SLOTS:
// pageview
void sendPageview(QString docHostname, QString page, QString title) const {
QUrl params = build_metric("pageview");
params.addQueryItem("dh", docHostname); // document hostname
params.addQueryItem("dp", page); // page
params.addQueryItem("dt", title); // title
send_metric(params);
}
// event
void sendEvent(QString eventCategory = "", QString eventAction = "",
QString eventLabel = "", int eventValue = 0) const {
QUrl params = build_metric("event");
if (_appName.size()) params.addQueryItem("an", _appName); // mobile event app tracking
if (_appVersion.size()) params.addQueryItem("av", _appVersion); // mobile event app tracking
if (eventCategory.size()) params.addQueryItem("ec", eventCategory);
if (eventAction.size()) params.addQueryItem("ea", eventAction);
if (eventLabel.size()) params.addQueryItem("el", eventLabel);
if (eventValue) params.addQueryItem("ev", QString::number(eventValue));
send_metric(params);
}
// transaction
void sendTransaction(QString transactionID, QString transactionAffiliation = "" /*...todo...*/) const {
QUrl params = build_metric("transaction");
params.addQueryItem("ti", transactionID);
if (transactionAffiliation.size()) params.addQueryItem("ta", transactionAffiliation);
send_metric(params);
}
// item
void sendItem(QString itemName) const {
QUrl params = build_metric("item");
params.addQueryItem("in", itemName);
//if (appName.size()) params.addQueryItem("an", appName);
send_metric(params);
}
// social
void sendSocial(QString socialNetwork, QString socialAction, QString socialActionTarget) const {
QUrl params = build_metric("social");
params.addQueryItem("sn", socialNetwork);
params.addQueryItem("sa", socialAction);
params.addQueryItem("st", socialActionTarget);
send_metric(params);
}
// exception
void sendException(QString exceptionDescription, bool exceptionFatal = true) const {
QUrl params = build_metric("exception");
if (exceptionDescription.size()) params.addQueryItem("exd", exceptionDescription);
if (!exceptionFatal) params.addQueryItem("exf", "0");
send_metric(params);
}
// timing
void sendTiming(/* todo */) const {
QUrl params = build_metric("timing");
//if (appName.size()) params.addQueryItem("an", appName);
send_metric(params);
}
// appview
void sendAppview(QString appName, QString appVersion = "", QString screenName = "") const {
QUrl params = build_metric("appview");
if (_appName.size()) params.addQueryItem("an", _appName);
else if (appName.size()) params.addQueryItem("an", appName);
if (_appVersion.size()) params.addQueryItem("av", _appVersion);
else if (appVersion.size()) params.addQueryItem("av", appVersion);
if (screenName.size()) params.addQueryItem("cd", screenName);
send_metric(params);
}
// custom dimensions / metrics
// todo
// experiment id / variant
// todo
//void startSession();
void endSession() const {
QUrl params = build_metric("event");
params.addQueryItem("sc", "end");
send_metric(params);
}
public:
void generateUserAgentEtc() {
QString locale = QLocale::system().name().toLower().replace("_", "-");
#ifdef __APPLE__
QString machine = "Macintosh; Intel Mac OS X 10.9; ";
#endif
#ifdef __linux__
QString machine = "X11; Linux ";
#ifdef __amd64__ || __x86_64__ || __ppc64__
machine += "x86_64; ";
#else
machine += "i686; ";
#endif
#endif
#ifdef Q_WS_WIN
QString machine = "Windows; ";
#endif
_userAgent = "Mozilla/5.0 (" + machine + "N; " + locale + ") GAnalytics/1.0 (Qt/" QT_VERSION_STR " )";
QNetworkRequest req;
qDebug() << "User-Agent:" << req.rawHeader("User-Agent").constData() << "->" << _userAgent;
#ifdef QT_GUI_LIB
QString geom = QString::number(QApplication::desktop()->screenGeometry().width())
+ "x" + QString::number(QApplication::desktop()->screenGeometry().height());
_screenResolution = geom;
//qDebug() << "screen resolution:" << _screenResolution;
setUserLanguage(locale);
#endif
}
private Q_SLOTS:
void postFinished(QNetworkReply * reply) {
//qDebug() << "reply:" << reply->readAll().toHex();
if (QNetworkReply::NoError != reply->error()) {
qDebug() << "postFinished error: " << reply->errorString() << "\n";
}
else {
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
//qDebug() << "http response code: " << httpStatus;
if (httpStatus < 200 || httpStatus > 299) {
_isFail = true;
}
}
_replies.erase(reply);
reply->deleteLater();
}
void postError(QNetworkReply::NetworkError code) {
qDebug() << "network error signal: " << code << "\n";
}
private:
GAnalytics(const GAnalytics &); // disable copy const constructor
QUrl build_metric(QString hitType) const {
QUrl params;
// required in v1
params.addQueryItem("v", "1" ); // version
params.addQueryItem("tid", _trackingID);
params.addQueryItem("cid", _clientID);
params.addQueryItem("t", hitType);
if (_userIPAddr.size())
params.addQueryItem("uip", _userIPAddr);
if (_screenResolution.size())
params.addQueryItem("sr", _screenResolution);
if (_viewportSize.size())
params.addQueryItem("vp", _viewportSize);
if (_userLanguage.size())
params.addQueryItem("ul", _userLanguage);
//if (_userAgent.size())
// params.addQueryItem("ua", _userAgent);
return params;
}
void send_metric(QUrl & params) const {
// when google has err'd us, then stop sending events!
if (_isFail)
return;
QUrl collect_url("http://www.google-analytics.com/collect");
QNetworkRequest request;
if (_userAgent.size())
request.setRawHeader("User-Agent", _userAgent.toUtf8());
QNetworkReply * reply;
if (_useGET) {
// add cache-buster "z" to params
//params.addQueryItem("z", QString::number(qrand()) );
collect_url.setQueryItems(params.queryItems());
request.setUrl(collect_url);
reply = _qnam.get(request);
}
else {
request.setUrl(collect_url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
reply = _qnam.post(request, params.encodedQuery());
}
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(postError(QNetworkReply::NetworkError)));
_replies[reply] = true;
}
mutable QNetworkAccessManager _qnam;
QString _trackingID;
QString _clientID;
bool _useGET; // true=GET, false=POST
QString _userID;
// various parameters:
bool _anonymizeIP;
bool _cacheBust;
//
QString _userIPAddr;
QString _userAgent;
QString _appName;
QString _appVersion;
#if 0 // todo
// traffic sources
QString _documentReferrer;
QString _campaignName;
QString _campaignSource;
QString _campaignMedium;
QString _campaignKeyword;
QString _campaignContent;
QString _campaignID;
QString _adwordsID;
QString _displayAdsID;
#endif
// system info
QString _screenResolution;
QString _viewportSize;
QString _userLanguage;
// etc...
// internal
bool _isFail;
mutable reply_map _replies;
};
<|endoftext|> |
<commit_before>/**
* @file container.hpp
* @brief component container class
* @author Byunghun Hwang<[email protected]>
* @date 2015. 8. 6
* @details Component container
*/
#ifndef _COSSB_CONTAINER_HPP_
#define _COSSB_CONTAINER_HPP_
#include <string>
#include <list>
#include <map>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
#include "driver.hpp"
using namespace std;
namespace cossb {
namespace container {
typedef std::map<string, driver::component_driver*> comp_container;
class component_container : private arch::singleton<component_container> {
public:
/**
* @brief construct
*/
component_container() = default;
/**
* @brief destructor
*/
virtual ~component_container() { clear(); }
private:
/**
* @brief return size of the component container
*/
int size() { return _container.size(); }
/**
* @brief empty check
* @return true, if the container is empty
*/
bool empty() { return _container.size()==0; }
/**
* @brief find component driver if it exists, and getting its driver
*/
driver::component_driver* get_driver(const char* component_name) {
comp_container::iterator itr = _container.find(component_name);
if(itr!=_container.end())
return itr->second;
else
return nullptr;
}
/**
* @brief add new component
* @return true, if success
*/
bool add(const char* component_name, driver::component_driver* driver) {
if(_container.find(component_name)==_container.end() && driver->valid()) {
_container.insert(comp_container::value_type(component_name, driver));
return true;
}
else {
delete driver;
return false;
}
}
/**
* @brief remove specific component
*/
bool remove(const char* component_name) {
comp_container::iterator itr = _container.find(component_name);
if(itr!=_container.end()) {
if(itr->second) {
delete itr->second;
itr->second = nullptr;
}
_container.erase(itr);
return true;
}
return false;
}
/**
* @brief check for component existence
*/
bool exist(const char* component_name) {
if(_container.find(component_name)!=_container.end())
return true;
else
return false;
}
/**
* @brief clear all components
*/
void clear() {
for(auto itr:_container) {
if(itr.second) {
delete itr.second;
itr.second = nullptr;
}
}
_container.clear();
}
private:
comp_container _container;
friend class manager::component_manager;
};
#define cossb_component_container cossb::container::component_container::instance()
} /* namespace container */
} /* namesapce cossb */
#endif /* _COSSB_CONTAINER_HPP_ */
<commit_msg>remove the list header<commit_after>/**
* @file container.hpp
* @brief component container class
* @author Byunghun Hwang<[email protected]>
* @date 2015. 8. 6
* @details Component container
*/
#ifndef _COSSB_CONTAINER_HPP_
#define _COSSB_CONTAINER_HPP_
#include <string>
#include <map>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
#include "driver.hpp"
using namespace std;
namespace cossb {
namespace container {
typedef std::map<string, driver::component_driver*> comp_container;
class component_container : private arch::singleton<component_container> {
public:
/**
* @brief construct
*/
component_container() = default;
/**
* @brief destructor
*/
virtual ~component_container() { clear(); }
private:
/**
* @brief return size of the component container
*/
int size() { return _container.size(); }
/**
* @brief empty check
* @return true, if the container is empty
*/
bool empty() { return _container.size()==0; }
/**
* @brief find component driver if it exists, and getting its driver
*/
driver::component_driver* get_driver(const char* component_name) {
comp_container::iterator itr = _container.find(component_name);
if(itr!=_container.end())
return itr->second;
else
return nullptr;
}
/**
* @brief add new component
* @return true, if success
*/
bool add(const char* component_name, driver::component_driver* driver) {
if(_container.find(component_name)==_container.end() && driver->valid()) {
_container.insert(comp_container::value_type(component_name, driver));
return true;
}
else {
delete driver;
return false;
}
}
/**
* @brief remove specific component
*/
bool remove(const char* component_name) {
comp_container::iterator itr = _container.find(component_name);
if(itr!=_container.end()) {
if(itr->second) {
delete itr->second;
itr->second = nullptr;
}
_container.erase(itr);
return true;
}
return false;
}
/**
* @brief check for component existence
*/
bool exist(const char* component_name) {
if(_container.find(component_name)!=_container.end())
return true;
else
return false;
}
/**
* @brief clear all components
*/
void clear() {
for(auto itr:_container) {
if(itr.second) {
delete itr.second;
itr.second = nullptr;
}
}
_container.clear();
}
private:
comp_container _container;
friend class manager::component_manager;
};
#define cossb_component_container cossb::container::component_container::instance()
} /* namespace container */
} /* namesapce cossb */
#endif /* _COSSB_CONTAINER_HPP_ */
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <malloc.h>
#include <vector>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/grpc_security.h"
#include "channel.h"
#include "credentials.h"
namespace grpc {
namespace node {
using v8::Arguments;
using v8::Array;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
Persistent<Function> Channel::constructor;
Persistent<FunctionTemplate> Channel::fun_tpl;
Channel::Channel(grpc_channel *channel, NanUtf8String *host)
: wrapped_channel(channel), host(host) {}
Channel::~Channel() {
if (wrapped_channel != NULL) {
grpc_channel_destroy(wrapped_channel);
}
delete host;
}
void Channel::Init(Handle<Object> exports) {
NanScope();
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(NanNew("Channel"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NanSetPrototypeTemplate(tpl, "close",
FunctionTemplate::New(Close)->GetFunction());
NanAssignPersistent(fun_tpl, tpl);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(NanNew("Channel"), constructor);
}
bool Channel::HasInstance(Handle<Value> val) {
NanScope();
return NanHasInstance(fun_tpl, val);
}
grpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; }
char *Channel::GetHost() { return **this->host; }
NAN_METHOD(Channel::New) {
NanScope();
if (args.IsConstructCall()) {
if (!args[0]->IsString()) {
return NanThrowTypeError("Channel expects a string and an object");
}
grpc_channel *wrapped_channel;
// Owned by the Channel object
NanUtf8String *host = new NanUtf8String(args[0]);
if (args[1]->IsUndefined()) {
wrapped_channel = grpc_channel_create(**host, NULL);
} else if (args[1]->IsObject()) {
grpc_credentials *creds = NULL;
Handle<Object> args_hash(args[1]->ToObject()->Clone());
if (args_hash->HasOwnProperty(NanNew("credentials"))) {
Handle<Value> creds_value = args_hash->Get(NanNew("credentials"));
if (!Credentials::HasInstance(creds_value)) {
return NanThrowTypeError(
"credentials arg must be a Credentials object");
}
Credentials *creds_object =
ObjectWrap::Unwrap<Credentials>(creds_value->ToObject());
creds = creds_object->GetWrappedCredentials();
args_hash->Delete(NanNew("credentials"));
}
Handle<Array> keys(args_hash->GetOwnPropertyNames());
grpc_channel_args channel_args;
channel_args.num_args = keys->Length();
channel_args.args = reinterpret_cast<grpc_arg *>(
calloc(channel_args.num_args, sizeof(grpc_arg)));
/* These are used to keep all strings until then end of the block, then
destroy them */
std::vector<NanUtf8String *> key_strings(keys->Length());
std::vector<NanUtf8String *> value_strings(keys->Length());
for (unsigned int i = 0; i < channel_args.num_args; i++) {
Handle<String> current_key(keys->Get(i)->ToString());
Handle<Value> current_value(args_hash->Get(current_key));
key_strings[i] = new NanUtf8String(current_key);
channel_args.args[i].key = **key_strings[i];
if (current_value->IsInt32()) {
channel_args.args[i].type = GRPC_ARG_INTEGER;
channel_args.args[i].value.integer = current_value->Int32Value();
} else if (current_value->IsString()) {
channel_args.args[i].type = GRPC_ARG_STRING;
value_strings[i] = new NanUtf8String(current_value);
channel_args.args[i].value.string = **value_strings[i];
} else {
free(channel_args.args);
return NanThrowTypeError("Arg values must be strings");
}
}
if (creds == NULL) {
wrapped_channel = grpc_channel_create(**host, &channel_args);
} else {
wrapped_channel =
grpc_secure_channel_create(creds, **host, &channel_args);
}
free(channel_args.args);
} else {
return NanThrowTypeError("Channel expects a string and an object");
}
Channel *channel = new Channel(wrapped_channel, host);
channel->Wrap(args.This());
NanReturnValue(args.This());
} else {
const int argc = 2;
Local<Value> argv[argc] = {args[0], args[1]};
NanReturnValue(constructor->NewInstance(argc, argv));
}
}
NAN_METHOD(Channel::Close) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("close can only be called on Channel objects");
}
Channel *channel = ObjectWrap::Unwrap<Channel>(args.This());
if (channel->wrapped_channel != NULL) {
grpc_channel_destroy(channel->wrapped_channel);
channel->wrapped_channel = NULL;
}
NanReturnUndefined();
}
} // namespace node
} // namespace grpc
<commit_msg>Fixed TLS host resolution problems<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <malloc.h>
#include <vector>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/grpc_security.h"
#include "channel.h"
#include "credentials.h"
namespace grpc {
namespace node {
using v8::Arguments;
using v8::Array;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
Persistent<Function> Channel::constructor;
Persistent<FunctionTemplate> Channel::fun_tpl;
Channel::Channel(grpc_channel *channel, NanUtf8String *host)
: wrapped_channel(channel), host(host) {}
Channel::~Channel() {
if (wrapped_channel != NULL) {
grpc_channel_destroy(wrapped_channel);
}
delete host;
}
void Channel::Init(Handle<Object> exports) {
NanScope();
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(NanNew("Channel"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NanSetPrototypeTemplate(tpl, "close",
FunctionTemplate::New(Close)->GetFunction());
NanAssignPersistent(fun_tpl, tpl);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(NanNew("Channel"), constructor);
}
bool Channel::HasInstance(Handle<Value> val) {
NanScope();
return NanHasInstance(fun_tpl, val);
}
grpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; }
char *Channel::GetHost() { return **this->host; }
NAN_METHOD(Channel::New) {
NanScope();
if (args.IsConstructCall()) {
if (!args[0]->IsString()) {
return NanThrowTypeError("Channel expects a string and an object");
}
grpc_channel *wrapped_channel;
// Owned by the Channel object
NanUtf8String *host = new NanUtf8String(args[0]);
NanUtf8String *host_override = NULL;
if (args[1]->IsUndefined()) {
wrapped_channel = grpc_channel_create(**host, NULL);
} else if (args[1]->IsObject()) {
grpc_credentials *creds = NULL;
Handle<Object> args_hash(args[1]->ToObject()->Clone());
if (args_hash->HasOwnProperty(NanNew(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG))) {
host_override = new NanUtf8String(args_hash->Get(NanNew(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG)));
}
if (args_hash->HasOwnProperty(NanNew("credentials"))) {
Handle<Value> creds_value = args_hash->Get(NanNew("credentials"));
if (!Credentials::HasInstance(creds_value)) {
return NanThrowTypeError(
"credentials arg must be a Credentials object");
}
Credentials *creds_object =
ObjectWrap::Unwrap<Credentials>(creds_value->ToObject());
creds = creds_object->GetWrappedCredentials();
args_hash->Delete(NanNew("credentials"));
}
Handle<Array> keys(args_hash->GetOwnPropertyNames());
grpc_channel_args channel_args;
channel_args.num_args = keys->Length();
channel_args.args = reinterpret_cast<grpc_arg *>(
calloc(channel_args.num_args, sizeof(grpc_arg)));
/* These are used to keep all strings until then end of the block, then
destroy them */
std::vector<NanUtf8String *> key_strings(keys->Length());
std::vector<NanUtf8String *> value_strings(keys->Length());
for (unsigned int i = 0; i < channel_args.num_args; i++) {
Handle<String> current_key(keys->Get(i)->ToString());
Handle<Value> current_value(args_hash->Get(current_key));
key_strings[i] = new NanUtf8String(current_key);
channel_args.args[i].key = **key_strings[i];
if (current_value->IsInt32()) {
channel_args.args[i].type = GRPC_ARG_INTEGER;
channel_args.args[i].value.integer = current_value->Int32Value();
} else if (current_value->IsString()) {
channel_args.args[i].type = GRPC_ARG_STRING;
value_strings[i] = new NanUtf8String(current_value);
channel_args.args[i].value.string = **value_strings[i];
} else {
free(channel_args.args);
return NanThrowTypeError("Arg values must be strings");
}
}
if (creds == NULL) {
wrapped_channel = grpc_channel_create(**host, &channel_args);
} else {
wrapped_channel =
grpc_secure_channel_create(creds, **host, &channel_args);
}
free(channel_args.args);
} else {
return NanThrowTypeError("Channel expects a string and an object");
}
Channel *channel;
if (host_override == NULL) {
channel = new Channel(wrapped_channel, host);
} else {
channel = new Channel(wrapped_channel, host_override);
}
channel->Wrap(args.This());
NanReturnValue(args.This());
} else {
const int argc = 2;
Local<Value> argv[argc] = {args[0], args[1]};
NanReturnValue(constructor->NewInstance(argc, argv));
}
}
NAN_METHOD(Channel::Close) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("close can only be called on Channel objects");
}
Channel *channel = ObjectWrap::Unwrap<Channel>(args.This());
if (channel->wrapped_channel != NULL) {
grpc_channel_destroy(channel->wrapped_channel);
channel->wrapped_channel = NULL;
}
NanReturnUndefined();
}
} // namespace node
} // namespace grpc
<|endoftext|> |
<commit_before>
/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/06/08.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "datatype.h"
#include "image.h"
#include "algo/loop.h"
#include "algo/threaded_loop.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "J-Donald Tournier ([email protected]) and David Raffelt ([email protected]) and Robert E. Smith ([email protected])";
DESCRIPTION
+ "compare two images for differences, optionally with a specified tolerance.";
ARGUMENTS
+ Argument ("data1", "an image.").type_image_in()
+ Argument ("data2", "another image.").type_image_in()
+ Argument ("tolerance", "the tolerance value (default = 0.0).").type_float(0.0).optional();
OPTIONS
+ Option ("abs", "test for absolute difference (the default)")
+ Option ("frac", "test for fractional absolute difference")
+ Option ("voxel", "test for fractional absolute difference relative to the maximum value in the voxel");
}
void run ()
{
auto in1 = Image<cdouble>::open (argument[0]);
auto in2 = Image<cdouble>::open (argument[1]);
check_dimensions (in1, in2);
for (size_t i = 0; i < in1.ndim(); ++i) {
if (std::isfinite (in1.size(i)))
if (in1.size(i) != in2.size(i))
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not have matching voxel spacings " +
str(in1.size(i)) + " vs " + str(in2.size(i)));
}
for (size_t i = 0; i < 3; ++i) {
for (size_t j = 0; j < 4; ++j) {
if (std::abs (in1.transform().matrix()(i,j) - in2.transform().matrix()(i,j)) > 0.001)
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not have matching header transforms "
+ "\n" + str(in1.transform().matrix()) + "vs \n " + str(in2.transform().matrix()) + ")");
}
}
const double tol = argument.size() == 3 ? argument[2] : 0.0;
const bool absolute = get_options ("abs").size();
const bool fractional = get_options ("frac").size();
const bool per_voxel = get_options ("voxel").size();
double largest_diff = 0.0;
size_t count = 0;
if (absolute + fractional + per_voxel > 1)
throw Exception ("options \"-abs\", \"-frac\", and \"-voxel\" are mutually exclusive");
// per-voxel:
if (per_voxel) {
if (in1.ndim() != 4)
throw Exception ("Option -voxel only works for 4D images");
struct RunKernel {
RunKernel (double& largest_diff, size_t& count, double tol) :
largest_diff (largest_diff), count (count), tol (tol), max_diff (0.0), n (0) { }
void operator() (decltype(in1)& a, decltype(in2)& b) {
double maxa = 0.0, maxb = 0.0;
for (auto l = Loop(3) (a, b); l; ++l) {
maxa = std::max (maxa, std::abs (cdouble(a.value())));
maxb = std::max (maxb, std::abs (cdouble(b.value())));
}
const double threshold = tol * 0.5 * (maxa + maxb);
for (auto l = Loop(3) (a, b); l; ++l) {
auto diff = std::abs (cdouble (a.value()) - cdouble (b.value()));
if (diff > threshold) {
++n;
max_diff = std::max (max_diff, diff);
}
}
}
double& largest_diff;
size_t& count;
const double tol;
double max_diff;
size_t n;
};
ThreadedLoop (in1, 0, 3).run (RunKernel (largest_diff, count, tol), in1, in2);
if (count)
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not match within " + str(tol) + " of maximal voxel value"
+ " (" + str(count) + " voxels over threshold, maximum per-voxel relative difference = " + str(largest_diff) + ")");
}
else { // frac or abs:
struct RunKernel { NOMEMALIGN
RunKernel (double& largest_diff, size_t& count, double tol, bool fractional) :
largest_diff (largest_diff), count (count), tol (tol), fractional (fractional), max_diff (0.0), n (0) { }
~RunKernel() { largest_diff = std::max (largest_diff, max_diff); count += n; }
void operator() (const decltype(in1)& a, const decltype(in2)& b) {
auto diff = std::abs (a.value() - b.value());
if (fractional)
diff /= 0.5 * std::abs (a.value() + b.value());
if (diff > tol) {
++n;
max_diff = std::max (max_diff, diff);
}
}
double& largest_diff;
size_t& count;
const double tol;
const bool fractional;
double max_diff;
size_t n;
};
ThreadedLoop (in1).run (RunKernel (largest_diff, count, tol, fractional), in1, in2);
if (count)
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not match within "
+ ( fractional ? "relative" : "absolute" ) + " precision of " + str(tol)
+ " (" + str(count) + " voxels over threshold, maximum absolute difference = " + str(largest_diff) + ")");
}
CONSOLE ("data checked OK");
}
<commit_msg>testing_diff_data: fix memalign<commit_after>
/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/06/08.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "datatype.h"
#include "image.h"
#include "algo/loop.h"
#include "algo/threaded_loop.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "J-Donald Tournier ([email protected]) and David Raffelt ([email protected]) and Robert E. Smith ([email protected])";
DESCRIPTION
+ "compare two images for differences, optionally with a specified tolerance.";
ARGUMENTS
+ Argument ("data1", "an image.").type_image_in()
+ Argument ("data2", "another image.").type_image_in()
+ Argument ("tolerance", "the tolerance value (default = 0.0).").type_float(0.0).optional();
OPTIONS
+ Option ("abs", "test for absolute difference (the default)")
+ Option ("frac", "test for fractional absolute difference")
+ Option ("voxel", "test for fractional absolute difference relative to the maximum value in the voxel");
}
void run ()
{
auto in1 = Image<cdouble>::open (argument[0]);
auto in2 = Image<cdouble>::open (argument[1]);
check_dimensions (in1, in2);
for (size_t i = 0; i < in1.ndim(); ++i) {
if (std::isfinite (in1.size(i)))
if (in1.size(i) != in2.size(i))
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not have matching voxel spacings " +
str(in1.size(i)) + " vs " + str(in2.size(i)));
}
for (size_t i = 0; i < 3; ++i) {
for (size_t j = 0; j < 4; ++j) {
if (std::abs (in1.transform().matrix()(i,j) - in2.transform().matrix()(i,j)) > 0.001)
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not have matching header transforms "
+ "\n" + str(in1.transform().matrix()) + "vs \n " + str(in2.transform().matrix()) + ")");
}
}
const double tol = argument.size() == 3 ? argument[2] : 0.0;
const bool absolute = get_options ("abs").size();
const bool fractional = get_options ("frac").size();
const bool per_voxel = get_options ("voxel").size();
double largest_diff = 0.0;
size_t count = 0;
if (absolute + fractional + per_voxel > 1)
throw Exception ("options \"-abs\", \"-frac\", and \"-voxel\" are mutually exclusive");
// per-voxel:
if (per_voxel) {
if (in1.ndim() != 4)
throw Exception ("Option -voxel only works for 4D images");
struct RunKernel { NOMEMALIGN
RunKernel (double& largest_diff, size_t& count, double tol) :
largest_diff (largest_diff), count (count), tol (tol), max_diff (0.0), n (0) { }
void operator() (decltype(in1)& a, decltype(in2)& b) {
double maxa = 0.0, maxb = 0.0;
for (auto l = Loop(3) (a, b); l; ++l) {
maxa = std::max (maxa, std::abs (cdouble(a.value())));
maxb = std::max (maxb, std::abs (cdouble(b.value())));
}
const double threshold = tol * 0.5 * (maxa + maxb);
for (auto l = Loop(3) (a, b); l; ++l) {
auto diff = std::abs (cdouble (a.value()) - cdouble (b.value()));
if (diff > threshold) {
++n;
max_diff = std::max (max_diff, diff);
}
}
}
double& largest_diff;
size_t& count;
const double tol;
double max_diff;
size_t n;
};
ThreadedLoop (in1, 0, 3).run (RunKernel (largest_diff, count, tol), in1, in2);
if (count)
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not match within " + str(tol) + " of maximal voxel value"
+ " (" + str(count) + " voxels over threshold, maximum per-voxel relative difference = " + str(largest_diff) + ")");
}
else { // frac or abs:
struct RunKernel { NOMEMALIGN
RunKernel (double& largest_diff, size_t& count, double tol, bool fractional) :
largest_diff (largest_diff), count (count), tol (tol), fractional (fractional), max_diff (0.0), n (0) { }
~RunKernel() { largest_diff = std::max (largest_diff, max_diff); count += n; }
void operator() (const decltype(in1)& a, const decltype(in2)& b) {
auto diff = std::abs (a.value() - b.value());
if (fractional)
diff /= 0.5 * std::abs (a.value() + b.value());
if (diff > tol) {
++n;
max_diff = std::max (max_diff, diff);
}
}
double& largest_diff;
size_t& count;
const double tol;
const bool fractional;
double max_diff;
size_t n;
};
ThreadedLoop (in1).run (RunKernel (largest_diff, count, tol, fractional), in1, in2);
if (count)
throw Exception ("images \"" + in1.name() + "\" and \"" + in2.name() + "\" do not match within "
+ ( fractional ? "relative" : "absolute" ) + " precision of " + str(tol)
+ " (" + str(count) + " voxels over threshold, maximum absolute difference = " + str(largest_diff) + ")");
}
CONSOLE ("data checked OK");
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.