blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bf5b4316ed47d5b68f0e24393e30e5bf913fb84d | 675b8850fd356cc5b753ca5e400d0997c1ddd3e2 | /SDK/PUBG_WindowsFileUtility_classes.hpp | c9e2ddf1b214b6648baa373fb134c14a4e1bd4bb | [] | no_license | Sheisback/PUBG-SDK | ebc18c0a1f5aef90615ea6ee1d3a5e76301414cf | c6ac4239cbcf524354d8df259ecc896693c7f59c | refs/heads/master | 2021-05-24T07:23:38.505271 | 2020-04-05T11:10:24 | 2020-04-05T11:10:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,318 | hpp | #pragma once
// PUBG (7.1.6.5) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_WindowsFileUtility_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class WindowsFileUtility.WFUFileListInterface
// 0x0000 (0x0028 - 0x0028)
class UWFUFileListInterface : public UInterface
{
public:
static UClass* StaticClass()
{
static UClass* ptr;
if(!ptr)
ptr = UObject::FindClass(_xor_("Class WindowsFileUtility.WFUFileListInterface"));
return ptr;
}
void OnListFileFound(struct FString* Filename, int* ByteCount, struct FString* FilePath);
void OnListDone(struct FString* DirectoryPath, TArray<struct FString>* Files, TArray<struct FString>* Folders);
void OnListDirectoryFound(struct FString* DirectoryName, struct FString* FilePath);
};
// Class WindowsFileUtility.WFUFileListLambdaDelegate
// 0x0058 (0x0080 - 0x0028)
class UWFUFileListLambdaDelegate : public UObject
{
public:
unsigned char UnknownData00[0x58]; // 0x0028(0x0058) MISSED OFFSET
static UClass* StaticClass()
{
static UClass* ptr;
if(!ptr)
ptr = UObject::FindClass(_xor_("Class WindowsFileUtility.WFUFileListLambdaDelegate"));
return ptr;
}
};
// Class WindowsFileUtility.WFUFolderWatchInterface
// 0x0000 (0x0028 - 0x0028)
class UWFUFolderWatchInterface : public UInterface
{
public:
static UClass* StaticClass()
{
static UClass* ptr;
if(!ptr)
ptr = UObject::FindClass(_xor_("Class WindowsFileUtility.WFUFolderWatchInterface"));
return ptr;
}
void OnFileChanged(struct FString* Filename, struct FString* FilePath);
void OnDirectoryChanged(struct FString* DirectoryName, struct FString* DirectoryPath);
};
// Class WindowsFileUtility.WFUFolderWatchLambdaDelegate
// 0x0058 (0x0080 - 0x0028)
class UWFUFolderWatchLambdaDelegate : public UObject
{
public:
unsigned char UnknownData00[0x58]; // 0x0028(0x0058) MISSED OFFSET
static UClass* StaticClass()
{
static UClass* ptr;
if(!ptr)
ptr = UObject::FindClass(_xor_("Class WindowsFileUtility.WFUFolderWatchLambdaDelegate"));
return ptr;
}
};
// Class WindowsFileUtility.WindowsFileUtilityFunctionLibrary
// 0x0000 (0x0028 - 0x0028)
class UWindowsFileUtilityFunctionLibrary : public UBlueprintFunctionLibrary
{
public:
static UClass* StaticClass()
{
static UClass* ptr;
if(!ptr)
ptr = UObject::FindClass(_xor_("Class WindowsFileUtility.WindowsFileUtilityFunctionLibrary"));
return ptr;
}
void STATIC_WatchFolder(struct FString* FullPath, class UObject** WatcherDelegate);
void STATIC_StopWatchingFolder(struct FString* FullPath, class UObject** WatcherDelegate);
bool STATIC_MoveFileTo(struct FString* From, struct FString* To);
void STATIC_ListContentsOfFolder(struct FString* FullPath, class UObject** ListDelegate);
bool STATIC_DeleteFolderRecursively(struct FString* FullPath);
bool STATIC_DeleteFileAt(struct FString* FullPath);
bool STATIC_DeleteEmptyFolder(struct FString* FullPath);
bool STATIC_CreateDirectoryAt(struct FString* FullPath);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"1263178881@qq.com"
] | 1263178881@qq.com |
af9fe9c4918fc10da630e61f2ec8a261a7370b12 | 9d6a017813b545f085015ec4f8446c3ed49313c6 | /jump-game/jump-game.cpp | d906c87c8f7f878033c599c6b63214ee48e2c5cc | [] | no_license | Manish-dracule/Leetcode-solutions | 4a3f6c88f4819be46292ef942a7ac919ba367679 | 99289c91882024e3cd7cd4cc1506fc08337316af | refs/heads/main | 2023-02-15T17:02:05.532527 | 2021-01-11T13:11:34 | 2021-01-11T13:11:34 | 326,438,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | cpp | class Solution {
public:
bool canJump(vector<int>& nums) {
int n=nums.size();
int maxi=0;
for(int i=0;i<n;i++){
if(maxi>=n-1)return true;
if(i>maxi)return false;
maxi=max(maxi,i+nums[i]);
}
return false;
}
};
| [
"68863157+Manish-dracule@users.noreply.github.com"
] | 68863157+Manish-dracule@users.noreply.github.com |
4b8e128be05623372accca3e070c8303be570497 | 1dd62168b38a5044949138d107fc31063b3a1f5b | /tomatotask.cpp | d93d3d7ae5bfbdc225a7cc79ef4b0885dd85b715 | [] | no_license | albert2lyu/TomatoWorkflow | 7e62b9567774d6461473d408edcad067f2675967 | 54c04235bdf45b4b6d65afb33797d9e0386d43f6 | refs/heads/master | 2020-04-23T01:47:59.967367 | 2017-02-23T10:27:22 | 2017-02-23T10:27:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56 | cpp | #include "tomatotask.h"
TomatoTask::TomatoTask()
{
}
| [
"banguijun@sina.com"
] | banguijun@sina.com |
a6467ca4afcc1615c249d5105b9f7194c363d0bb | 463f7deea1c29d3bc4c20777f2b4f0f54d958967 | /Lab1/Lab1/Lab1.cpp | 15e0b90da55fbfa6251214b815d3daa862568646 | [] | no_license | jzxhuang/ECE250 | e54d6986d5c3d33923b643c13acb888dc596bf88 | 6d884ca5d27e3aef55c0a2f7c6540b7e586fd082 | refs/heads/master | 2021-07-14T01:26:36.987948 | 2017-10-18T23:39:11 | 2017-10-18T23:39:11 | 105,413,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,790 | cpp | // Lab1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <exception>
#include "Dynamic_stack.h"
using namespace std;
int main()
{
Dynamic_stack stack;
Dynamic_stack stack2(20);
Dynamic_stack stack3(0);
cout << "Stack 1 size: " << stack.size() << endl << "Capcity: " << stack.capacity() << endl;
cout << "Stack 2 size: " << stack2.size() << endl << "Capacity: "<< stack2.capacity() << endl;
cout << "Stack 3 size: " << stack3.size() << endl << "Capacity: " << stack3.capacity() << endl;
try {
stack3.top();
}
catch (underflow &e)
{
cout << "Error: Underflow" << endl;
}
stack.push(3);
stack.push(5);
stack3.push(1);
cout << "stack 3 top " << stack3.top() << "stack 3 capacity " << stack3.capacity() << endl;
stack3.push(4);
cout << "stack 3 top " << stack3.top() << "stack 3 size " << stack3.size() << "stack 3 capcaity" << stack3.capacity() << endl;
try {
stack3.pop();
}
catch (underflow &e)
{
cout << "Error: Underflow" << endl;
}
try {
cout << stack3.top() << endl;
}
catch (underflow &e) {
cout << "Error: Underflow" << endl;
}
try {
stack3.pop();
}
catch (underflow &e)
{
cout << "Error: Underflow" << endl;
}
try {
cout << stack3.top() << endl;
}
catch (underflow &e) {
cout << "Error: Underflow" << endl;
}
try {
stack3.pop();
}
catch (underflow &e)
{
cout << "Error: Underflow" << endl;
}
stack3.push(6);
try {
cout << stack3.top() << endl;
}
catch (underflow &e) {
cout << "Error: Underflow" << endl;
}
stack3.clear();
cout << stack3.capacity() << " " << stack3.empty() << " " << stack3.size() << " " << endl;
try {
cout << stack3.top() << endl;
}
catch (underflow &e) {
cout << "Error: Underflow" << endl;
}
return 0;
}
| [
"jeff.huang62@gmail.com"
] | jeff.huang62@gmail.com |
b3539308f0039a238a38d083b18efb3f814a9cfa | e99bae4e1c4ab2d3ec29ddceb1eee1207daa40e6 | /CodeTemplates /stanlgo/bit1.cpp | 1a8fb5b7acd0adfe4265dc6d4f546978458e0e64 | [] | no_license | ashmanmode/BitsAndBytes | 083590c4ad22682d1156e090dc1f558ced9926de | 6dffbb18ddbf04245d1cbe453ea975fed76a9969 | refs/heads/master | 2021-05-01T04:55:30.304918 | 2017-03-21T08:19:30 | 2017-03-21T08:19:30 | 70,502,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cpp | #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define maxsiz 1000000
#define F first
#define S second
#define si(a) scanf("%d",&a)
#define sl(a) scanf("%llu",&a)
#define pi(a) printf("%d",a)
#define pl(a) printf("%llu",a)
#define fr(i,k,n) for(int i = k ; i < n ; i++ )
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define printvect(a,n) fr(i,0,n) cout << a[i] << " " ;
typedef unsigned long long int ull;
int main()
{
ull a;
sl(a);
if(a == 1)
cout << 1 << endl;
else if(a==2)
cout << 6 << endl;
else
{
ull ans = ((a%mod)*( (a+1)%mod ))%mod ;
//a -= 2 ;
ull b = a-2;
ull p = 1;
ull a1 = 2;
while (b > 0)
{
if (b%2==1)
{
p *= a1;
p = p%mod;
}
b /= 2;
a1 = (a1 * a1)% mod;
}
p = p%mod ;
ans = ( p*ans )%mod;
cout << ans << endl ;
}
}
| [
"ash.manmode@gmail.com"
] | ash.manmode@gmail.com |
36ca21068ed668e815086cfde0f635296f2d2e8f | feef586dab1e9562a62efd955aeb587c5a7a2c60 | /src/avd_turtle3/hello.cpp | 9a47516f16f061a476c9a1ef241c5b812d433d41 | [] | no_license | avd5146/avd_ws | 690c758bc42af4ad965c80eafc9bf547cec94319 | e667f886c5e00d9a1730edcdd640555d036a3a17 | refs/heads/master | 2021-01-17T07:20:54.700225 | 2017-08-15T03:19:54 | 2017-08-15T03:19:54 | 83,702,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 228 | cpp | #include <ros/ros.h>
int main()
{
printf("Hello");
printf("Hello");
printf("Hello");
printf("Hello");
printf("\n");
printf("Hello");
printf("Hello");
printf("Hello");
printf("Hello");
//printf("Hello");
return 0;
}
| [
"ankur.dalal@mavs.uta.edu"
] | ankur.dalal@mavs.uta.edu |
0de3fd195ddbff1dd3a9cbe67479f7ece1ee418e | 2351c922fbee24a3856d885fc70263dae58a9eb0 | /src/princekin/xlsxinfo/xlsxinfo.cpp | f3f779f4fd6d2bb15d29086c6fc749d753376e0e | [] | no_license | waitMonster/android | dc4298c9e4827389e24782a9dfa33c7dab84eae1 | 6f9b223ba330ff3bb22e048348df1309930c31b0 | refs/heads/master | 2021-08-16T15:42:39.163958 | 2017-11-17T10:47:20 | 2017-11-17T10:47:20 | 111,359,369 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,889 | cpp | #include "xlsxinfo.h"
XlsxInfo::XlsxInfo()
{
}
void XlsxInfo::copyFile(const QString &arg_source, const QString &arg_target)
{
QFile::copy(arg_source,arg_target);
}
QString XlsxInfo::getApkName()
{
QString apkName;
QString filePath;
QStringList strList;
QStringList splitResult;
apkName="";
filePath=gConfigDir + QDir::separator() + "install-apk-name.txt";
strList=Helper::getList(filePath);
if(!strList.isEmpty())
{
apkName=strList.at(0);//sohuvideo.apk
splitResult=apkName.split(".");
}
return apkName;
}
QString XlsxInfo::getIconResPath(const QString &arg_apkName)
{
QString filePath;
QString tagName;
QString cmdLine;
QString iconResPath;
QStringList valueList;
tagName="application:";
filePath=gApkDir + QDir::separator() + arg_apkName;
cmdLine="cmd /c aapt dump badging " + filePath + " | findstr application:";
valueList=ExeCmd::runCmd_getAppName(cmdLine,tagName);
if(valueList.size()>=4)
{
iconResPath=valueList.at(3);
}
return iconResPath;
}
QString XlsxInfo::getAppChineseName(const QString &arg_apkName)
{
QString filePath;
QString tagName;
QString cmdLine;
QString appChineseName;
QStringList valueList;
tagName="application:";
filePath=gApkDir + QDir::separator() + arg_apkName;
cmdLine="cmd /c aapt dump badging " + filePath + " | findstr application:";
valueList=ExeCmd::runCmd_getAppName(cmdLine,tagName);
if(valueList.size()>=4)
{
appChineseName=valueList.at(1);
}
return appChineseName;
}
QString XlsxInfo::getAppVersion(const QString &arg_apkName)
{
QString filePath;
QString tagName;
QString cmdLine;
QString appVersion;
tagName="versionName=";
filePath=gApkDir + QDir::separator() + arg_apkName;
cmdLine="cmd /c aapt dump badging " + filePath + " | findstr versionName=";
appVersion=ExeCmd::runCmd_getVersionName(cmdLine,tagName);
return appVersion;
}
QString XlsxInfo::getAppSize(const QString &arg_apkName)
{
QString filePath;
QString fileSize;
filePath=gApkDir + QDir::separator() + arg_apkName;
QFileInfo info(filePath);
qint64 m=info.size();
int x=m/1024/1024;
fileSize=QString::number(x);
return fileSize;
}
QString XlsxInfo::getDate()
{
QString time;
QDateTime currentTime=QDateTime::currentDateTime();
time=currentTime.toString("yyyy/MM/dd");
return time;
}
QString XlsxInfo::getPlatform()
{
return "android";
}
QString XlsxInfo::getMobileBrand(const QString &arg_deviceId)
{
QString brand;
QString chineseBrand;
QString filePath;
QString cmdLine;
QHash<QString,QString> bradHash;
//lenovo=联想
filePath=gConfigDir + QDir::separator() + "brand.txt";
bradHash=Helper::getBrand(filePath);
cmdLine="adb -s " + arg_deviceId + " shell getprop ro.product.brand";
brand=ExeCmd::runCmd_getProp(cmdLine);
chineseBrand=bradHash.value(brand);//中国
return chineseBrand;
}
QString XlsxInfo::getMobileModel(const QString &arg_deviceId)
{
QString cmdLine;
QString model;
cmdLine="adb -s " + arg_deviceId + " shell getprop ro.product.model";
model=ExeCmd::runCmd_getModel(cmdLine);//Lenovo_K920
return model;
}
QString XlsxInfo::getMobileVersion(const QString &arg_deviceId)
{
QString cmdLine;
QString version;
cmdLine="adb -s " + arg_deviceId + " shell getprop ro.build.version.release";
version=ExeCmd::runCmd_getProp(cmdLine);//"4.4.2"
return version;
}
QString XlsxInfo::getMobileVmsize(const QString &arg_deviceId)
{
QString cmdLine;
QString wmSize;
cmdLine="adb -s " + arg_deviceId + " shell wm size";
wmSize=ExeCmd::runCmd_getWmsize(cmdLine);
return wmSize;
}
QString XlsxInfo::getIconPath(const QString &arg_apkName,const QString &arg_iconResPath)
{
QString cmdLine;
QString apkBaseName;
QString iconPath;
QString filePath;
QString apkPngDir="";
QStringList splitResult;
splitResult=arg_apkName.split(".");
apkBaseName=splitResult.at(0);
splitResult=arg_iconResPath.split("/");
int len=splitResult.size();
for(int i=0;i<len-1;i++)
{
apkPngDir=apkPngDir+splitResult.at(i)+"\\";
}
apkPngDir=apkPngDir+splitResult.at(len-1);
iconPath=gApkDir+QDir::separator() + apkBaseName + QDir::separator() + arg_iconResPath;
iconPath=QDir::toNativeSeparators(iconPath);
QFile f(iconPath);
if(f.exists())
{
//如果存在,不用解压
}
else
{
QString saveDir=gApkDir + QDir::separator() + apkBaseName;
Helper::createPath(saveDir);
filePath=gApkDir + QDir::separator() + arg_apkName;
cmdLine="WinRAR x -ibck -o+ " + filePath + " " + apkPngDir + " " + saveDir;
ExeCmd::runCmd(cmdLine);
}
return iconPath;
}
| [
"chorushechang@126.com"
] | chorushechang@126.com |
4a77dc1b5f6bc2e1ea22ac2e1edcea983e8930b9 | 4f0fc889b8f53a446d13bfc291858d3b882ffb66 | /libraries/chain/include/enudex/chain/assert_evaluator.hpp | b0142d0b341eb0c0bcfd9db337411dac0b9a4aab | [
"MIT"
] | permissive | hwlsniper/enudex-core | 8492c90a895c3c4459fac2e465e230efe2d306b9 | 6a01603557e1ab83446a492b4eec4cc3c446f1e0 | refs/heads/master | 2021-04-05T23:54:58.221979 | 2018-03-11T02:07:57 | 2018-03-11T02:07:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,622 | hpp | /*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <enudex/chain/protocol/operations.hpp>
#include <enudex/chain/evaluator.hpp>
#include <enudex/chain/database.hpp>
namespace enudex { namespace chain {
class assert_evaluator : public evaluator<assert_evaluator>
{
public:
typedef assert_operation operation_type;
void_result do_evaluate( const assert_operation& o );
void_result do_apply( const assert_operation& o );
};
} } // enudex::chain
| [
"admin@enumivo.org"
] | admin@enumivo.org |
9260e944436354e9905c9ab2316904dde69b9b76 | 2d5a651995ca6ba53b169b5e58ef75159715e886 | /Source/Core/Numeric/SVDecomposer.cpp | 17e28aa64c0fbcb8c468219e07e0a04676e62542 | [
"BSD-3-Clause"
] | permissive | GoTamura/KVS | 4a4aabd5dac5c5362b7404f4d9b50ae33bb0cbb6 | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | refs/heads/develop | 2021-06-12T05:27:34.959934 | 2019-04-11T23:57:26 | 2019-04-11T23:57:26 | 181,405,935 | 0 | 0 | BSD-3-Clause | 2019-04-15T03:29:11 | 2019-04-15T03:29:09 | null | UTF-8 | C++ | false | false | 17,128 | cpp | /*****************************************************************************/
/**
* @file SVDecomposer.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id: SVDecomposer.cpp 1385 2012-12-04 03:25:29Z naohisa.sakamoto@gmail.com $
*/
/*****************************************************************************/
#include "SVDecomposer.h"
#include <cmath>
#include <kvs/Macro>
#include <kvs/Math>
namespace kvs
{
template <typename T> size_t SVDecomposer<T>::m_max_iterations = 30;
/*===========================================================================*/
/**
* @brief Sets a maximum number of iterations.
* @param max_iterations [in] maximum number of iterations
*/
/*===========================================================================*/
template <typename T>
void SVDecomposer<T>::SetMaxIterations( const size_t max_iterations )
{
m_max_iterations = max_iterations;
}
/*===========================================================================*/
/**
* @brief Constructs a new SVDecomposer class.
*/
/*===========================================================================*/
template <typename T>
SVDecomposer<T>::SVDecomposer()
{
}
/*===========================================================================*/
/**
* @brief Constructs a new SVDecomposer class.
* @param m [in] 3x3 matrix
*/
/*===========================================================================*/
template <typename T>
SVDecomposer<T>::SVDecomposer( const kvs::Matrix33<T>& m )
{
this->setMatrix( m );
this->decompose();
}
/*===========================================================================*/
/**
* @brief Constructs a new SVDecomposer class.
* @param m [in] 4x4 matrix
*/
/*===========================================================================*/
template <typename T>
SVDecomposer<T>::SVDecomposer( const kvs::Matrix44<T>& m )
{
this->setMatrix( m );
this->decompose();
}
/*===========================================================================*/
/**
* @brief Constructs a new SVDecomposer class.
* @param m [in] MxM matrix
*/
/*===========================================================================*/
template <typename T>
SVDecomposer<T>::SVDecomposer( const Matrix<T>& m )
{
this->setMatrix( m );
this->decompose();
}
/*===========================================================================*/
/**
* @brief '=' operator for the SVDecomposer class.
* @param s [in] SVDecomposer
*/
/*===========================================================================*/
template <typename T>
SVDecomposer<T>& SVDecomposer<T>::operator = ( const SVDecomposer<T>& s )
{
m_u = s.m_u;
m_w = s.m_w;
m_v = s.m_v;
return( *this );
}
/*===========================================================================*/
/**
* @brief Returns the U matrix.
* @return U matrix
*/
/*===========================================================================*/
template <typename T>
const kvs::Matrix<T>& SVDecomposer<T>::U() const
{
return( m_u );
}
/*===========================================================================*/
/**
* @brief Returns the W vector.
* @return W vector
*/
/*===========================================================================*/
template <typename T>
const kvs::Vector<T>& SVDecomposer<T>::W() const
{
return( m_w );
}
/*===========================================================================*/
/**
* @brief Returns the V matrix.
* @return V matrix
*/
/*===========================================================================*/
template <typename T>
const kvs::Matrix<T>& SVDecomposer<T>::V() const
{
return( m_v );
}
/*===========================================================================*/
/**
* @brief Returns the left singular matrix.
* @return left singular matrix
*/
/*===========================================================================*/
template <typename T>
const kvs::Matrix<T>& SVDecomposer<T>::leftSingularMatrix() const
{
return( m_u );
}
/*===========================================================================*/
/**
* @brief Returns the singular values.
* @return singular values
*/
/*===========================================================================*/
template <typename T>
const kvs::Vector<T>& SVDecomposer<T>::singularValues() const
{
return( m_w );
}
/*===========================================================================*/
/**
* @brief Returns the right singular matrix.
* @return right singular matrix
*/
/*===========================================================================*/
template <typename T>
const kvs::Matrix<T>& SVDecomposer<T>::rightSingularMatrix() const
{
return( m_v );
}
/*===========================================================================*/
/**
* @brief Sets a 3x3 matrix.
* @param m [in] 3x3 matrix
*/
/*===========================================================================*/
template <typename T>
void SVDecomposer<T>::setMatrix( const kvs::Matrix33<T>& m )
{
m_w.setSize( 3 );
m_v.setSize( 3, 3 );
m_u.setSize( 3, 3 );
for ( size_t i = 0; i < 3; i++ )
{
for ( size_t j = 0; j < 3; j++ )
{
m_u[i][j] = m[i][j];
}
}
}
/*===========================================================================*/
/**
* @brief Sets a 4x4 matrix.
* @param m [in] 4x4 matrix
*/
/*===========================================================================*/
template <typename T>
void SVDecomposer<T>::setMatrix( const kvs::Matrix44<T>& m )
{
m_w.setSize( 4 );
m_v.setSize( 4, 4 );
m_u.setSize( 4, 4 );
for ( size_t i = 0; i < 4; i++ )
{
for ( size_t j = 0; j < 4; j++ )
{
m_u[i][j] = m[i][j];
}
}
}
/*===========================================================================*/
/**
* @brief Sets a MxM matrix.
* @param m [in] MxM matrix
*/
/*===========================================================================*/
template <typename T>
void SVDecomposer<T>::setMatrix( const Matrix<T>& m )
{
m_u = m;
m_w.setSize( m.columnSize() );
m_v.setSize( m.columnSize(), m.columnSize() );
}
/*===========================================================================*/
/**
* @brief Decompose.
*/
/*===========================================================================*/
template <typename T>
void SVDecomposer<T>::decompose()
{
int row = m_u.rowSize();
int column = m_u.columnSize();
kvs::Vector<T> rv1( column );
int l = 0;
int nm = 0;
int its;
int flag;
T c, f, h, s, x, y, z;
T g = T(0);
T scale = T(0);
T anorm = T(0);
// Householder reduction to bidiagonal form
for( int i = 0; i < column; i++ )
{
rv1[i] = scale * g;
l = i+1;
g = T(0);
scale = T(0);
s = T(0);
if( i < row )
{
for( int k = i; k < row; k++ ) scale += kvs::Math::Abs( m_u[k][i] );
if( !kvs::Math::IsZero( scale ) )
{
for( int k = i; k < row; k++ )
{
m_u[k][i] /= scale;
s += m_u[k][i] * m_u[k][i];
}// end of for-loop 'k'
f = m_u[i][i];
g = -kvs::Math::Sgn( static_cast<T>(std::sqrt((double)s)), f );
h = f * g - s ;
m_u[i][i] = f - g ;
for( int j = l; j < column; j++ )
{
s = T(0);
for( int k = i; k < row; k++ ) s += m_u[k][i] * m_u[k][j];
f = s / h ;
for( int k = i; k < row; k++ ) m_u[k][j] += f * m_u[k][i];
} // end of for-loop 'j'
for( int k = i ; k < row; k++ ) m_u[k][i] *= scale ;
} // if scale
} // if i <= m
m_w[i] = scale * g ;
g = s = scale = T(0);
if( i < row && i != ( column - 1 ) )
{
for( int k = l ; k < column; k++ ) scale += kvs::Math::Abs( m_u[i][k] ) ;
if( !kvs::Math::IsZero( scale ) )
{
for( int k = l; k < column; k++ )
{
m_u[i][k] /= scale ;
s += m_u[i][k] * m_u[i][k];
} // for k
f = m_u[i][l];
g = -kvs::Math::Sgn( static_cast<T>(std::sqrt((double)s)), f );
h = f * g - s ;
m_u[i][l] = f - g ;
for( int k = l; k < column; k++ ) rv1[k] = m_u[i][k] / h ;
for( int j = l; j < row; j++ )
{
s = T(0);
for( int k = l; k < column; k++ ) s += m_u[j][k] * m_u[i][k];
for( int k = l; k < column; k++ ) m_u[j][k] += s * rv1[k];
} // for j
for( int k = l; k < column; k++ ) m_u[i][k] *= scale;
} // if scale
} // if i != m && i != n
anorm = kvs::Math::Max( anorm, kvs::Math::Abs(m_w[i]) + kvs::Math::Abs(rv1[i]) );
} // for i
// Accumulation of right-hand transformations.
for( int i = column - 1; i >= 0; i-- )
{
if( i < column )
{
if( !kvs::Math::IsZero( g ) )
{
for( int j = l; j < column; j++ )
m_v[j][i] = ( m_u[i][j] / m_u[i][l] ) / g ;
// double division to reduce underflow
for( int j = l ; j < column; j++ )
{
s = T(0);
for( int k = l; k < column; k++ ) s += m_u[i][k] * m_v[k][j];
for( int k = l; k < column; k++ ) m_v[k][j] += s * m_v[k][i];
} // for j
} // if g
for( int j = l; j < column; j++ ) m_v[i][j] = m_v[j][i] = T(0);
} // if i < n
m_v[i][i] = T(1);
g = rv1[i];
l = i;
} // for i
for( int i = kvs::Math::Min( row, column ) - 1; i >= 0; i-- )
{
l = i + 1 ;
g = m_w[i] ;
for( int j = l; j < column; j++ ) m_u[i][j] = T(0);
if( !kvs::Math::IsZero( g ) )
{
g = T(1) / g ;
for( int j = l; j < column; j++ )
{
s = T(0);
for( int k = l; k < row; k++ ) s += m_u[k][i] * m_u[k][j];
f = ( s / m_u[i][i] ) * g;
for( int k = i; k < row; k++ ) m_u[k][j] += f * m_u[k][i];
} // for j
for( int j = i; j < row; j++ ) m_u[j][i] *= g ;
}
else
{
for( int j = i; j < row; j++ ) m_u[j][i] = T(0) ;
}
++ m_u[i][i];
} // for i
//Diagonalization of the bidiagonal form; Loop over
for( int k = column - 1; k >= 0; k-- )
{
// singular values, and over allowed iterations.
const int max_iterations = static_cast<int>( m_max_iterations );
for( its = 0 ; its < max_iterations; its++ )
{
// Test for splitting.
flag = 1;
for( l = k; l >= 0; l-- )
{
nm = l - 1 ; // Note that rv1[1] is always zero.
if( kvs::Math::Abs( rv1[l] ) + anorm == anorm )
{
flag = 0 ;
break;
}
if( kvs::Math::Abs( m_w[nm] ) + anorm == anorm ) break;
} // for l
if( flag )
{
c = T(0);
s = T(1);
for( int i = l; i <= k; i++ )
{
f = s * rv1[i];
rv1[i] = c * rv1[i];
if( kvs::Math::Abs( f ) + anorm == anorm ) break;
g = m_w[i];
h = kvs::Math::Pythag( f, g );
m_w[i] = h;
h = T(1) / h ;
c = g * h ;
s = -f * h;
for( int j = 0 ; j < row; j++ )
{
y = m_u[j][nm];
z = m_u[j][i];
m_u[j][nm] = y * c + z * s;
m_u[j][i] = z * c - y * s;
} // for j
} // for i
} // if flag
// Convergence
z = m_w[k];
if( l == k )
{
// singular value is made non negative.
if( z < T(0) )
{
m_w[k] = -z;
for ( int j = 0; j < column; j++ ) m_v[j][k] = -m_v[j][k];
} // if z < 0
break;
} // if l == k
// Not converged.
KVS_ASSERT( its != static_cast<int>( m_max_iterations - 1 ) );
x = m_w[l];
nm = k - 1 ;
y = m_w[nm] ;
g = rv1[nm] ;
h = rv1[k] ;
f = ( (y-z)*(y+z) + (g-h)*(g+h) ) / ( T(2) * h * y ) ;
g = kvs::Math::Pythag( f, T(1) );
f = ( (x-z)*(x+z) + h * ( ( y / ( f + kvs::Math::Sgn(g,f) ) ) - h ) ) / x ;
c = T(1);
s = T(1);
// Next QR transformation;
for( int j = l; j <= nm; j++ )
{
int i = j + 1 ;
g = rv1[i];
y = m_w[i];
h = s * g;
g = c * g;
z = kvs::Math::Pythag( f, h );
rv1[j] = z ;
c = f / z ;
s = h / z ;
f = x * c + g * s ;
g = g * c - x * s ;
h = y * s ;
y *= c;
for( int jj = 0; jj < column; jj++ )
{
x = m_v[jj][j];
z = m_v[jj][i];
m_v[jj][j] = x * c + z * s;
m_v[jj][i] = z * c - x * s;
} // for jj
z = kvs::Math::Pythag( f, h );
m_w[j] = z;
// Rotation can be arbitrary if z =0;
if( z )
{
z = T(1) / z;
c = f * z;
s = h * z;
} // if
f = ( c * g ) + ( s * y );
x = ( c * y ) - ( s * g );
for( int jj = 0; jj < row; jj++ )
{
y = m_u[jj][j];
z = m_u[jj][i];
m_u[jj][j] = y * c + z * s;
m_u[jj][i] = z * c - y * s;
} // for jj
} // for j
rv1[l] = T(0);
rv1[k] = f;
m_w[k] = x;
} // for its
} // for k
SVDecomposer<T>::sort( &m_u, &m_v, &m_w );
}
/*===========================================================================*/
/**
* @brief Sort the left singular matrix, right singular matrix and the singular values. (descending order)
* @param umat [out] pointer to the left singular matrix
* @param vmat [out] pointer to right singular matrix
* @param wvec [out] pointer to singular values
*/
/*===========================================================================*/
template <typename T>
void SVDecomposer<T>::sort( kvs::Matrix<T>* umat, kvs::Matrix<T>* vmat, kvs::Vector<T>* wvec )
{
int dim = umat->rowSize();
for( int k = 0; k < dim - 1; k++ )
{
// Search maximum value and index.
int max_index = k;
T max_value = (*wvec)[ max_index ];
for( int i = k + 1; i < dim; i++ )
{
if( (*wvec)[i] > max_value )
{
max_index = i;
max_value = (*wvec)[i];
}
}
// Swap the row-vector.
if( max_index != k )
{
(*wvec)[ max_index ] = (*wvec)[k];
(*wvec)[k] = max_value;
for( int j = 0; j < dim; j++ )
{
T temp_u = (*umat)[j][max_index];
(*umat)[j][max_index] = (*umat)[j][k];
(*umat)[j][k] = temp_u;
T temp_v = (*vmat)[j][max_index];
(*vmat)[j][max_index] = (*vmat)[j][k];
(*vmat)[j][k] = temp_v;
}
}
}
}
template <typename T>
void SVDecomposer<T>::correctSingularValues()
{
int column = m_u.columnSize();
// Editing of the singular values.
T w_max = m_w[0];
T w_min = w_max * T( KVS__MATH_TINY_VALUE );
for( int i = 0; i < column; i++ )
{
if( m_w[i] < w_min ) m_w[i] = T(0);
}
}
// template instantiation
template class SVDecomposer<float>;
template class SVDecomposer<double>;
} // end of namespace kvs
| [
"naohisa.sakamoto@gmail.com"
] | naohisa.sakamoto@gmail.com |
05f5f514c557eb53821d2306e2087c2be7b05e5b | 758624fa8ca121c885005c8e89873738262f6b36 | /calamity/src/utils/io/file.hpp | 559030dba3e06c3f0d836da7a8805da46ea5c12e | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ClayCore/calamity | 11bba42a20d60234d720a6c3830f19d5371da31e | ddc9226648e4457531db33c27d67229f6f538455 | refs/heads/master | 2023-07-12T09:21:23.700001 | 2021-08-21T13:05:21 | 2021-08-21T13:05:21 | 390,212,098 | 1 | 0 | BSD-3-Clause | 2021-08-15T10:27:18 | 2021-07-28T04:25:20 | C++ | UTF-8 | C++ | false | false | 174 | hpp | #pragma once
#include "zcommon.hpp"
namespace Calamity::File
{
std::optional<std::vector<std::string>> load_file(std::string file_path);
} // namespace Calamity::File
| [
"claymorealt@op.pl"
] | claymorealt@op.pl |
9a84f119614825741de750570c7cc209fb1ec409 | c99cdc49376de34f73543ddf21a5730ca45888fe | /11000.cpp | d36e8bc6d1fe9d30e5e5444ff7fbd42418317760 | [] | no_license | ParkSale/Boj | 6dda75b47bc5b0938f1756a56e2432f3a05f0ca6 | 5d98f8024a2bf84e3aa86c50de8cdd55466e51e1 | refs/heads/master | 2020-09-18T18:24:46.408515 | 2020-07-29T06:01:56 | 2020-07-29T06:01:56 | 224,163,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
struct info {
int x, y;
bool operator < (const info& a) const {
return y > a.y;
}
};
priority_queue<info> pq;
int N;
pii arr[200005];
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> N;
for (int i = 1, a, b; i <= N; i++) {
cin >> a >> b;
arr[i] = { a,b };
}
sort(arr + 1, arr + N + 1);
int ans = 0;
for (int i = 1; i <= N; i++) {
if (pq.empty()) {
pq.push({ arr[i].first, arr[i].second });
}
else {
int n = pq.top().y;
if (arr[i].first >= n) {
while (!pq.empty()) {
info p = pq.top();
if (p.y <= arr[i].first) {
pq.pop();
}
else break;
}
pq.push({ arr[i].first,arr[i].second });
}
else {
pq.push({ arr[i].first,arr[i].second });
}
}
ans = max(ans, (int)pq.size());
}
cout << ans;
} | [
"34956785+ParkSale@users.noreply.github.com"
] | 34956785+ParkSale@users.noreply.github.com |
a7ff318b2a28ca356096570cb1896f522f887b4c | d76f25f09c37703f17056db0c6a8f68d625b1b48 | /8_2021/23.08.2021/cpp_14.cpp | 824be4e3cffe20b2d95c26aa38896a8ede7715c3 | [] | no_license | kingmadridli/Staj_1 | a87fbed8bcbb4cb57f98fcafc824136b9c786c4a | 0e466f802dcec31961f67f24414f93092206288b | refs/heads/main | 2023-08-21T23:58:56.638234 | 2021-10-16T11:40:54 | 2021-10-16T11:40:54 | 400,750,623 | 0 | 0 | null | null | null | null | ISO-8859-9 | C++ | false | false | 673 | cpp | #include <iostream>
using namespace std;
// For Döngüsü
int main(){
/*
int a = 50;
int b = 30;
cout<<a++<<endl; // Önce yazdır sonra artır.
cout<<++b<<endl; // Önce artır sonra yazdır.
cout<<a; // artırılmış hali
*/
/*
int i;
for (i=1;i<=10;i++) // i, 1 den 10 kadar 1'er 'er artaracak şekilde döngüyü sağla
{
cout<<"Merhaba Dunya"<<endl;
}
*/
int a;
int i;
//cout<<"Bir sayi giriniz :"<<endl;
//cin>>a;
for (i=1;i<=10;i++)
{
cout<<"Bir sayi giriniz :"<<endl;
cin>>a;
if (a % 2 == 0)
{
cout<<"Cifttir "<<endl;
}
else
{
cout<<"Tektir. "<<endl;
}
}
}
| [
"59164210+kingmadridli@users.noreply.github.com"
] | 59164210+kingmadridli@users.noreply.github.com |
1a45f1f0f5c20fddee7093bb3f8213498d9697cf | d40c63146b7311db2e0f5aef61929f58f1dfd78d | /depends/src/subversion-1.9.7/subversion/bindings/javahl/native/SVNClient.cpp | 7801ea053896392fe63947f9b0fbd3f1abdc89d3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unicode",
"HPND-Markus-Kuhn",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"X11",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sleepingwit/jal123 | 4bce06c979067647420691daf9fb531f4d71bfd9 | 1bbbd4ac5b71e233a34f885c7e6bd2a74dfc6770 | refs/heads/master | 2020-03-15T15:58:19.413180 | 2018-05-15T09:40:46 | 2018-05-15T09:40:46 | 132,225,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61,042 | cpp | /**
* @copyright
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
* @endcopyright
*
* @file SVNClient.cpp
* @brief: Implementation of the SVNClient class
*/
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include "SVNClient.h"
#include "JNIUtil.h"
#include "CopySources.h"
#include "DiffSummaryReceiver.h"
#include "ClientContext.h"
#include "Prompter.h"
#include "RemoteSession.h"
#include "Pool.h"
#include "Targets.h"
#include "Revision.h"
#include "OutputStream.h"
#include "RevisionRange.h"
#include "VersionExtended.h"
#include "BlameCallback.h"
#include "ProplistCallback.h"
#include "LogMessageCallback.h"
#include "InfoCallback.h"
#include "PatchCallback.h"
#include "CommitCallback.h"
#include "StatusCallback.h"
#include "ChangelistCallback.h"
#include "ListCallback.h"
#include "ImportFilterCallback.h"
#include "JNIByteArray.h"
#include "CommitMessage.h"
#include "EnumMapper.h"
#include "StringArray.h"
#include "PropertyTable.h"
#include "DiffOptions.h"
#include "CreateJ.h"
#include "JNIStringHolder.h"
#include "svn_auth.h"
#include "svn_dso.h"
#include "svn_types.h"
#include "svn_client.h"
#include "svn_sorts.h"
#include "svn_time.h"
#include "svn_diff.h"
#include "svn_config.h"
#include "svn_io.h"
#include "svn_hash.h"
#include "svn_dirent_uri.h"
#include "svn_path.h"
#include "svn_utf.h"
#include "private/svn_subr_private.h"
#include "svn_private_config.h"
#include "ExternalItem.hpp"
#include "jniwrapper/jni_list.hpp"
#include "jniwrapper/jni_stack.hpp"
#include "jniwrapper/jni_string_map.hpp"
SVNClient::SVNClient(jobject jthis_in)
: m_lastPath("", pool), context(jthis_in, pool)
{
}
SVNClient::~SVNClient()
{
}
SVNClient *SVNClient::getCppObject(jobject jthis)
{
static jfieldID fid = 0;
jlong cppAddr = SVNBase::findCppAddrForJObject(jthis, &fid,
JAVAHL_CLASS("/SVNClient"));
return (cppAddr == 0 ? NULL : reinterpret_cast<SVNClient *>(cppAddr));
}
void SVNClient::dispose(jobject jthis)
{
static jfieldID fid = 0;
SVNBase::dispose(jthis, &fid, JAVAHL_CLASS("/SVNClient"));
}
jobject SVNClient::getVersionExtended(bool verbose)
{
JNIEnv *const env = JNIUtil::getEnv();
jclass clazz = env->FindClass(JAVAHL_CLASS("/types/VersionExtended"));
if (JNIUtil::isJavaExceptionThrown())
return NULL;
static volatile jmethodID ctor = 0;
if (!ctor)
{
ctor = env->GetMethodID(clazz, "<init>", "()V");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
static volatile jfieldID fid = 0;
if (!fid)
{
fid = env->GetFieldID(clazz, "cppAddr", "J");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
jobject j_ext_info = env->NewObject(clazz, ctor);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
VersionExtended *vx = new VersionExtended(verbose);
env->SetLongField(j_ext_info, fid, vx->getCppAddr());
env->DeleteLocalRef(clazz);
return j_ext_info;
}
jstring SVNClient::getAdminDirectoryName()
{
SVN::Pool subPool(pool);
jstring name =
JNIUtil::makeJString(svn_wc_get_adm_dir(subPool.getPool()));
if (JNIUtil::isJavaExceptionThrown())
return NULL;
return name;
}
jboolean SVNClient::isAdminDirectory(const char *name)
{
SVN::Pool subPool(pool);
return svn_wc_is_adm_dir(name, subPool.getPool()) ? JNI_TRUE : JNI_FALSE;
}
const char *SVNClient::getLastPath()
{
return m_lastPath.c_str();
}
/**
* List directory entries of a URL.
*/
void SVNClient::list(const char *url, Revision &revision,
Revision &pegRevision, svn_depth_t depth,
int direntFields, bool fetchLocks,
ListCallback *callback)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_NULL_PTR_EX(url, "path or url", );
Path urlPath(url, subPool);
SVN_JNI_ERR(urlPath.error_occurred(), );
SVN_JNI_ERR(svn_client_list3(urlPath.c_str(),
pegRevision.revision(),
revision.revision(),
depth,
direntFields,
fetchLocks,
FALSE, // include_externals
ListCallback::callback,
callback,
ctx, subPool.getPool()), );
}
void
SVNClient::status(const char *path, svn_depth_t depth,
bool onServer, bool onDisk, bool getAll,
bool noIgnore, bool ignoreExternals,
bool depthAsSticky, StringArray &changelists,
StatusCallback *callback)
{
SVN::Pool subPool(pool);
svn_revnum_t youngest = SVN_INVALID_REVNUM;
svn_opt_revision_t rev;
SVN_JNI_NULL_PTR_EX(path, "path", );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
callback->setWcCtx(ctx->wc_ctx);
Path checkedPath(path, subPool);
SVN_JNI_ERR(checkedPath.error_occurred(), );
rev.kind = svn_opt_revision_unspecified;
SVN_JNI_ERR(svn_client_status6(&youngest, ctx, checkedPath.c_str(),
&rev, depth,
getAll, onServer, onDisk,
noIgnore, ignoreExternals, depthAsSticky,
changelists.array(subPool),
StatusCallback::callback, callback,
subPool.getPool()), );
}
/* Convert a vector of revision ranges to an APR array of same. */
static apr_array_header_t *
rev_range_vector_to_apr_array(std::vector<RevisionRange> &revRanges,
SVN::Pool &subPool)
{
apr_array_header_t *ranges =
apr_array_make(subPool.getPool(),
static_cast<int>(revRanges.size()),
sizeof(svn_opt_revision_range_t *));
std::vector<RevisionRange>::const_iterator it;
for (it = revRanges.begin(); it != revRanges.end(); ++it)
{
const svn_opt_revision_range_t *range = it->toRange(subPool);
if (range->start.kind == svn_opt_revision_unspecified
&& range->end.kind == svn_opt_revision_unspecified)
{
svn_opt_revision_range_t *full =
reinterpret_cast<svn_opt_revision_range_t *>
(apr_pcalloc(subPool.getPool(), sizeof(*range)));
full->start.kind = svn_opt_revision_number;
full->start.value.number = 1;
full->end.kind = svn_opt_revision_head;
full->end.value.number = 0;
APR_ARRAY_PUSH(ranges, const svn_opt_revision_range_t *) = full;
}
else
{
APR_ARRAY_PUSH(ranges, const svn_opt_revision_range_t *) = range;
}
if (JNIUtil::isExceptionThrown())
return NULL;
}
return ranges;
}
void SVNClient::logMessages(const char *path, Revision &pegRevision,
std::vector<RevisionRange> &logRanges,
bool stopOnCopy, bool discoverPaths,
bool includeMergedRevisions, StringArray &revProps,
int limit, LogMessageCallback *callback)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Targets target(path, subPool);
const apr_array_header_t *targets = target.array(subPool);
SVN_JNI_ERR(target.error_occurred(), );
apr_array_header_t *ranges =
rev_range_vector_to_apr_array(logRanges, subPool);
if (JNIUtil::isExceptionThrown())
return;
SVN_JNI_ERR(svn_client_log5(targets, pegRevision.revision(), ranges,
limit, discoverPaths, stopOnCopy,
includeMergedRevisions,
revProps.array(subPool),
LogMessageCallback::callback, callback, ctx,
subPool.getPool()), );
}
jlong SVNClient::checkout(const char *moduleName, const char *destPath,
Revision &revision, Revision &pegRevision,
svn_depth_t depth, bool ignoreExternals,
bool allowUnverObstructions)
{
SVN::Pool subPool;
SVN_JNI_NULL_PTR_EX(moduleName, "moduleName", -1);
SVN_JNI_NULL_PTR_EX(destPath, "destPath", -1);
Path url(moduleName, subPool);
Path path(destPath, subPool);
SVN_JNI_ERR(url.error_occurred(), -1);
SVN_JNI_ERR(path.error_occurred(), -1);
svn_revnum_t rev;
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return -1;
SVN_JNI_ERR(svn_client_checkout3(&rev, url.c_str(),
path.c_str(),
pegRevision.revision(),
revision.revision(),
depth,
ignoreExternals,
allowUnverObstructions,
ctx,
subPool.getPool()),
-1);
return rev;
}
void SVNClient::remove(Targets &targets, CommitMessage *message, bool force,
bool keep_local, PropertyTable &revprops,
CommitCallback *callback)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(message, subPool);
if (ctx == NULL)
return;
const apr_array_header_t *targets2 = targets.array(subPool);
SVN_JNI_ERR(targets.error_occurred(), );
SVN_JNI_ERR(svn_client_delete4(targets2, force, keep_local,
revprops.hash(subPool),
CommitCallback::callback, callback,
ctx, subPool.getPool()), );
}
void SVNClient::revert(StringArray &paths, svn_depth_t depth,
StringArray &changelists,
bool clear_changelists,
bool metadata_only)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Targets targets(paths, subPool);
SVN_JNI_ERR(targets.error_occurred(), );
SVN_JNI_ERR(svn_client_revert3(targets.array(subPool), depth,
changelists.array(subPool),
clear_changelists,
metadata_only,
ctx, subPool.getPool()), );
}
void SVNClient::add(const char *path,
svn_depth_t depth, bool force,
bool no_ignore, bool no_autoprops,
bool add_parents)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_add5(intPath.c_str(), depth, force,
no_ignore, no_autoprops, add_parents, ctx,
subPool.getPool()), );
}
jlongArray SVNClient::update(Targets &targets, Revision &revision,
svn_depth_t depth, bool depthIsSticky,
bool makeParents, bool ignoreExternals,
bool allowUnverObstructions)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
apr_array_header_t *revs;
if (ctx == NULL)
return NULL;
const apr_array_header_t *array = targets.array(subPool);
SVN_JNI_ERR(targets.error_occurred(), NULL);
SVN_JNI_ERR(svn_client_update4(&revs, array,
revision.revision(),
depth,
depthIsSticky,
ignoreExternals,
allowUnverObstructions,
TRUE /* adds_as_modification */,
makeParents,
ctx, subPool.getPool()),
NULL);
JNIEnv *env = JNIUtil::getEnv();
jlongArray jrevs = env->NewLongArray(revs->nelts);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jlong *jrevArray = env->GetLongArrayElements(jrevs, NULL);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
for (int i = 0; i < revs->nelts; ++i)
{
jlong rev = APR_ARRAY_IDX(revs, i, svn_revnum_t);
jrevArray[i] = rev;
}
env->ReleaseLongArrayElements(jrevs, jrevArray, 0);
return jrevs;
}
void SVNClient::commit(Targets &targets, CommitMessage *message,
svn_depth_t depth, bool noUnlock, bool keepChangelist,
StringArray &changelists, PropertyTable &revprops,
CommitCallback *callback)
{
SVN::Pool subPool(pool);
const apr_array_header_t *targets2 = targets.array(subPool);
SVN_JNI_ERR(targets.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(message, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_commit6(targets2, depth,
noUnlock, keepChangelist,
TRUE,
FALSE, // include_file_externals
FALSE, // include_dir_externals
changelists.array(subPool),
revprops.hash(subPool),
CommitCallback::callback, callback,
ctx, subPool.getPool()),
);
}
namespace {
typedef Java::ImmutableList<JavaHL::ExternalItem> PinList;
typedef Java::ImmutableMap<PinList> PinMap;
struct PinListFunctor
{
explicit PinListFunctor(const Java::Env& env, SVN::Pool& pool, int refs_len)
: m_pool(pool),
m_refs(apr_array_make(pool.getPool(), refs_len,
sizeof(svn_wc_external_item2_t*)))
{}
void operator()(const JavaHL::ExternalItem& item)
{
APR_ARRAY_PUSH(m_refs, svn_wc_external_item2_t*) =
item.get_external_item(m_pool);
}
SVN::Pool& m_pool;
apr_array_header_t *m_refs;
};
struct PinMapFunctor
{
explicit PinMapFunctor(const Java::Env& env, SVN::Pool& pool)
: m_env(env),
m_pool(pool),
m_pin_set(svn_hash__make(pool.getPool()))
{}
void operator()(const std::string& path, const PinList& refs)
{
PinListFunctor lf(m_env, m_pool, refs.length());
refs.for_each(lf);
const char* key = static_cast<const char*>(
apr_pmemdup(m_pool.getPool(), path.c_str(), path.size() + 1));
svn_hash_sets(m_pin_set, key, lf.m_refs);
}
const Java::Env& m_env;
SVN::Pool& m_pool;
apr_hash_t *m_pin_set;
};
apr_hash_t *get_externals_to_pin(jobject jexternalsToPin, SVN::Pool& pool)
{
if (!jexternalsToPin)
return NULL;
const Java::Env env;
JNIEnv *jenv = env.get();
try
{
PinMap pin_map(env, jexternalsToPin);
PinMapFunctor mf(env, pool);
pin_map.for_each(mf);
return mf.m_pin_set;
}
SVN_JAVAHL_JNI_CATCH;
return NULL;
}
} // anonymous namespace
void SVNClient::copy(CopySources ©Sources, const char *destPath,
CommitMessage *message, bool copyAsChild,
bool makeParents, bool ignoreExternals,
bool metadataOnly,
bool pinExternals, jobject jexternalsToPin,
PropertyTable &revprops, CommitCallback *callback)
{
SVN::Pool subPool(pool);
apr_array_header_t *srcs = copySources.array(subPool);
SVN_JNI_NULL_PTR_EX(srcs, "sources", );
SVN_JNI_NULL_PTR_EX(destPath, "destPath", );
Path destinationPath(destPath, subPool);
SVN_JNI_ERR(destinationPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(message, subPool);
if (ctx == NULL)
return;
apr_hash_t *pin_set = get_externals_to_pin(jexternalsToPin, subPool);
if (!JNIUtil::isJavaExceptionThrown())
SVN_JNI_ERR(svn_client_copy7(srcs, destinationPath.c_str(),
copyAsChild, makeParents, ignoreExternals,
metadataOnly,
pinExternals, pin_set,
revprops.hash(subPool),
CommitCallback::callback, callback,
ctx, subPool.getPool()), );
}
void SVNClient::move(Targets &srcPaths, const char *destPath,
CommitMessage *message, bool force, bool moveAsChild,
bool makeParents, bool metadataOnly, bool allowMixRev,
PropertyTable &revprops, CommitCallback *callback)
{
SVN::Pool subPool(pool);
const apr_array_header_t *srcs = srcPaths.array(subPool);
SVN_JNI_ERR(srcPaths.error_occurred(), );
SVN_JNI_NULL_PTR_EX(destPath, "destPath", );
Path destinationPath(destPath, subPool);
SVN_JNI_ERR(destinationPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(message, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_move7((apr_array_header_t *) srcs,
destinationPath.c_str(), moveAsChild,
makeParents,
allowMixRev,
metadataOnly,
revprops.hash(subPool),
CommitCallback::callback, callback, ctx,
subPool.getPool()), );
}
void SVNClient::mkdir(Targets &targets, CommitMessage *message,
bool makeParents, PropertyTable &revprops,
CommitCallback *callback)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(message, subPool);
if (ctx == NULL)
return;
const apr_array_header_t *targets2 = targets.array(subPool);
SVN_JNI_ERR(targets.error_occurred(), );
SVN_JNI_ERR(svn_client_mkdir4(targets2, makeParents,
revprops.hash(subPool),
CommitCallback::callback, callback,
ctx, subPool.getPool()), );
}
void SVNClient::cleanup(const char *path,
bool break_locks,
bool fix_recorded_timestamps,
bool clear_dav_cache,
bool remove_unused_pristines,
bool include_externals)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_cleanup2(intPath.c_str(),
break_locks,
fix_recorded_timestamps,
clear_dav_cache,
remove_unused_pristines,
include_externals,
ctx, subPool.getPool()),);
}
void SVNClient::resolve(const char *path, svn_depth_t depth,
svn_wc_conflict_choice_t choice)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_resolve(intPath.c_str(), depth, choice,
ctx, subPool.getPool()), );
}
jlong SVNClient::doExport(const char *srcPath, const char *destPath,
Revision &revision, Revision &pegRevision,
bool force, bool ignoreExternals,
bool ignoreKeywords,
svn_depth_t depth, const char *nativeEOL)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(srcPath, "srcPath", -1);
SVN_JNI_NULL_PTR_EX(destPath, "destPath", -1);
Path sourcePath(srcPath, subPool);
SVN_JNI_ERR(sourcePath.error_occurred(), -1);
Path destinationPath(destPath, subPool);
SVN_JNI_ERR(destinationPath.error_occurred(), -1);
svn_revnum_t rev;
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return -1;
SVN_JNI_ERR(svn_client_export5(&rev, sourcePath.c_str(),
destinationPath.c_str(),
pegRevision.revision(),
revision.revision(), force,
ignoreExternals, ignoreKeywords,
depth,
nativeEOL, ctx,
subPool.getPool()),
-1);
return rev;
}
jlong SVNClient::doSwitch(const char *path, const char *url,
Revision &revision, Revision &pegRevision,
svn_depth_t depth, bool depthIsSticky,
bool ignoreExternals,
bool allowUnverObstructions,
bool ignoreAncestry)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", -1);
SVN_JNI_NULL_PTR_EX(url, "url", -1);
Path intUrl(url, subPool);
SVN_JNI_ERR(intUrl.error_occurred(), -1);
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), -1);
svn_revnum_t rev;
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return -1;
SVN_JNI_ERR(svn_client_switch3(&rev, intPath.c_str(),
intUrl.c_str(),
pegRevision.revision(),
revision.revision(),
depth,
depthIsSticky,
ignoreExternals,
allowUnverObstructions,
ignoreAncestry,
ctx,
subPool.getPool()),
-1);
return rev;
}
void SVNClient::doImport(const char *path, const char *url,
CommitMessage *message, svn_depth_t depth,
bool noIgnore, bool noAutoProps,
bool ignoreUnknownNodeTypes,
PropertyTable &revprops,
ImportFilterCallback *ifCallback,
CommitCallback *commitCallback)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
SVN_JNI_NULL_PTR_EX(url, "url", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
Path intUrl(url, subPool);
SVN_JNI_ERR(intUrl.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(message, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_import5(intPath.c_str(), intUrl.c_str(), depth,
noIgnore, noAutoProps, ignoreUnknownNodeTypes,
revprops.hash(subPool),
ImportFilterCallback::callback, ifCallback,
CommitCallback::callback, commitCallback,
ctx, subPool.getPool()), );
}
jobject
SVNClient::suggestMergeSources(const char *path, Revision &pegRevision)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return NULL;
apr_array_header_t *sources;
SVN_JNI_ERR(svn_client_suggest_merge_sources(&sources, path,
pegRevision.revision(),
ctx, subPool.getPool()),
NULL);
return CreateJ::StringSet(sources);
}
void SVNClient::merge(const char *path1, Revision &revision1,
const char *path2, Revision &revision2,
const char *localPath, bool forceDelete, svn_depth_t depth,
bool ignoreMergeinfo, bool diffIgnoreAncestry,
bool dryRun, bool allowMixedRev, bool recordOnly)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path1, "path1", );
SVN_JNI_NULL_PTR_EX(path2, "path2", );
SVN_JNI_NULL_PTR_EX(localPath, "localPath", );
Path intLocalPath(localPath, subPool);
SVN_JNI_ERR(intLocalPath.error_occurred(), );
Path srcPath1(path1, subPool);
SVN_JNI_ERR(srcPath1.error_occurred(), );
Path srcPath2(path2, subPool);
SVN_JNI_ERR(srcPath2.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_merge5(srcPath1.c_str(), revision1.revision(),
srcPath2.c_str(), revision2.revision(),
intLocalPath.c_str(),
depth,
ignoreMergeinfo, diffIgnoreAncestry,
forceDelete, recordOnly, dryRun,
allowMixedRev, NULL, ctx,
subPool.getPool()), );
}
void SVNClient::merge(const char *path, Revision &pegRevision,
std::vector<RevisionRange> *rangesToMerge,
const char *localPath, bool forceDelete, svn_depth_t depth,
bool ignoreMergeinfo, bool diffIgnoreAncestry,
bool dryRun, bool allowMixedRev, bool recordOnly)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
SVN_JNI_NULL_PTR_EX(localPath, "localPath", );
Path intLocalPath(localPath, subPool);
SVN_JNI_ERR(intLocalPath.error_occurred(), );
Path srcPath(path, subPool);
SVN_JNI_ERR(srcPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
apr_array_header_t *ranges =
(!rangesToMerge ? NULL
: rev_range_vector_to_apr_array(*rangesToMerge, subPool));
if (JNIUtil::isExceptionThrown())
return;
SVN_JNI_ERR(svn_client_merge_peg5(srcPath.c_str(),
ranges,
pegRevision.revision(),
intLocalPath.c_str(),
depth,
ignoreMergeinfo, diffIgnoreAncestry,
forceDelete, recordOnly,
dryRun, allowMixedRev, NULL, ctx,
subPool.getPool()), );
}
/* SVNClient::mergeReintegrate is implemented in deprecated.cpp. */
jobject
SVNClient::getMergeinfo(const char *target, Revision &pegRevision)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return NULL;
svn_mergeinfo_t mergeinfo;
Path intLocalTarget(target, subPool);
SVN_JNI_ERR(intLocalTarget.error_occurred(), NULL);
SVN_JNI_ERR(svn_client_mergeinfo_get_merged(&mergeinfo,
intLocalTarget.c_str(),
pegRevision.revision(), ctx,
subPool.getPool()),
NULL);
if (mergeinfo == NULL)
return NULL;
return CreateJ::Mergeinfo(mergeinfo, subPool.getPool());
}
void SVNClient::getMergeinfoLog(int type, const char *pathOrURL,
Revision &pegRevision,
const char *mergeSourceURL,
Revision &srcPegRevision,
Revision &srcStartRevision,
Revision &srcEndRevision,
bool discoverChangedPaths,
svn_depth_t depth,
StringArray &revProps,
LogMessageCallback *callback)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_NULL_PTR_EX(pathOrURL, "path or url", );
Path urlPath(pathOrURL, subPool);
SVN_JNI_ERR(urlPath.error_occurred(), );
SVN_JNI_NULL_PTR_EX(mergeSourceURL, "merge source url", );
Path srcURL(mergeSourceURL, subPool);
SVN_JNI_ERR(srcURL.error_occurred(), );
SVN_JNI_ERR(svn_client_mergeinfo_log2((type == 1),
urlPath.c_str(),
pegRevision.revision(),
srcURL.c_str(),
srcPegRevision.revision(),
srcStartRevision.revision(),
srcEndRevision.revision(),
LogMessageCallback::callback,
callback,
discoverChangedPaths,
depth,
revProps.array(subPool),
ctx,
subPool.getPool()), );
return;
}
/**
* Get a property.
*/
jbyteArray SVNClient::propertyGet(const char *path, const char *name,
Revision &revision, Revision &pegRevision,
StringArray &changelists)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", NULL);
SVN_JNI_NULL_PTR_EX(name, "name", NULL);
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), NULL);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return NULL;
apr_hash_t *props;
SVN_JNI_ERR(svn_client_propget5(&props, NULL, name,
intPath.c_str(), pegRevision.revision(),
revision.revision(), NULL, svn_depth_empty,
changelists.array(subPool), ctx,
subPool.getPool(), subPool.getPool()),
NULL);
apr_hash_index_t *hi;
// only one element since we disabled recurse
hi = apr_hash_first(subPool.getPool(), props);
if (hi == NULL)
return NULL; // no property with this name
svn_string_t *propval;
apr_hash_this(hi, NULL, NULL, reinterpret_cast<void**>(&propval));
if (propval == NULL)
return NULL;
return JNIUtil::makeJByteArray(propval);
}
void SVNClient::properties(const char *path, Revision &revision,
Revision &pegRevision, svn_depth_t depth,
StringArray &changelists,
ProplistCallback *callback)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_proplist4(intPath.c_str(), pegRevision.revision(),
revision.revision(), depth,
changelists.array(subPool),
callback->inherited(),
ProplistCallback::callback, callback,
ctx, subPool.getPool()), );
}
void SVNClient::propertySetLocal(Targets &targets, const char *name,
JNIByteArray &value, svn_depth_t depth,
StringArray &changelists, bool force)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(name, "name", );
svn_string_t *val;
if (value.isNull())
val = NULL;
else
val = svn_string_ncreate
(reinterpret_cast<const char *>(value.getBytes()),
value.getLength(),
subPool.getPool());
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
const apr_array_header_t *targetsApr = targets.array(subPool);
SVN_JNI_ERR(svn_client_propset_local(name, val, targetsApr,
depth, force,
changelists.array(subPool),
ctx, subPool.getPool()), );
}
void SVNClient::propertySetRemote(const char *path, long base_rev,
const char *name,
CommitMessage *message,
JNIByteArray &value, bool force,
PropertyTable &revprops,
CommitCallback *callback)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(name, "name", );
svn_string_t *val;
if (value.isNull())
val = NULL;
else
val = svn_string_ncreate
(reinterpret_cast<const char *>(value.getBytes()),
value.getLength(),
subPool.getPool());
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(message, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_propset_remote(name, val, intPath.c_str(),
force, base_rev,
revprops.hash(subPool),
CommitCallback::callback, callback,
ctx, subPool.getPool()), );
}
void SVNClient::diff(const char *target1, Revision &revision1,
const char *target2, Revision &revision2,
Revision *pegRevision, const char *relativeToDir,
OutputStream &outputStream, svn_depth_t depth,
StringArray &changelists,
bool ignoreAncestry, bool noDiffDelete, bool force,
bool showCopiesAsAdds, bool ignoreProps, bool propsOnly,
DiffOptions const& options)
{
SVN::Pool subPool(pool);
const char *c_relToDir = relativeToDir ?
svn_dirent_canonicalize(relativeToDir, subPool.getPool()) :
relativeToDir;
bool noDiffAdded = false; /* ### Promote to argument */
SVN_JNI_NULL_PTR_EX(target1, "target", );
// target2 is ignored when pegRevision is provided.
if (pegRevision == NULL)
SVN_JNI_NULL_PTR_EX(target2, "target2", );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Path path1(target1, subPool);
SVN_JNI_ERR(path1.error_occurred(), );
apr_array_header_t *diffOptions = options.optionsArray(subPool);
if (pegRevision)
{
SVN_JNI_ERR(svn_client_diff_peg6(diffOptions,
path1.c_str(),
pegRevision->revision(),
revision1.revision(),
revision2.revision(),
c_relToDir,
depth,
ignoreAncestry,
noDiffAdded,
noDiffDelete,
showCopiesAsAdds,
force,
ignoreProps,
propsOnly,
options.useGitDiffFormat(),
SVN_APR_LOCALE_CHARSET,
outputStream.getStream(subPool),
NULL /* error file */,
changelists.array(subPool),
ctx,
subPool.getPool()),
);
}
else
{
// "Regular" diff (without a peg revision).
Path path2(target2, subPool);
SVN_JNI_ERR(path2.error_occurred(), );
SVN_JNI_ERR(svn_client_diff6(diffOptions,
path1.c_str(),
revision1.revision(),
path2.c_str(),
revision2.revision(),
c_relToDir,
depth,
ignoreAncestry,
noDiffAdded,
noDiffDelete,
showCopiesAsAdds,
force,
ignoreProps,
propsOnly,
options.useGitDiffFormat(),
SVN_APR_LOCALE_CHARSET,
outputStream.getStream(subPool),
NULL /* error stream */,
changelists.array(subPool),
ctx,
subPool.getPool()),
);
}
}
void SVNClient::diff(const char *target1, Revision &revision1,
const char *target2, Revision &revision2,
const char *relativeToDir, OutputStream &outputStream,
svn_depth_t depth, StringArray &changelists,
bool ignoreAncestry, bool noDiffDelete, bool force,
bool showCopiesAsAdds, bool ignoreProps, bool propsOnly,
DiffOptions const& options)
{
diff(target1, revision1, target2, revision2, NULL, relativeToDir,
outputStream, depth, changelists, ignoreAncestry, noDiffDelete, force,
showCopiesAsAdds, ignoreProps, propsOnly, options);
}
void SVNClient::diff(const char *target, Revision &pegRevision,
Revision &startRevision, Revision &endRevision,
const char *relativeToDir, OutputStream &outputStream,
svn_depth_t depth, StringArray &changelists,
bool ignoreAncestry, bool noDiffDelete, bool force,
bool showCopiesAsAdds, bool ignoreProps, bool propsOnly,
DiffOptions const& options)
{
diff(target, startRevision, NULL, endRevision, &pegRevision,
relativeToDir, outputStream, depth, changelists,
ignoreAncestry, noDiffDelete, force, showCopiesAsAdds,
ignoreProps, propsOnly, options);
}
void
SVNClient::diffSummarize(const char *target1, Revision &revision1,
const char *target2, Revision &revision2,
svn_depth_t depth, StringArray &changelists,
bool ignoreAncestry,
DiffSummaryReceiver &receiver)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(target1, "target1", );
SVN_JNI_NULL_PTR_EX(target2, "target2", );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Path path1(target1, subPool);
SVN_JNI_ERR(path1.error_occurred(), );
Path path2(target2, subPool);
SVN_JNI_ERR(path2.error_occurred(), );
SVN_JNI_ERR(svn_client_diff_summarize2(path1.c_str(), revision1.revision(),
path2.c_str(), revision2.revision(),
depth,
ignoreAncestry,
changelists.array(subPool),
DiffSummaryReceiver::summarize,
&receiver,
ctx, subPool.getPool()), );
}
void
SVNClient::diffSummarize(const char *target, Revision &pegRevision,
Revision &startRevision, Revision &endRevision,
svn_depth_t depth, StringArray &changelists,
bool ignoreAncestry, DiffSummaryReceiver &receiver)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(target, "target", );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Path path(target, subPool);
SVN_JNI_ERR(path.error_occurred(), );
SVN_JNI_ERR(svn_client_diff_summarize_peg2(path.c_str(),
pegRevision.revision(),
startRevision.revision(),
endRevision.revision(),
depth,
ignoreAncestry,
changelists.array(subPool),
DiffSummaryReceiver::summarize,
&receiver, ctx,
subPool.getPool()), );
}
apr_hash_t *SVNClient::streamFileContent(const char *path,
Revision &revision,
Revision &pegRevision,
bool expand_keywords,
bool return_props,
OutputStream &outputStream)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", NULL);
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), NULL);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return NULL;
apr_hash_t *props = NULL;
SVN_JNI_ERR(svn_client_cat3((return_props ? &props : NULL),
outputStream.getStream(subPool),
intPath.c_str(),
pegRevision.revision(), revision.revision(),
expand_keywords, ctx,
subPool.getPool(), subPool.getPool()),
NULL);
return props;
}
jbyteArray SVNClient::revProperty(const char *path,
const char *name, Revision &rev)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", NULL);
SVN_JNI_NULL_PTR_EX(name, "name", NULL);
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), NULL);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return NULL;
const char *URL;
svn_string_t *propval;
svn_revnum_t set_rev;
SVN_JNI_ERR(svn_client_url_from_path2(&URL, intPath.c_str(), ctx,
subPool.getPool(),
subPool.getPool()),
NULL);
if (URL == NULL)
{
SVN_JNI_ERR(svn_error_create(SVN_ERR_UNVERSIONED_RESOURCE, NULL,
_("Either a URL or versioned item is required.")),
NULL);
}
SVN_JNI_ERR(svn_client_revprop_get(name, &propval, URL,
rev.revision(), &set_rev, ctx,
subPool.getPool()),
NULL);
if (propval == NULL)
return NULL;
return JNIUtil::makeJByteArray(propval);
}
void SVNClient::relocate(const char *from, const char *to, const char *path,
bool ignoreExternals)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
SVN_JNI_NULL_PTR_EX(from, "from", );
SVN_JNI_NULL_PTR_EX(to, "to", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
Path intFrom(from, subPool);
SVN_JNI_ERR(intFrom.error_occurred(), );
Path intTo(to, subPool);
SVN_JNI_ERR(intTo.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_relocate2(intPath.c_str(), intFrom.c_str(),
intTo.c_str(), ignoreExternals, ctx,
subPool.getPool()), );
}
void SVNClient::blame(const char *path, Revision &pegRevision,
Revision &revisionStart, Revision &revisionEnd,
bool ignoreMimeType, bool includeMergedRevisions,
BlameCallback *callback, DiffOptions const& options)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
SVN_JNI_ERR(svn_client_blame5(
intPath.c_str(), pegRevision.revision(), revisionStart.revision(),
revisionEnd.revision(),
options.fileOptions(subPool), ignoreMimeType,
includeMergedRevisions, BlameCallback::callback, callback, ctx,
subPool.getPool()),
);
}
void SVNClient::addToChangelist(Targets &srcPaths, const char *changelist,
svn_depth_t depth, StringArray &changelists)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
const apr_array_header_t *srcs = srcPaths.array(subPool);
SVN_JNI_ERR(srcPaths.error_occurred(), );
SVN_JNI_ERR(svn_client_add_to_changelist(srcs, changelist, depth,
changelists.array(subPool),
ctx, subPool.getPool()), );
}
void SVNClient::removeFromChangelists(Targets &srcPaths, svn_depth_t depth,
StringArray &changelists)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
const apr_array_header_t *srcs = srcPaths.array(subPool);
SVN_JNI_ERR(srcPaths.error_occurred(), );
SVN_JNI_ERR(svn_client_remove_from_changelists(srcs, depth,
changelists.array(subPool),
ctx, subPool.getPool()), );
}
void SVNClient::getChangelists(const char *rootPath,
StringArray *changelists,
svn_depth_t depth,
ChangelistCallback *callback)
{
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
const apr_array_header_t *cl_array = (!changelists ? NULL
: changelists->array(subPool));
SVN_JNI_ERR(svn_client_get_changelists(rootPath, cl_array,
depth, ChangelistCallback::callback,
callback, ctx, subPool.getPool()),
);
}
void SVNClient::lock(Targets &targets, const char *comment, bool force)
{
SVN::Pool subPool(pool);
const apr_array_header_t *targetsApr = targets.array(subPool);
SVN_JNI_ERR(targets.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
SVN_JNI_ERR(svn_client_lock(targetsApr, comment, force, ctx,
subPool.getPool()), );
}
void SVNClient::unlock(Targets &targets, bool force)
{
SVN::Pool subPool(pool);
const apr_array_header_t *targetsApr = targets.array(subPool);
SVN_JNI_ERR(targets.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
SVN_JNI_ERR(svn_client_unlock(
targetsApr, force, ctx, subPool.getPool()), );
}
void SVNClient::setRevProperty(const char *path,
const char *name, Revision &rev,
const char *value, const char *original_value,
bool force)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
SVN_JNI_NULL_PTR_EX(name, "name", );
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
const char *URL;
SVN_JNI_ERR(svn_client_url_from_path2(&URL, intPath.c_str(), ctx,
subPool.getPool(),
subPool.getPool()), );
if (URL == NULL)
{
SVN_JNI_ERR(svn_error_create(SVN_ERR_UNVERSIONED_RESOURCE, NULL,
_("Either a URL or versioned item is required.")),
);
}
svn_string_t *val = svn_string_create(value, subPool.getPool());
svn_string_t *orig_val;
if (original_value != NULL)
orig_val = svn_string_create(original_value, subPool.getPool());
else
orig_val = NULL;
svn_revnum_t set_revision;
SVN_JNI_ERR(svn_client_revprop_set2(name, val, orig_val, URL, rev.revision(),
&set_revision, force, ctx,
subPool.getPool()), );
}
jstring SVNClient::getVersionInfo(const char *path, const char *trailUrl,
bool lastChanged)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", NULL);
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), NULL);
int wc_format;
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return NULL;
SVN_JNI_ERR(svn_wc_check_wc2(&wc_format, ctx->wc_ctx, intPath.c_str(),
subPool.getPool()),
NULL);
if (! wc_format)
{
svn_node_kind_t kind;
SVN_JNI_ERR(svn_io_check_path(intPath.c_str(), &kind,
subPool.getPool()),
NULL);
if (kind == svn_node_dir)
{
return JNIUtil::makeJString("exported");
}
else
{
char buffer[2048];
apr_snprintf(buffer, sizeof(buffer),
_("'%s' not versioned, and not exported\n"), path);
return JNIUtil::makeJString(buffer);
}
}
svn_wc_revision_status_t *result;
const char *local_abspath;
SVN_JNI_ERR(svn_dirent_get_absolute(&local_abspath, intPath.c_str(),
subPool.getPool()), NULL);
SVN_JNI_ERR(svn_wc_revision_status2(&result, ctx->wc_ctx, local_abspath,
trailUrl, lastChanged,
ctx->cancel_func, ctx->cancel_baton,
subPool.getPool(),
subPool.getPool()), NULL);
std::ostringstream value;
value << result->min_rev;
if (result->min_rev != result->max_rev)
{
value << ":";
value << result->max_rev;
}
if (result->modified)
value << "M";
if (result->switched)
value << "S";
if (result->sparse_checkout)
value << "P";
return JNIUtil::makeJString(value.str().c_str());
}
void SVNClient::upgrade(const char *path)
{
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", );
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Path checkedPath(path, subPool);
SVN_JNI_ERR(checkedPath.error_occurred(), );
SVN_JNI_ERR(svn_client_upgrade(path, ctx, subPool.getPool()), );
}
jobject SVNClient::revProperties(const char *path, Revision &revision)
{
apr_hash_t *props;
SVN::Pool subPool(pool);
SVN_JNI_NULL_PTR_EX(path, "path", NULL);
Path intPath(path, subPool);
SVN_JNI_ERR(intPath.error_occurred(), NULL);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
const char *URL;
svn_revnum_t set_rev;
SVN_JNI_ERR(svn_client_url_from_path2(&URL, intPath.c_str(), ctx,
subPool.getPool(),
subPool.getPool()),
NULL);
if (ctx == NULL)
return NULL;
SVN_JNI_ERR(svn_client_revprop_list(&props, URL, revision.revision(),
&set_rev, ctx, subPool.getPool()),
NULL);
return CreateJ::PropertyMap(props, subPool.getPool());
}
void
SVNClient::info(const char *path,
Revision &revision, Revision &pegRevision, svn_depth_t depth,
svn_boolean_t fetchExcluded, svn_boolean_t fetchActualOnly,
svn_boolean_t includeExternals,
StringArray &changelists, InfoCallback *callback)
{
SVN_JNI_NULL_PTR_EX(path, "path", );
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Path checkedPath(path, subPool);
SVN_JNI_ERR(checkedPath.error_occurred(), );
SVN_JNI_ERR(svn_client_info4(checkedPath.c_str(),
pegRevision.revision(),
revision.revision(), depth,
fetchExcluded, fetchActualOnly,
includeExternals,
changelists.array(subPool),
InfoCallback::callback, callback,
ctx, subPool.getPool()), );
}
void
SVNClient::patch(const char *patchPath, const char *targetPath, bool dryRun,
int stripCount, bool reverse, bool ignoreWhitespace,
bool removeTempfiles, PatchCallback *callback)
{
SVN_JNI_NULL_PTR_EX(patchPath, "patchPath", );
SVN_JNI_NULL_PTR_EX(targetPath, "targetPath", );
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Path checkedPatchPath(patchPath, subPool);
SVN_JNI_ERR(checkedPatchPath.error_occurred(), );
Path checkedTargetPath(targetPath, subPool);
SVN_JNI_ERR(checkedTargetPath.error_occurred(), );
// Should parameterize the following, instead of defaulting to FALSE
SVN_JNI_ERR(svn_client_patch(checkedPatchPath.c_str(),
checkedTargetPath.c_str(),
dryRun, stripCount, reverse,
ignoreWhitespace, removeTempfiles,
PatchCallback::callback, callback,
ctx, subPool.getPool()), );
}
void SVNClient::vacuum(const char *path,
bool remove_unversioned_items,
bool remove_ignored_items,
bool fix_recorded_timestamps,
bool remove_unused_pristines,
bool include_externals)
{
SVN_JNI_NULL_PTR_EX(path, "path", );
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return;
Path checkedPath(path, subPool);
SVN_JNI_ERR(checkedPath.error_occurred(),);
SVN_JNI_ERR(svn_client_vacuum(checkedPath.c_str(),
remove_unversioned_items,
remove_ignored_items,
fix_recorded_timestamps,
remove_unused_pristines,
include_externals,
ctx, subPool.getPool()), );
}
jobject
SVNClient::openRemoteSession(const char* path, int retryAttempts)
{
static const svn_opt_revision_t HEAD = { svn_opt_revision_head, {0}};
static const svn_opt_revision_t NONE = { svn_opt_revision_unspecified, {0}};
SVN_JNI_NULL_PTR_EX(path, "path", NULL);
SVN::Pool subPool(pool);
svn_client_ctx_t *ctx = context.getContext(NULL, subPool);
if (ctx == NULL)
return NULL;
Path checkedPath(path, subPool);
SVN_JNI_ERR(checkedPath.error_occurred(), NULL);
struct PathInfo
{
std::string url;
std::string uuid;
static svn_error_t *callback(void *baton,
const char *,
const svn_client_info2_t *info,
apr_pool_t *)
{
PathInfo* const pi = static_cast<PathInfo*>(baton);
pi->url = info->URL;
pi->uuid = info->repos_UUID;
return SVN_NO_ERROR;
}
} path_info;
SVN_JNI_ERR(svn_client_info4(
checkedPath.c_str(), &NONE,
(svn_path_is_url(checkedPath.c_str()) ? &HEAD : &NONE),
svn_depth_empty, FALSE, TRUE, FALSE, NULL,
PathInfo::callback, &path_info,
ctx, subPool.getPool()),
NULL);
/* Decouple the RemoteSession's context from SVNClient's context
by creating a copy of the prompter here. */
jobject jremoteSession = RemoteSession::open(
retryAttempts, path_info.url.c_str(), path_info.uuid.c_str(),
context.getConfigDirectory(),
context.getUsername(), context.getPassword(),
context.clonePrompter(), context.getSelf(),
context.getConfigEventHandler(), context.getTunnelCallback());
if (JNIUtil::isJavaExceptionThrown())
jremoteSession = NULL;
return jremoteSession;
}
ClientContext &
SVNClient::getClientContext()
{
return context;
}
| [
"sleepingwit@outlook.com"
] | sleepingwit@outlook.com |
f79b1e58ab2e02a2110b9799605f730a880fce12 | 300a2cadeab3a55cbb01a2a6f4642a8af522158a | /UltrasonicStructSplit/UltrasonicStructSplit.h | a8f1fc9dd85947c9bbaf880f4a6eba2dd265dc05 | [] | no_license | FAUtonOHM2017/aadc2017 | 2adb934ae0e3576ce085cc8411df181a231eb6df | 481fff7b713e518a7156339a499293d3455228ba | refs/heads/master | 2021-08-14T14:23:37.973854 | 2017-11-16T00:29:26 | 2017-11-16T00:29:26 | 110,901,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,845 | h | /**
* Copyright (c)
Audi Autonomous Driving Cup. TEAM FAUtonOHM. 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.�
4. Neither the name of Audi 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 AUDI AG 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 AUDI AG 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.
ADTF Filter for splitting up the defined 'Ultrasonic Struct' into its different components
**********************************************************************
* $Author:: $ hiller $Date:: 2015-12-13 00:00:00#$ $Rev:: 1.0 $
**********************************************************************/
#ifndef _ULTRASONIC_STRUCT_SPLIT_H_
#define _ULTRASONIC_STRUCT_SPLIT_H_
#define OID_ADTF_US_STRUCT_SPLIT "adtf.user.ultrasonic_struct_split"
//*************************************************************************************************
class UltrasonicStructSplit: public adtf::cFilter {
ADTF_DECLARE_FILTER_VERSION(OID_ADTF_US_STRUCT_SPLIT, "Ultrasonic Struct Split", OBJCAT_DataFilter, "Ultrasonic Struct Split", 1, 0, 0, "FAUtonOHM");
protected:
cInputPin ultrasonicStruct_input;
cOutputPin US_FrontLeft_out;
cOutputPin US_FrontCenterLeft_out;
cOutputPin US_FrontCenter_out;
cOutputPin US_FrontCenterRight_out;
cOutputPin US_FrontRight_out;
cOutputPin US_SideLeft_out;
cOutputPin US_SideRight_out;
cOutputPin US_RearLeft_out;
cOutputPin US_RearCenter_out;
cOutputPin US_RearRight_out;
public:
UltrasonicStructSplit(const tChar* __info);
virtual ~UltrasonicStructSplit();
protected:
tResult Init(tInitStage eStage, __exception);
tResult Start(__exception = NULL);
tResult Stop(__exception = NULL);
tResult Shutdown(tInitStage eStage, __exception);
// implements IPinEventSink
tResult OnPinEvent(IPin* pSource, tInt nEventCode, tInt nParam1, tInt nParam2, IMediaSample* pMediaSample);
private:
tInt nSize_tVal;
typedef struct temptSignalVal {
tUInt32 arduino_timestep;
tFloat32 data_value;
temptSignalVal() :
arduino_timestep(0), data_value(0.0) {
}
} temptSignalValue;
typedef struct {
temptSignalValue FrontLeft;
temptSignalValue FrontCenterLeft;
temptSignalValue FrontCenter;
temptSignalValue FrontCenterRight;
temptSignalValue FrontRight;
temptSignalValue SideLeft;
temptSignalValue SideRight;
temptSignalValue RearLeft;
temptSignalValue RearCenter;
temptSignalValue RearRight;
} tempUltrasonicStruct;
// struct to save temporary sub-structs of mediatype "UltrasonicStruct"
tempUltrasonicStruct temp_US_struct;
/*! creates all the input Pins*/
tResult CreateInputPins(__exception = NULL);
/*! creates all the output Pins*/
tResult CreateOutputPins(__exception = NULL);
/** Necessary for inputs**/
/*! descriptor for ultrasonic sensor struct data */
cObjectPtr<IMediaTypeDescription> m_pDescriptionUltrasonicStruct;
/*! the id for the struct-part 'tFrontLeft' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tFrontLeft;
/*! the id for the struct-part 'tFrontCenterLeft' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tFrontCenterLeft;
/*! the id for the struct-part 'tFrontCenter' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tFrontCenter;
/*! the id for the struct-part 'tFrontCenterRight' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tFrontCenterRight;
/*! the id for the struct-part 'tFrontRight' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tFrontRight;
/*! the id for the struct-part 'tSideLeft' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tSideLeft;
/*! the id for the struct-part 'tSideRight' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tSideRight;
/*! the id for the struct-part 'tRearLeft' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tRearLeft;
/*! the id for the struct-part 'tRearCenter' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tRearCenter;
/*! the id for the struct-part 'tRearRight' of the media description for input pin of ultrasoncic struct data */
tBufferID tbufID_tRearRight;
/*! indicates if bufferIDs were set */
tBool tboolIDs_UltrasonicStructSet;
/** Necessary for outputs**/
/*! descriptor for tSignalValue output data */
cObjectPtr<IMediaTypeDescription> m_pDescription_tSignalValue;
/*! the id for the f32value of the media description for input pin of the ultrasoncic data */
tBufferID tbufID_tSignalValue_F32Value;
/*! the id for the arduino time stamp of the media description for input pin of the ultrasoncic data */
tBufferID tbufID_tSignalValue_ArduinoTimestamp;
/*! indicates if bufferIDs were set */
tBool tboolIDs_outputsSet;
/** From cSEnsorAnalyzer.h :
for functionality: "__synchronized_obj(m_oProcessUsDataCritSection)";
critical section for the processing of the ultrasonic data samples because function can be called from different onPinEvents
--> In Header definiert : cCriticalSection m_oProcessUsDataCritSection; **/
};
//*************************************************************************************************
#endif // _ULTRASONIC_STRUCT_SPLIT_H_
| [
"andreas.doll@fau.de"
] | andreas.doll@fau.de |
a7ba8d3ff7eb66bd385e7de1dc7d1348fa3f999c | fafdf1e62cf622035ee82666ba6ae7108127d140 | /kynapse7/include/kypdg/boundary/boundarysimplifypolyline.h | 9213c6506e2f15c71f8652952cb4c10c6db75836 | [] | no_license | saerich/RaiderZ-Evolved-SDK | 7f18942ddc6c566d47c3a6222c03fad7543738a4 | b576e6757b6a781a656be7ba31eb0cf5e8a23391 | refs/heads/master | 2023-02-12T03:21:26.442348 | 2020-08-30T15:39:54 | 2020-08-30T15:39:54 | 281,213,173 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,838 | h | /*
* Copyright 2010 Autodesk, Inc. All rights reserved.
* Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download,
* or which otherwise accompanies this software in either electronic or hard copy form.
*/
// primary contact: GUAL - secondary contact: NOBODY
#ifndef KyPdg_BoundarySimplifyPolyline_H
#define KyPdg_BoundarySimplifyPolyline_H
#include "kypdg/boundary/boundaryedge.h"
#include "kypdg/boundary/boundaryvertex.h"
#include "kypdg/boundary/boundarypolygon.h"
#include <kypdg/common/stllist.h>
namespace Kaim
{
class BoundarySimplifyVertex
{
KY_DEFINE_NEW_DELETE_OPERATORS
public:
BoundarySimplifyVertex() : m_vertex(KY_NULL), m_inSmallEdge(KY_NULL), m_outSmallEdge(KY_NULL) {}
BoundarySimplifyVertex(BoundaryEdge* inSmallEdge, BoundaryVertex* vertex, BoundaryEdge* outSmallEdge)
{
m_pos.x = (KyFloat32)vertex->m_exclBoundaryPos.x;
m_pos.y = (KyFloat32)vertex->m_exclBoundaryPos.y;
m_pos.z = vertex->m_altitude;
m_vertex = vertex;
m_inSmallEdge = inSmallEdge;
m_outSmallEdge = outSmallEdge;
}
public:
Vec3f m_pos;
BoundaryVertex* m_vertex;
BoundaryEdge* m_inSmallEdge;
BoundaryEdge* m_outSmallEdge;
};
// Linked list of BoundaryVertices for simplification usage
class BoundarySimplifyPolyline
{
KY_DEFINE_NEW_DELETE_OPERATORS
public:
typedef BoundarySimplifyVertex Vertex;
public:
BoundarySimplifyPolyline()
{
Init(KyUInt32MAXVAL, Boundary::ContourWinding_Unset, Boundary::EdgeType_Unset, Boundary::PolylineCycle_Unset);
}
void Init(KyUInt32 index, Boundary::ContourWinding contourWinding, Boundary::EdgeType edgeType, Boundary::PolylineCycle cycle)
{
m_index = index;
m_contourWinding = contourWinding;
m_edgeType = edgeType;
m_vertices.clear();
m_cycle = cycle;
m_horizontalTolerance = 0.01f;
m_verticalTolerance = -1.0f;
m_next = KY_NULL;
}
void AddVertex(BoundaryEdge* inEdge, BoundaryVertex* vertex, BoundaryEdge* outEdge)
{
BoundarySimplifyVertex simplifyVertex(inEdge, vertex, outEdge);
m_vertices.push_back(simplifyVertex);
if (inEdge)
PutEdgeInPolyline(inEdge);
if (outEdge)
PutEdgeInPolyline(outEdge);
}
void PutEdgeInPolyline(BoundaryEdge* edge)
{
edge->m_simplifyPolyline = this;
edge->m_simplifyPolylineOrder = Boundary::StraightOrder;
if (edge->m_pair)
{
edge->m_pair->m_simplifyPolyline = this;
edge->m_pair->m_simplifyPolylineOrder = Boundary::ReverseOrder;
}
}
public:
KyUInt32 m_index;
StlList<BoundarySimplifyVertex> m_vertices;
Boundary::ContourWinding m_contourWinding;
Boundary::EdgeType m_edgeType;
Boundary::PolylineCycle m_cycle; // if (m_cycle == Polyline_Cycle) then m_vertices.first != vertices.last
KyFloat32 m_horizontalTolerance;
KyFloat32 m_verticalTolerance;
BoundarySimplifyPolyline* m_next;
};
}
#endif
| [
"fabs1996@live.co.uk"
] | fabs1996@live.co.uk |
551d5dae8b62d78ad94c9cccdea697cee4eecee5 | 107c4be4a71129f7c301d6797f0a8838e2bb8c01 | /Mars Exploration Simulator/Events/Assign.cpp | 1304faa33053d950bc7c594df3f50b73833508f8 | [
"MIT"
] | permissive | mohamednabilabdelfattah/Mars-Exploration_Simulator | 9965b70904b4e01537dca9d22c02dae7c3e9ce58 | 5b4183e7c5656bef0aab833153acd141daa29ec8 | refs/heads/master | 2023-07-28T07:02:59.170037 | 2021-09-17T03:13:03 | 2021-09-17T03:13:03 | 408,034,003 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | #include"Assign.h"
//constructor
Assign::Assign(int eV) :Event(eV)
{}
//destructor
Assign::~Assign() {}
//execute
void Assign::execute(MarsStation* ms)
{
while (ms->assignEmergencyMission(getEventDay()));
while (ms->assignMountainousMission(getEventDay()));
while (ms->assignPolarMission(getEventDay()));
} | [
"mohamed.nabi.5596@gmail.com"
] | mohamed.nabi.5596@gmail.com |
40e2ec46cde6b5a885d1b0387430849e44841434 | dfe8243fa713292ab2e7a8f87ad76f36c6b2d9e7 | /include/menu.h | 4312d3766bee73dc33d6e5911a055944127b4966 | [] | no_license | heytensai/herotown | 44b280ad3eea3db31cfb9d5c90d37640247f45e5 | 8468e8bec8b93abf8f1baf8e2f22ad08ab05618a | refs/heads/master | 2021-01-22T07:32:46.700673 | 2014-12-30T05:56:12 | 2014-12-30T05:56:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | h | #ifndef MENU_H
#define MENU_H
#include "globals.h"
#include "video.h"
class Menu
{
protected:
Video *video;
public:
bool running;
int result;
Menu(Video *video);
void render();
void event_loop();
};
class ScoreMenu : public Menu
{
public:
int score1;
int score2;
ScoreMenu(Video *video);
void render();
void event_loop();
};
class IntroMenu : public Menu
{
public:
int timer_option;
IntroMenu(Video *video);
void render();
void event_loop();
bool exit();
};
#endif /* MENU_H */
| [
"tensai@zmonkey.org"
] | tensai@zmonkey.org |
690a5b2e1a809249c4b16e6ca9162048ea14912e | 7752c7ea2dcf00ffd23db5a08d4074d5c291ae34 | /ancho-master/code/IE/anchocommons/AnchoCommons/JSValueWrapper.hpp | 193065b9b79d8f3533e53331ecb2a13594ca27ba | [
"LicenseRef-scancode-other-permissive"
] | permissive | GreatRepos/analysisfile | 6a513cdb65714f43727f635db75542c93d9477a2 | d05532f52abf195b00933f6bdd2afe417e44b4e8 | refs/heads/master | 2020-12-28T17:23:51.887166 | 2014-03-13T20:28:44 | 2014-03-13T20:28:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,327 | hpp | #pragma once
#include <AnchoCommons/detail/JSValueIterators.hpp>
#include <map>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <Exceptions.h>
namespace Ancho {
namespace Utils {
namespace detail {
inline CComVariant getMember(CComVariant &aObject, const std::wstring &aProperty)
{
if (aObject.vt != VT_DISPATCH || aObject.pdispVal == NULL) {
ANCHO_THROW(ENotAnObject());
}
DISPID did = 0;
LPOLESTR lpNames[] = {(LPOLESTR)aProperty.c_str()};
if (FAILED(aObject.pdispVal->GetIDsOfNames(IID_NULL, lpNames, 1, LOCALE_USER_DEFAULT, &did))) {
return CComVariant();
}
CComVariant result;
DISPPARAMS params = {0};
IF_FAILED_THROW(aObject.pdispVal->Invoke(did, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, ¶ms, &result, NULL, NULL));
return result;
}
inline void setMember(CComVariant &aObject, const std::wstring &aProperty, const CComVariant &aValue)
{
if (aObject.vt != VT_DISPATCH || aObject.pdispVal == NULL) {
ANCHO_THROW(ENotAnObject());
}
CIDispatchHelper helper(aObject.pdispVal);
IF_FAILED_THROW(helper.SetPropertyByRef((LPOLESTR)aProperty.c_str(), aValue));
}
inline bool isArray(CComVariant &aObject) {
if (aObject.vt != VT_DISPATCH) {
return false;
}
CComVariant len = getMember(aObject, L"length");
return len.vt != VT_EMPTY;
}
} //namespace detail
//* Representation of null value
struct null_t{null_t(){}};
inline bool operator==(const null_t &, const null_t &) { return true; }
inline bool operator!=(const null_t &, const null_t &) { return false; }
class JSValueWrapper;
class JSValueWrapperConst;
class JSObjectWrapper;
class JSObjectWrapperConst;
class JSArrayWrapper;
class JSArrayWrapperConst;
#define JS_VALUE_TO_TYPE(TYPENAME, NAME, VARTYPE, EXCEPTION)\
TYPENAME to##NAME() const { \
if (!is##NAME()) { \
ANCHO_THROW(EXCEPTION()); \
} \
return TYPENAME((VARTYPE)(mCurrentValue.llVal));\
}
#define JS_VALUE_IS_TYPE(NAME, VT)\
bool is##NAME() const { \
HRESULT hr = mCurrentValue.ChangeType(VT);\
if (FAILED(hr)) {\
return false;\
}\
return true;\
}
#define JS_VALUE_TYPE_METHODS(TYPENAME, NAME, VARTYPE, VT, EXCEPTION)\
JS_VALUE_IS_TYPE(NAME, VT)\
JS_VALUE_TO_TYPE(TYPENAME, NAME, VARTYPE, EXCEPTION)
//Wrapper for JS objects - currently read-only access
class JSValueWrapperConst
{
public:
friend void swap(JSValueWrapperConst &aVal1, JSValueWrapperConst &aVal2);
friend class JSObjectWrapper;
friend class JSArrayWrapper;
friend class JSObjectWrapperConst;
friend class JSArrayWrapperConst;
JSValueWrapperConst() {}
explicit JSValueWrapperConst(const CComVariant &aVariant)
: mCurrentValue(aVariant) {}
explicit JSValueWrapperConst(const VARIANT &aVariant)
: mCurrentValue(aVariant) {}
JSValueWrapperConst(const JSValueWrapperConst &aValue)
: mCurrentValue(aValue.mCurrentValue) {}
explicit JSValueWrapperConst(const JSValueWrapper &aValue);
explicit JSValueWrapperConst(int aValue)
: mCurrentValue(aValue) {}
explicit JSValueWrapperConst(double aValue)
: mCurrentValue(aValue) {}
explicit JSValueWrapperConst(const std::wstring &aValue)
: mCurrentValue(aValue.c_str()) {}
explicit JSValueWrapperConst(bool aValue)
: mCurrentValue(aValue) {}
explicit JSValueWrapperConst(CComPtr<IDispatch> aValue)
: mCurrentValue(aValue) {}
JS_VALUE_TYPE_METHODS(std::wstring, String, BSTR, VT_BSTR, ENotAString)
JS_VALUE_IS_TYPE(Bool, VT_BOOL);
bool toBool() const {
if (!isBool()) {
ANCHO_THROW(ENotABool());
}
return mCurrentValue.boolVal != VARIANT_FALSE;
}
JS_VALUE_TYPE_METHODS(int, Int, INT, VT_I4, ENotAnInt)
JS_VALUE_TYPE_METHODS(double, Double, double, VT_R8, ENotADouble)
void attach(VARIANT &aVariant)
{
IF_FAILED_THROW(mCurrentValue.Attach(&aVariant));
}
bool isNull()const
{ return mCurrentValue.vt == VT_EMPTY; }
bool isObject() const
{ return mCurrentValue.vt == VT_DISPATCH && !isArray(); }
JSObjectWrapperConst toObject()const;
bool isArray() const
{ return detail::isArray(mCurrentValue); }
JSArrayWrapperConst toArray()const;
JSValueWrapperConst & operator=(JSValueWrapperConst aVal);
JSValueWrapperConst & operator=(JSValueWrapper aVal);
template<typename TVisitor>
typename TVisitor::result_type applyVisitor(TVisitor aVisitor)const
{
switch (mCurrentValue.vt) {
case VT_EMPTY:
return aVisitor(null_t());
case VT_BOOL:
return aVisitor(toBool());
case VT_I4:
return aVisitor(toInt());
case VT_R8:
return aVisitor(toDouble());
case VT_BSTR:
return aVisitor(toString());
default:
if (isArray()) {
return aVisitor(toArray());
}
if (isObject()) {
return aVisitor(toObject());
}
ATLASSERT(false);
return TVisitor::result_type();
}
}
protected:
CComVariant getMember(const std::wstring &aProperty) const
{ return detail::getMember(mCurrentValue, aProperty); }
mutable CComVariant mCurrentValue;
};
class JSValueWrapper: public JSValueWrapperConst
{
public:
friend class JSObjectWrapper;
friend class JSArrayWrapper;
friend class JSObjectWrapperConst;
friend class JSArrayWrapperConst;
//typedef MemberForwardIterator NameIterator;
JSValueWrapper() {}
explicit JSValueWrapper(const CComVariant &aVariant)
: JSValueWrapperConst(aVariant) {}
explicit JSValueWrapper(const VARIANT &aVariant)
: JSValueWrapperConst(aVariant) {}
JSValueWrapper(const JSValueWrapper &aVariant)
: JSValueWrapperConst(aVariant.mCurrentValue) {}
explicit JSValueWrapper(int aValue)
: JSValueWrapperConst(aValue) {}
explicit JSValueWrapper(double aValue)
: JSValueWrapperConst(aValue) {}
explicit JSValueWrapper(const std::wstring &aValue)
: JSValueWrapperConst(aValue) {}
explicit JSValueWrapper(bool aValue)
: JSValueWrapperConst(aValue) {}
explicit JSValueWrapper(CComPtr<IDispatch> aValue)
: JSValueWrapperConst(aValue) {}
void attach(VARIANT &aVariant)
{
IF_FAILED_THROW(mCurrentValue.Attach(&aVariant));
}
JSObjectWrapper toObject();
JSArrayWrapper toArray();
JSValueWrapper & operator=(JSValueWrapper aVal)
{
swap(*this, aVal);
return *this;
}
protected:
};
class JSValueAssigner: public JSValueWrapper
{
public:
JSValueAssigner(const CComVariant &aOwner, const std::wstring &aPropertyName, const CComVariant &aValue)
: JSValueWrapper(aValue), mOwner(aOwner), mPropertyName(aPropertyName)
{ /*empty*/ }
JSValueAssigner operator=(const std::wstring &aValue)const
{
Utils::detail::setMember(mOwner, mPropertyName, CComVariant(aValue.c_str()));
return *this;
}
JSValueAssigner operator=(const wchar_t *aValue)const
{
Utils::detail::setMember(mOwner, mPropertyName, CComVariant(aValue));
return *this;
}
JSValueAssigner operator=(int aValue)const
{
Utils::detail::setMember(mOwner, mPropertyName, CComVariant(aValue));
return *this;
}
JSValueAssigner operator=(double aValue)const
{
Utils::detail::setMember(mOwner, mPropertyName, CComVariant(aValue));
return *this;
}
JSValueAssigner operator=(bool aValue)const
{
Utils::detail::setMember(mOwner, mPropertyName, CComVariant(aValue));
return *this;
}
protected:
mutable CComVariant mOwner;
std::wstring mPropertyName;
};
//Wrapper for JS objects
class JSObjectWrapperConst
{
public:
friend class JSValueWrapperConst;
typedef detail::MemberForwardIterator NameIterator;
JSObjectWrapperConst & operator=(JSValueWrapperConst aVal);
/*{
swap(*this, aVal);
return *this;
}*/
JSValueWrapperConst
operator[](const std::wstring &aProperty)const
{
return JSValueWrapperConst(getMember(aProperty));
}
NameIterator memberNames()const
{
if (mCurrentValue.vt != VT_DISPATCH) {
ANCHO_THROW(ENotAnObject());
}
CComQIPtr<IDispatchEx> dispex = mCurrentValue.pdispVal;
if (!dispex) {
ANCHO_THROW(ENotIDispatchEx());
}
return NameIterator(dispex);
}
operator JSValueWrapperConst()
{
return JSValueWrapperConst(mCurrentValue);
}
protected:
JSObjectWrapperConst(const JSValueWrapperConst &aValue)
: mCurrentValue(aValue.mCurrentValue)
{
if (!aValue.isObject()) {
ANCHO_THROW(ENotAnObject());
}
}
CComVariant getMember(const std::wstring &aProperty) const
{ return detail::getMember(mCurrentValue, aProperty); }
mutable CComVariant mCurrentValue;
};
//Wrapper for JS objects
class JSObjectWrapper: public JSObjectWrapperConst
{
public:
friend class JSValueWrapper;
typedef detail::MemberForwardIterator NameIterator;
JSObjectWrapper & operator=(JSValueWrapper aVal);
/*{
swap(*this, aVal);
return *this;
}*/
JSValueAssigner
operator[](const std::wstring &aProperty)
{
return JSValueAssigner(mCurrentValue, aProperty, getMember(aProperty));
}
NameIterator memberNames()const
{
if (mCurrentValue.vt != VT_DISPATCH) {
ANCHO_THROW(ENotAnObject());
}
CComQIPtr<IDispatchEx> dispex = mCurrentValue.pdispVal;
if (!dispex) {
ANCHO_THROW(ENotIDispatchEx());
}
return NameIterator(dispex);
}
operator JSValueWrapper()
{
return JSValueWrapper(mCurrentValue);
}
protected:
JSObjectWrapper(const JSValueWrapper &aValue)
: JSObjectWrapperConst(aValue)
{ }
};
//Wrapper for JS objects - currently read-only access
class JSArrayWrapperConst
{
public:
friend class JSValueWrapperConst;
typedef detail::MemberForwardIterator NameIterator;
JSArrayWrapper & operator=(JSValueWrapper aVal);
/*{
swap(*this, aVal);
return *this;
}*/
JSValueWrapperConst
operator[](int aIdx)const
{
return operator[](boost::lexical_cast<std::wstring>(aIdx));
}
JSValueWrapperConst
operator[](const std::wstring &aProperty)const
{
return JSValueWrapperConst(getMember(aProperty));
}
size_t length()const
{
CComVariant len = getMember(L"length");
if (len.vt == VT_EMPTY) {
ANCHO_THROW(ENotAnArray());
}
HRESULT hr = len.ChangeType(VT_I4);
if (FAILED(hr)) {
ANCHO_THROW(ENotAnArray());
}
return static_cast<size_t>(len.lVal);
}
size_t size()const
{
return length();
}
protected:
JSArrayWrapperConst(const JSValueWrapperConst &aValue)
: mCurrentValue(aValue.mCurrentValue)
{
if (!aValue.isArray()) {
ANCHO_THROW(ENotAnArray());
}
}
CComVariant getMember(const std::wstring &aProperty) const
{ return detail::getMember(mCurrentValue, aProperty); }
mutable CComVariant mCurrentValue;
};
class JSArrayWrapper: public JSArrayWrapperConst
{
public:
friend class JSValueWrapper;
//TODO : rest of the interface methods required by 'Sequence' concept
typedef detail::MemberForwardIterator NameIterator;
JSArrayWrapper & operator=(JSValueWrapper aVal);
/*{
swap(*this, aVal);
return *this;
}*/
//TODO: return assignable object
JSValueWrapper
operator[](int aIdx)
{
return JSValueAssigner(mCurrentValue, boost::lexical_cast<std::wstring>(aIdx), getMember(boost::lexical_cast<std::wstring>(aIdx)));
}
JSValueWrapper
operator[](const std::wstring &aProperty)
{
return JSValueWrapper(getMember(aProperty));
}
void push_back(JSValueWrapperConst aValue)
{
detail::setMember(this->mCurrentValue, boost::lexical_cast<std::wstring>(this->size()), aValue.mCurrentValue);
}
protected:
JSArrayWrapper(const JSValueWrapper &aValue)
: JSArrayWrapperConst(aValue)
{ }
};
inline JSValueWrapperConst::JSValueWrapperConst(const JSValueWrapper &aValue)
: mCurrentValue(aValue.mCurrentValue)
{ /*empty*/ }
inline JSValueWrapperConst & JSValueWrapperConst::operator=(JSValueWrapperConst aVal)
{
swap(*this, aVal);
return *this;
}
inline JSValueWrapperConst & JSValueWrapperConst::operator=(JSValueWrapper aVal)
{
swap(*this, static_cast<JSValueWrapperConst>(aVal));
return *this;
}
inline JSObjectWrapperConst JSValueWrapperConst::toObject() const
{
if (!isObject()) {
ANCHO_THROW(ENotAnObject());
}
return JSObjectWrapperConst(*this);
}
inline JSArrayWrapperConst JSValueWrapperConst::toArray() const
{
if (!isArray()) {
ANCHO_THROW(ENotAnObject());
}
return JSArrayWrapperConst(*this);
}
inline void swap(JSValueWrapperConst &aVal1, JSValueWrapperConst &aVal2)
{
std::swap(aVal1.mCurrentValue, aVal2.mCurrentValue);
}
inline JSObjectWrapper JSValueWrapper::toObject()
{
if (!isObject()) {
ANCHO_THROW(ENotAnObject());
}
return JSObjectWrapper(*this);
}
inline JSArrayWrapper JSValueWrapper::toArray()
{
if (!isArray()) {
ANCHO_THROW(ENotAnArray());
}
return JSArrayWrapper(*this);
}
} //namespace Utils
} //namespace Ancho
| [
"yingkailiang0920@gmail.com"
] | yingkailiang0920@gmail.com |
d5012f7250c89c4512d2e5674325307595e0d34a | f0ee987789f5a6fe8f104890e95ee56e53f5b9b2 | /child-CURRENT_RELEASE_v13.08-r/Child/Code/MeshElements/meshElements.h | d8dc4df324a0c429d0bff1a60cfdc03996f2182a | [] | no_license | echoi/Coupling_SNAC_CHILD | 457c01adc439e6beb257ac8a33915d5db9a5591b | b888c668084a3172ffccdcc5c4b8e7fff7c503f2 | refs/heads/master | 2021-01-01T18:34:00.403660 | 2015-10-26T13:48:18 | 2015-10-26T13:48:18 | 19,891,618 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 53,355 | h | //-*-c++-*-
/*************************************************************************/\
/**
** @file meshElements.h
** @brief Header file for mesh elements tNode, tEdge,
** and tTriangle. Each of these mesh elements is
** implemented as an object, as described below.
** (formerly called gridElements)
**
** This file contains declarations of the three classes that collectively
** make up the triangulated mesh. These classes are:
** - tNode: nodes (ie, the points in the triangulation)
** - tEdge: directed edges, described by a starting node and an
** ending node
** - tTriangle: triangles in the mesh, with each triangle maintaining
** pointers to its 3 vertex nodes, its 3 neighboring
** triangles, and its 3 clockwise-oriented edges
**
** Lists of each of these 3 types of mesh element are maintained by the
** tMesh class, which implements the mesh and its routines. Connectivity
** between mesh elements is managed using pointers, as follows:
** - Each tNode object points to one of its "spokes" (the tEdges that
** originate at the node). In the current implementation, each
** tNode also maintains a list of all its spokes. In a future
** version such lists will only be created when needed by mesh
** modification routines (to reduce memory overhead).
** - Each tEdge points to its origin and destination nodes, and to
** the tEdge that lies counterclockwise relative to the origin node.
** tEdge objects also contain the coordinates of the the Voronoi
** vertex that lies on the righthand side of the tEdge. (A Voronoi
** vertex is the intersection between 3 Voronoi cells, and in a
** Delaunay triangulation is found at the circumcenter of triangle).
** - Each tTriangle object points to its 3 vertex nodes, its 3
** neighboring triangles (or null if no neighboring triangle exists
** across a given face), and the 3 clockwise-oriented tEdges. The
** data structure uses the "opposite" numbering scheme, so that
** triangle node 1 represents the vertex that is opposite to
** neighboring triangle 1, and so on. Node 1 is also the origin for
** edge 1, etc.
**
** Significant modifications:
** - 2/2/00: GT transferred get/set, constructors, and other small
** functions from .cpp file to inline them
**
** $Id: meshElements.h,v 1.83 2008-07-07 16:18:58 childcvs Exp $
** (file consolidated from earlier separate tNode, tEdge, & tTriangle
** files, 1/20/98 gt)
*/
/**************************************************************************/
#ifndef MESHELEMENTS_H
#define MESHELEMENTS_H
#include <iostream>
#include <vector>
#include <math.h> // for sqrt() used in inlined fn below
#include "../Definitions.h"
#include "../tList/tList.h"
#include "../tPtrList/tPtrList.h"
#include "../tArray/tArray.h"
#include "../tArray/tArray2.h"
#include "../Geometry/geometry.h" // for Point2D definitions & fns
#include "../tInputFile/tInputFile.h"
using namespace std;
class tEdge;
class tTriangle;
/**************************************************************************/
/**
** @class tNode
**
** tNodes are the points in a Delaunay triangulation, and their data
** include x and y coordinates, a z value (which could be elevation or
** some other variable), an ID, the point's Voronoi area and its reciprocal,
** and a pointer to one of its "spokes" (edges that originate at the node).
** Because each spoke points to its counter-clockwise neighbor, tNode
** objects only need to point to one of their spokes. However, for
** convenience, the current implementation of tNode also contains a list
** of pointers to all spokes (a "spoke list" of type tPtrList). In the
** future, to conserve memory usage, these spoke lists will only be
** allocated when needed by various mesh modification routines.
**
** Other tNode variables include the area of the corresponding Voronoi
** cell, an ID number, and a flag indicating the node's boundary status.
** Possible boundary status codes are non-boundary (mesh interior), closed
** (outer boundary, not counted as part of the solution domain), and
** open (boundary node not part of the solution domain but representing
** a valid exit point for mass or energy flows). Note that these boundary
** codes are used by tMesh to segregate nodes according to whether they
** are boundary or non-boundary points. Note also that while all hull
** points must be boundaries, interior points do not necessarily have to
** be flagged as non-boundaries (e.g., one could include an "island" of
** boundary points in the interior of a mesh if needed).
**
** Modifications:
** - 2/99 GT added tNode::AttachNewSpoke and tEdge::WelcomeCCWNeighbor
** - 2/00 GT added getVoronoiVertexList and getVoronoiVertexXYZList.
** These fns can be used in adding new nodes at V. Vertices.
**
*/
/**************************************************************************/
class tNode
{
public:
tNode(); // default constructor
tNode( const tNode & ); // copy constructor
tNode( const tInputFile & );
virtual ~tNode() { edg = 0; }
const tNode &operator=( const tNode & ); // assignment operator
tArray< double > get3DCoords() const; // returns x,y,z
tArray< double > get2DCoords() const; // returns x,y
// SL, 7/2003: added less costly versions that pass references
void get3DCoords( tArray< double >& ) const;
void get2DCoords( tArray< double >& ) const;
void get2DCoords( tArray2< double >& ) const;
inline int getID() const; // returns ID number
inline int getPermID() const; // returns permanent ID number
inline double getX() const; // returns x coord
inline double getY() const; // returns y coord
inline double getZ() const; // returns z value
double getVArea() const; // returns Voronoi area
double getVArea_Rcp() const; // returns 1/Voronoi area
tBoundary_t getBoundaryFlag() const; // returns boundary code
bool isNonBoundary() const;
tEdge * getEdg(); // returns ptr to one spoke
tEdge const * getEdg() const; // returns ptr to one spoke
void getVoronoiVertexList( tList<Point2D> * ); // Returns list of V vertices
void getVoronoiVertexXYZList( tList<Point3D> * ); // As above plus interp z
void setID( int ); // sets ID number
void setPermID( int ); // sets Permanent ID
inline void setX( double ); // sets x coord
inline void setY( double ); // sets y coord
inline void setZ( double ); // sets z value
virtual void ChangeZ( double ); // adds or subtracts from the current z value
void setVArea( double ); // sets Voronoi area
void setVArea_Rcp( double ); // sets 1 / Voronoi area
void set2DCoords( double, double ); // sets x and y values
void set3DCoords( double, double, double ); // sets x, y, and z values
void setBoundaryFlag( tBoundary_t ); // sets boundary status flag
void setEdg( tEdge * ); // sets ptr to one spoke
double Dist( tNode const *, tNode const * ) const; // distance from node to line (node1,node2)
tEdge *EdgToNod( tNode const * );// finds spoke connected to given node
double ComputeVoronoiArea(); // calculates node's Voronoi area
void ConvertToClosedBoundary(); // makes node a closed bdy & updates edges
virtual void WarnSpokeLeaving( tEdge *); // signals node that spoke is being deleted
virtual void InitializeNode(); // used when new nodes are created,
// for now only has a purpose in inherited classes
virtual tArray< double > FuturePosn();
virtual void UpdateCoords() {}
virtual bool isMobile() const { return false;}
virtual bool flowThrough( tEdge const * ) const { return false; }
virtual tNode *splitFlowEdge() { return 0; }
virtual void setDownstrmNbr( tNode * ) {}
virtual void PrepForAddition( tTriangle const *, double ) {}
virtual void PrepForMovement( tTriangle const *, double ) {}
void setListPtr(void *ptr) { listObj.setListPtr(ptr); }
void *getListPtr() const { return listObj.getListPtr(); }
inline virtual tArray<int> getEdgePtrIndices();
inline virtual void setEdgePtrsFromVector( vector<tEdge*>& );
#ifndef NDEBUG
void TellAll() const; // Debugging routine that outputs node data
#endif
private:
static bool freezeElevations; // option for running model without
// changing elevations
protected:
tListable listObj;
int id; // ID number
int permid; // Permanent ID number (no renumbering!)
double x; // x coordinate
double y; // y coordinate
double z; // z value (representing height or any other variable)
double varea; // Voronoi cell area
double varea_rcp; // Reciprocal of Voronoi area = 1/varea (for speed)
tBoundary_t boundary; // Boundary status code
private:
tEdge * edg; // Ptr to one edge
public:
int public1; // a "public" member that can be used for various purpose
};
/***************************************************************************\
** @class tEdge
**
** tEdge objects represent the directed edges in a Delaunay triangulation
** of tNode objects. "Directed" means that the edge has directionality
** from one point to the other; one is the origin and the other the
** the destination. In addition to pointing to its origin and destination
** nodes, each tEdge points to the tEdge that shares the same origin and
** lies immediately counter-clockwise. This makes it possible to obtain,
** given one tEdge, all of the tEdges connected to a given origin node.
** Other data maintained by a tEdge include its length, slope (if
** applicable), a boundary flag, the coordinates of the Voronoi vertex
** vertex associated with the right-hand triangle, and the length of
** the corresponding Voronoi cell edge.
**
** The boundary status of a tEdge object depends on the boundary status
** of the two nodes to which it is connected: if either node is a closed
** boundary, the edge's is a "no flow" (boundary) edge; otherwise it is a
** "flow allowed" (non-boundary) edge.
**
** Note that an edge's slope is defined as the (Zo - Zd)/L, where Zo and
** Zd are the z values of the origin and destination nodes, respectively,
** and L is the edge's (projected) length.
**
** Modifications:
** - added FindComplement function, 4/98 GT
** - added cwedg and tri pointers with corresponding get and set functions,
** 2/99 SL
** - added compedg pointer and corresponding get and set functions, 4/00 SL
**
\***************************************************************************/
class tEdge
{
public:
typedef enum {
kFlowAllowed = 1,
kFlowNotAllowed = 0
} tEdgeBoundary_t;
inline static
const char* EdgeBoundName( tEdgeBoundary_t b ){
switch(b){
case kFlowAllowed:
return "1-Allowed";
case kFlowNotAllowed:
return "0-NonAllowed";
}
/*NOTREACHED*/
abort();
}
tEdge(); // default constructor
tEdge( const tEdge & ); // copy constructor
tEdge( tNode*, tNode* ); // makes edge between two nodes
tEdge( int, tNode*, tNode* ); // makes edge between two nodes w/ given id
~tEdge() {org=dest=0; ccwedg=cwedg=compedg=0; tri=0;} // destructor
const tEdge &operator=( const tEdge & ); // assignment operator
void InitializeEdge( tNode*, tNode*, tNode const *, bool useFuturePosn = false );
inline int getID() const; // returns ID number
tBoundary_t getBoundaryFlag() const; // returns boundary status (flow or no flow)
bool isNonBoundary() const;
inline double getLength() const; // returns edge's length (projected)
inline double getSlope() const; // slope = "z" gradient from org to dest nodes
double getOrgZ() const; // returns origin's z value
double getDestZ() const; // returns destination's z value
inline const tNode *getOriginPtr() const; // returns ptr to origin node (const)
inline const tNode *getDestinationPtr() const; // returns ptr to dest node (const)
inline tNode *getOriginPtrNC(); // returns ptr to origin node (non-const)
inline tNode *getDestinationPtrNC(); // returns ptr to destination node (non-const)
inline tEdge * getCCWEdg(); // returns ptr to counter-clockwise neighbor
inline tEdge * getCWEdg();
inline tEdge* getComplementEdge();
inline tEdge const * getComplementEdge() const;
inline void setComplementEdge( tEdge* );
inline tArray2< double > const & getRVtx() const; // returns Voronoi vertex for RH triangle
inline void getRVtx( tArray2< double >& ) const; // less costly ref-passing version
inline double getVEdgLen() const; // returns length of assoc'd Voronoi cell edge
inline tEdgeBoundary_t FlowAllowed() const; // returns boundary status ("flow allowed")
inline void setID( int ); // sets ID number
inline void setLength( double ); // sets edge length
inline void setSlope( double ); // sets slope
inline void setOriginPtr( tNode * ); // sets origin ptr
inline void setDestinationPtr( tNode * ); // sets destination ptr
static tEdgeBoundary_t isFlowAllowed( const tNode*, const tNode* );
void setFlowAllowed( tEdgeBoundary_t ); // sets boundary code
inline void setFlowAllowed( const tNode*, const tNode* ); // sets boundary code
void UpdateBoundaryStatusForEdgeAndComplement( tEdgeBoundary_t new_boundary_status );
double CalcLength(); // computes & sets length
double CalcSlope(); // computes & sets slope
void setCCWEdg( tEdge * edg ); // sets ptr to counter-clockwise neighbor
void setCWEdg( tEdge * edg );
void setRVtx( tArray2< double > const &); // sets coords of Voronoi vertex RH tri
void setVEdgLen( double ); // sets length of corresponding Voronoi edge
double CalcVEdgLen(); // computes, sets & returns length of V cell edg
inline tArray2< double > const & getEVec() const {return eVec;}
inline tArray2< double > const & getVVec() const {return vVec;}
tEdge * FindComplement(); // returns ptr to edge's complement
inline tTriangle* TriWithEdgePtr();
inline void setTri( tTriangle* );
bool CheckConsistency();
inline bool isFlippable() const;
void setListPtr(void *ptr) { listObj.setListPtr(ptr); }
void *getListPtr() const { return listObj.getListPtr(); }
#ifndef NDEBUG
void TellCoords(); // debug routine that reports edge coordinates
#endif
private:
tListable listObj;
int id; // ID number
tEdgeBoundary_t flowAllowed; // boundary flag, usu. false when org & dest = closed bds
double len; // edge length
double slope; // edge slope
tArray2< double > rvtx; // (x,y) coords of Voronoi vertex in RH triangle
double vedglen; // length of Voronoi edge shared by org & dest cells
tArray2< double > eVec; // vector corresponding to edge
tArray2< double > vVec; // vector corresponding to Voronoi edge
tNode *org, *dest; // ptrs to origin and destination nodes
tEdge *ccwedg; // ptr to counter-clockwise (left-hand) edge w/ same origin
tEdge *cwedg; // ptr to clockwise (right-hand) edge w/ same origin
tEdge *compedg; // ptr to complement edge
tTriangle *tri; // ptr to triangle (if any) that contains pointer to edge;
// it's set from tTriangle::setEPtr( tEdge* ptr )
};
/**************************************************************************/
/**
** @class tTriangle
**
** tTriangles are the Delaunay triangles that form the triangulated mesh.
** Each tTriangle maintains pointers to its three nodes (vertices), three
** adjacent triangles (if they exist), and to the three counter-clockwise
** directed edges. For example, a tTriangle containing points a, b, and c
** (where the order abc is counter-clockwise) would point to tNodes a,b,c
** and tEdges a->b, b->c, and c->a, as well as to the tTriangles that share
** sides ab, bc, and ac.
**
** Numbering convention:
** - points p0,p1,p2 are in counter-clockwise order
** - adjacent triangle t0 lies opposite point p0
** - directed edge e0 has points p0->p2
**
** Modifications:
** - added function FindCircumcenter(), 1/11/98 gt
** - added index_ and associated functions 08/2003
**
*/
/**************************************************************************/
class tTriangle
{
public:
tTriangle(); // default constructor
tTriangle( const tTriangle & ); // copy constructor
tTriangle( int, tNode*, tNode*, tNode* );
tTriangle( int, tNode*, tNode*, tNode*, tEdge*, tEdge*, tEdge* );
~tTriangle(); // destructor
// ~tTriangle() {p[0]=p[1]=p[2]=0; e[0]=e[1]=e[2]=0; t[0]=t[1]=t[2]=0;} // destructor
const tTriangle &operator=( const tTriangle & ); // assignment operator
void InitializeTriangle( tNode*, tNode*, tNode* );
inline int getID() const; // returns ID number
inline tNode *pPtr( int ) const; // returns ptr to given vertex (0,1, or 2)
inline tEdge *ePtr( int ) const; // returns ptr to given clockwise edge
inline tTriangle *tPtr( int ) const; // returns ptr to given neighboring tri
inline void setID( int ); // sets ID number
inline void setPPtr( int, tNode * ); // sets ptr to given vertex
inline void setEPtr( int, tEdge * ); // sets ptr to given clockwise edge
inline void setTPtr( int, tTriangle * ); // sets ptr to given neighboring tri
inline int nVOp( const tTriangle * ) const;// returns side # (0,1 or 2) of nbr triangle
int nVtx( const tNode * ) const; // returns vertex # (0,1 or 2) of given node
tArray2<double> FindCircumcenter() const; // computes & returns tri's circumcenter
const unsigned char *index() const { return index_; }
void SetIndexIDOrdered(); // build the ordering index array
inline bool isIndexIDOrdered() const;
bool containsPoint(double, double) const; // does "this" contains the point (x,y)
tTriangle* NbrToward( double, double );
#ifndef NDEBUG
void TellAll() const; // debugging routine
#endif
void setListPtr(void *ptr) { listObj.setListPtr(ptr); }
void *getListPtr() const { return listObj.getListPtr(); }
private:
tListable listObj;
tNode *p[3]; // ptrs to 3 nodes (vertices)
tEdge *e[3]; // ptrs to 3 clockwise-oriented edges
tTriangle *t[3]; // ptrs to 3 neighboring triangles (or 0 if no nbr exists)
int id; // triangle ID number
unsigned char index_[3]; // index used for ordered output
inline void SetIndex(); // build the ordering index array in simple order
};
/**************************************************************************/
/**
** @class tSpkIter
**
*/
/**************************************************************************/
class tSpkIter
{
public:
tSpkIter();
tSpkIter( tNode* );
~tSpkIter();
void Reset( tNode* );
tNode* CurNode();
tEdge* CurSpoke();
int getNumSpokes();
int First();
int Last();
int Next();
int Prev();
int Get( int );
int Get( const tEdge* );
int Where() const;
tEdge* FirstP();
tEdge* LastP();
tEdge* NextP();
tEdge* PrevP();
tEdge* GetP( int );
tEdge* GetP( tEdge const * );
tEdge* ReportNextP();
tEdge* ReportPrevP();
inline bool AtEnd();
inline bool isEmpty();
int insertAtPrev( tEdge* );
int insertAtNext( tEdge* );
inline int insertAtFront( tEdge* );
int insertAtBack( tEdge* );
tEdge* removePrev();
tEdge* removeNext();
tEdge* removeFromFront();
tEdge* removeFromBack();
private:
tNode* curnode;
tEdge* curedg;
int counter;
};
/***************************************************************************\
\** Inlined Functions for class tNode ************************************/
/***********************************************************************\
**
** Constructors & destructors:
**
** Default: initializes values to zero.
** Copy: copies all values and makes duplicate spoke list
** Destructor: no longer used
**
\***********************************************************************/
//default constructor
inline tNode::tNode() :
listObj(),
id(0),
x(0.), y(0.), z(0.),
varea(0.), varea_rcp(0.),
boundary(kNonBoundary), edg(0),
public1(-1)
{}
//copy constructor
inline tNode::tNode( const tNode &original ) :
listObj(original.listObj),
id(original.id), permid(original.id),
x(original.x), y(original.y), z(original.z),
varea(original.varea), varea_rcp(original.varea_rcp),
boundary(original.boundary), edg(original.edg),
public1(original.public1)
{}
inline tNode::tNode( const tInputFile & infile )
:
listObj(),
id(0),
x(0.), y(0.), z(0.),
varea(0.), varea_rcp(0.),
boundary(kNonBoundary), edg(0),
public1(-1)
{ // static boolean to enable running model without changing elevations:
freezeElevations = infile.ReadBool( "OPT_FREEZE_ELEVATIONS", false );
}
/*X tNode::~tNode()
{
if (0)//DEBUG
std::cout << " ~tNode()" << std::endl;
}*/
/***********************************************************************\
**
** Overloaded operators:
**
** assignment: copies all values (spokelist's assignment operator
** creates duplicate copy of list)
** right shift: takes input for x, y and z values from input stream
** left shift: sends the following data to the output stream:
** node ID, x, y, z values, and IDs of neighboring nodes,
** which are obtained through the spokelist.
**
\***********************************************************************/
//assignment
inline const tNode &tNode::operator=( const tNode &right )
{
if( &right != this )
{
listObj = right.listObj,
id = right.id;
permid = right.permid;
x = right.x;
y = right.y;
z = right.z;
boundary = right.boundary;
varea = right.varea;
varea_rcp = right.varea_rcp;
edg = right.edg;
public1 = right.public1;
}
return *this;
}
//right shift
inline std::istream &operator>>( std::istream &input, tNode &node )
{
double x, y, z;
std::cout << "x y z:" << std::endl;
input >> x >> y >> z;
node.setX(x);
node.setY(y);
node.setZ(z);
return input;
}
//left shift
inline std::ostream &operator<<( std::ostream &output, tNode const &node )
{
output << node.getID() << ": " << node.getX() << " " << node.getY() << " "
<< node.getZ()
<< std::endl;
return output;
}
/***********************************************************************\
**
** tNode "get" functions:
**
** get3DCoords - returns x, y, z as a 3-element array
** get2DCoords - returns x & y coords as a 2-element array
** getID - returns ID #
** getX - returns node's x coord
** getY - returns node's y coord
** getZ - returns node's z value
** getVArea - returns Voronoi area
** getVArea_Rcp - returns 1 / Voronoi area
** getBoundaryFlag - returns boundary code
** getEdg - returns pointer to one spoke
**
\***********************************************************************/
inline tArray< double >
tNode::get3DCoords() const
{
return tArray< double > (x, y, z);
}
inline void tNode::get3DCoords( tArray< double >& xyz ) const
{
if( xyz.getSize() != 3 ) xyz.setSize(3);
xyz[0] = x;
xyz[1] = y;
xyz[2] = z;
}
inline tArray< double >
tNode::get2DCoords() const
{
return tArray< double > (x, y);
}
inline void tNode::get2DCoords( tArray< double >& xy ) const
{
if( xy.getSize() != 2 ) xy.setSize(2);
xy.at(0) = x;
xy.at(1) = y;
}
inline void tNode::get2DCoords( tArray2< double >& xy ) const
{
xy.at(0) = x;
xy.at(1) = y;
}
inline int tNode::getID() const {return id;}
inline int tNode::getPermID() const {return permid;}
inline double tNode::getX() const {return x;}
inline double tNode::getY() const {return y;}
inline double tNode::getZ() const {return z;}
inline double tNode::getVArea() const {return varea;}
inline double tNode::getVArea_Rcp() const {return varea_rcp;}
inline tBoundary_t tNode::getBoundaryFlag() const {return boundary;}
inline bool tNode::isNonBoundary() const {return getBoundaryFlag() == kNonBoundary;}
inline tEdge * tNode::getEdg() {return edg;}
inline tEdge const * tNode::getEdg() const {return edg;}
/***********************************************************************\
**
** tNode "set" functions:
**
** setID - sets ID number to val
** setX - sets x coord to val
** setY - sets y coord to val
** setZ - sets z value to val
** setVArea - sets Voronoi area to val
** setVArea_Rcp - sets 1/Voronoi area to val
** setBoundaryFlag - returns boundary code
** set3DCoords - sets x, y, z to val1, val2, val3
** set2DCoords - sets x & y to val1 and val2
** setEdg - sets edge ptr to theEdg
**
** Note: unless otherwise noted, no runtime value checking is done
** (aside from assert statements)
**
\***********************************************************************/
inline void tNode::setID( int val ) {id = val;}
inline void tNode::setPermID( int val ) {permid = val;}
inline void tNode::setX( double val ) {x = val;}
inline void tNode::setY( double val ) {y = val;}
inline void tNode::setZ( double val ) {z = val;}
inline void tNode::setVArea( double val )
{
assert( val>=0.0 );
varea = val;
/*varea = ( val >= 0.0 ) ? val : 0.0;*/
}
inline void tNode::setVArea_Rcp( double val )
{
assert( val>=0.0 );
varea_rcp = val;
/*varea_rcp = ( val >= 0.0 ) ? val : 0.0;*/
}
inline void tNode::setBoundaryFlag( tBoundary_t val )
{
boundary = val;
}
inline void tNode::set2DCoords( double val1, double val2 )
{
setX( val1 );
setY( val2 );
}
inline void tNode::set3DCoords( double val1, double val2, double val3 )
{
setX( val1 );
setY( val2 );
setZ( val3 );
}
inline void tNode::setEdg( tEdge * theEdg )
{
edg = theEdg;
if (0)//DEBUG
std::cout << "Assigning edge " << theEdg->getID()
<< " to node " << getID() << std::endl;
}
/***********************************************************************\
**
** tNode::ChangeZ: Adds delz to current z value
**
\***********************************************************************/
inline void tNode::ChangeZ( double delz )
{ if( !freezeElevations ) z += delz; }
/*******************************************************************\
**
** tNode::WarnSpokeLeaving( tEdge * edglvingptr )
**
** This function is called when an edge is being removed from the edge list.
** If edg (the edge pointer member of tNode) is pointing to the edge
** which will be removed, this edg must be updated.
**
** edglvingptr is as it says, a pointer to the edge which will be
** removed.
**
** Called from tMesh::ExtricateEdge
**
** 9/98 NG and GT
\*******************************************************************/
inline void tNode::WarnSpokeLeaving( tEdge * edglvingptr )
{
assert(edg);
if( edglvingptr == edg )
edg = edg->getCCWEdg();
}
/**********************************************************************\
**
** tNode::InitializeNode()
**
** A virtual function.
** This functions doesn't do anything here, only in inherited classes.
** Used for initializing things in newly created nodes that are set up
** for the rest of the nodes when the mesh is created.
**
** 1/1999 NG
\**********************************************************************/
inline void tNode::InitializeNode()
{
}
/*******************************************************************\
tNode::FuturePosn() virtual function; here, just calls get2DCoords()
11/98 SL
5/2003 AD
\*******************************************************************/
inline tArray< double > tNode::FuturePosn() {return get2DCoords();}
/*******************************************************************\
tNode::getEdgePtrIndices() virtual function; here, returns
one-member array with edg ID
10/10 SL
\*******************************************************************/
inline tArray< int > tNode::getEdgePtrIndices()
{
tArray<int> ar(1);
ar[0] = edg->getID();
return ar;
}
/*******************************************************************\
tNode::setEdgePtrsFromVector() virtual function; here, sets edg
10/10 SL
\*******************************************************************/
inline void tNode::setEdgePtrsFromVector( vector<tEdge*>& ePtrs )
{
edg = ePtrs[0];
}
/**************************************************************************\
\*** Functions for class tEdge ******************************************/
/***********************************************************************\
**
** Constructors & destructors:
**
** Default: initializes values to zero and makes rvtx a 2-elem array
** Copy: copies all values
** Destructor: no longer used
**
\***********************************************************************/
//default constructor
inline tEdge::tEdge() :
listObj(),
id(0), flowAllowed(kFlowNotAllowed), len(0.), slope(0.),
rvtx(),
vedglen(0.),
org(0), dest(0), ccwedg(0), cwedg(0),
compedg(0), tri(0)
{
if (0)//DEBUG
std::cout << "tEdge()" << std::endl;
}
//copy constructor
inline tEdge::tEdge( const tEdge &original ) :
listObj(original.listObj),
id(original.id), flowAllowed(original.flowAllowed),
len(original.len), slope(original.slope),
rvtx(original.rvtx),
vedglen(original.vedglen),
org(original.org), dest(original.dest), ccwedg(original.ccwedg),
cwedg(original.cwedg), compedg(original.compedg), tri(original.tri)
{}
inline tEdge::tEdge(tNode* n1, tNode* n2) :
listObj(),
id(0), flowAllowed(kFlowNotAllowed), len(0.), slope(0.),
rvtx(),
vedglen(0.),
org(0), dest(0), ccwedg(0), cwedg(0),
compedg(0), tri(0)
{
setOriginPtr( n1 );
setDestinationPtr( n2 );
setFlowAllowed( n1, n2 );
}
inline tEdge::tEdge(int id_, tNode* n1, tNode* n2) :
listObj(),
id(id_), flowAllowed(kFlowNotAllowed), len(0.), slope(0.),
rvtx(),
vedglen(0.),
org(0), dest(0), ccwedg(0), cwedg(0),
compedg(0), tri(0)
{
setOriginPtr( n1 );
setDestinationPtr( n2 );
setFlowAllowed( n1, n2 );
}
//tEdge::~tEdge() {/*std::cout << " ~tEdge()" << std::endl;*/}
/***********************************************************************\
**
** Overloaded operators:
**
** assignment: copies all values (spokelist's assignment operator
** creates duplicate copy of list)
** left shift: sends the following data to the output stream:
** edge ID, length, slope, and origin and destination IDs
**
\***********************************************************************/
inline const tEdge &tEdge::operator=( const tEdge &original )
{
if( &original != this )
{
listObj = original.listObj;
id = original.id;
len = original.len;
slope = original.slope;
rvtx = original.rvtx;
vedglen = original.vedglen;
org = original.org;
dest = original.dest;
ccwedg = original.ccwedg;
cwedg = original.cwedg;
flowAllowed = original.flowAllowed;
compedg = original.compedg;
tri = original.tri;
}
return *this;
}
//left shift
inline std::ostream &operator<<( std::ostream &output, const tEdge &edge )
{
output << edge.getID() << " " << edge.getLength() << " " << edge.getSlope() << " "
<< edge.getOriginPtr()->getID()
<< " " << edge.getDestinationPtr()->getID() << std::endl;
return output;
}
/***********************************************************************\
**
** tEdge "get" functions:
**
** getID - returns ID #
** getBoundaryFlag - returns boundary code
** getLength - returns projectd length
** getSlope - returns slope
** getOriginPtr - returns const ptr to origin node
** getDestinationPtr - returns const ptr to destination node
** getOriginPtrNC - returns non-const ptr to origin node
** getDestinationPtrNC - returns non-const ptr to destination node
** getOrgZ- returns z value of origin node
** getDestZ - returns z value of destination node
** getCCWEdg - returns ptr to counterclockwise neighboring edge
** FlowAllowed - returns the boundary flag, which indicates whether
** or not the edge is an active flow conduit (which is
** true as long as neither endpoint is a closed bdy node)
** getRVtx - returns coordinates of right-hand Voronoi vertex as a
** 2-element array
** getVEdgLen - returns the length of the corresponding Voronoi edge
**
\***********************************************************************/
inline int tEdge::getID() const {return id;}
//return 0 if flow allowed to match kNonBoundary:
inline tBoundary_t tEdge::getBoundaryFlag() const
{return ( flowAllowed == kFlowAllowed )?kNonBoundary:kClosedBoundary; }
inline bool tEdge::isNonBoundary() const {return getBoundaryFlag() == kNonBoundary;}
inline double tEdge::getLength() const {return len;}
inline double tEdge::getSlope() const {return slope;}
inline const tNode *tEdge::getOriginPtr() const {return org;}
inline const tNode *tEdge::getDestinationPtr() const {return dest;}
inline tNode *tEdge::getOriginPtrNC() {return org;}
inline tNode *tEdge::getDestinationPtrNC() {return dest;}
inline double tEdge::getOrgZ() const
{
assert( org!=0 );
return( org->getZ() );
}
inline double tEdge::getDestZ() const
{
assert( dest!=0 );
return( dest->getZ() );
}
inline tEdge * tEdge::getCCWEdg()
{
return ccwedg;
}
inline tEdge * tEdge::getCWEdg()
{
return cwedg;
}
inline tEdge* tEdge::getComplementEdge()
{
return compedg;
}
inline tEdge const* tEdge::getComplementEdge() const
{
return compedg;
}
inline void tEdge::setComplementEdge( tEdge* edg )
{
compedg = edg;
}
inline tEdge::tEdgeBoundary_t tEdge::FlowAllowed() const
{
return flowAllowed;
}
inline tArray2< double > const &
tEdge::getRVtx() const
{
return rvtx;
}
inline void tEdge::getRVtx( tArray2< double >& arr ) const
{
arr = rvtx;
}
inline double tEdge::getVEdgLen() const {return vedglen;}
inline tTriangle* tEdge::TriWithEdgePtr() {return tri;}
/***********************************************************************\
**
** tEdge "set" functions:
**
** setID - sets ID # to val
** setLength - sets length to val
** setSlope - sets slope to slp
** setOriginPtr - sets origin pointer to ptr (if ptr is nonzero)
** setDestinationPtr - sets destination pointer to ptr (if nonzero)
** setFlowAllowed - sets flowAllowed status to val
** setCCWEdg - sets ptr to counter-clockwise neighbor to edg
** setRVtx - sets the coordinates of the right-hand Voronoi vertex
** (ie, the Voronoi vertex at the circumcenter of the RH
** triangle) to the 1st two elements in arr, which is
** assumed to be a 2-element array
** setVEdgLen - sets vedglen to val (vedglen is the length of the
** corresponding Voronoi cell edge)
**
** Note: unless otherwise noted, no checking of range or validity is
** performed in these routines (aside from assert statements)
**
\***********************************************************************/
inline void tEdge::setID( int val ) {
assert( id>=0 );
id = val;
}
inline void tEdge::setLength( double val )
{
assert( val>=0.0 );
len = val;
}
inline void tEdge::setSlope( double slp )
{ slope = slp; }
inline void tEdge::setOriginPtr( tNode * ptr ) {if( ptr != 0 ) org = ptr;}
inline void tEdge::setDestinationPtr( tNode * ptr )
{if( ptr != 0 ) dest = ptr;}
inline void tEdge::setFlowAllowed( tEdgeBoundary_t val )
{
assert( val==kFlowAllowed || val==kFlowNotAllowed );
flowAllowed = val;
}
inline tEdge::tEdgeBoundary_t tEdge::isFlowAllowed( const tNode* n1, const tNode* n2 )
{
assert( n1 && n2 );
return ( n1->getBoundaryFlag() != kClosedBoundary
&& n2->getBoundaryFlag() != kClosedBoundary
&& !( n1->getBoundaryFlag()==kOpenBoundary
&& n2->getBoundaryFlag()==kOpenBoundary ) ) ?
kFlowAllowed : kFlowNotAllowed;
}
inline void tEdge::setFlowAllowed( const tNode* n1, const tNode* n2 )
{
flowAllowed = tEdge::isFlowAllowed(n1, n2);
}
inline void tEdge::setCCWEdg( tEdge * edg )
{
assert( edg != 0 );
ccwedg = edg;
}
inline void tEdge::setCWEdg( tEdge * edg )
{
cwedg = edg;
}
inline void tEdge::setRVtx( tArray2< double > const & arr )
{
if (0)//DEBUG
std::cout << "setRVtx for edge " << id
<< " to x, y, " << arr.at(0) << ", " << arr.at(1) << std::endl;
rvtx = arr;
}
inline void tEdge::setVEdgLen( double val )
{
assert( val>=0.0 );
vedglen = val;
}
inline void tEdge::setTri( tTriangle* tptr )
{
tri = tptr;
}
inline bool tEdge::isFlippable() const
{
// An edge is not flippable if
// - both nodes are mobile
// - the edge is a flow edge for the origin or the complement
// edge is a flow edge for the destination
return !(
org->isMobile() && dest->isMobile() &&
(org->flowThrough(this) ||
dest->flowThrough(this->getComplementEdge())
)
);
}
/**************************************************************************\
**
** tEdge::CalcSlope
**
** Computes the slope of the edge as ( Zorg - Zdest ) / length.
**
** Returns: the slope
** Modifies: slope (data mbr)
** Assumes: length >0; org and dest valid.
**
\**************************************************************************/
inline double tEdge::CalcSlope()
{
assert( org!=0 ); // Failure = edge has no origin and/or destination node
assert( dest!=0 );
assert( len>0.0 );
slope = ( org->getZ() - dest->getZ() ) / len;
return slope;
}
/**************************************************************************\
**
** tEdge::CalcLength
**
** Computes the edge length and returns it. (Length is the projected
** on the x,y plane). Assumes org and dest are valid.
**
** Modified: Sets edge vector (eVec) for "this" and sets len and
** eVec for compedg. -SL, 11/2010
\**************************************************************************/
inline double tEdge::CalcLength()
{
assert( org!=0 ); // Failure = edge has no origin and/or destination node
assert( dest!=0 );
assert( compedg!=0 );
double dx = org->getX() - dest->getX();
double dy = org->getY() - dest->getY();
len = sqrt( dx*dx + dy*dy );
eVec.at(0) = dx;
eVec.at(1) = dy;
compedg->len = len;
compedg->eVec.at(0) = -dx;
compedg->eVec.at(1) = -dy;
return len;
}
/**************************************************************************\
**
** tEdge::CalcVEdgLen
**
** Calculates the length of the Voronoi cell edge associated with the
** current triangle edge. The Voronoi cell edge length is equal to the
** distance between the Voronoi vertex of the right-hand triangle and
** the Voronoi vertex of the left-hand triangle. The vertex for the
** right-hand triangle is stored with rvtx[] (and is assumed to be up to
** date), and the vertex for the left-hand triangle is stored in the
** edge's counter-clockwise (left-hand) neighbor (also assumed valid and
** up to date).
**
** Data mbrs modified: vedglen
** Returns: the Voronoi edge length
** Assumes: ccwedg valid, rvtx[] up to date
**
** Modified: Sets Voronoi vector (vVec) for "this" and sets vedglen and
** vVec for compedg. -SL, 11/2010
\**************************************************************************/
inline double tEdge::CalcVEdgLen()
{
assert( ccwedg!=0 );
assert( compedg!=0 );
double dx, dy;
dx = rvtx.at(0) - ccwedg->rvtx.at(0);
dy = rvtx.at(1) - ccwedg->rvtx.at(1);
vedglen = sqrt( dx*dx + dy*dy );
vVec.at(0) = dx;
vVec.at(1) = dy;
compedg->vedglen = vedglen;
compedg->vVec.at(0) = -dx;
compedg->vVec.at(1) = -dy;
return( vedglen );
}
/**************************************************************************\
** Functions for class tTriangle.
\**************************************************************************/
/***********************************************************************\
**
** Constructors & destructors:
**
** Default: initializes node, edge, and triangle ptrs to zero.
** Copy: copies all values
** ID & Vertices: creates a triangle w/ pointers to three vertices,
** and sets up edge pointers as well. Does not set
** triangle pointers however (these are zero'd).
** Destructor: no longer used
**
** Modifications:
** - ID & vertices constructor added 1/2000, GT
**
\***********************************************************************/
inline
void tTriangle::SetIndex()
{
index_[0] = 0;
index_[1] = 1;
index_[2] = 2;
}
//default
inline tTriangle::tTriangle() :
listObj(),
id(-1)
{
for( int i=0; i<3; i++ )
{
p[i] = 0;
e[i] = 0;
t[i] = 0;
}
SetIndex();
if (0)//DEBUG
std::cout << "tTriangle()" << std::endl;
}
//copy constructor
inline tTriangle::tTriangle( const tTriangle &init ) :
listObj(init.listObj),
id(init.id)
{
for( int i=0; i<3; i++ )
{
p[i] = init.p[i];
setEPtr( i, init.e[i] ); // sets edge's tri pointer as well!
t[i] = init.t[i];
index_[i] = init.index_[i];
}
if (0)//DEBUG
std::cout << "tTriangle( orig )" << std::endl;
}
// construct with id and 3 vertices
inline tTriangle::tTriangle( int id_, tNode* n0, tNode* n1, tNode* n2 ) :
listObj(),
id(id_)
{
assert( n0 != 0 && n1 != 0 && n2 != 0 );
p[0] = n0;
p[1] = n1;
p[2] = n2;
setEPtr( 0, n0->EdgToNod( n2 ) );
setEPtr( 1, n1->EdgToNod( n0 ) );
setEPtr( 2, n2->EdgToNod( n1 ) );
t[0] = t[1] = t[2] = 0;
SetIndex();
}
inline tTriangle::tTriangle( int id_, tNode* n0, tNode* n1, tNode* n2,
tEdge* e0, tEdge* e1, tEdge* e2 ) :
listObj(),
id(id_)
{
assert( n0 != 0 && n1 != 0 && n2 != 0 && e0 != 0 && e1 != 0 && e2 != 0 );
p[0] = n0;
p[1] = n1;
p[2] = n2;
setEPtr( 0, e0 );
setEPtr( 1, e1 );
setEPtr( 2, e2 );
t[0] = t[1] = t[2] = 0;
SetIndex();
}
/***********************************************************************\
**
** Overloaded operators:
**
** assignment: copies all values
** left shift: sends the following data to the output stream:
** triangle ID and the IDs of its 3 nodes, clockwise
** edges, ad neighboring triangles (or -1 if no
** neighboring triangle exists across a given face)
** right shift: reads triangle ID and 3 other unspecified IDs from
** the input stream (the latter are not currently used
** for anything)
**
\***********************************************************************/
//overloaded assignment operator
inline const tTriangle &tTriangle::operator=( const tTriangle &init )
{
if( &init != this )
{
listObj = init.listObj;
id = init.id;
for( int i=0; i<3; i++ )
{
p[i] = init.p[i];
setEPtr( i, init.e[i] ); // sets edge's tri pointer as well!
t[i] = init.t[i];
index_[i] = init.index_[i];
}
}
return *this;
}
//left shift
inline std::ostream &operator<<( std::ostream &output, const tTriangle &tri )
{
int i;
output << tri.getID() << ":";
for( i=0; i<3; i++ )
output << " " << tri.pPtr(i)->getID();
output << ";";
for( i=0; i<3; i++ )
output << " " << tri.ePtr(i)->getID();
output << ";";
for( i=0; i<3; i++ )
{
if( tri.tPtr(i) != 0 )
output << " " << tri.tPtr(i)->getID();
else
output << " -1";
}
output << std::endl;
return output;
}
inline std::istream &operator>>( std::istream &input, tTriangle &tri )
{
int id, id1, id2, id3;
std::cout << "triangle id, origin id, dest id:";
input >> id >> id1 >> id2 >> id3; //temporarily assign id vals to ptrs
tri.setID(id);
return input;
}
/***********************************************************************\
**
** tTriangle "get" functions:
**
** getID - returns ID #
** pPtr - returns ptr to one of the 3 vertex nodes, as specified by
** _index_ (index is 0, 1, or 2)
** ePtr - returns ptr to one of the 3 clockwise edges, as specified by
** _index_ (index is 0, 1, or 2)
** tPtr - returns ptr to one of the 3 adjacent triangles, as specified
** by _index_ (index is 0, 1, or 2)
**
\***********************************************************************/
inline int tTriangle::getID() const {return id;}
inline tNode *tTriangle::pPtr( int index ) const
{
assert( index >= 0 && index < 3 );
return p[index];
}
inline tEdge *tTriangle::ePtr( int index ) const
{
assert( index >= 0 && index < 3 );
return e[index];
}
inline tTriangle *tTriangle::tPtr( int index ) const
{
assert( index >= 0 && index < 3 );
return t[index];
}
/***********************************************************************\
**
** tTriangle "set" functions:
**
** setID - sets ID #
** setPPtr - sets pointer to one of the 3 vertex nodes, as specified
** by _index_ (index is 0, 1, or 2)
** setEPtr - sets pointer to one of the 3 clockwise edges, as specified
** by _index_ (index is 0, 1, or 2)
** setTPtr - sets pointer to one of the 3 adjacent triangles, as
** specified by _index_ (index is 0, 1, or 2)
**
\***********************************************************************/
inline void tTriangle::setID( int val ) {id = ( val >= 0 ) ? val : 0;}
inline void tTriangle::setPPtr( int index, tNode * ndptr )
{
assert( index >= 0 && index < 3 );
p[index] = ndptr;
}
inline void tTriangle::setEPtr( int index, tEdge * egptr )
{
assert( index >= 0 && index < 3 );
if( egptr == 0 && e[index] != 0 &&
e[index]->TriWithEdgePtr() == this) {
e[index]->setTri(0);
}
e[index] = egptr;
if( egptr != 0 )
egptr->setTri( this );
}
inline void tTriangle::setTPtr( int index, tTriangle * trptr )
{
assert( index >= 0 && index < 3 );
t[index] = trptr;
}
/**************************************************************************\
**
** tTriangle::nVOp
**
** Returns the side number (0, 1, or 2) of the neighboring triangle ct.
** Assumes that ct _is_ one of the neighboring triangles.
**
\**************************************************************************/
inline int tTriangle::nVOp( const tTriangle *ct ) const
{
for( int i=0; i<3; ++i )
if( t[i] == ct ) return i;
assert( 0 ); /*NOTREACHED*/
abort();
}
/**************************************************************************\
**
** tTriangle::nVtx
**
** Returns the vertex number (0, 1, or 2) associated with node cn.
** (In other words, it says whether cn is vertex 0, 1, or 2 in the
** triangle).
** Assumes that cn _is_ one of the triangle's vertices.
**
\**************************************************************************/
inline int tTriangle::nVtx( const tNode *cn ) const
{
for( int i=0; i<3; ++i )
if( p[i] == cn ) return i;
assert( 0 ); /*NOTREACHED*/
abort();
}
/*****************************************************************************\
**
** tTriangle::isIndexIDOrdered
**
** Tell whether index_ has been ID ordered
**
\*****************************************************************************/
inline bool tTriangle::isIndexIDOrdered() const {
return
BOOL(
( index_[1] == (index_[0]+1)%3 ) &&
( index_[2] == (index_[1]+1)%3 ) &&
( pPtr(index_[0])->getID() < pPtr(index_[1])->getID() ) &&
( pPtr(index_[0])->getID() < pPtr(index_[2])->getID() )
);
}
/**************************************************************************\
**
** tSpkIter
**
\**************************************************************************/
inline tSpkIter::tSpkIter() :
curnode(0),
curedg(0),
counter(0)
{}
inline tSpkIter::tSpkIter( tNode* nPtr ) :
curnode(0),
curedg(0),
counter(0)
{
assert( nPtr != 0 );
curnode = nPtr;
curedg = curnode->getEdg();
}
inline tSpkIter::~tSpkIter()
{
curnode = 0;
curedg = 0;
}
inline tNode* tSpkIter::CurNode() {return curnode;}
inline tEdge* tSpkIter::CurSpoke() {return curedg;}
inline int tSpkIter::getNumSpokes()
{
tEdge* fe = curnode->getEdg();
tEdge* ce = fe;
int ctr = 1;
while( ( ce = ce->getCCWEdg() ) != fe )
++ctr;
return ctr;
}
inline void tSpkIter::Reset( tNode* nPtr )
{
assert( nPtr != 0 );
curnode = nPtr;
curedg = curnode->getEdg();
counter = 0;
}
inline int tSpkIter::First()
{
curedg = curnode->getEdg();
counter = 0;
if( curedg != 0 ) return 1;
return 0;
}
inline tEdge* tSpkIter::FirstP()
{
if( First() ) return curedg;
return 0;
}
inline int tSpkIter::Last()
{
curedg = curnode->getEdg()->getCWEdg();
counter = -1;
if( curedg != 0 ) return 1;
return 0;
}
inline tEdge* tSpkIter::LastP()
{
if( Last() ) return curedg;
return 0;
}
inline int tSpkIter::Next()
{
curedg = curedg->getCCWEdg();
++counter;
if( curedg != 0 ) return 1;
return 0;
}
inline tEdge* tSpkIter::NextP()
{
if( Next() ) return curedg;
return 0;
}
inline int tSpkIter::Prev()
{
curedg = curedg->getCWEdg();
--counter;
if( curedg != 0 ) return 1;
return 0;
}
inline tEdge* tSpkIter::PrevP()
{
if( Prev() ) return curedg;
return 0;
}
inline int tSpkIter::Get( int num )
{
if( !First() ) return 0;
while( curedg->getID() != num && !AtEnd() )
curedg = curedg->getCCWEdg();
if( !AtEnd() ) return 1;
return 0;
}
inline tEdge* tSpkIter::GetP( int num )
{
if( Get( num ) ) return curedg;
return 0;
}
inline int tSpkIter::Get( const tEdge* ePtr )
{
if( ePtr == 0 ) return 0;
if( !First() ) return 0;
while( curedg != ePtr && !AtEnd() )
curedg = curedg->getCCWEdg();
if( !AtEnd() ) return 1;
return 0;
}
inline tEdge* tSpkIter::GetP( const tEdge* ePtr )
{
if( Get( ePtr ) ) return curedg;
return 0;
}
inline int tSpkIter::Where() const
{
if( curedg == 0 ) return -1;
return curedg->getID();
}
inline tEdge* tSpkIter::ReportNextP()
{
return curedg->getCCWEdg();
}
inline tEdge* tSpkIter::ReportPrevP()
{
return curedg->getCWEdg();
}
inline bool tSpkIter::AtEnd()
{
if( isEmpty() ) return true;
return ( curedg == curnode->getEdg() && counter != 0 );
}
inline bool tSpkIter::isEmpty()
{
return( curnode->getEdg() == 0 );
}
inline int tSpkIter::insertAtPrev( tEdge* ePtr )
{
if( ePtr == 0 ) return 0;
if( isEmpty() ) return insertAtFront( ePtr );
assert( ePtr->getOriginPtr() == curnode );
ePtr->setCCWEdg( curedg );
ePtr->setCWEdg( curedg->getCWEdg() );
curedg->getCWEdg()->setCCWEdg( ePtr );
curedg->setCWEdg( ePtr );
return 1;
}
inline int tSpkIter::insertAtNext( tEdge* ePtr )
{
if( ePtr == 0 ) return 0;
if( isEmpty() ) return insertAtFront( ePtr );
assert( ePtr->getOriginPtr() == curnode );
ePtr->setCWEdg( curedg );
ePtr->setCCWEdg( curedg->getCCWEdg() );
curedg->getCCWEdg()->setCWEdg( ePtr );
curedg->setCCWEdg( ePtr );
return 1;
}
inline int tSpkIter::insertAtFront( tEdge* ePtr )
{
if( ePtr == 0 ) return 0;
assert( ePtr->getOriginPtr() == curnode );
if( isEmpty() )
{
curnode->setEdg( ePtr );
ePtr->setCCWEdg( ePtr );
ePtr->setCWEdg( ePtr );
return 1;
}
tEdge* ofe = curnode->getEdg();
ePtr->setCCWEdg( ofe );
ePtr->setCWEdg( ofe->getCWEdg() );
ofe->getCWEdg()->setCCWEdg( ePtr );
ofe->setCWEdg( ePtr );
curnode->setEdg( ePtr );
return 1;
}
inline int tSpkIter::insertAtBack( tEdge* ePtr )
{
if( ePtr == 0 ) return 0;
if( isEmpty() ) return insertAtFront( ePtr );
assert( ePtr->getOriginPtr() == curnode );
tEdge* ofe = curnode->getEdg();
ePtr->setCCWEdg( ofe );
ePtr->setCWEdg( ofe->getCWEdg() );
ofe->getCWEdg()->setCCWEdg( ePtr );
ofe->setCWEdg( ePtr );
return 1;
}
inline tEdge* tSpkIter::removePrev()
{
if( isEmpty() ) return 0;
if( curedg->getCWEdg() == curedg )
{
curnode->setEdg( 0 );
return curedg;
}
tEdge* re = curedg->getCWEdg();
re->getCWEdg()->setCCWEdg( re->getCCWEdg() );
re->getCCWEdg()->setCWEdg( re->getCWEdg() );
return re;
}
inline tEdge* tSpkIter::removeNext()
{
if( isEmpty() ) return 0;
if( curedg->getCCWEdg() == curedg )
{
curnode->setEdg( 0 );
return curedg;
}
tEdge* re = curedg->getCCWEdg();
re->getCWEdg()->setCCWEdg( re->getCCWEdg() );
re->getCCWEdg()->setCWEdg( re->getCWEdg() );
return re;
}
inline tEdge* tSpkIter::removeFromFront()
{
if( isEmpty() ) return 0;
tEdge* re = curnode->getEdg();
if( re->getCCWEdg() == re )
{
curnode->setEdg( 0 );
return re;
}
curnode->setEdg( re->getCCWEdg() );
re->getCWEdg()->setCCWEdg( re->getCCWEdg() );
re->getCCWEdg()->setCWEdg( re->getCWEdg() );
if( curedg == re ) curedg = curnode->getEdg();
return re;
}
inline tEdge* tSpkIter::removeFromBack()
{
if( isEmpty() ) return 0;
tEdge* re = curnode->getEdg()->getCWEdg();
if( re->getCCWEdg() == re )
{
curnode->setEdg( 0 );
return re;
}
re->getCWEdg()->setCCWEdg( re->getCCWEdg() );
re->getCCWEdg()->setCWEdg( re->getCWEdg() );
if( curedg == re ) curedg = curnode->getEdg()->getCWEdg();
return re;
}
#endif
| [
"eunseo@Mohr.ceri.memphis.edu"
] | eunseo@Mohr.ceri.memphis.edu |
9e14626237f3a3578093f2b22b47c7f2dea016d6 | 4dc8ba6b2ae4ec978310c918c1b23e6a7d45e450 | /src/GPIO/RPi4GPIO.cpp | ef00d31ce0e89433ed20cf99573fec7fdfb2a1a4 | [
"MIT"
] | permissive | mitchdz/Smart-Doorbell | 42a2cf526b951384f7976bfb5d76144807de008f | cbc04691a65d37ce1a19cba2138d2f8363acf290 | refs/heads/main | 2023-04-05T14:21:33.555921 | 2021-02-17T21:51:30 | 2021-02-17T21:51:30 | 337,545,958 | 0 | 0 | MIT | 2021-02-09T21:50:34 | 2021-02-09T21:50:33 | null | UTF-8 | C++ | false | false | 2,138 | cpp | /*
* MIT License
*
* Copyright (c) 2021 Lena Voytek
*
* 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.
*
* RPi4GPIO
*
* This module acts as a driver for Raspberry Pi 4 GPIO pins
*/
#include "RPi4GPIO.h"
#include "RPi4.h"
void RPi4GPIO::noInterrupts()
{
// save current interrupts
irq1 = IRQ_ENABLE1;
irq2 = IRQ_ENABLE2;
irqbasic = IRQ_ENABLE_BASIC;
// disable interrupts
IRQ_DISABLE1 = irq1;
IRQ_DISABLE2 = irq2;
IRQ_DISABLE_BASIC = irqbasic;
}
void RPi4GPIO::interrupts()
{
if(IRQ_ENABLE1 == 0)
{
IRQ_ENABLE1 = irq1;
IRQ_ENABLE2 = irq2;
IRQ_ENABLE_BASIC = irqbasic;
}
}
void RPi4GPIO::pinMode(PIN pin, unsigned int mode)
{
int reg = pin / 10;
int offset = (pin % 10) * 3;
GPFSEL[reg] &= ~((0b111 & ~mode) << offset);
GPFSEL[reg] |= ((0b111 & mode) << offset);
}
void RPi4GPIO::digitalWrite(PIN pin, int val)
{
int reg = pin / 32;
int offset = pin % 32;
if(val)
GPSET[reg] = 1 << offset;
else
GPCLR[reg] = 1 << offset;
}
int RPi4GPIO::digitalRead(PIN pin)
{
int reg = pin / 32;
int offset = pin % 32;
return (GPLEV[reg] >> offset) & 0x00000001;
} | [
"dvoytek@email.arizona.edu"
] | dvoytek@email.arizona.edu |
e2871707e20c329e3c8d5c0a7d40406ab409a406 | e582ee445ead5726d297e95742bb696e4c2ed3e7 | /ColonizingGame.cpp | 791403a671ad74de08faed7dcca53d8894b18ad6 | [] | no_license | aljazk/ColonizingGame | 2d8742b350b50dbd953c25f739499379971ef837 | d39c49364b3bacd387239d9f8cc7b2f4fddf2136 | refs/heads/master | 2022-12-14T16:51:49.525472 | 2020-09-09T20:47:52 | 2020-09-09T20:47:52 | 294,226,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | // ColonizingGame.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "Window.h"
int main()
{
Window window;
window.Run();
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| [
"aljaz.konecnik@gmail.com"
] | aljaz.konecnik@gmail.com |
c6703c14f5981226fe499ee5dd2e34e553769c83 | c208946c65e9ecd381448c3b4b94ceda29940f4b | /Project1/Pawn.h | 27e857ec87024afeda941b8528759fa3823c1f5e | [] | no_license | StanleyAlbayeros/BattleChess3D | b30ac61ba8941f02559fe76181e90442a713c20e | 6c9ffb78131ab0cc891997649b2b729837b314a1 | refs/heads/master | 2023-06-24T21:22:57.652300 | 2017-10-16T03:46:23 | 2017-10-16T03:46:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | h | #pragma once
#include "Pieces.h"
class Pawn :
public Pieces
{
public:
bool debugMode;
Pawn(bool debug, Position pos);
~Pawn();
private:
string pieceName = "Pawn";
//string pieceID = "P";
};
| [
"drkztan@gmail.com"
] | drkztan@gmail.com |
19c34277ad00f39eaff28544ad72b43e983b2a7e | e741f43e6f28669f1330faa422bbf44c496b63b4 | /old/session12Permutations/c++map.cc | a7c81ec1592572b64b85a1bfbac929f45f4063d8 | [] | no_license | StevensDeptECE/CPE593 | d5ee7816a42d9db112a9618fb95c14922ccd8e75 | 3ca8115e84287a2afd18d27976720c159ab056a2 | refs/heads/master | 2023-04-26T21:07:47.252333 | 2023-04-19T01:25:09 | 2023-04-19T01:25:09 | 102,521,068 | 50 | 51 | null | 2023-03-05T17:45:52 | 2017-09-05T19:22:17 | C++ | UTF-8 | C++ | false | false | 429 | cc | #include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
map<string, double> stock;
stock["IBM"] = 119.5;
stock["BIDU"] = 138;
stock["AAPL"] = 152;
for (map<string,double>::iterator i = stock.begin(); i != stock.end(); ++i)
cout << i->first << " ==> " << i->second << '\n';
cout << "\n\n\n";
for (auto p : stock) {
cout << p.first << " ==> " << p.second << '\n';
}
cout << '\n';
}
| [
"Dov.Kruger@gmail.com"
] | Dov.Kruger@gmail.com |
4588f2051db29b27c1659d53df3e02d3b8ced88e | 90a1ad5c2b9fd6a221b91fe2a163c47c8ddd8ee6 | /GlarekEngineProject/Engine/Engine/Source/Game/Event/EventDispatcher.cpp | 4439406b6cebd304d03e541e241fac3b7e7a87df | [] | no_license | yananliu000/Projects | 1e5f04a9c66707f9bacb448795ba690e2dbd88b6 | 37d5ff68f7c19b2f71ec766f8cb7156d9d6241f5 | refs/heads/master | 2022-11-16T09:46:08.157540 | 2020-07-09T21:26:47 | 2020-07-09T21:26:47 | 256,191,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,742 | cpp | #include "EventDispatcher.h"
size_t Engine::EventDispatcher::AddEventListener(u32 id, EventCallback callback)
{
//find the vec associated with the event
auto listenersItr = m_eventListeners.find(id);
if (listenersItr == m_eventListeners.end()) //not find in the map
{
m_eventListeners.emplace(id, std::vector<EventCallback>{callback});
return 0; //cause it's the first event of this type(ID), index 0
}
//find it
//check for empty slot
auto& listenerMap = listenersItr->second;
for (size_t iListener = 0; iListener < listenerMap.size(); ++iListener)
{
if (listenerMap[iListener] == nullptr)
{
listenerMap[iListener] = callback;
return iListener;
}
}
//no empty slot
listenerMap.push_back(callback);
return listenerMap.size() - 1;
}
void Engine::EventDispatcher::RemoveEventListener(u32 id, size_t index)
{
//find the listeners under the same type
auto& listeners = m_eventListeners[id];
if (index < listeners.size()) //find the listener
listeners[index] = nullptr;
}
void Engine::EventDispatcher::ProcessEvents()
{
//move all events here
auto events = std::move(m_eventQueue);
//for every event
for (auto& pEvent : events)
{
//find all listeners associated with the event
auto& listeners = m_eventListeners[pEvent->GetEventId()];
//for every listener: execute the callback
for (auto& listener : listeners)
{
if (listener)
listener(pEvent.get());
}
}
}
void Engine::EventDispatcher::ProcessEventImmediately(std::unique_ptr<IEvent> pEvent)
{
//find all listeners associated with the event
auto& listeners = m_eventListeners[pEvent->GetEventId()];
//for every listener: execute the callback
for (auto& listener : listeners)
{
if (listener)
listener(pEvent.get());
}
}
| [
"42784645+yananliu000@users.noreply.github.com"
] | 42784645+yananliu000@users.noreply.github.com |
02fb1aa3c9694ab2d57f2581d9a49bde12d0ba75 | faa932aa4c28315ee8175c3307b1b5cf53ac8d43 | /LongestPrefix.cpp | 04718d75f26ea427eb8d303965a73bf996bc9442 | [] | no_license | bsarvan/code_algorithms | 2daad99da90894d830f5fc38d647cfae49141821 | 43855386c3646bd84effacef3362b925835d6ba0 | refs/heads/master | 2023-06-09T12:39:56.112624 | 2021-06-27T14:15:55 | 2021-06-27T14:15:55 | 380,757,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,572 | cpp | //
// main.cpp
// LongestPrefix
//
// Created by bsarvan on 26/01/18.
// Copyright © 2018 bsarvan. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
/* Function to find the Longest Unique Prefix */
string uniquePrefixUtil(string str1, string str2) {
string result;
size_t n1 = str1.length();
size_t n2 = str2.length();
for (size_t i=0,j=0; i<n1 && j<n2; i++,j++) {
if (str1[i] != str2[j]) {
result.push_back(str1[i]);
break;
} else {
result.push_back((str1[i]));
}
}
return result;
}
/*
So, you can pick any random string from the array and start checking its characters
from the beginning in order to see if they can be a part of the common substring.
*/
string commonPrefixUtil(string str1, string str2)
{
string result;
int n1 = str1.length(), n2 = str2.length();
// Compare str1 and str2
for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)
{
if (str1[i] != str2[j])
break;
result += str2[j];
}
return (result);
}
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix (vector<string> A, int n)
{
string prefix = A[0];
for (int i=1; i<=n-1; i++)
prefix = commonPrefixUtil(prefix, A[i]);
return (prefix);
}
int main(int argc, const char * argv[]) {
vector<string> S = {"abcd", "abd"};
cout<<"Longest Prefix - "<<commonPrefix(S, S.size())<<endl;
return 0;
}
| [
"bharat.sarvan@LM-ILB-BHARATHS.local"
] | bharat.sarvan@LM-ILB-BHARATHS.local |
d529d69aca17f9b5c8062226236c86ebdb3f1e74 | 8e817f7ea712deacadffa87614681157fef71827 | /smql/Tree.cpp | 474f6c56f05b874161f3ffbfcf9269f98de1145e | [] | no_license | wenj/db | 0518298cf14442eb891071909d9292e80292bbc4 | 5ac6e45d023319aa696f658f0839cc889949f20f | refs/heads/master | 2021-09-02T11:36:10.090138 | 2018-01-02T09:01:52 | 2018-01-02T09:01:52 | 110,957,722 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | //
// Created by lenovo on 2017/12/20.
//
#include "Tree.h"
const int Tree::OP_GE = 1;
const int Tree::OP_GT = Tree::OP_GE + 1;
const int Tree::OP_EQ = Tree::OP_GT + 1;
const int Tree::OP_LT = Tree::OP_EQ + 1;
const int Tree::OP_LE = Tree::OP_LT + 1;
const int Tree::OP_NE = Tree::OP_LE + 1;
| [
"zhanghuimeng1997@gmail.com"
] | zhanghuimeng1997@gmail.com |
42b7a2bd1efbf454c0d5b610a8940a50de7daf5b | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_788_collectd-5.7.1.cpp | aa4a24f6bf5749f174388dd89ef5a07bcc926397 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55 | cpp | void dnstop_set_pcap_obj(pcap_t *po) { pcap_obj = po; } | [
"993273596@qq.com"
] | 993273596@qq.com |
ba34f10aa9dbca19e4e1c4ee3fa5b2fec787a603 | bff9ee7f0b96ac71e609a50c4b81375768541aab | /deps/src/boost_1_65_1/libs/asio/test/latency/coroutine.hpp | e1f02b423c67e92bb5ec194b4b8a6f3946dbebe5 | [
"BSL-1.0",
"BSD-3-Clause"
] | permissive | rohitativy/turicreate | d7850f848b7ccac80e57e8042dafefc8b949b12b | 1c31ee2d008a1e9eba029bafef6036151510f1ec | refs/heads/master | 2020-03-10T02:38:23.052555 | 2018-04-11T02:20:16 | 2018-04-11T02:20:16 | 129,141,488 | 1 | 0 | BSD-3-Clause | 2018-04-11T19:06:32 | 2018-04-11T19:06:31 | null | UTF-8 | C++ | false | false | 2,189 | hpp | //
// coroutine.hpp
// ~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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 COROUTINE_HPP
#define COROUTINE_HPP
class coroutine
{
public:
coroutine() : value_(0) {}
bool is_child() const { return value_ < 0; }
bool is_parent() const { return !is_child(); }
bool is_complete() const { return value_ == -1; }
private:
friend class coroutine_ref;
int value_;
};
class coroutine_ref
{
public:
coroutine_ref(coroutine& c) : value_(c.value_), modified_(false) {}
coroutine_ref(coroutine* c) : value_(c->value_), modified_(false) {}
~coroutine_ref() { if (!modified_) value_ = -1; }
operator int() const { return value_; }
int& operator=(int v) { modified_ = true; return value_ = v; }
private:
void operator=(const coroutine_ref&);
int& value_;
bool modified_;
};
#define CORO_REENTER(c) \
switch (coroutine_ref _coro_value = c) \
case -1: if (_coro_value) \
{ \
goto terminate_coroutine; \
terminate_coroutine: \
_coro_value = -1; \
goto bail_out_of_coroutine; \
bail_out_of_coroutine: \
break; \
} \
else case 0:
#define CORO_YIELD_IMPL(n) \
for (_coro_value = (n);;) \
if (_coro_value == 0) \
{ \
case (n): ; \
break; \
} \
else \
switch (_coro_value ? 0 : 1) \
for (;;) \
case -1: if (_coro_value) \
goto terminate_coroutine; \
else for (;;) \
case 1: if (_coro_value) \
goto bail_out_of_coroutine; \
else case 0:
#define CORO_FORK_IMPL(n) \
for (_coro_value = -(n);; _coro_value = (n)) \
if (_coro_value == (n)) \
{ \
case -(n): ; \
break; \
} \
else
#if defined(_MSC_VER)
# define CORO_YIELD CORO_YIELD_IMPL(__COUNTER__ + 1)
# define CORO_FORK CORO_FORK_IMPL(__COUNTER__ + 1)
#else // defined(_MSC_VER)
# define CORO_YIELD CORO_YIELD_IMPL(__LINE__)
# define CORO_FORK CORO_FORK_IMPL(__LINE__)
#endif // defined(_MSC_VER)
#endif // COROUTINE_HPP
| [
"znation@apple.com"
] | znation@apple.com |
468480be244427d73dcc1a73794edcd606a8ce3d | 475b86242448df8787daa2b1a08dc272cbbf73a0 | /tokenizer/seq_stream.h | ac44ed2124cd90a53db498383b047874c8caf504 | [
"MIT"
] | permissive | schwa-lab/libschwa-python | 81e0e061bf63c0765e086c05805f60bc4f91fe4e | aebe5b0cf91e55b9e054ecff46a6e74fcd19f490 | refs/heads/develop | 2020-06-06T05:13:07.991702 | 2014-09-04T03:28:34 | 2014-09-04T03:28:34 | 17,269,031 | 5 | 0 | null | 2014-09-04T01:56:19 | 2014-02-27T23:39:45 | Python | UTF-8 | C++ | false | false | 2,140 | h | /* -*- Mode: C++; indent-tabs-mode: nil -*- */
#ifndef SEQ_STREAM_H_
#define SEQ_STREAM_H_
#include "_python.h"
#include <vector>
#include <schwa/_base.h>
#include "pystream.h"
namespace schwa {
namespace tokenizer {
using PyVector = std::vector<PyObject *>;
class PySeqStream : public PyStream {
protected:
PyVector _paragraphs;
PyVector _sentences;
PyVector _tokens;
virtual PyObject *vector2seq(PyVector &vec) const = 0;
public:
PySeqStream(void) : PyStream() { }
virtual ~PySeqStream(void);
virtual void add(Type type, const char *raw, size_t begin, size_t len, const char *norm=nullptr) override;
virtual void error(const char *raw, size_t begin, size_t len) override { }
PyObject *return_value(void) override;
virtual void begin_sentence(void) override { }
virtual void end_sentence(void) override;
virtual void begin_paragraph(void) override { }
virtual void end_paragraph(void) override;
virtual void begin_heading(int depth) override { begin_paragraph(); }
virtual void end_heading(int depth) override { end_paragraph(); }
virtual void begin_list(void) override { }
virtual void end_list(void) override;
virtual void begin_item(void) override { }
virtual void end_item(void) override { }
virtual void begin_document(void) override { }
virtual void end_document(void) override { }
private:
SCHWA_DISALLOW_COPY_AND_ASSIGN(PySeqStream);
};
class PyListStream : public PySeqStream {
protected:
PyObject *vector2seq(PyVector &vec) const override;
public:
PyListStream(void) : PySeqStream() { }
virtual ~PyListStream(void) { }
private:
SCHWA_DISALLOW_COPY_AND_ASSIGN(PyListStream);
};
class PyTupleStream : public PySeqStream {
protected:
PyObject *vector2seq(PyVector &vec) const override;
public:
PyTupleStream(void) : PySeqStream() { }
virtual ~PyTupleStream(void) { }
private:
SCHWA_DISALLOW_COPY_AND_ASSIGN(PyTupleStream);
};
}
}
#endif // SEQ_STREAM_H_
| [
"tim.dawborn@gmail.com"
] | tim.dawborn@gmail.com |
5909b3d5a793cbac6f5dc90a75acdab3f03bb416 | a03b73a7e665d6a6063f687bea3d4b58cd153606 | /aten/src/ATen/native/ConvUtils.h | 96ed0e591a088f2d0f1d086e0c97db6c2aea7201 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | joshionkar23/pytorch | 8fa5909a1944f5edda9e90433b03b6d4fb588ade | b894dc06de3e0750d9db8bd20b92429f6d873fa1 | refs/heads/master | 2020-12-28T02:22:36.189506 | 2020-02-04T04:46:09 | 2020-02-04T04:47:51 | 238,146,856 | 1 | 0 | NOASSERTION | 2020-02-04T07:21:13 | 2020-02-04T07:21:12 | null | UTF-8 | C++ | false | false | 3,507 | h | #pragma once
namespace at { namespace native {
// ---------------------------------------------------------------------
//
// Math
//
// ---------------------------------------------------------------------
constexpr int input_batch_size_dim = 0; // also grad_input
constexpr int input_channels_dim = 1;
constexpr int output_batch_size_dim = 0; // also grad_output
constexpr int output_channels_dim = 1;
constexpr int weight_output_channels_dim = 0;
constexpr int weight_input_channels_dim = 1;
// Often written as 2 + max_dim (extra dims for batch size and channels)
constexpr int max_dim = 3;
// NB: conv_output_size and conv_input_size are not bijections,
// as conv_output_size loses information; this is why conv_input_size
// takes an extra output_padding argument to resolve the ambiguity.
static inline std::vector<int64_t> conv_output_size(
IntArrayRef input_size, IntArrayRef weight_size,
IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
) {
// ASSERT(input_size.size() > 2)
// ASSERT(input_size.size() == weight_size.size())
bool has_dilation = dilation.size() > 0;
auto dim = input_size.size();
std::vector<int64_t> output_size(dim);
output_size[0] = input_size[input_batch_size_dim];
output_size[1] = weight_size[weight_output_channels_dim];
for (size_t d = 2; d < dim; ++d) {
auto dilation_ = has_dilation ? dilation[d - 2] : 1;
auto kernel = dilation_ * (weight_size[d] - 1) + 1;
output_size[d] = (input_size[d] + (2 * padding[d - 2]) - kernel) / stride[d - 2] + 1;
}
return output_size;
}
static inline std::vector<int64_t> conv_input_size(
IntArrayRef output_size, IntArrayRef weight_size,
IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
) {
// ASSERT(output_size.size() > 2)
// ASSERT(output_size.size() == weight_size.size())
auto dim = output_size.size();
std::vector<int64_t> input_size(dim);
input_size[0] = output_size[output_batch_size_dim];
input_size[1] = weight_size[weight_input_channels_dim] * groups;
for (size_t d = 2; d < dim; ++d) {
int kernel = dilation[d - 2] * (weight_size[d] - 1) + 1;
input_size[d] = (output_size[d] - 1) * stride[d - 2] - (2 * padding[d - 2]) +
kernel + output_padding[d - 2];
}
return input_size;
}
static inline std::vector<int64_t> conv_weight_size(
IntArrayRef input_size, IntArrayRef output_size,
IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
) {
auto dim = input_size.size();
std::vector<int64_t> weight_size(dim);
weight_size[0] = output_size[1];
weight_size[1] = input_size[1] / groups;
for (size_t d = 2; d < dim; ++d) {
int kernel = input_size[d] - (output_size[d] - 1) * stride[d - 2]
+ 2 * padding[d - 2] - output_padding[d - 2];
weight_size[d] = (kernel - 1) / dilation[d - 2] + 1;
}
return weight_size;
}
static inline Tensor reshape_bias(int64_t dim, const Tensor& bias) {
std::vector<int64_t> shape(dim, 1);
shape[1] = -1;
return bias.reshape(shape);
}
static inline bool cudnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
if (!detail::getCUDAHooks().compiledWithCuDNN()) {
return false;
}
long cudnn_version = detail::getCUDAHooks().versionCuDNN();
return (cudnn_version >= 7603) &&
(input.suggest_memory_format() == at::MemoryFormat::ChannelsLast);
}
}} // namespace at::native
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
9f4519a56e904a3297c9dc6ab03557562294454b | f7abe020be31ecd16757719b49f30c6059276d16 | /src/MessageStack.cpp | 7542573676494a5621dee7535289176b003246e6 | [
"FSFAP"
] | permissive | alevar/AdaptiveVision | 15eedf6d63cc924e28a61653bc28548dc8d64852 | 0009b7b8698182a59a6ff4832cba222519e623c2 | refs/heads/master | 2020-02-26T13:43:27.124926 | 2016-09-13T17:14:11 | 2016-09-13T17:14:11 | 45,806,607 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | cpp | /*==================================================
==================================================*/
#include <iostream>
#include <sstream>
#include <vector>
#include <sstream>
#include <arpa/inet.h>
#include <stdlib.h>
#include "MessageStack.h"
#include "Message.h"
#include "MessageOpCode.h"
#include "MessageType.h"
using namespace std;
MessageStack::MessageStack(int N){
bottom_ = new Message[N];
top_ = bottom_;
size_ = N;
}
MessageStack::~MessageStack()
{
delete [] bottom_;
}
int MessageStack::num_items() const
{
return (top_ - bottom_ );
}
void MessageStack::push(Message message)
{
*top_ = message;
top_++;
}
Message MessageStack::pop()
{
top_--;
return *top_;
}
int MessageStack::full() const
{
return (num_items() >= size_);
}
int MessageStack::empty() const
{
return (num_items() <= 0);
}
void MessageStack::print() const
{
cout << "Stack currently holds " << num_items() << " items: " ;
// for (InstructionCode *element=bottom_; element<top_; element++)
// {
// cout << " " << *element;
// }
cout << "\n";
}
| [
"alevar@gmail.com"
] | alevar@gmail.com |
f84391513b5f5929c5f020fbe0fd774c72ac5eef | 28690c8767e907ad83304a6b58fec76c6ba1f46c | /ThirdPartyLibs/include/CGAL/Arr_linear_traits_2.h | 847b0487c40b5833123ce0235a89a376a12b27ff | [] | no_license | haisenzhao/SmartCFS | c9d7e2f73cde25a5957d1c3268cc5ddbbe7f5af2 | 2c066792dab2ca99b02bc035e77d09b4b5619aa2 | refs/heads/master | 2023-08-20T17:51:37.254851 | 2021-09-27T20:55:36 | 2021-09-27T20:55:36 | 271,935,428 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,569 | h | // Copyright (c) 2006,2007,2009,2010,2011 Tel-Aviv University (Israel).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s) : Ron Wein <wein@post.tau.ac.il>
// : Waqar Khan <wkhan@mpi-inf.mpg.de>
#ifndef CGAL_ARR_LINEAR_TRAITS_2_H
#define CGAL_ARR_LINEAR_TRAITS_2_H
/*! \file
* The traits-class for handling linear objects (lines, rays and segments)
* in the arrangement package.
*/
#include <CGAL/tags.h>
#include <CGAL/intersections.h>
#include <CGAL/Arr_tags.h>
#include <CGAL/Arr_enums.h>
#include <CGAL/Arr_geometry_traits/Segment_assertions.h>
#include <fstream>
namespace CGAL {
template <class Kernel_> class Arr_linear_object_2;
/*! \class
* A traits class for maintaining an arrangement of linear objects (lines,
* rays and segments), aoviding cascading of computations as much as possible.
*/
template <class Kernel_>
class Arr_linear_traits_2 : public Kernel_ {
friend class Arr_linear_object_2<Kernel_>;
public:
typedef Kernel_ Kernel;
typedef typename Kernel::FT FT;
typedef typename Algebraic_structure_traits<FT>::Is_exact
Has_exact_division;
// Category tags:
typedef Tag_true Has_left_category;
typedef Tag_true Has_merge_category;
typedef Tag_false Has_do_intersect_category;
typedef Arr_open_side_tag Left_side_category;
typedef Arr_open_side_tag Bottom_side_category;
typedef Arr_open_side_tag Top_side_category;
typedef Arr_open_side_tag Right_side_category;
typedef typename Kernel::Line_2 Line_2;
typedef typename Kernel::Ray_2 Ray_2;
typedef typename Kernel::Segment_2 Segment_2;
typedef CGAL::Segment_assertions<Arr_linear_traits_2<Kernel> >
Segment_assertions;
/*!
* \class Representation of a linear with cached data.
*/
class _Linear_object_cached_2
{
public:
typedef typename Kernel::Line_2 Line_2;
typedef typename Kernel::Ray_2 Ray_2;
typedef typename Kernel::Segment_2 Segment_2;
typedef typename Kernel::Point_2 Point_2;
protected:
Line_2 l; // The supporting line.
Point_2 ps; // The source point (if exists).
Point_2 pt; // The target point (if exists).
bool has_source; // Is the source point valid
// (false for a line).
bool has_target; // Is the target point valid
// (false for a line and for a ray).
bool is_right; // Is the object directed to the right
// (for segments and rays).
bool is_vert; // Is this a vertical object.
bool is_horiz; // Is this a horizontal object.
bool has_pos_slope; // Does the supporting line has a positive
// slope (if all three flags is_vert, is_horiz
// and has_pos_slope are false, then the line
// has a negative slope).
bool is_degen; // Is the object degenerate (a single point).
public:
/*!
* Default constructor.
*/
_Linear_object_cached_2 () :
has_source (true),
has_target (true),
is_vert (false),
is_horiz (false),
has_pos_slope (false),
is_degen (true)
{}
/*!
* Constructor for segment from two points.
* \param p1 source point.
* \param p2 target point.
* \pre The two points must not be equal.
*/
_Linear_object_cached_2(const Point_2& source, const Point_2& target) :
ps (source),
pt (target),
has_source (true),
has_target (true)
{
Kernel kernel;
Comparison_result res = kernel.compare_xy_2_object()(source, target);
is_degen = (res == EQUAL);
is_right = (res == SMALLER);
CGAL_precondition_msg (! is_degen,
"Cannot construct a degenerate segment.");
l = kernel.construct_line_2_object()(source, target);
is_vert = kernel.is_vertical_2_object()(l);
is_horiz = kernel.is_horizontal_2_object()(l);
has_pos_slope = _has_positive_slope();
}
/*!
* Constructor from a segment.
* \param seg The segment.
* \pre The segment is not degenerate.
*/
_Linear_object_cached_2 (const Segment_2& seg)
{
Kernel kernel;
CGAL_assertion_msg (! kernel.is_degenerate_2_object() (seg),
"Cannot construct a degenerate segment.");
typename Kernel_::Construct_vertex_2
construct_vertex = kernel.construct_vertex_2_object();
ps = construct_vertex(seg, 0);
has_source = true;
pt = construct_vertex(seg, 1);
has_target = true;
Comparison_result res = kernel.compare_xy_2_object()(ps, pt);
CGAL_assertion (res != EQUAL);
is_degen = false;
is_right = (res == SMALLER);
l = kernel.construct_line_2_object()(seg);
is_vert = kernel.is_vertical_2_object()(seg);
is_horiz = kernel.is_horizontal_2_object()(seg);
has_pos_slope = _has_positive_slope();
}
/*!
* Constructor from a ray.
* \param ray The ray.
* \pre The ray is not degenerate.
*/
_Linear_object_cached_2 (const Ray_2& ray)
{
Kernel kernel;
CGAL_assertion_msg (! kernel.is_degenerate_2_object() (ray),
"Cannot construct a degenerate ray.");
typename Kernel_::Construct_point_on_2
construct_vertex = kernel.construct_point_on_2_object();
ps = construct_vertex(ray, 0); // The source point.
has_source = true;
pt = construct_vertex(ray, 1); // Some point on the ray.
has_target = false;
Comparison_result res = kernel.compare_xy_2_object()(ps, pt);
CGAL_assertion (res != EQUAL);
is_degen = false;
is_right = (res == SMALLER);
l = kernel.construct_line_2_object()(ray);
is_vert = kernel.is_vertical_2_object()(ray);
is_horiz = kernel.is_horizontal_2_object()(ray);
has_pos_slope = _has_positive_slope();
}
/*!
* Constructor from a line.
* \param ln The line.
* \pre The line is not degenerate.
*/
_Linear_object_cached_2 (const Line_2& ln) :
l (ln),
has_source (false),
has_target (false)
{
Kernel kernel;
CGAL_assertion_msg (! kernel.is_degenerate_2_object() (ln),
"Cannot construct a degenerate line.");
typename Kernel_::Construct_point_on_2
construct_vertex = kernel.construct_point_on_2_object();
ps = construct_vertex(ln, 0); // Some point on the line.
has_source = false;
pt = construct_vertex(ln, 1); // Some point further on the line.
has_target = false;
Comparison_result res = kernel.compare_xy_2_object()(ps, pt);
CGAL_assertion (res != EQUAL);
is_degen = false;
is_right = (res == SMALLER);
is_vert = kernel.is_vertical_2_object()(ln);
is_horiz = kernel.is_horizontal_2_object()(ln);
has_pos_slope = _has_positive_slope();
}
/*!
* Check whether the x-coordinate of the left point is infinite.
* \return ARR_LEFT_BOUNDARY if the left point is near the boundary;
* ARR_INTERIOR if the x-coordinate is finite.
*/
Arr_parameter_space left_infinite_in_x () const
{
if (is_vert || is_degen)
return (ARR_INTERIOR);
return (is_right) ?
(has_source ? ARR_INTERIOR : ARR_LEFT_BOUNDARY) :
(has_target ? ARR_INTERIOR : ARR_LEFT_BOUNDARY);
}
/*!
* Check whether the y-coordinate of the left point is infinite.
* \return ARR_BOTTOM_BOUNDARY if the left point is at y = -oo;
* ARR_INTERIOR if the y-coordinate is finite.
* ARR_TOP_BOUNDARY if the left point is at y = +oo;
*/
Arr_parameter_space left_infinite_in_y () const
{
if (is_horiz || is_degen)
return ARR_INTERIOR;
if (is_vert) {
return (is_right) ?
(has_source ? ARR_INTERIOR : ARR_BOTTOM_BOUNDARY) :
(has_target ? ARR_INTERIOR : ARR_BOTTOM_BOUNDARY);
}
if ((is_right && has_source) || (! is_right && has_target))
return ARR_INTERIOR;
return (has_pos_slope ? ARR_BOTTOM_BOUNDARY : ARR_TOP_BOUNDARY);
}
/*!
* Check whether the left point is finite.
*/
bool has_left () const
{
if (is_right)
return (has_source);
else
return (has_target);
}
/*!
* Obtain the (lexicographically) left endpoint.
* \pre The left point is finite.
*/
const Point_2& left () const
{
CGAL_precondition (has_left());
return (is_right ? ps : pt);
}
/*!
* Set the (lexicographically) left endpoint.
* \param p The point to set.
* \pre p lies on the supporting line to the left of the right endpoint.
*/
void set_left (const Point_2& p, bool CGAL_assertion_code(check_validity) = true)
{
CGAL_precondition (! is_degen);
CGAL_precondition_code (
Kernel kernel;
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, l,
Has_exact_division()) &&
(! check_validity || ! has_right() ||
kernel.compare_xy_2_object() (p, right()) == SMALLER));
if (is_right)
{
ps = p;
has_source = true;
}
else
{
pt = p;
has_target = true;
}
}
/*!
* Set the (lexicographically) left endpoint as infinite.
*/
void set_left ()
{
CGAL_precondition (! is_degen);
if (is_right)
has_source = false;
else
has_target = false;
}
/*!
* Check whether the x-coordinate of the right point is infinite.
* \return ARR_RIGHT_BOUNDARY if the right point is near the boundary;
* ARR_INTERIOR if the x-coordinate is finite.
*/
Arr_parameter_space right_infinite_in_x () const
{
if (is_vert || is_degen)
return ARR_INTERIOR;
return (is_right) ?
(has_target ? ARR_INTERIOR : ARR_RIGHT_BOUNDARY) :
(has_source ? ARR_INTERIOR : ARR_RIGHT_BOUNDARY);
}
/*!
* Check whether the y-coordinate of the right point is infinite.
* \return ARR_BOTTOM_BOUNDARY if the right point is at y = -oo;
* ARR_INTERIOR if the y-coordinate is finite.
* ARR_TOP_BOUNDARY if the right point is at y = +oo;
*/
Arr_parameter_space right_infinite_in_y () const
{
if (is_horiz || is_degen)
return ARR_INTERIOR;
if (is_vert) {
return (is_right) ?
(has_target ? ARR_INTERIOR : ARR_TOP_BOUNDARY) :
(has_source ? ARR_INTERIOR : ARR_TOP_BOUNDARY);
}
if ((is_right && has_target) || (! is_right && has_source))
return ARR_INTERIOR;
return (has_pos_slope ? ARR_TOP_BOUNDARY : ARR_BOTTOM_BOUNDARY);
}
/*!
* Check whether the right point is finite.
*/
bool has_right () const
{
if (is_right)
return (has_target);
else
return (has_source);
}
/*!
* Obtain the (lexicographically) right endpoint.
* \pre The right endpoint is finite.
*/
const Point_2& right () const
{
CGAL_precondition (has_right());
return (is_right ? pt : ps);
}
/*!
* Set the (lexicographically) right endpoint.
* \param p The point to set.
* \pre p lies on the supporting line to the right of the left endpoint.
*/
void set_right (const Point_2& p, bool CGAL_assertion_code(check_validity) = true)
{
CGAL_precondition (! is_degen);
CGAL_precondition_code (
Kernel kernel;
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, l,
Has_exact_division()) &&
(! check_validity || ! has_left() ||
kernel.compare_xy_2_object() (p, left()) == LARGER));
if (is_right)
{
pt = p;
has_target = true;
}
else
{
ps = p;
has_source = true;
}
}
/*!
* Set the (lexicographically) right endpoint as infinite.
*/
void set_right ()
{
CGAL_precondition (! is_degen);
if (is_right)
has_target = false;
else
has_source = false;
}
/*!
* Obtain the supporting line.
*/
const Line_2& supp_line () const
{
CGAL_precondition (! is_degen);
return (l);
}
/*!
* Check whether the curve is vertical.
*/
bool is_vertical () const
{
CGAL_precondition (! is_degen);
return (is_vert);
}
/*!
* Check whether the curve is degenerate.
*/
bool is_degenerate () const
{
return (is_degen);
}
/*!
* Check whether the curve is directed lexicographic from left to right
*/
bool is_directed_right () const
{
return (is_right);
}
/*!
* Check whether the given point is in the x-range of the object.
* \param p The query point.
* \return (true) is in the x-range of the segment; (false) if it is not.
*/
bool is_in_x_range (const Point_2& p) const
{
Kernel kernel;
typename Kernel_::Compare_x_2 compare_x = kernel.compare_x_2_object();
Comparison_result res1;
if (left_infinite_in_x() == ARR_INTERIOR)
{
if (left_infinite_in_y() != ARR_INTERIOR)
// Compare with some point on the curve.
res1 = compare_x (p, ps);
else
res1 = compare_x (p, left());
}
else
{
// p is obviously to the right.
res1 = LARGER;
}
if (res1 == SMALLER)
return (false);
else if (res1 == EQUAL)
return (true);
Comparison_result res2;
if (right_infinite_in_x() == ARR_INTERIOR)
{
if (right_infinite_in_y() != ARR_INTERIOR)
// Compare with some point on the curve.
res2 = compare_x (p, ps);
else
res2 = compare_x (p, right());
}
else
{
// p is obviously to the right.
res2 = SMALLER;
}
return (res2 != LARGER);
}
/*!
* Check whether the given point is in the y-range of the object.
* \param p The query point.
* \pre The object is vertical.
* \return (true) is in the y-range of the segment; (false) if it is not.
*/
bool is_in_y_range (const Point_2& p) const
{
CGAL_precondition (is_vertical());
Kernel kernel;
typename Kernel_::Compare_y_2 compare_y = kernel.compare_y_2_object();
Arr_parameter_space inf = left_infinite_in_y();
Comparison_result res1;
CGAL_assertion (inf != ARR_TOP_BOUNDARY);
if (inf == ARR_INTERIOR)
res1 = compare_y (p, left());
else
res1 = LARGER; // p is obviously above.
if (res1 == SMALLER)
return (false);
else if (res1 == EQUAL)
return (true);
Comparison_result res2;
inf = right_infinite_in_y();
CGAL_assertion (inf != ARR_BOTTOM_BOUNDARY);
if (inf == ARR_INTERIOR)
res2 = compare_y (p, right());
else
res2 = SMALLER; // p is obviously below.
return (res2 != LARGER);
}
private:
/*!
* Determine if the supporting line has a positive slope.
*/
bool _has_positive_slope () const
{
if (is_vert)
return (true);
if (is_horiz)
return (false);
// Construct a horizontal line and compare its slope the that of l.
Kernel kernel;
Line_2 l_horiz = kernel.construct_line_2_object() (Point_2 (0, 0),
Point_2 (1, 0));
return (kernel.compare_slope_2_object() (l, l_horiz) == LARGER);
}
};
public:
// Traits objects
typedef typename Kernel::Point_2 Point_2;
typedef Arr_linear_object_2<Kernel> X_monotone_curve_2;
typedef Arr_linear_object_2<Kernel> Curve_2;
typedef unsigned int Multiplicity;
public:
/*!
* Default constructor.
*/
Arr_linear_traits_2 ()
{}
/// \name Basic functor definitions.
//@{
/*! A functor that compares the x-coordinates of two points */
class Compare_x_2 {
protected:
typedef Arr_linear_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits * m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
* The constructor is declared private to allow only the functor
* obtaining function, which is a member of the nesting class,
* constructing it.
*/
Compare_x_2(const Traits * traits) : m_traits(traits) {}
//! Allow its functor obtaining function calling the private constructor.
friend class Arr_linear_traits_2<Kernel>;
public:
/*!
* Compare the x-coordinates of two points.
* \param p1 The first point.
* \param p2 The second point.
* \return LARGER if x(p1) > x(p2);
* SMALLER if x(p1) < x(p2);
* EQUAL if x(p1) = x(p2).
*/
Comparison_result operator() (const Point_2& p1, const Point_2& p2) const
{
const Kernel * kernel = m_traits;
return (kernel->compare_x_2_object()(p1, p2));
}
};
/*! Obtain a Compare_x_2 functor. */
Compare_x_2 compare_x_2_object () const
{
return Compare_x_2(this);
}
/*! A functor that compares the he endpoints of an $x$-monotone curve. */
class Compare_endpoints_xy_2{
public:
/*! Compare the endpoints of an $x$-monotone curve lexicographically.
* (assuming the curve has a designated source and target points).
* \param cv The curve.
* \return SMALLER if the curve is directed right;
* LARGER if the curve is directed left.
*/
Comparison_result operator() (const X_monotone_curve_2& xcv) const
{ return (xcv.is_directed_right()) ? (SMALLER) : (LARGER); }
};
Compare_endpoints_xy_2 compare_endpoints_xy_2_object() const
{
return Compare_endpoints_xy_2();
}
class Trim_2{
protected:
typedef Arr_linear_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
* The constructor is declared private to allow only the functor
* obtaining function, which is a member of the nesting class,
* constructing it.
*/
Trim_2(const Traits * traits) : m_traits(traits) {}
//! Allow its functor obtaining function calling the private constructor.
friend class Arr_linear_traits_2<Kernel>;
public:
X_monotone_curve_2 operator()( const X_monotone_curve_2 xcv,
const Point_2 src,
const Point_2 tgt )
{
/*
* "Line_segment, line, and ray" will become line segments
* when trimmed.
*/
Equal_2 equal = Equal_2();
Compare_y_at_x_2 compare_y_at_x = m_traits->compare_y_at_x_2_object();
//preconditions
//check if source and taget are two distinct points and they lie on the line.
CGAL_precondition(!equal(src, tgt));
CGAL_precondition(compare_y_at_x(src, xcv) == EQUAL);
CGAL_precondition(compare_y_at_x(tgt, xcv) == EQUAL);
//create trimmed line_segment
X_monotone_curve_2 trimmed_segment;
if( xcv.is_directed_right() && tgt.x() < src.x() )
trimmed_segment = Segment_2(tgt, src);
else if( !xcv.is_directed_right() && tgt.x() > src.x())
trimmed_segment = Segment_2(tgt, src);
else
trimmed_segment = Segment_2(src, tgt);
return trimmed_segment;
}
};
Trim_2 trim_2_object() const
{
return Trim_2(this);
}
class Construct_opposite_2{
protected:
typedef Arr_linear_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
* The constructor is declared private to allow only the functor
* obtaining function, which is a member of the nesting class,
* constructing it.
*/
Construct_opposite_2(const Traits * traits) : m_traits(traits) {}
//! Allow its functor obtaining function calling the private constructor.
friend class Arr_linear_traits_2<Kernel>;
public:
X_monotone_curve_2 operator()(const X_monotone_curve_2& xcv)const
{
CGAL_precondition (! xcv.is_degenerate());
X_monotone_curve_2 opp_xcv;
if( xcv.is_segment() )
{
opp_xcv = Segment_2(xcv.target(), xcv.source());
}
if( xcv.is_line() )
{
opp_xcv = Line_2(xcv.get_pt(), xcv.get_ps());
}
if( xcv.is_ray() )
{
Point_2 opp_tgt = Point_2( -(xcv.get_pt().x()), -(xcv.get_pt().y()));
opp_xcv = Ray_2( xcv.source(), opp_tgt);
}
return opp_xcv;
}
};
/*! Get a Construct_opposite_2 functor object. */
Construct_opposite_2 construct_opposite_2_object() const
{
return Construct_opposite_2(this);
}
/*! A functor that compares the x-coordinates of two points */
class Compare_xy_2 {
public:
/*!
* Compare two points lexigoraphically: by x, then by y.
* \param p1 The first point.
* \param p2 The second point.
* \return LARGER if x(p1) > x(p2), or if x(p1) = x(p2) and y(p1) > y(p2);
* SMALLER if x(p1) < x(p2), or if x(p1) = x(p2) and y(p1) < y(p2);
* EQUAL if the two points are equal.
*/
Comparison_result operator() (const Point_2& p1, const Point_2& p2) const
{
Kernel kernel;
return (kernel.compare_xy_2_object()(p1, p2));
}
};
/*! Obtain a Compare_xy_2 functor object. */
Compare_xy_2 compare_xy_2_object () const
{
return Compare_xy_2();
}
/*! A functor that obtains the left endpoint of a segment or a ray. */
class Construct_min_vertex_2
{
public:
/*!
* Get the left endpoint of the x-monotone curve (segment).
* \param cv The curve.
* \pre The left end of cv is a valid (bounded) point.
* \return The left endpoint.
*/
const Point_2& operator() (const X_monotone_curve_2& cv) const
{
CGAL_precondition (! cv.is_degenerate());
CGAL_precondition (cv.has_left());
return (cv.left());
}
};
/*! Obtain a Construct_min_vertex_2 functor object. */
Construct_min_vertex_2 construct_min_vertex_2_object () const
{
return Construct_min_vertex_2();
}
/*! A functor that obtains the right endpoint of a segment or a ray. */
class Construct_max_vertex_2
{
public:
/*!
* Get the right endpoint of the x-monotone curve (segment).
* \param cv The curve.
* \pre The right end of cv is a valid (bounded) point.
* \return The right endpoint.
*/
const Point_2& operator() (const X_monotone_curve_2& cv) const
{
CGAL_precondition (! cv.is_degenerate());
CGAL_precondition (cv.has_right());
return (cv.right());
}
};
/*! Obtain a Construct_max_vertex_2 functor object. */
Construct_max_vertex_2 construct_max_vertex_2_object () const
{
return Construct_max_vertex_2();
}
/*! A functor that checks whether a given linear curve is vertical. */
class Is_vertical_2
{
public:
/*!
* Check whether the given x-monotone curve is a vertical segment.
* \param cv The curve.
* \return (true) if the curve is a vertical segment; (false) otherwise.
*/
bool operator() (const X_monotone_curve_2& cv) const
{
CGAL_precondition (! cv.is_degenerate());
return (cv.is_vertical());
}
};
/*! Obtain an Is_vertical_2 functor object. */
Is_vertical_2 is_vertical_2_object () const
{
return Is_vertical_2();
}
/*! A functor that compares the y-coordinates of a point and a line at
* the point x-coordinate
*/
class Compare_y_at_x_2 {
protected:
typedef Arr_linear_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
* The constructor is declared private to allow only the functor
* obtaining function, which is a member of the nesting class,
* constructing it.
*/
Compare_y_at_x_2(const Traits * traits) : m_traits(traits) {}
//! Allow its functor obtaining function calling the private constructor.
friend class Arr_linear_traits_2<Kernel>;
public:
/*!
* Return the location of the given point with respect to the input curve.
* \param cv The curve.
* \param p The point.
* \pre p is in the x-range of cv.
* \return SMALLER if y(p) < cv(x(p)), i.e. the point is below the curve;
* LARGER if y(p) > cv(x(p)), i.e. the point is above the curve;
* EQUAL if p lies on the curve.
*/
Comparison_result operator() (const Point_2& p,
const X_monotone_curve_2& cv) const
{
CGAL_precondition (! cv.is_degenerate());
CGAL_precondition (cv.is_in_x_range (p));
const Kernel * kernel = m_traits;
if (! cv.is_vertical())
// Compare p with the segment's supporting line.
return (kernel->compare_y_at_x_2_object()(p, cv.supp_line()));
// Compare with the vertical segment's end-points.
typename Kernel::Compare_y_2 compare_y = kernel->compare_y_2_object();
const Comparison_result res1 =
cv.has_left() ? compare_y (p, cv.left()) : LARGER;
const Comparison_result res2 =
cv.has_right() ? compare_y (p, cv.right()) : SMALLER;
return (res1 == res2) ? res1 : EQUAL;
}
};
/*! Obtain a Compare_y_at_x_2 functor object. */
Compare_y_at_x_2 compare_y_at_x_2_object () const
{
return Compare_y_at_x_2(this);
}
/*! A functor that compares compares the y-coordinates of two linear
* curves immediately to the left of their intersection point.
*/
class Compare_y_at_x_left_2
{
public:
/*!
* Compare the y value of two x-monotone curves immediately to the left
* of their intersection point.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param p The intersection point.
* \pre The point p lies on both curves, and both of them must be also be
* defined (lexicographically) to its left.
* \return The relative position of cv1 with respect to cv2 immdiately to
* the left of p: SMALLER, LARGER or EQUAL.
*/
Comparison_result operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
const Point_2& CGAL_precondition_code(p)) const
{
CGAL_precondition (! cv1.is_degenerate());
CGAL_precondition (! cv2.is_degenerate());
Kernel kernel;
// Make sure that p lies on both curves, and that both are defined to its
// left (so their left endpoint is lexicographically smaller than p).
CGAL_precondition_code (
typename Kernel::Compare_xy_2 compare_xy = kernel.compare_xy_2_object();
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, cv1,
Has_exact_division()) &&
Segment_assertions::_assert_is_point_on (p, cv2,
Has_exact_division()));
CGAL_precondition ((! cv1.has_left() ||
compare_xy(cv1.left(), p) == SMALLER) &&
(! cv2.has_left() ||
compare_xy(cv2.left(), p) == SMALLER));
// Compare the slopes of the two segments to determine thir relative
// position immediately to the left of q.
// Notice we use the supporting lines in order to compare the slopes,
// and that we swap the order of the curves in order to obtain the
// correct result to the left of p.
return (kernel.compare_slope_2_object()(cv2.supp_line(), cv1.supp_line()));
}
};
/*! Obtain a Compare_y_at_x_left_2 functor object. */
Compare_y_at_x_left_2 compare_y_at_x_left_2_object () const
{
return Compare_y_at_x_left_2();
}
/*! A functor that compares compares the y-coordinates of two linear
* curves immediately to the right of their intersection point.
*/
class Compare_y_at_x_right_2
{
public:
/*!
* Compare the y value of two x-monotone curves immediately to the right
* of their intersection point.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param p The intersection point.
* \pre The point p lies on both curves, and both of them must be also be
* defined (lexicographically) to its right.
* \return The relative position of cv1 with respect to cv2 immdiately to
* the right of p: SMALLER, LARGER or EQUAL.
*/
Comparison_result operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
const Point_2& CGAL_precondition_code(p)) const
{
CGAL_precondition (! cv1.is_degenerate());
CGAL_precondition (! cv2.is_degenerate());
Kernel kernel;
// Make sure that p lies on both curves, and that both are defined to its
// right (so their right endpoint is lexicographically larger than p).
CGAL_precondition_code (
typename Kernel::Compare_xy_2 compare_xy = kernel.compare_xy_2_object();
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, cv1,
Has_exact_division()) &&
Segment_assertions::_assert_is_point_on (p, cv2,
Has_exact_division()));
CGAL_precondition ((! cv1.has_right() ||
compare_xy(cv1.right(), p) == LARGER) &&
(! cv2.has_right() ||
compare_xy(cv2.right(), p) == LARGER));
// Compare the slopes of the two segments to determine thir relative
// position immediately to the left of q.
// Notice we use the supporting lines in order to compare the slopes.
return (kernel.compare_slope_2_object()(cv1.supp_line(),
cv2.supp_line()));
}
};
/*! Obtain a Compare_y_at_x_right_2 functor object. */
Compare_y_at_x_right_2 compare_y_at_x_right_2_object () const
{
return Compare_y_at_x_right_2();
}
/*! A functor that checks whether two points and two linear curves are
* identical.
*/
class Equal_2
{
public:
/*!
* Check whether the two x-monotone curves are the same (have the same
* graph).
* \param cv1 The first curve.
* \param cv2 The second curve.
* \return (true) if the two curves are the same; (false) otherwise.
*/
bool operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2) const
{
CGAL_precondition (! cv1.is_degenerate());
CGAL_precondition (! cv2.is_degenerate());
Kernel kernel;
typename Kernel::Equal_2 equal = kernel.equal_2_object();
// Check that the two supporting lines are the same.
if (! equal (cv1.supp_line(), cv2.supp_line()) &&
! equal (cv1.supp_line(),
kernel.construct_opposite_line_2_object()(cv2.supp_line())))
{
return (false);
}
// Check that either the two left endpoints are at infinity, or they
// are bounded and equal.
if ((cv1.has_left() != cv2.has_left()) ||
(cv1.has_left() && ! equal (cv1.left(), cv2.left())))
{
return (false);
}
// Check that either the two right endpoints are at infinity, or they
// are bounded and equal.
return ((cv1.has_right() == cv2.has_right()) &&
(! cv1.has_right() || equal (cv1.right(), cv2.right())));
}
/*!
* Check whether the two points are the same.
* \param p1 The first point.
* \param p2 The second point.
* \return (true) if the two point are the same; (false) otherwise.
*/
bool operator() (const Point_2& p1, const Point_2& p2) const
{
Kernel kernel;
return (kernel.equal_2_object()(p1, p2));
}
};
/*! Obtain an Equal_2 functor object. */
Equal_2 equal_2_object () const
{
return Equal_2();
}
//@}
/// \name Functor definitions to handle boundaries
//@{
/*! A function object that obtains the parameter space of a geometric
* entity along the x-axis
*/
class Parameter_space_in_x_2 {
public:
/*! Obtains the parameter space at the end of a line along the x-axis.
* \param xcv the line
* \param ce the line end indicator:
* ARR_MIN_END - the minimal end of xc or
* ARR_MAX_END - the maximal end of xc
* \return the parameter space at the ce end of the line xcv.
* ARR_LEFT_BOUNDARY - the line approaches the identification arc from
* the right at the line left end.
* ARR_INTERIOR - the line does not approache the identification arc.
* ARR_RIGHT_BOUNDARY - the line approaches the identification arc from
* the left at the line right end.
*/
Arr_parameter_space operator()(const X_monotone_curve_2 & xcv,
Arr_curve_end ce) const
{
CGAL_precondition (! xcv.is_degenerate());
return (ce == ARR_MIN_END) ?
xcv.left_infinite_in_x() : xcv.right_infinite_in_x();
}
/*! Obtains the parameter space at a point along the x-axis.
* \param p the point.
* \return the parameter space at p.
*/
Arr_parameter_space operator()(const Point_2 ) const
{
return ARR_INTERIOR;
}
};
/*! Obtain a Parameter_space_in_x_2 function object */
Parameter_space_in_x_2 parameter_space_in_x_2_object() const
{ return Parameter_space_in_x_2(); }
/*! A function object that obtains the parameter space of a geometric
* entity along the y-axis
*/
class Parameter_space_in_y_2 {
public:
/*! Obtains the parameter space at the end of a line along the y-axis .
* Note that if the line end coincides with a pole, then unless the line
* coincides with the identification arc, the line end is considered to
* be approaching the boundary, but not on the boundary.
* If the line coincides with the identification arc, it is assumed to
* be smaller than any other object.
* \param xcv the line
* \param ce the line end indicator:
* ARR_MIN_END - the minimal end of xc or
* ARR_MAX_END - the maximal end of xc
* \return the parameter space at the ce end of the line xcv.
* ARR_BOTTOM_BOUNDARY - the line approaches the south pole at the line
* left end.
* ARR_INTERIOR - the line does not approache a contraction point.
* ARR_TOP_BOUNDARY - the line approaches the north pole at the line
* right end.
*/
Arr_parameter_space operator()(const X_monotone_curve_2 & xcv,
Arr_curve_end ce) const
{
CGAL_precondition (! xcv.is_degenerate());
return (ce == ARR_MIN_END) ?
xcv.left_infinite_in_y() : xcv.right_infinite_in_y();
}
/*! Obtains the parameter space at a point along the y-axis.
* \param p the point.
* \return the parameter space at p.
*/
Arr_parameter_space operator()(const Point_2 ) const
{
return ARR_INTERIOR;
}
};
/*! Obtain a Parameter_space_in_y_2 function object */
Parameter_space_in_y_2 parameter_space_in_y_2_object() const
{ return Parameter_space_in_y_2(); }
/*! A function object that compares the x-limits of arc ends on the
* boundary of the parameter space
*/
class Compare_x_at_limit_2 {
protected:
typedef Arr_linear_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
* The constructor is declared private to allow only the functor
* obtaining function, which is a member of the nesting class,
* constructing it.
*/
Compare_x_at_limit_2(const Traits* traits) : m_traits(traits) {}
//! Allow its functor obtaining function calling the private constructor.
friend class Arr_linear_traits_2<Kernel>;
public:
/*! Compare the x-limit of a vertical line at a point with the x-limit of
* a line end on the boundary at y = +/- oo.
* \param p the point direction.
* \param xcv the line, the endpoint of which is compared.
* \param ce the line-end indicator -
* ARR_MIN_END - the minimal end of xc or
* ARR_MAX_END - the maximal end of xc.
* \return the comparison result:
* SMALLER - x(p) < x(xc, ce);
* EQUAL - x(p) = x(xc, ce);
* LARGER - x(p) > x(xc, ce).
* \pre p lies in the interior of the parameter space.
* \pre the ce end of the line xcv lies on a boundary, implying
* that xcv1 is vertical.
*/
Comparison_result operator()(const Point_2 & p,
const X_monotone_curve_2 & xcv,
Arr_curve_end ) const
{
CGAL_precondition(! xcv.is_degenerate());
CGAL_precondition(xcv.is_vertical());
const Kernel* kernel = m_traits;
return (kernel->compare_x_at_y_2_object()(p, xcv.supp_line()));
}
/*! Compare the x-limits of 2 arcs ends on the boundary of the
* parameter space at y = +/- oo.
* \param xcv1 the first arc.
* \param ce1 the first arc end indicator -
* ARR_MIN_END - the minimal end of xcv1 or
* ARR_MAX_END - the maximal end of xcv1.
* \param xcv2 the second arc.
* \param ce2 the second arc end indicator -
* ARR_MIN_END - the minimal end of xcv2 or
* ARR_MAX_END - the maximal end of xcv2.
* \return the second comparison result:
* SMALLER - x(xcv1, ce1) < x(xcv2, ce2);
* EQUAL - x(xcv1, ce1) = x(xcv2, ce2);
* LARGER - x(xcv1, ce1) > x(xcv2, ce2).
* \pre the ce1 end of the line xcv1 lies on a boundary, implying
* that xcv1 is vertical.
* \pre the ce2 end of the line xcv2 lies on a boundary, implying
* that xcv2 is vertical.
*/
Comparison_result operator()(const X_monotone_curve_2 & xcv1,
Arr_curve_end /* ce1 */,
const X_monotone_curve_2 & xcv2,
Arr_curve_end /*! ce2 */) const
{
CGAL_precondition(! xcv1.is_degenerate());
CGAL_precondition(! xcv2.is_degenerate());
CGAL_precondition(xcv1.is_vertical());
CGAL_precondition(xcv2.is_vertical());
const Kernel* kernel = m_traits;
const Point_2 p = kernel->construct_point_2_object()(ORIGIN);
return (kernel->compare_x_at_y_2_object()(p, xcv1.supp_line(),
xcv2.supp_line()));
}
};
/*! Obtain a Compare_x_at_limit_2 function object */
Compare_x_at_limit_2 compare_x_at_limit_2_object() const
{ return Compare_x_at_limit_2(this); }
/*! A function object that compares the x-coordinates of arc ends near the
* boundary of the parameter space
*/
class Compare_x_near_limit_2 {
public:
/*! Compare the x-coordinates of 2 arcs ends near the boundary of the
* parameter space at y = +/- oo.
* \param xcv1 the first arc.
* \param ce1 the first arc end indicator -
* ARR_MIN_END - the minimal end of xcv1 or
* ARR_MAX_END - the maximal end of xcv1.
* \param xcv2 the second arc.
* \param ce2 the second arc end indicator -
* ARR_MIN_END - the minimal end of xcv2 or
* ARR_MAX_END - the maximal end of xcv2.
* \return the second comparison result:
* SMALLER - x(xcv1, ce1) < x(xcv2, ce2);
* EQUAL - x(xcv1, ce1) = x(xcv2, ce2);
* LARGER - x(xcv1, ce1) > x(xcv2, ce2).
* \pre the ce end of the line xcv1 lies on a boundary, implying
* that xcv1 is vertical.
* \pre the ce end of the line xcv2 lies on a boundary, implying
* that xcv2 is vertical.
* \pre the the $x$-coordinates of xcv1 and xcv2 at their ce ends are
* equal, implying that the curves overlap!
*/
Comparison_result
operator()(const X_monotone_curve_2& CGAL_precondition_code(xcv1),
const X_monotone_curve_2& CGAL_precondition_code(xcv2),
Arr_curve_end /*! ce2 */) const
{
CGAL_precondition(! xcv1.is_degenerate());
CGAL_precondition(! xcv2.is_degenerate());
CGAL_precondition(xcv1.is_vertical());
CGAL_precondition(xcv2.is_vertical());
return EQUAL;
}
};
/*! Obtain a Compare_x_near_limit_2 function object */
Compare_x_near_limit_2 compare_x_near_limit_2_object() const
{ return Compare_x_near_limit_2(); }
/*! A function object that compares the y-limits of arc ends on the
* boundary of the parameter space.
*/
class Compare_y_near_boundary_2 {
protected:
typedef Arr_linear_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
* The constructor is declared private to allow only the functor
* obtaining function, which is a member of the nesting class,
* constructing it.
*/
Compare_y_near_boundary_2(const Traits* traits) : m_traits(traits) {}
//! Allow its functor obtaining function calling the private constructor.
friend class Arr_linear_traits_2<Kernel>;
public:
/*! Compare the y-limits of 2 lines at their ends on the boundary
* of the parameter space at x = +/- oo.
* \param xcv1 the first arc.
* \param xcv2 the second arc.
* \param ce the line end indicator.
* \return the second comparison result.
* \pre the ce ends of the lines xcv1 and xcv2 lie either on the left
* boundary or on the right boundary of the parameter space.
*/
Comparison_result operator()(const X_monotone_curve_2 & xcv1,
const X_monotone_curve_2 & xcv2,
Arr_curve_end ce) const
{
// Make sure both curves are defined at x = -oo (or at x = +oo).
CGAL_precondition(! xcv1.is_degenerate());
CGAL_precondition(! xcv2.is_degenerate());
CGAL_precondition((ce == ARR_MIN_END &&
xcv1.left_infinite_in_x() == ARR_LEFT_BOUNDARY &&
xcv2.left_infinite_in_x() == ARR_LEFT_BOUNDARY) ||
(ce == ARR_MAX_END &&
xcv1.right_infinite_in_x() == ARR_RIGHT_BOUNDARY &&
xcv2.right_infinite_in_x() == ARR_RIGHT_BOUNDARY));
// Compare the slopes of the two supporting lines.
const Kernel* kernel = m_traits;
const Comparison_result res_slopes =
kernel->compare_slope_2_object()(xcv1.supp_line(), xcv2.supp_line());
if (res_slopes == EQUAL) {
// In case the two supporting line are parallel, compare their
// relative position at x = 0, which is the same as their position
// at infinity.
const Point_2 p = kernel->construct_point_2_object()(ORIGIN);
return (kernel->compare_y_at_x_2_object()(p, xcv1.supp_line(),
xcv2.supp_line()));
}
// Flip the slope result if we compare at x = -oo:
return (ce == ARR_MIN_END) ? CGAL::opposite(res_slopes) : res_slopes;
}
};
/*! Obtain a Compare_y_limit_on_boundary_2 function object */
Compare_y_near_boundary_2 compare_y_near_boundary_2_object() const
{ return Compare_y_near_boundary_2(this); }
//@}
/// \name Functor definitions for supporting intersections.
//@{
class Make_x_monotone_2
{
public:
/*!
* Cut the given curve into x-monotone subcurves and insert them into the
* given output iterator. As segments are always x_monotone, only one
* object will be contained in the iterator.
* \param cv The curve.
* \param oi The output iterator, whose value-type is Object. The output
* object is a wrapper of an X_monotone_curve_2 which is
* essentially the same as the input curve.
* \return The past-the-end iterator.
*/
template<class OutputIterator>
OutputIterator operator() (const Curve_2& cv, OutputIterator oi) const
{
// Wrap the curve with an object.
*oi = make_object (cv);
++oi;
return (oi);
}
};
/*! Obtain a Make_x_monotone_2 functor object. */
Make_x_monotone_2 make_x_monotone_2_object () const
{
return Make_x_monotone_2();
}
class Split_2
{
public:
/*!
* Split a given x-monotone curve at a given point into two sub-curves.
* \param cv The curve to split
* \param p The split point.
* \param c1 Output: The left resulting subcurve (p is its right endpoint).
* \param c2 Output: The right resulting subcurve (p is its left endpoint).
* \pre p lies on cv but is not one of its end-points.
*/
void operator() (const X_monotone_curve_2& cv, const Point_2& p,
X_monotone_curve_2& c1, X_monotone_curve_2& c2) const
{
CGAL_precondition (! cv.is_degenerate());
// Make sure that p lies on the interior of the curve.
CGAL_precondition_code (
Kernel kernel;
typename Kernel::Compare_xy_2 compare_xy = kernel.compare_xy_2_object();
);
CGAL_precondition
(Segment_assertions::_assert_is_point_on (p, cv,
Has_exact_division()) &&
(! cv.has_left() || compare_xy(cv.left(), p) == SMALLER) &&
(! cv.has_right() || compare_xy(cv.right(), p) == LARGER));
// Perform the split.
c1 = cv;
c1.set_right (p);
c2 = cv;
c2.set_left (p);
return;
}
};
/*! Obtain a Split_2 functor object. */
Split_2 split_2_object () const
{
return Split_2();
}
class Intersect_2
{
public:
/*!
* Find the intersections of the two given curves and insert them into the
* given output iterator. As two segments may itersect only once, only a
* single intersection will be contained in the iterator.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param oi The output iterator.
* \return The past-the-end iterator.
*/
template<class OutputIterator>
OutputIterator operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
OutputIterator oi) const
{
CGAL_precondition (! cv1.is_degenerate());
CGAL_precondition (! cv2.is_degenerate());
// Intersect the two supporting lines.
Kernel kernel;
CGAL::Object obj = kernel.intersect_2_object()(cv1.supp_line(),
cv2.supp_line());
if (obj.is_empty())
{
// The supporting line are parallel lines and do not intersect:
return (oi);
}
// Check whether we have a single intersection point.
const Point_2 *ip = object_cast<Point_2> (&obj);
if (ip != NULL)
{
// Check whether the intersection point ip lies on both segments.
const bool ip_on_cv1 = cv1.is_vertical() ? cv1.is_in_y_range(*ip) :
cv1.is_in_x_range(*ip);
if (ip_on_cv1)
{
const bool ip_on_cv2 = cv2.is_vertical() ? cv2.is_in_y_range(*ip) :
cv2.is_in_x_range(*ip);
if (ip_on_cv2)
{
// Create a pair representing the point with its multiplicity,
// which is always 1 for line segments.
std::pair<Point_2,Multiplicity> ip_mult (*ip, 1);
*oi = make_object (ip_mult);
oi++;
}
}
return (oi);
}
// In this case, the two supporting lines overlap.
// We start with the entire cv1 curve as the overlapping subcurve,
// then clip it to form the true overlapping curve.
typename Kernel::Compare_xy_2 compare_xy = kernel.compare_xy_2_object();
X_monotone_curve_2 ovlp = cv1;
if (cv2.has_left())
{
// If the left endpoint of cv2 is to the right of cv1's left endpoint,
// clip the overlapping subcurve.
if (! cv1.has_left())
{
ovlp.set_left (cv2.left(), false);
}
else
{
if (compare_xy (cv1.left(), cv2.left()) == SMALLER)
ovlp.set_left (cv2.left(), false);
}
}
if (cv2.has_right())
{
// If the right endpoint of cv2 is to the left of cv1's right endpoint,
// clip the overlapping subcurve.
if (! cv1.has_right())
{
ovlp.set_right (cv2.right(), false);
}
else
{
if (compare_xy (cv1.right(), cv2.right()) == LARGER)
ovlp.set_right (cv2.right(), false);
}
}
// Examine the resulting subcurve.
Comparison_result res = SMALLER;
if (ovlp.has_left() && ovlp.has_right())
res = compare_xy (ovlp.left(), ovlp.right());
if (res == SMALLER)
{
// We have discovered a true overlapping subcurve:
*oi = make_object (ovlp);
oi++;
}
else if (res == EQUAL)
{
// The two objects have the same supporting line, but they just share
// a common endpoint. Thus we have an intersection point, but we leave
// the multiplicity of this point undefined.
std::pair<Point_2,Multiplicity> ip_mult (ovlp.left(), 0);
*oi = make_object (ip_mult);
oi++;
}
return (oi);
}
};
/*! Obtain an Intersect_2 functor object. */
Intersect_2 intersect_2_object () const
{
return Intersect_2();
}
class Are_mergeable_2
{
public:
/*!
* Check whether it is possible to merge two given x-monotone curves.
* \param cv1 The first curve.
* \param cv2 The second curve.
* \return (true) if the two curves are mergeable - if they are supported
* by the same line and share a common endpoint; (false) otherwise.
*/
bool operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2) const
{
CGAL_precondition (! cv1.is_degenerate());
CGAL_precondition (! cv2.is_degenerate());
Kernel kernel;
typename Kernel::Equal_2 equal = kernel.equal_2_object();
// Check whether the two curves have the same supporting line.
if (! equal (cv1.supp_line(), cv2.supp_line()) &&
! equal (cv1.supp_line(),
kernel.construct_opposite_line_2_object()(cv2.supp_line())))
return (false);
// Check whether the left endpoint of one curve is the right endpoint of the
// other.
return ((cv1.has_right() && cv2.has_left() &&
equal (cv1.right(), cv2.left())) ||
(cv2.has_right() && cv1.has_left() &&
equal (cv2.right(), cv1.left())));
}
};
/*! Obtain an Are_mergeable_2 functor object. */
Are_mergeable_2 are_mergeable_2_object () const
{
return Are_mergeable_2();
}
/*! \class Merge_2
* A functor that merges two x-monotone arcs into one.
*/
class Merge_2
{
protected:
typedef Arr_linear_traits_2<Kernel> Traits;
/*! The traits (in case it has state) */
const Traits* m_traits;
/*! Constructor
* \param traits the traits (in case it has state)
*/
Merge_2(const Traits* traits) : m_traits(traits) {}
friend class Arr_linear_traits_2<Kernel>;
public:
/*!
* Merge two given x-monotone curves into a single curve (segment).
* \param cv1 The first curve.
* \param cv2 The second curve.
* \param c Output: The merged curve.
* \pre The two curves are mergeable.
*/
void operator() (const X_monotone_curve_2& cv1,
const X_monotone_curve_2& cv2,
X_monotone_curve_2& c) const
{
CGAL_precondition(m_traits->are_mergeable_2_object()(cv2, cv1));
CGAL_precondition(!cv1.is_degenerate());
CGAL_precondition(!cv2.is_degenerate());
Equal_2 equal = m_traits->equal_2_object();
// Check which curve extends to the right of the other.
if (cv1.has_right() && cv2.has_left() &&
equal(cv1.right(), cv2.left()))
{
// cv2 extends cv1 to the right.
c = cv1;
if (cv2.has_right())
c.set_right(cv2.right());
else
c.set_right(); // Unbounded endpoint.
}
else {
CGAL_precondition(cv2.has_right() && cv1.has_left() &&
equal(cv2.right(), cv1.left()));
// cv1 extends cv2 to the right.
c = cv2;
if (cv1.has_right())
c.set_right(cv1.right());
else
c.set_right(); // Unbounded endpoint.
}
}
};
/*! Obtain a Merge_2 functor object. */
Merge_2 merge_2_object () const { return Merge_2(this); }
//@}
/// \name Functor definitions for the landmarks point-location strategy.
//@{
typedef double Approximate_number_type;
class Approximate_2
{
public:
/*!
* Return an approximation of a point coordinate.
* \param p The exact point.
* \param i The coordinate index (either 0 or 1).
* \pre i is either 0 or 1.
* \return An approximation of p's x-coordinate (if i == 0), or an
* approximation of p's y-coordinate (if i == 1).
*/
Approximate_number_type operator() (const Point_2& p,
int i) const
{
CGAL_precondition (i == 0 || i == 1);
if (i == 0)
return (CGAL::to_double(p.x()));
else
return (CGAL::to_double(p.y()));
}
};
/*! Obtain an Approximate_2 functor object. */
Approximate_2 approximate_2_object () const
{
return Approximate_2();
}
class Construct_x_monotone_curve_2
{
public:
/*!
* Return an x-monotone curve connecting the two given endpoints.
* \param p The first point.
* \param q The second point.
* \pre p and q must not be the same.
* \return A segment connecting p and q.
*/
X_monotone_curve_2 operator() (const Point_2& p,
const Point_2& q) const
{
Kernel kernel;
Segment_2 seg = kernel.construct_segment_2_object() (p, q);
return (X_monotone_curve_2 (seg));
}
};
/*! Obtain a Construct_x_monotone_curve_2 functor object. */
Construct_x_monotone_curve_2 construct_x_monotone_curve_2_object () const
{
return Construct_x_monotone_curve_2();
}
//@}
};
/*!
* \class A representation of a segment, as used by the Arr_segment_traits_2
* traits-class.
*/
template <class Kernel_>
class Arr_linear_object_2 :
public Arr_linear_traits_2<Kernel_>::_Linear_object_cached_2
{
typedef typename Arr_linear_traits_2<Kernel_>::_Linear_object_cached_2
Base;
public:
typedef Kernel_ Kernel;
typedef typename Kernel::Point_2 Point_2;
typedef typename Kernel::Segment_2 Segment_2;
typedef typename Kernel::Ray_2 Ray_2;
typedef typename Kernel::Line_2 Line_2;
public:
/*!
* Default constructor.
*/
Arr_linear_object_2 () :
Base()
{}
/*!
* Constructor from two points.
* \param s The source point.
* \param t The target point.
* \pre The two points must not be the same.
*/
Arr_linear_object_2(const Point_2& s, const Point_2& t):
Base(s, t)
{}
/*!
* Constructor from a segment.
* \param seg The segment.
* \pre The segment is not degenerate.
*/
Arr_linear_object_2 (const Segment_2& seg) :
Base (seg)
{}
/*!
* Constructor from a ray.
* \param ray The segment.
* \pre The ray is not degenerate.
*/
Arr_linear_object_2 (const Ray_2& ray) :
Base (ray)
{}
/*!
* Constructor from a line.
* \param line The line.
* \pre The line is not degenerate.
*/
Arr_linear_object_2 (const Line_2& line) :
Base (line)
{}
/*!
* Check whether the object is actually a segment.
*/
bool is_segment () const
{
return (! this->is_degen && this->has_source && this->has_target);
}
/*!
* Cast to a segment.
* \pre The linear object is really a segment.
*/
Segment_2 segment () const
{
CGAL_precondition (is_segment());
Kernel kernel;
Segment_2 seg = kernel.construct_segment_2_object() (this->ps, this->pt);
return seg;
}
/*!
* Check whether the object is actually a ray.
*/
bool is_ray () const
{
return (! this->is_degen && (this->has_source != this->has_target));
}
/*!
* Cast to a ray.
* \pre The linear object is really a ray.
*/
Ray_2 ray () const
{
CGAL_precondition (is_ray());
Kernel kernel;
Ray_2 ray = (this->has_source) ?
kernel.construct_ray_2_object() (this->ps, this->l) :
kernel.construct_ray_2_object()
(this->pt, kernel.construct_opposite_line_2_object()(this->l));
return ray;
}
/*!
* Check whether the object is actually a line.
*/
bool is_line () const
{
return (! this->is_degen && ! this->has_source && ! this->has_target);
}
/*!
* Cast to a line.
* \pre The linear object is really a line.
*/
Line_2 line () const
{
CGAL_precondition (is_line());
return (this->l);
}
/*!
* Get the supporting line.
* \pre The object is not a point.
*/
const Line_2& supporting_line () const
{
CGAL_precondition (! this->is_degen);
return (this->l);
}
/*!
* Get the source point.
* \pre The object is a point, a segment or a ray.
*/
const Point_2& source() const
{
CGAL_precondition (! is_line());
if (this->is_degen)
return (this->ps); // For a point.
if (this->has_source)
return (this->ps); // For a segment or a ray.
else
return (this->pt); // For a "flipped" ray.
}
/*!
* Get the target point.
* \pre The object is a point or a segment.
*/
const Point_2& target() const
{
CGAL_precondition (! is_line() && ! is_ray());
return (this->pt);
}
/*!
* Create a bounding box for the linear object.
*/
Bbox_2 bbox() const
{
CGAL_precondition(this->is_segment());
Kernel kernel;
Segment_2 seg = kernel.construct_segment_2_object() (this->ps, this->pt);
return (kernel.construct_bbox_2_object() (seg));
}
// Introducing casting operators instead from a curve to
// Kernel::Segment_2, Kernel::Ray_2, and Kernel::Line_2 creates an
// umbiguity. The compiler will barf on the last one, because there are
// 2 constructors of Kernel::Line_2: one from Kernel::Segment_2 and one
// from Kernel::Ray_2. Together with the cast to Kernel::Line_2, the
// compiler will have 3 equivalent options to choose from.
};
/*!
* Exporter for the segment class used by the traits-class.
*/
template <class Kernel, class OutputStream>
OutputStream& operator<< (OutputStream& os,
const Arr_linear_object_2<Kernel>& lobj)
{
// Print a letter identifying the object type, then the object itself.
if (lobj.is_segment())
os << " S " << lobj.segment();
else if (lobj.is_ray())
os << " R " << lobj.ray();
else
os << " L " << lobj.line();
return (os);
}
/*!
* Importer for the segment class used by the traits-class.
*/
template <class Kernel, class InputStream>
InputStream& operator>> (InputStream& is, Arr_linear_object_2<Kernel>& lobj)
{
// Read the object type.
char c;
do
{
is >> c;
} while ((c != 'S' && c != 's') &&
(c != 'R' && c != 'r') &&
(c != 'L' && c != 'l'));
// Read the object accordingly.
if (c == 'S' || c == 's')
{
typename Kernel::Segment_2 seg;
is >> seg;
lobj = seg;
}
else if (c == 'R' || c == 'r')
{
typename Kernel::Ray_2 ray;
is >> ray;
lobj = ray;
}
else
{
typename Kernel::Line_2 line;
is >> line;
lobj = line;
}
return (is);
}
} //namespace CGAL
#endif
| [
"haisenzhao@gmail.com"
] | haisenzhao@gmail.com |
eb263b0451b9ad0a64251fc1d146e894fbcf5406 | 93427e5015233aea8284ab7dc37a4b59b9d6c500 | /template/template.hpp | 12444e9c452a5246aec3a0d40f3aea52b60b831e | [
"CC0-1.0"
] | permissive | zxc123qwe456asd789/library | fd978a387c8dd805ef1a7ffc1118272c6878b64a | 13c01442cc5082da181acdaa414554ace30b6ae3 | refs/heads/master | 2023-05-28T22:50:47.466753 | 2021-06-12T04:10:24 | 2021-06-12T04:10:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,209 | hpp | #pragma once
using namespace std;
// intrinstic
#include <immintrin.h>
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfenv>
#include <cfloat>
#include <chrono>
#include <cinttypes>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <iomanip>
#include <ios>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <streambuf>
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// utility
#include "util.hpp"
// bit operation
#include "bitop.hpp"
// inout
#include "inout.hpp"
// debug
#include "debug.hpp"
// macro
#include "macro.hpp"
namespace Nyaan {
void solve();
}
int main() { Nyaan::solve(); }
| [
"suteakadapyon3@gmail.com"
] | suteakadapyon3@gmail.com |
59024e3ae6ad9ab891510275befbf04684bed83d | 3cd4cc83515c335728b7c16e7610f25dd8e087fe | /examples/Examples/Chap10/vtkTestClass.h | b61939af35aa9d609871ec8bcce04927d95efc0f | [] | no_license | liuyaoxinneo/VTK | a223cf1f05639299ce6afae23c19d2989d55578b | 90dc403896aef1ba828e413950e4ffe3ab041eb6 | refs/heads/master | 2021-05-08T08:02:22.252992 | 2017-10-15T13:55:37 | 2017-10-15T13:55:37 | 106,976,917 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,057 | h | /**********************************************************************
文件名: vtkTestClass.h
Copyright (c) 张晓东, 罗火灵. All rights reserved.
更多信息请访问:
http://www.vtkchina.org (VTK中国)
http://blog.csdn.net/www_doling_net (东灵工作室)
**********************************************************************/
#ifndef __vtkTestClass_h
#define __vtkTestClass_h
#include <vtkObject.h>
class vtkTestClass: public vtkObject
{
public:
vtkTypeMacro(vtkTestClass,vtkObject);
static vtkTestClass *New();
vtkGetMacro(Flag, bool);
vtkGetMacro(Speed, double);
vtkGetVector3Macro(Position,double);
vtkSetMacro(Flag,bool);
vtkSetMacro(Speed,double);
vtkSetVector3Macro(Position,double);
vtkBooleanMacro(Flag, bool);
void PrintSelf(ostream &os, vtkIndent indent);
private:
double Speed;
double Position[3];
bool Flag;
protected:
vtkTestClass();
~vtkTestClass();
private:
vtkTestClass(const vtkTestClass&); // Not implemented.
void operator=(const vtkTestClass&); // Not implemented.
};
#endif | [
"neo19941120@hotmail.com"
] | neo19941120@hotmail.com |
bd3f3f8bd41fcb3cf04dc58fdc722c5be3f11391 | 0d709da61a4684f1aabe3bdb8edf78be238e2e27 | /Exam - Mar 2020/02.MemoryMonitor/main.cpp | 5173ca08108e62743c7e1dd41d8b65325441d7f1 | [] | no_license | Vikadie/Cpp-codes | f1f947e104049fc90f3c46ab83d244cac351882c | c59cc576f8d839a0d74bcd66862d527e70b3aee6 | refs/heads/master | 2022-12-12T23:02:45.605465 | 2020-09-06T17:34:59 | 2020-09-06T17:34:59 | 283,164,981 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 335 | cpp | #include <iostream>
#include <string>
#include "CommandExecutor.h"
int main()
{
int commands = 0;
std::string input;
std::cin >> commands;
std::cin.ignore();
CommandExecutor commandExecutor;
for(int i = 0; i < commands; ++i)
{
getline(std::cin, input);
commandExecutor.extractCommand(input);
}
return 0;
}
| [
"68245263+Vikadie@users.noreply.github.com"
] | 68245263+Vikadie@users.noreply.github.com |
e0311409e95960738fa431314058b2df1ec76949 | f25efd73c7196f3edcc8f8263390d10e095fb5e8 | /ElevatorSimulation/elevator.h | 318140eea55e4d67f46ff23454a0949ea456958b | [] | no_license | phongnh23/elevator-simulation | 5270c91a7db2055f674963c5e4a87d5be1e9694b | 063f42fde6ed551f74b049aac7ffc8513ce3c0fd | refs/heads/master | 2020-03-29T18:23:46.382116 | 2018-09-26T01:31:53 | 2018-09-26T01:31:53 | 150,209,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,225 | h | #ifndef ELEVATOR_H
#define ELEVATOR_H
#include <QWidget>
#include <QPushButton>
#include "elevatorthread.h"
namespace Ui {
class Elevator;
}
class Elevator : public QWidget
{
Q_OBJECT
public:
explicit Elevator(QWidget *parent = 0, int toNumber = 1);
~Elevator();
int getCurrentFloor();
void setCurrentFloor(int value);
// int getNextFloor();//
Direction getDirection();
ElevatorThread *getOperation() const;
int getOutRequest(int floor);
// void setOutRequest(int floor, int request);//
// void setOpenRequest();//
int getWeight() const;
void setWeight(int value);
int getSize() const;
void setSize(int value);
void clearData();
void setSpeed(int value);
private slots:
void on_closeButton_pressed();
void on_openButton_pressed();
void on_closeButton_released();
void on_openButton_released();
void on_button_0_clicked();
void on_button_1_clicked();
void on_button_2_clicked();
void on_button_3_clicked();
void on_button_4_clicked();
void on_button_5_clicked();
void on_button_6_clicked();
void on_button_7_clicked();
void on_button_8_clicked();
void on_button_9_clicked();
void on_button_10_clicked();
void on_button_11_clicked();
void on_button_12_clicked();
void on_button_13_clicked();
void on_button_14_clicked();
void on_button_15_clicked();
void on_button_16_clicked();
void on_button_17_clicked();
void on_button_18_clicked();
void on_button_19_clicked();
void on_button_20_clicked();
void onPainterChanged();
void onStateChanged(QString state);
void onCurrentFloorChanged(int currentFloor);
void onInRequestCompleted(int currentFloor);
void onElevatorAttributeChanged(int weight, int size, int floorButton); // modify weight and size labels, and floorButton light
private:
Ui::Elevator *ui;
ElevatorThread *operation;
bool isFloorButtonClicked[21];
int speed;
void paintEvent(QPaintEvent *event) override;
void buttonClickFunction(QPushButton* button, int index);
signals:
void floorButtonClicked(int floor);
void floorButtonUnclicked(int floor);
};
#endif // ELEVATOR_H
| [
"phongnh23@viettel.com.vn"
] | phongnh23@viettel.com.vn |
112f3f23da2bc9e5ea4403d7d8412623054d9720 | 2b67670a7ce2d34be25a60ca97d131216a3aba3d | /core/src/db/merge/MergeAdaptiveStrategy.cpp | 6b948a8737e1221a6c07c27cacb4d9b969c6290b | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"JSON",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zilliztech/mishards-cloud | 3485ec276c5f3f954e624ad6ace64582c6f870c2 | 9469cc4aca1b7627857505e7297c32283f1dfad8 | refs/heads/master | 2023-04-03T16:36:49.722201 | 2021-03-30T08:17:50 | 2021-03-30T08:17:50 | 219,909,270 | 1 | 1 | Apache-2.0 | 2021-03-30T08:17:50 | 2019-11-06T04:06:18 | C++ | UTF-8 | C++ | false | false | 3,016 | cpp | // Copyright (C) 2019-2020 Zilliz. 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.
#include "db/merge/MergeAdaptiveStrategy.h"
#include "utils/Log.h"
#include <algorithm>
#include <vector>
namespace milvus {
namespace engine {
Status
MergeAdaptiveStrategy::RegroupFiles(meta::FilesHolder& files_holder, MergeFilesGroups& files_groups) {
meta::SegmentsSchema sort_files, ignore_files;
meta::SegmentsSchema& files = files_holder.HoldFiles();
for (meta::SegmentsSchema::reverse_iterator iter = files.rbegin(); iter != files.rend(); ++iter) {
meta::SegmentSchema& file = *iter;
if (file.index_file_size_ > 0 && (int64_t)file.file_size_ > file.index_file_size_) {
// file that no need to merge
ignore_files.push_back(file);
continue;
}
sort_files.push_back(file);
}
files_holder.UnmarkFiles(ignore_files);
// no need to merge single file
if (sort_files.size() < 2) {
return Status::OK();
}
// two files, simply merge them
if (sort_files.size() == 2) {
files_groups.emplace_back(sort_files);
return Status::OK();
}
// arrange files by file size in descending order
std::sort(sort_files.begin(), sort_files.end(),
[](const meta::SegmentSchema& left, const meta::SegmentSchema& right) {
return left.file_size_ > right.file_size_;
});
// pick files to merge
int64_t index_file_size = sort_files[0].index_file_size_;
while (true) {
meta::SegmentsSchema temp_group;
int64_t sum_size = 0;
for (auto iter = sort_files.begin(); iter != sort_files.end();) {
meta::SegmentSchema& file = *iter;
if (sum_size + (int64_t)(file.file_size_) <= index_file_size) {
temp_group.push_back(file);
sum_size += file.file_size_;
iter = sort_files.erase(iter);
} else {
if ((iter + 1 == sort_files.end()) && sum_size < index_file_size) {
temp_group.push_back(file);
sort_files.erase(iter);
break;
} else {
++iter;
}
}
}
if (!temp_group.empty()) {
files_groups.emplace_back(temp_group);
}
if (sort_files.empty()) {
break;
}
}
return Status::OK();
}
} // namespace engine
} // namespace milvus
| [
"noreply@github.com"
] | noreply@github.com |
9a717071280c8838ec2e7c38eaa92b890ac19e79 | e0f09befa235125ea4c9a54869982d0300a2f609 | /library/include/sml/SarsaGradient.hpp | 7f235e192c838369b450234b7709ee4f44f12854 | [] | no_license | matthieu637/smile | 8b22695a38fa31d7238a2c4c87896ef452bc68dc | 610f70c0b1daec132aa3a607d69e496302a60653 | refs/heads/master | 2021-01-17T13:25:28.744544 | 2016-08-01T13:42:19 | 2016-08-01T13:42:19 | 8,015,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,994 | hpp | #ifndef SARSAGRADIENT_HPP
#define SARSAGRADIENT_HPP
///
///\file SarsaGradient.hpp
///\brief Algorithme par descente de gradient de QLearning avec des fonctions d'approximation
///
#include <boost/numeric/ublas/vector.hpp>
#include <sml/RLGradientDescent.hpp>
#include <simu/MCar.hpp>
#include <algorithm>
namespace sml {
template <class State>
class SarsaGradient : public RLGradientDescent<State>
{
public:
///
///\brief Constructeur
///\param features : les quadrillages
/// nbFeature : le nombre total de rectagle de tous les quadrillages
/// atmp : le modèle d'action
/// initial : l'action initiale
/// conf : la configuration d'apprentissage
SarsaGradient(featuredList<State>* features, unsigned int nbFeature, const ActionTemplate* atmp, const State& s,
const DAction& a, RLParam param, StrategyEffectsAdvice sea=None) :
RLGradientDescent<State>(features, nbFeature/*12288*/, atmp, s, a, param, sea), e2(zero_vector<double>(nbFeature))
{
this->startEpisode(s, a);
}
// SarsaGradient(const SarsaGradient& q) : RLGradientDescent<State>(q)
// {
//
// }
~SarsaGradient() {
}
///
///\brief Retourner l'action à faire selon cet algorithme
///\param state : l'état présent
/// r : la récompense
/// lrate : le taux d'apprentissage
/// epsilon : politique "epsilon-greedy"
/// lambda : importance de l'historique
/// discount : importance du prochain état de la récompense
/// accumulative : si les traces est accumulative ou non
LearnReturn _learn(const State& state, double r, bool goal)
{
DAction* a = this->lastAction;
float delta = r - this->Qa(*a);
// For all a in A(s')
this->computeQa(state);
DAction* ap = this->Qa.argmax();
bool gotGreedy = false;
if( sml::Utils::rand01(this->param.epsilon)) {
delete ap;
ap = new DAction(this->atmpl, rand() % this->atmpl->sizeNeeded());
gotGreedy = true;
}
if(!goal)
delta = delta + this->param.gamma * this->Qa(*ap);
this->updateWeights(delta);
this->decayTraces();
this->addTraces(state, *ap);
//take action a, observe reward, and next state
delete this->lastAction;
this->lastAction = ap;
adviceMaxUpdate();
return {ap, gotGreedy};
}
void _startEpisode(const State& s, const DAction& a) {
this->decayTraces();
this->addTraces(s, a);
historique_max.clear();
//LOG_DEBUG("reset");
}
void had_choosed(const State& state, const DAction& ba, double r, bool, bool goal) {
DAction* a = this->lastAction;
float delta = r - this->Qa(*a);
// For all a in A(s')
this->computeQa(state);
DAction* ap = new DAction(ba);
if(!goal)
delta = delta + this->param.gamma * this->Qa(*ap);
this->updateWeights(delta);
this->decayTraces();
this->addTraces(state, *ap);
//take action a, observe reward, and next state
delete this->lastAction;
this->lastAction = ap;
adviceMaxUpdate();
}
void should_do(const State& state, const DAction& ba, double r, bool goal) {
DAction* a = this->lastAction;
float delta = r - this->Qa(*a);
// For all a in A(s')
this->computeQa(state);
DAction* ap = new DAction(ba);
if(!goal)
delta = delta + this->param.gamma * this->Qa(*ap);
this->updateWeights(delta);
this->decayTraces();
this->addTraces(state, *ap);// TODO: MAX STRAT RM THIS?
//take action a, observe reward, and next state
delete this->lastAction;
this->lastAction = ap;
// that was the default update of Q(s,a)
//now take advise in consideration
if(this->adviceStrat == Max) {
historique_max.push_back(pair<State, DAction *>(state, new DAction(ba)));
// list<int>* activeIndex = this->extractFeatures(state, ba);
// for(list<int>::iterator it = activeIndex->begin(); it != activeIndex->end() ; ++it) {
// int index = *it;
// if(this->param.accumu)
// e2[index] += 1.;
// else
// e2[index] = 1.;
// }
// delete activeIndex;
}
adviceMaxUpdate();
}
Policy<State>* copyPolicy() {
return new SarsaGradient(*this);
}
private:
void adviceMaxUpdate() {
//SHUFFLE IF NOT WORK LOOK AT INFORMATION Q(a) - Q(a*)
//rm from history
//for(int i=0;i< historique_max.size();i++){
// historique_max[i] = historique_max[(int)Utils::randin(0, historique_max.size())];
//}
random_shuffle(historique_max.begin(), historique_max.end());
for(typename deque<pair<State, DAction* >>::iterator it = historique_max.begin(); it != historique_max.end() ;) {
// if(sml::Utils::rand01(0.1f))
if(adviceMax(it->first, *it->second))
it = historique_max.erase(it);
else ++it;
}
//LOG_DEBUG(historique_max.size());
//e2 *= this->param.lambda;
}
bool adviceMax(const State& state, const DAction& ba) {
//LOG_DEBUG("test "<< ba);
this->computeQa(state);
DAction* amax = this->Qa.argmax();
if(!(*amax == ba)) {
list<int>* f_amax = this->extractFeatures(state, *amax);
list<int>* f_ba = this->extractFeatures(state, ba);
// LOG_DEBUG(f_amax->size() << " " << f_ba->size());
list<int>::iterator it=f_ba->begin();
for(list<int>::iterator it2=f_amax->begin(); it2 != f_amax->end(); ++it2) {
this->teta[*it] = this->teta[*it] - 2. *(this->param.alpha/this->param.tiling) /** this->e[*it]*/ * (this->teta[*it] - this->teta[*it2]) ;
//this->e[*it] = 0L;
++it;
}
delete f_amax;
delete f_ba;
delete amax;
return false;
}
delete amax;
return true;
}
// void adviceMax(const State& state, const DAction& ba) {
// this->computeQa(state);
// // DAction* amax = this->Qa.argmaxGreaterThan();
// DAction* amax = this->Qa.argmax();
// list<int>* f_amax = this->extractFeatures(state, *amax);
// list<int>* f_ba = this->extractFeatures(state, ba);
//
// // LOG_DEBUG(f_amax->size() << " " << f_ba->size());
//
// list<int>::iterator it=f_ba->begin();
// for(list<int>::iterator it2=f_amax->begin(); it2 != f_amax->end(); ++it2) {
// this->teta[*it] = this->teta[*it2];
// ++it;
// }
//
// delete amax;
// delete f_amax;
// delete f_ba;
//
// }
private:
deque<pair<State, DAction* >> historique_max;
dbvector e2;
};
}
#endif // SARSAGRADIENT_HPP
| [
"contact@matthieu-zimmer.net"
] | contact@matthieu-zimmer.net |
307459128f09b8b3d7609702462d0767b00ea4b8 | 3bdf849c236e3efe5a5799aeb1a4022d4b3b463c | /include/logger/impl/utils.h | 7bb6a33c52229fb4ce79a1eed45845a3b0c23379 | [] | no_license | code-dreamer/QtLogger | aa0a98cec22e1611747068b307b2e600a717f8e0 | b82861d53e3c1e8a3e235195e1ea0bb4849cb69c | refs/heads/master | 2021-01-10T18:40:35.762445 | 2015-01-22T09:58:35 | 2015-01-22T09:58:35 | 29,597,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,722 | h | #pragma once
#ifdef UNUSED
# error "UNUSED already defined"
#else
# define UNUSED(identifier) /* identifier */
#endif
#define DISABLE_COPY_ASSIGN(ClassName) \
private: \
ClassName(const ClassName&); \
ClassName(const ClassName&&); \
ClassName& operator=(const ClassName&); \
ClassName& operator=(const ClassName&&);
//#define DISABLE_WARNINGS __pragma(warning(push, 0))
//#define ENABLE_WARNINGS __pragma(warning(pop))
#include <cassert>
#if defined(ASSERT)
# pragma message ("ASSERT already defined.")
#else
# define ASSERT(condition) assert(condition)
#endif
#if defined(ASSERT_MSG)
# pragma message ("ASSERT_MSG already defined.")
#else
# if defined(DEBUG)
# define ASSERT_MSG(condition, message) \
(void)( (!!(condition)) || (_wassert(_CRT_WIDE(#condition) _CRT_WIDE("\nMessage: ") _CRT_WIDE(#message), _CRT_WIDE(__FILE__), __LINE__), 0) )
# else
# define ASSERT_MSG(condition, message) ((void)0)
# endif
#endif
#if defined(CHECK_PTR)
# pragma message ("CHECK_PTR already defined.")
#else
# define CHECK_PTR(pointer) \
ASSERT_MSG(pointer != nullptr, "Invalid pointer"); \
Q_CHECK_PTR(pointer)
#endif
#if defined(CHECK_QSTRING)
# pragma message ("CHECK_QSTRING already defined.")
#else
# define CHECK_QSTRING(qstring) \
ASSERT( !qstring.isEmpty() )
#endif
#if defined(CHECK_STDSTRING)
# pragma message ("CHECK_STDSTRING already defined.")
#else
# define CHECK_STDSTRING(stdstring) \
ASSERT( !stdstring.isEmpty() )
#endif
#if defined(CHECK_CSTRING)
# pragma message ("CHECK_CSTRING already defined.")
#else
# define CHECK_CSTRING(cstring) \
CHECK_PTR(cstring); \
ASSERT(strlen(cstring) > 0);
#endif
#if defined(CHECK_CWSTRING)
# pragma message ("CHECK_CWSTRING already defined.")
#else
# define CHECK_CWSTRING(cwstring) \
CHECK_PTR(cwstring); \
ASSERT(wcslen(cwstring) > 0);
#endif
#ifdef _S
# error "_S already defined"
#else
# define _S(string) QLatin1String(string)
#endif
#ifdef _C
# error "_C already defined"
#else
# define _C(symbol) QLatin1Char(symbol)
#endif
template<typename T>
static void safeDelete(T*& ptr)
{
CHECK_PTR(ptr);
typedef char TypeIsCompleteCheck[sizeof(T)];
if (ptr != nullptr) {
delete ptr;
ptr = nullptr;
}
}
template<typename T>
static void safeSeleteA(T*& ptr)
{
CHECK_PTR(ptr);
typedef char TypeIsCompleteCheck[sizeof(T)];
if (ptr != nullptr) {
delete[] ptr;
ptr = nullptr;
}
}
// x=target, y=mask
#define BITMASK_SET(x,y) ((x) |= (y))
#define BITMASK_CLEAR(x,y) ((x) &= (~(y)))
#define BITMASK_FLIP(x,y) ((x) ^= (y))
#define BITMASK_CHECK(x,y) ((x) & (y))
| [
"andrey.lankin.work@gmail.com"
] | andrey.lankin.work@gmail.com |
c18081051697b8ea35f65ea0cb0c6a65d96cccfa | f6851f1c37012d6443c76542f87f637dcdef3de6 | /C-CTP/src/QuantBox.C2CTP/QuantBox.C2CTP.cpp | 362a5ab587eb34c701aa21d00891df8fb04d38aa | [
"BSD-3-Clause"
] | permissive | anoval/CTP | 1b8992c76ade9ea890a4df29d293bb9254914e81 | 7ad506724f81026bb55cabf9c7a8e7d757c284f5 | refs/heads/master | 2021-01-16T18:58:48.293744 | 2012-12-04T16:31:08 | 2012-12-04T16:31:08 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,664 | cpp | // QuantBox.C2CTP.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "QuantBox.C2CTP.h"
#include "MdUserApi.h"
#include "TraderApi.h"
#include "CTPMsgQueue.h"
inline CCTPMsgQueue* CTP_GetQueue(void* pMsgQueue)
{
return static_cast<CCTPMsgQueue*>(pMsgQueue);
}
inline CMdUserApi* MD_GetApi(void* pMdUserApi)
{
return static_cast<CMdUserApi*>(pMdUserApi);
}
inline CTraderApi* TD_GetApi(void* pTraderApi)
{
return static_cast<CTraderApi*>(pTraderApi);
}
QUANTBOXC2CTP_API void* __stdcall CTP_CreateMsgQueue()
{
return new CCTPMsgQueue();
}
QUANTBOXC2CTP_API void __stdcall CTP_ReleaseMsgQueue(void* pMsgQueue)
{
if(pMsgQueue)
{
delete CTP_GetQueue(pMsgQueue);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnConnect(void* pMsgQueue,fnOnConnect pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnDisconnect(void* pMsgQueue,fnOnDisconnect pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnErrRtnOrderAction(void* pMsgQueue,fnOnErrRtnOrderAction pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnErrRtnOrderInsert(void* pMsgQueue,fnOnErrRtnOrderInsert pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspError(void* pMsgQueue,fnOnRspError pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspOrderAction(void* pMsgQueue,fnOnRspOrderAction pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspOrderInsert(void* pMsgQueue,fnOnRspOrderInsert pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryDepthMarketData(void* pMsgQueue,fnOnRspQryDepthMarketData pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryInstrument(void* pMsgQueue,fnOnRspQryInstrument pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryInstrumentCommissionRate(void* pMsgQueue,fnOnRspQryInstrumentCommissionRate pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryInstrumentMarginRate(void* pMsgQueue,fnOnRspQryInstrumentMarginRate pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryInvestorPosition(void* pMsgQueue,fnOnRspQryInvestorPosition pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryOrder(void* pMsgQueue,fnOnRspQryOrder pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryTrade(void* pMsgQueue,fnOnRspQryTrade pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRspQryTradingAccount(void* pMsgQueue,fnOnRspQryTradingAccount pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRtnDepthMarketData(void* pMsgQueue,fnOnRtnDepthMarketData pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRtnOrder(void* pMsgQueue,fnOnRtnOrder pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API void __stdcall CTP_RegOnRtnTrade(void* pMsgQueue,fnOnRtnTrade pCallback)
{
if(pMsgQueue)
{
CTP_GetQueue(pMsgQueue)->RegisterCallback(pCallback);
}
}
QUANTBOXC2CTP_API bool __stdcall CTP_ProcessMsgQueue(void* pMsgQueue)
{
if(pMsgQueue)
{
return CTP_GetQueue(pMsgQueue)->Process();
}
return false;
}
QUANTBOXC2CTP_API void __stdcall CTP_ClearMsgQueue(void* pMsgQueue)
{
if(pMsgQueue)
{
return CTP_GetQueue(pMsgQueue)->Clear();
}
}
QUANTBOXC2CTP_API void __stdcall CTP_StartMsgQueue(void* pMsgQueue)
{
if(pMsgQueue)
{
return CTP_GetQueue(pMsgQueue)->StartThread();
}
}
QUANTBOXC2CTP_API void __stdcall CTP_StopMsgQueue(void* pMsgQueue)
{
if(pMsgQueue)
{
return CTP_GetQueue(pMsgQueue)->StopThread();
}
}
QUANTBOXC2CTP_API void* __stdcall MD_CreateMdApi()
{
return new CMdUserApi();
}
QUANTBOXC2CTP_API void __stdcall MD_RegMsgQueue2MdApi(void* pMdUserApi,void* pMsgQueue)
{
if(pMdUserApi)
{
MD_GetApi(pMdUserApi)->RegisterMsgQueue((CCTPMsgQueue*)pMsgQueue);
}
}
QUANTBOXC2CTP_API void __stdcall MD_Connect(void* pMdUserApi,
const char* szPath,
const char* szAddresses,
const char* szBrokerId,
const char* szInvestorId,
const char* szPassword)
{
if(pMdUserApi
&&szPath
&&szAddresses
&&szBrokerId
&&szInvestorId
&&szPassword)
{
MD_GetApi(pMdUserApi)->Connect(szPath,szAddresses,szBrokerId,szInvestorId,szPassword);
}
}
QUANTBOXC2CTP_API void __stdcall MD_Disconnect(void* pMdUserApi)
{
if(pMdUserApi)
{
MD_GetApi(pMdUserApi)->Disconnect();
}
}
QUANTBOXC2CTP_API void __stdcall MD_Subscribe(void* pMdUserApi,const char* szInstrumentIDs)
{
if(pMdUserApi
&&szInstrumentIDs)
{
MD_GetApi(pMdUserApi)->Subscribe(szInstrumentIDs);
}
}
QUANTBOXC2CTP_API void __stdcall MD_Unsubscribe(void* pMdUserApi,const char* szInstrumentIDs)
{
if(pMdUserApi
&&szInstrumentIDs)
{
MD_GetApi(pMdUserApi)->Unsubscribe(szInstrumentIDs);
}
}
QUANTBOXC2CTP_API void __stdcall MD_ReleaseMdApi(void* pMdUserApi)
{
if(pMdUserApi)
{
delete MD_GetApi(pMdUserApi);
}
}
QUANTBOXC2CTP_API void* __stdcall TD_CreateTdApi()
{
return new CTraderApi();
}
QUANTBOXC2CTP_API void __stdcall TD_RegMsgQueue2TdApi(void* pTraderApi,void* pMsgQueue)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->RegisterMsgQueue((CCTPMsgQueue*)pMsgQueue);
}
}
QUANTBOXC2CTP_API void __stdcall TD_Connect(
void* pTraderApi,
const char* szPath,
const char* szAddresses,
const char* szBrokerId,
const char* szInvestorId,
const char* szPassword,
THOST_TE_RESUME_TYPE nResumeType,
const char* szUserProductInfo,
const char* szAuthCode)
{
if(pTraderApi
&&szPath
&&szAddresses
&&szBrokerId
&&szInvestorId
&&szPassword)
{
if(szUserProductInfo&&szAuthCode)
TD_GetApi(pTraderApi)->Connect(szPath,szAddresses,szBrokerId,szInvestorId,szPassword,nResumeType,szUserProductInfo,szAuthCode);
else
TD_GetApi(pTraderApi)->Connect(szPath,szAddresses,szBrokerId,szInvestorId,szPassword,nResumeType,"","");
}
}
QUANTBOXC2CTP_API int __stdcall TD_SendOrder(
void* pTraderApi,
const char* szInstrument,
TThostFtdcDirectionType Direction,
const char* szCombOffsetFlag,
const char* szCombHedgeFlag,
TThostFtdcVolumeType VolumeTotalOriginal,
double LimitPrice,
TThostFtdcOrderPriceTypeType OrderPriceType,
TThostFtdcTimeConditionType TimeCondition,
TThostFtdcContingentConditionType ContingentCondition,
double StopPrice)
{
if(pTraderApi
&&szInstrument
&&szCombOffsetFlag
&&szCombHedgeFlag)
{
return TD_GetApi(pTraderApi)->ReqOrderInsert(szInstrument,
Direction,
szCombOffsetFlag,
szCombHedgeFlag,
VolumeTotalOriginal,
LimitPrice,
OrderPriceType,
TimeCondition,
ContingentCondition,
StopPrice);
}
return 0;
}
QUANTBOXC2CTP_API void __stdcall TD_CancelOrder(void* pTraderApi,CThostFtdcOrderField *pOrder)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->ReqOrderAction(pOrder);
}
}
QUANTBOXC2CTP_API void __stdcall TD_Disconnect(void* pTraderApi)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->Disconnect();
}
}
QUANTBOXC2CTP_API void __stdcall TD_ReleaseTdApi(void* pTraderApi)
{
if(pTraderApi)
{
delete TD_GetApi(pTraderApi);
}
}
QUANTBOXC2CTP_API void __stdcall TD_ReqQryInvestorPosition(void* pTraderApi,const char* szInstrumentId)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->ReqQryInvestorPosition(NULL==szInstrumentId?"":szInstrumentId);
}
}
QUANTBOXC2CTP_API void __stdcall TD_ReqQryTradingAccount(void* pTraderApi)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->ReqQryTradingAccount();
}
}
QUANTBOXC2CTP_API void __stdcall TD_ReqQryInstrument(void* pTraderApi,const char* szInstrumentId)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->ReqQryInstrument(NULL==szInstrumentId?"":szInstrumentId);
}
}
QUANTBOXC2CTP_API void __stdcall TD_ReqQryInstrumentCommissionRate(void* pTraderApi,const char* szInstrumentId)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->ReqQryInstrumentCommissionRate(szInstrumentId);
}
}
QUANTBOXC2CTP_API void __stdcall TD_ReqQryInstrumentMarginRate(void* pTraderApi,const char* szInstrumentId)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->ReqQryInstrumentMarginRate(szInstrumentId);
}
}
QUANTBOXC2CTP_API void __stdcall TD_ReqQryDepthMarketData(void* pTraderApi,const char* szInstrumentId)
{
if(pTraderApi)
{
TD_GetApi(pTraderApi)->ReqQryDepthMarketData(szInstrumentId);
}
} | [
"wu-kan@163.com"
] | wu-kan@163.com |
b5665f1bc084eb7614e008a189c626e60d15bbbc | 1497386b0fe450e6c3881c8c6d52d9e6ad9117ab | /trunk/CrypTool/DlgFactorisationDemo.cpp | a989ee127eb89bcd8da8ea8743579c74c0236c81 | [
"Apache-2.0"
] | permissive | flomar/CrypTool-VS2015 | 403f538d6cad9b2f16fbf8846d94456c0944569b | 6468257af2e1002418882f22a9ed9fabddde096d | refs/heads/master | 2021-01-21T14:39:58.113648 | 2017-02-22T14:10:19 | 2017-02-22T14:10:19 | 57,972,666 | 0 | 5 | null | null | null | null | ISO-8859-1 | C++ | false | false | 31,798 | cpp | /**************************************************************************
Copyright [2009] [CrypTool Team]
This file is part of CrypTool.
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.
**************************************************************************/
// DlgTutorialFactorisation.cpp: Implementierungsdatei
//
#include "stdafx.h"
#include "CrypToolApp.h"
#include "DlgFactorisationDemo.h"
#include "IntegerArithmetic.h"
#include "DlgProgressFactorisation.h"
#include "DialogeMessage.h"
#include <time.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// Dialogfeld CDlgFactorisationDemo
CDlgFactorisationDemo::CDlgFactorisationDemo(CWnd* pParent)
: CDialog(CDlgFactorisationDemo::IDD, pParent)
{
//{{AFX_DATA_INIT(CDlgFactorisationDemo)
m_CompositeNoStr = _T("");
m_bruteForce = TRUE;
m_Brent = TRUE;
m_Pollard = TRUE;
m_Williams = TRUE;
m_Lenstra = TRUE;
m_QSieve = TRUE;
m_Factorisation = _T("");
m_Name = _T("");
m_benoetigte_zeit_global = _T("");
m_benoetigte_zeit_pro_factorisation = _T("");
//}}AFX_DATA_INIT
factorList = 0;
duration1 = 0;
duration2 = 0;
m_inputReadOnly = 0;
}
CDlgFactorisationDemo::~CDlgFactorisationDemo()
{
while ( factorList != 0 )
{
NumFactor *tmp = factorList;
factorList = factorList->next;
delete tmp;
}
}
void CDlgFactorisationDemo::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgFactorisationDemo)
DDX_Control(pDX, IDC_BUTTON1, m_DialogeDetails);
DDX_Control(pDX, IDC_CHECK1, m_bruteForceCtrl);
DDX_Control(pDX, IDC_EDIT1, m_CompositeNoCtrl);
DDX_Control(pDX, IDC_BUTTON_VOLLSTAENDIG_FAKTORISATION, m_vollstaendig);
DDX_Control(pDX, IDC_BUTTON_Faktorisieren, m_weiter);
DDX_Control(pDX, IDC_RICHEDIT2, m_FactorisationCtrl);
DDX_Text(pDX, IDC_EDIT1, m_CompositeNoStr);
DDX_Check(pDX, IDC_CHECK1, m_bruteForce);
DDX_Check(pDX, IDC_CHECK2, m_Brent);
DDX_Check(pDX, IDC_CHECK3, m_Pollard);
DDX_Check(pDX, IDC_CHECK4, m_Williams);
DDX_Check(pDX, IDC_CHECK5, m_Lenstra);
DDX_Check(pDX, IDC_CHECK6, m_QSieve);
DDX_Text(pDX, IDC_RICHEDIT2, m_Factorisation);
DDX_Text(pDX, IDC_EDIT2, m_Name);
DDX_Text(pDX, IDS_STRING_BENOETIGTE_ZEIT_FAKT, m_benoetigte_zeit_global);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgFactorisationDemo, CDialog)
//{{AFX_MSG_MAP(CDlgFactorisationDemo)
ON_BN_CLICKED(IDC_BUTTON_CANCEL, OnButtonEnd)
ON_BN_CLICKED(IDC_BUTTON_Faktorisieren, OnButtonFactorisation)
ON_BN_CLICKED(IDC_BUTTON_VOLLSTAENDIG_FAKTORISATION, OnButtonVollstaendigFaktorisation)
ON_EN_UPDATE(IDC_EDIT1, OnUpdateEditEingabe)
ON_BN_CLICKED(IDC_BUTTON1, OnShowFactorisationDetails)
ON_BN_CLICKED(IDC_BUTTON_LOAD_NUMBER, OnBnClickedLoadNumber)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Behandlungsroutinen für Nachrichten CDlgFactorisationDemo
void CDlgFactorisationDemo::OnButtonEnd()
{
// TODO: Code für die Behandlungsroutine der Steuerelement-Benachrichtigung hier einfügen
CDialog::OnOK();
}
//////////////////////////////////////////////////////////////////////////////
CDlgProgressFactorisation dlg;
UINT singleThreadBrent( PVOID x )
{
CTutorialFactorisation *f;
f = (CTutorialFactorisation*)x;
BOOL ret = f->Brent();
return 0;
}
UINT singleThreadPollard( PVOID x )
{
CTutorialFactorisation *f;
f = (CTutorialFactorisation*)x;
BOOL ret = f->Pollard();
return 0;
}
UINT singleThreadWilliams( PVOID x )
{
CTutorialFactorisation *f;
f = (CTutorialFactorisation*)x;
BOOL ret = f->Williams();
return 0;
}
UINT singleThreadLenstra( PVOID x )
{
CTutorialFactorisation *f;
f = (CTutorialFactorisation*)x;
BOOL ret = f->Lenstra();
return 0;
}
UINT singleThreadQuadraticSieve( PVOID x )
{
CTutorialFactorisation *f;
f = (CTutorialFactorisation*)x;
BOOL ret = f->QuadraticSieve();
return 0;
}
void CDlgFactorisationDemo::OnButtonFactorisation()
{
int i, started;
CString name;
// differ between English and German version ("quadratisches Sieb" <-> "quadratic sieve")
LoadString(AfxGetInstanceHandle(), IDS_QUADRATIC_SIEVE, pc_str, STR_LAENGE_STRING_TABLE);
CTutorialFactorisation Brent(0,"Brent"), Pollard(1,"Pollard"),
Williams(2,"Williams"), Lenstra(3,"Lenstra"), QSieve(4, pc_str);
// Da man die gesamte Laufzeit braucht, wurden die folgenden Deklaration global gemacht!!
// clock_t FactStart;
// clock_t FactFinish;
// double duration;
UpdateData(TRUE);
CString UpnFormula;
int err_ndx;
BOOL error;
error = CheckFormula(m_CompositeNoStr,10,UpnFormula,err_ndx);
if (error==0)
{
//Fehler in der Eingabe, von Parser abgefangen
m_CompositeNoCtrl.SetSel(err_ndx-1,m_CompositeNoStr.GetLength());
m_CompositeNoCtrl.SetFocus();
Message(IDS_STRING_INPUT_FALSE, MB_ICONEXCLAMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
return;
}
int laenge_eingabe;
laenge_eingabe = m_CompositeNoStr.GetLength();
if ( laenge_eingabe )
{
m_weiter.EnableWindow(true);
m_vollstaendig.EnableWindow(true);
}
CString next_factor = Search_First_Composite_Factor();
// Falls noch zusammengesetzten Faktoren die eingegebene Zahl teilen:
if (next_factor!="lolo")
{
int Out_SetN = f.SetN(next_factor);
int bitlength_next_factor = f.bitlength();
if (Out_SetN==EVAL_NULL || Out_SetN==EVAL_EINS)
{
//Sie müssen eine ganze Zahl eingeben, die von 0 und 1 verschieden ist.
m_CompositeNoCtrl.SetSel(0,-1);
m_CompositeNoCtrl.SetFocus();
Message(IDS_STRING_FAKTORISATION_NOT_NULL_OR_ONE, MB_ICONEXCLAMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
return;
}
if (Out_SetN==EVAL_OK)
{
BOOL factorized = FALSE;
CString f1, f2;
SHOW_HOUR_GLASS // aktiviert die Sanduhr
if (!m_bruteForce && !m_Brent && !m_Pollard && !m_Williams && !m_Lenstra && !m_QSieve)
{
//Sie müssen mindestens ein Verfahren wählen!
Message(IDS_STRING_FAKTORISATION_VERFAHREN, MB_ICONEXCLAMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
return;
}
if ( f.IsPrime(next_factor) )
{// Die eingegebene Zahl ist eine Primzahl
Message(IDS_STRING_FAKTORISATION_PRIMZAHL, MB_ICONEXCLAMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
return;
}
FactStart = clock();
if ( !factorized && m_bruteForce )
{
CTutorialFactorisation fact;
fact.SetN(next_factor);
if ( TRUE == (factorized = fact.BruteForce()) )
{
fact.GetFactor1Str( f1 );
fact.GetFactor2Str( f2 );
name = "Brute Force";
}
}
if (next_factor.GetLength()>21)
{
dlg.m_zahl=_T("");
dlg.m_zahl.Insert(0, next_factor.Mid(0,9));
dlg.m_zahl += CString("...");
dlg.m_zahl += next_factor.Right(9);
}
else
{
dlg.m_zahl=_T("");
dlg.m_zahl=next_factor;
}
dlg.m_curThread = 0;
dlg.m_numThreads = 0;
dlg.m_displayed = 0;
dlg.m_OldThread = -1;
dlg.m_registeredThreads = 0;
dlg.m_retcode = IDCANCEL;
dlg.m_Factorisations[0] = &Brent;
dlg.m_Factorisations[1] = &Pollard;
dlg.m_Factorisations[2] = &Williams;
dlg.m_Factorisations[3] = &Lenstra;
dlg.m_Factorisations[4] = &QSieve;
for(i=0;i<5;i++) {
dlg.m_Factorisations[i]->m_iterations = 0;
dlg.m_Factorisations[i]->factorized = 0;
dlg.m_Factorisations[i]->status = 0;
dlg.m_Factorisations[i]->SetN(next_factor);
}
started = 0;
if ( !factorized && m_Brent )
{
Brent.m_Thread = AfxBeginThread( singleThreadBrent, PVOID(&Brent) );
started++;
}
if ( !factorized && m_Pollard )
{
Pollard.m_Thread = AfxBeginThread( singleThreadPollard, PVOID(&Pollard) );
started++;
}
if ( !factorized && m_Williams )
{
Williams.m_Thread = AfxBeginThread( singleThreadWilliams, PVOID(&Williams) );
started++;
}
if ( !factorized && m_Lenstra )
{
Lenstra.m_Thread = AfxBeginThread( singleThreadLenstra, PVOID(&Lenstra) );
started++;
}
if ( !factorized && m_QSieve )
{
if ( 132 < bitlength_next_factor*log(2.0)/log(10.0) )
{
Message(IDS_FACTORISATION_OVERFLOW, MB_ICONEXCLAMATION);
UpdateData();
m_QSieve = 0;
UpdateData(FALSE);
}
else if ( 93 < bitlength_next_factor*log(2.0)/log(10.0) )
{
LoadString(AfxGetInstanceHandle(),IDS_FACTORISATION_MEMORY_REQUEST,pc_str,STR_LAENGE_STRING_TABLE);
if ( IDNO == MessageBox(pc_str, NULL, MB_YESNO) )
{
QSieve.m_Thread = AfxBeginThread( singleThreadQuadraticSieve, PVOID(&QSieve) );
started++;
}
else
{
UpdateData();
m_QSieve = 0;
UpdateData(FALSE);
}
}
else
{
QSieve.m_Thread = AfxBeginThread( singleThreadQuadraticSieve, PVOID(&QSieve) );
started++;
}
}
bool l_factorisation_aborted = false;
int l_dlg_return;
dlg.m_totalThreads = started;
LoadString(AfxGetInstanceHandle(),IDS_STRING_FACTORISATION_TIMER,pc_str,STR_LAENGE_STRING_TABLE);
dlg.SetCaption(pc_str);
if ( started && IDOK != (l_dlg_return = dlg.DoModal()) )
{
if (l_dlg_return == IDCANCEL) l_factorisation_aborted = true;
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
}
for(i=0;i<5;i++) {
if(dlg.m_Factorisations[i]->factorized) {
factorized = TRUE;
name = dlg.m_Factorisations[i]->m_Name;
dlg.m_Factorisations[i]->GetFactor1Str( f1 );
dlg.m_Factorisations[i]->GetFactor2Str( f2 );
}
}
if ( factorized )
{
expandFactorisation( next_factor, f1, f2 );
m_Name = name;
}
else if ( l_factorisation_aborted )
{
Message(IDS_STRING_FAKTORISATION_ABORTED, MB_ICONEXCLAMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
}
// Hier wird man angefordert mit einem anderen Algorithmus zu arbeiten!!
else
{
// special case: if the user selected only the brute-force method,
// tell him about the limit up to which this method is looking for primes
if( m_bruteForce == TRUE && m_Brent == FALSE && m_Pollard == FALSE &&
m_Williams == FALSE && m_Lenstra == FALSE && m_QSieve == FALSE) {
char bruteForcePrimeLimit[2048];
memset(bruteForcePrimeLimit, 0, 2048);
LoadString(AfxGetInstanceHandle(),IDS_STRING_FACTORIZATION_BRUTE_FORCE_LIMIT,pc_str,STR_LAENGE_STRING_TABLE);
sprintf(bruteForcePrimeLimit, pc_str, LIMIT1);
AfxMessageBox(bruteForcePrimeLimit, MB_ICONEXCLAMATION);
//m_Name = "";
}
else {
// this is the normal "use another algorithm" notification
Message(IDS_STRING_FAKTORISATION_NEU_WAEHLEN, MB_ICONEXCLAMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
}
}
FactFinish = clock();
duration1 =((double) (FactFinish - FactStart) / CLOCKS_PER_SEC) + duration1; //gesamte Laufzeit
duration2 =((double) (FactFinish - FactStart) / CLOCKS_PER_SEC) ; //einzelne Laufzeit
double temp;
modf(duration1,&temp);
zeit_condtruct1.day= (int) floor(temp/86400);
zeit_condtruct1.hour= (int) floor((temp - zeit_condtruct1.day*86400)/3600);
zeit_condtruct1.min= (int) floor((temp - zeit_condtruct1.day*86400- zeit_condtruct1.hour*3600)/60);
zeit_condtruct1.sec= (int) (temp - zeit_condtruct1.day*86400- zeit_condtruct1.hour*3600-zeit_condtruct1.min*60);
zeit_condtruct1.msec= (int) floor((duration1-temp)*1000);
modf(duration2,&temp);
zeit_condtruct2.day= (int) floor(temp/86400);
zeit_condtruct2.hour= (int) floor((temp - zeit_condtruct2.day*86400)/3600);
zeit_condtruct2.min= (int) floor((temp - zeit_condtruct2.day*86400- zeit_condtruct2.hour*3600)/60);
zeit_condtruct2.sec= (int) (temp - zeit_condtruct2.day*86400- zeit_condtruct2.hour*3600-zeit_condtruct2.min*60);
zeit_condtruct2.msec= (int) floor((duration2-temp)*1000);
char line2[256], timeStr2[64];
CString timeStr1;
if ( zeit_condtruct1.day >= 1)
timeStr1.Format(IDS_STRING_FMT_DAYS, zeit_condtruct1.day,zeit_condtruct1.hour, zeit_condtruct1.min,zeit_condtruct1.sec);
else if (zeit_condtruct1.hour >= 1)
timeStr1.Format(IDS_STRING_FMT_HRS, zeit_condtruct1.hour, zeit_condtruct1.min,zeit_condtruct1.sec);
else if (zeit_condtruct1.min >= 1)
timeStr1.Format(IDS_STRING_FMT_MIN, zeit_condtruct1.min,zeit_condtruct1.sec);
else
timeStr1.Format(IDS_STRING_FMT_SEC, zeit_condtruct1.sec, zeit_condtruct1.msec);
timeStr1.TrimLeft();
int nfactors = 0;
for (NumFactor *factor = factorList; factor ; factor = factor->next)
nfactors += factor->exponent;
m_benoetigte_zeit_global.Format(IDS_FACTORS_FOUND, nfactors, timeStr1);
if ( zeit_condtruct2.day >= 1)
{
LoadString(AfxGetInstanceHandle(),IDS_STRING_FMT_DAYS,pc_str,STR_LAENGE_STRING_TABLE);
sprintf(timeStr2,pc_str, zeit_condtruct2.day,zeit_condtruct2.hour, zeit_condtruct2.min,zeit_condtruct2.sec);
}
else if (zeit_condtruct2.hour >= 1)
{
LoadString(AfxGetInstanceHandle(),IDS_STRING_FMT_HRS,pc_str,STR_LAENGE_STRING_TABLE);
sprintf(timeStr2,pc_str, zeit_condtruct2.hour, zeit_condtruct2.min,zeit_condtruct2.sec);
}
else if (zeit_condtruct2.min >= 1)
{
LoadString(AfxGetInstanceHandle(),IDS_STRING_FMT_MIN,pc_str,STR_LAENGE_STRING_TABLE);
sprintf(timeStr2,pc_str, zeit_condtruct2.min,zeit_condtruct2.sec);
}
else
{
LoadString(AfxGetInstanceHandle(),IDS_STRING_FMT_SEC,pc_str,STR_LAENGE_STRING_TABLE);
sprintf(timeStr2,pc_str, zeit_condtruct2.sec, zeit_condtruct2.msec);
}
LoadString(AfxGetInstanceHandle(),IDS_STRING_BENOETIGTE_ZEIT_FAKT,pc_str,STR_LAENGE_STRING_TABLE);
sprintf( line2, pc_str, timeStr2 );
m_benoetigte_zeit_pro_factorisation=timeStr2;
HIDE_HOUR_GLASS // deaktiviert die Sanduhr
UpdateData(FALSE);
Set_NonPrime_Factor_Red();
if ( factorized )
{
DetailsFactorisation.InsertFactDetail(next_factor, f1, f2,
m_Name, m_benoetigte_zeit_pro_factorisation,
(int)f.IsPrime( f1 ) + ((int)f.IsPrime(f2))*2,
(int)ceil(BitLength(f1)), (int)ceil(BitLength(f2)));
m_DialogeDetails.EnableWindow();
}
else
{
if ( l_factorisation_aborted )
{
LoadString(AfxGetInstanceHandle(),IDS_STRING_FAKTORISATION_ABORT_MSG,pc_str,STR_LAENGE_STRING_TABLE);
}
else
{
LoadString(AfxGetInstanceHandle(),IDS_STRING_FAKTORISATION_STOP_MSG,pc_str,STR_LAENGE_STRING_TABLE);
}
DetailsFactorisation.InsertFactDetail(next_factor, CString(""), CString(""), CString(pc_str),
m_benoetigte_zeit_pro_factorisation,
0, 0, 0);
m_DialogeDetails.EnableWindow();
}
}
else if(Out_SetN == EVAL_NEG)
{
// Falsche Eingabe: Eingabe ist keine positive ganze Zahl
m_CompositeNoCtrl.SetSel(0,-1);
m_CompositeNoCtrl.SetFocus();
Message(IDS_STRING_FAKTORISATION_FALSCHE_EINGABE, MB_ICONEXCLAMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
}
else
{
// Eingabe ist zu groß (1024-bit); wird nicht von der Demo unterstützt.
m_CompositeNoCtrl.SetSel(0,-1);
m_CompositeNoCtrl.SetFocus();
Message(IDS_STRING_BIG_NUMBER, MB_ICONINFORMATION);
// flomar, October 2012: the new 'single go' implementation
dlg.abortFactorizationInOneGo();
}
}
// Die Zahl ist jetzt vollständig faktorisiert
else
{
m_weiter.EnableWindow(false);
m_vollstaendig.EnableWindow(false);
Message(IDS_STRING_FAKTORISATION_VOLLSTAENDIG, MB_ICONINFORMATION);
}
}
/*
BOOL IsSmallerNumStr( CString &NumStr1, CString &NumStr2 )
{
}
*/
void CDlgFactorisationDemo::expandFactorisation(CString &composite, CString &f1, CString &f2)
{
long expFactor = 1;
if ( factorList )
{ // 1. delete composite
NumFactor * ndx = factorList;
if ( 0 != ndx && ndx->factorStr == composite )
{
expFactor = ndx->exponent;
factorList = ndx->next;
delete ndx;
}
else
{
if ( 0 != ndx )
while ( 0 != ndx->next && ndx->next->factorStr != composite ) ndx = ndx->next;
if ( ndx->next && ndx->next->factorStr == composite )
{
expFactor = ndx->next->exponent;
NumFactor *toDel = ndx->next;
ndx->next = ndx->next->next;
delete toDel;
}
}
}
{ // 2. insert first factor
NumFactor * ndx = factorList;
if ( 0 == ndx )
{
factorList = new NumFactor;
factorList->exponent = expFactor;
factorList->factorStr = f1;
factorList->isPrime = f.IsPrime( f1 );
factorList->next = 0;
}
else
{
if ( ndx->factorStr.GetLength() > f1.GetLength() ||
(ndx->factorStr.GetLength() == f1.GetLength() && ndx->factorStr > f1) )
{
factorList = new NumFactor;
factorList->exponent = expFactor;
factorList->factorStr = f1;
factorList->isPrime = f.IsPrime( f1 );
factorList->next = ndx;
}
else if ( ndx->factorStr == f1 )
{
factorList->exponent = factorList->exponent + expFactor;
}
else
{
while ( 0 != ndx->next && ( (ndx->next->factorStr.GetLength() < f1.GetLength()) ||
(ndx->next->factorStr.GetLength() == f1.GetLength() && ndx->next->factorStr < f1) ) )
ndx = ndx->next;
if ( ndx->next && ndx->next->factorStr == f1 ) ndx->next->exponent = ndx->next->exponent + expFactor;
else
{
NumFactor * insFactor = new NumFactor;
insFactor->exponent = expFactor;
insFactor->factorStr = f1;
insFactor->isPrime = f.IsPrime( f1 );
insFactor->next = ndx->next;
ndx->next = insFactor;
}
}
}
}
{ // 3. insert second factor
NumFactor * ndx = factorList;
if ( ndx->factorStr.GetLength() > f2.GetLength() ||
(ndx->factorStr.GetLength() == f2.GetLength() && ndx->factorStr > f2) )
{
factorList = new NumFactor;
factorList->exponent = expFactor;
factorList->factorStr = f2;
factorList->isPrime = f.IsPrime( f2 );
factorList->next = ndx;
}
else if ( ndx->factorStr == f2 && ndx->isPrime ==0)
{
// Roger 30.10.2001
// factorList->exponent++;
factorList->exponent= factorList->exponent + expFactor;
}
else if ( ndx->factorStr == f2 && ndx->isPrime ==1)
{
// Roger 30.10.2001
factorList->exponent = factorList->exponent + expFactor;
// factorList->exponent= (factorList->exponent)*2;
}
else
{
while ( 0 != ndx->next && ( (ndx->next->factorStr.GetLength() < f2.GetLength()) ||
(ndx->next->factorStr.GetLength() == f2.GetLength() && ndx->next->factorStr < f2) ) )
ndx = ndx->next;
if ( ndx->next && ndx->next->factorStr == f2 ) ndx->next->exponent = ndx->next->exponent + expFactor;
else
{
NumFactor * insFactor = new NumFactor;
insFactor->exponent = expFactor;
insFactor->factorStr = f2;
insFactor->isPrime = f.IsPrime( f2 );
insFactor->next = ndx->next;
ndx->next = insFactor;
}
}
}
{ // 4. Print actual factorisation
m_Factorisation = _T("");
NumFactor * ndx = factorList;
while ( ndx )
{
m_Factorisation += ndx->factorStr.GetBuffer(128);
if ( ndx->exponent > 1 )
{
char tmpStr[20]; sprintf(tmpStr,"^%i", ndx->exponent);
m_Factorisation += tmpStr;
}
if ( ndx->next )
{
m_Factorisation += " * ";
}
ndx = ndx->next;
}
}
}
void CDlgFactorisationDemo::Set_NonPrime_Factor_Red()
{
CHARFORMAT cf;
// flomar, 09/06/2012: don't forget to initialize the struct properly, otherwise we
// may encounter weird behavior under VS2010; for some reason VS2008 seems to be fine
// even without explicitly initializing everything to zero
memset(&cf, 0, sizeof(cf));
// go on as usual...
cf.cbSize = sizeof (CHARFORMAT);
cf.dwMask= CFM_COLOR;//
cf.crTextColor =RGB(0,0,0);
m_FactorisationCtrl.SetSel(0,-1);
m_FactorisationCtrl.SetSelectionCharFormat(cf);
NumFactor *ndx = factorList;
if ( !ndx ) return;
int anfang = 0, ende = 0, expLen;
int firstcomposite = -1;
while ( ndx )
{
if ( ndx->exponent > 1 )
{
// Beginn Bugfix Jan Blumenstein (JB)
expLen = (int)floor(log(double(ndx->exponent))/log(10.0))+2;
//expLen = ceil(log(double(ndx->exponent))/log(10.0))+1; // falsch, wenn ndx->exponent = 10, 100, 1000, ...
// Ende Bugfix JB
}
else
{
expLen = 0;
}
ende = anfang + ndx->factorStr.GetLength();
// Markiere Text ....
if ( !ndx->isPrime )
{
cf.cbSize = sizeof (CHARFORMAT);
cf.dwMask= CFM_COLOR;
cf.crTextColor =RGB(255,0,0);
m_FactorisationCtrl.SetSel(anfang, ende);
m_FactorisationCtrl.SetSelectionCharFormat(cf);
if (firstcomposite == -1)
firstcomposite = anfang;
}
ndx = ndx->next;
anfang = ende + 3 + expLen;
}
// scroll to first composite factor (or to the beginning if completely factorized)
m_FactorisationCtrl.HideSelection(FALSE,TRUE);
if (firstcomposite == -1)
firstcomposite = 0;
m_FactorisationCtrl.SetSel(firstcomposite, firstcomposite);
}
CString CDlgFactorisationDemo::Search_First_Composite_Factor()
{
NumFactor *ndx = factorList;
if ( !ndx ) return m_CompositeNoStr;
while ( ndx )
{
if ( !ndx->isPrime )
{
return ndx->factorStr;
}
ndx = ndx->next;
}
return "lolo";
}
void CDlgFactorisationDemo::OnButtonVollstaendigFaktorisation()
{
// flomar, October 2012: belated implementation of 'factorize all'
// functionality; the solution is quite hackish; essentially, what
// I'm doing is this: initialize the 'dlg' object so that an internal
// 'aborted' variable is set to false; after that I repeatedly call
// the function 'OnButtonFaktorisieren' to factorize the current
// composite factor-- whenever an error occurs or the user cancels
// the factorization, the 'aborted' variable is set to true by
// calling the function 'dlg.abortFactorizationInOneGo()', which
// in turn will break the main factorization loop; after countless
// hours of debugging and getting familiar with the existing code
// base for the 'single go' approach I decided to do it this
// way; in case you like pain, feel free to re-write it...
// get the initial composite factor
CString initialCompositeFactor = Search_First_Composite_Factor();
// initialize control variable for our loop
dlg.startFactorizationInOneGo();
// this while loop repeatedly runs the "factorize" function until
// either the composite factor is completey factorized (nice
// 'keyword' BTW), or the factorization was aborted/cancelled
while(Search_First_Composite_Factor() != "lolo" && !dlg.wasFactorizationInOneGoAborted()) {
OnButtonFactorisation();
}
// this trailing call to "factorize" will automatically prompt
// the user with the factorization result and internally disable
// the "factorize" and "factorize all" buttons (this becomes
// effective only if the factorization was not aborted)
if(!dlg.wasFactorizationInOneGoAborted()) {
OnButtonFactorisation();
}
}
BOOL CDlgFactorisationDemo::OnInitDialog()
{
CDialog::OnInitDialog();
m_weiter.EnableWindow(false);
// TODO: Zusätzliche Initialisierung hier einfügen
m_vollstaendig.EnableWindow(false);
// Initialisiere die Schlüsselliste mit allen verfügbaren asymmetrischen Schlüsseln
m_bruteForceCtrl.SetCheck(1);
if ( m_CompositeNoStr.GetLength() )
{
m_weiter.EnableWindow(true);
m_weiter.SetFocus();
}
if ( !factorList )
{
m_DialogeDetails.EnableWindow(FALSE);
}
if ( m_inputReadOnly )
{
m_CompositeNoCtrl.SetReadOnly(TRUE);
m_weiter.SetFocus();
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX-Eigenschaftenseiten sollten FALSE zurückgeben
}
void CDlgFactorisationDemo::InitialiseFactorList()
{
m_Factorisation = "";
m_benoetigte_zeit_global="";
m_benoetigte_zeit_pro_factorisation="";
duration1=0;
duration2=0;
while ( factorList != 0 )
{
NumFactor *tmp = factorList;
factorList = factorList->next;
delete tmp;
}
factorList = 0;
DetailsFactorisation.ClearFactDetail();
m_Name = "";
}
void CDlgFactorisationDemo::OnUpdateEditEingabe()
{
int sels, sele, i, k;
char c;
CString res;
UpdateData(TRUE); // get the displayed value in m_text
m_CompositeNoCtrl.GetSel(sels, sele);
CheckEdit(m_CompositeNoStr,sels,sele);
res.Empty();
if(theApp.TextOptions.getIgnoreCase()) m_CompositeNoStr.MakeUpper();
for(k=i=0;i<m_CompositeNoStr.GetLength();i++) {
c = m_CompositeNoStr[i];
res += c;
k++;
}
m_CompositeNoStr = res;
if ( m_CompositeNoStr.GetLength() )
{
m_weiter.EnableWindow(true);
m_vollstaendig.EnableWindow(true);
}
else
{
m_weiter.EnableWindow(false);
m_vollstaendig.EnableWindow(false);
}
InitialiseFactorList();
m_DialogeDetails.EnableWindow(FALSE);
UpdateData(FALSE);
m_CompositeNoCtrl.SetSel(sels,sele);
}
void CDlgFactorisationDemo::CheckEdit(CString &m_edit, int &sels, int &sele)
{
// sorgt dafür, daß keine syntaktisch falsche Eingabe in die Eingabefelder
// möglich ist, führende Nullen werden entfernt, die Variablen sels und sele dienen der
// Formatierung
{
while((0==m_edit.IsEmpty())&&('0'==m_edit.GetAt(0)))
//Ruft Funktion IsEmpty auf. Diese gibt 0 zurück, wenn der CString nicht leer ist
//GetAt(a) gibt Zeichen zurück, das an der a. Position steht
//in diesem Fall, wenn dieses Zeichen 0 ist, dann geht er in die Schleife
//Diese Funktionen gelten für die übergebenen Wert aus dem Dialog.
//* Überprüfung, ob überhaupt was in dem Eingabefeld steht, UND ob das erste Zeichen 0 ist.
{
m_edit=m_edit.Right(m_edit.GetLength()-1);
//* Var. m_edit ist Beispielsweise 0567. Der Rückgabe der Funktion Right gibt dir letzten x
//* Stellen eines CStrings zurück, in diesem Fall gibt er mir 3 Stllen zurück (length-1), so dass die 0 gelöscht wird
sels=sele=0;
}
int exp_counter=0;
for(int i=0;i<m_edit.GetLength();i++)
{
char ch=m_edit.GetAt(i);
char ch2;
if (i>=1) ch2=m_edit.GetAt(i-1);
//* GetAt=holt sich das Zeichen an der i. Stelle
if(((ch>='0')&&(ch<='9'))
||((ch=='^'||ch=='+'||ch=='-' ||ch=='*') && (ch2!='^' && ch2!='+' && ch2!='-' && ch2!='*') && i>=1 )
//||((ch=='^'||ch=='+'||ch=='-' ||ch=='/') && i==0)
||ch=='('||ch==')')
{
}
else
{
m_edit=m_edit.Left(i)+m_edit.Right(m_edit.GetLength()-i-1);
//* die ersten i Stellen von links werden mit den Stellen rechts vom ungültigen Zeichen verbunden
//* -1 damit das Zeichen an der Position i von m_edit gelöscht wird.
if(i<=sele)
{
sele--;
sels--;
}
i--;
}
}
}
}
void CDlgFactorisationDemo::OnShowFactorisationDetails()
{
// TODO: Code für die Behandlungsroutine der Steuerelement-Benachrichtigung hier einfügen
DetailsFactorisation.m_factorisedNumber = "";
DetailsFactorisation.m_Factor1isPrime = "";
DetailsFactorisation.m_Factor2isPrime = "";
DetailsFactorisation.m_factor2 = "";
DetailsFactorisation.m_factor1 = "";
DetailsFactorisation.m_Factorisation = m_Factorisation;
DetailsFactorisation.m_orignNumber = m_CompositeNoStr;
DetailsFactorisation.m_benoetigte_zeit_global = m_benoetigte_zeit_global;
if ( DetailsFactorisation.DoModal() == IDCANCEL )
{
// ToDo: Flag Setzen für das Speichern der Datei
CAppDocument *NewDoc;
NewDoc = theApp.OpenDocumentFileNoMRU(DetailsFactorisation.outfile);
remove(DetailsFactorisation.outfile);
LoadString(AfxGetInstanceHandle(),IDS_DETFACTORISATION_HL_OUTPUT,
pc_str,STR_LAENGE_STRING_TABLE);
char line[256];
CString tmp = DetailsFactorisation.m_orignNumber;
if ( tmp.GetLength() < 20 )
{
sprintf( line, pc_str, tmp.GetBuffer(0) );
}
else
{
CString tmp2 = tmp.Left(9) + "..." + tmp.Right(8);
sprintf( line, pc_str, tmp2.GetBuffer(0) );
}
NewDoc->SetTitle(line);
// Message(STR_LAENGE_STRING_TABLE, MB_ICONINFORMATION);
// flomar, 05/08/2012: when the "details" dialog is closed
// with IDCANCEL, we're closing *this* dialog as well; this
// is for user convenience in the RSA demonstration dialog;
// we might change this approach so the regular execution of
// the factorization dialog (without the RSA demonstration
// dialog on top) is not affected
EndDialog(IDCANCEL);
}
}
void CDlgFactorisationDemo::OnBnClickedLoadNumber()
{
// TODO: Fügen Sie hier Ihren Kontrollbehandlungscode für die Benachrichtigung ein.
//SEQUENCE_OF_Extension *thisextension = NULL;
CFile file;
char *buffer = 0;
CFileException e;
// pop up file selector box
CFileDialog Dlg(TRUE, ".*", NULL, OFN_HIDEREADONLY,"All Files (*.*)|*.*||", this);
if(IDCANCEL == Dlg.DoModal())
{
return;
}
// Get path name to prime number file
CString p_file = Dlg.GetPathName();
try {
// read input file
if(!file.Open(p_file,CFile::modeRead | CFile::typeBinary, &e ))
{
// Unable to open file
Message(IDS_STRING_FILEOPENERROR, MB_ICONEXCLAMATION);
return;
}
ASSERT(file.GetLength() < ULONG_MAX);
unsigned long fileLength = (unsigned long)file.GetLength();
// Create buffer
buffer = (char *) calloc(fileLength + 1,sizeof(char));
if (!buffer)
{
Message(AFX_IDP_FAILED_MEMORY_ALLOC, MB_ICONEXCLAMATION);
return;
}
// load Sourcedata
file.Read(buffer, fileLength);
file.Close();
// Save sourcedata in string and remove whitespaces
CString str = buffer;
str.Remove('\n');
str.Remove(0x0d);
str.Remove(0x20);
free(buffer);
// flomar, 11/09/2011: furthermore, remove all non-digit characters and then check if we
// are below the 8192kbit threshold (or a decimal length of 2467, see IDS_STRING_BIG_NUMBER);
// I don't want to invoke the BigNumber class at this point, as this would be too much of an
// overkill for simply displaying a warning message (which would be displayed by subsequent
// calls later on anyway) a tad earlier just for user convenience
CString strTemp = "";
for(int i=0; i<str.GetLength(); i++) {
char character = str[i];
if(character >= '0' && character <= '9') {
strTemp.AppendChar(character);
}
}
str = strTemp;
if(str.GetLength() > 2467) {
Message(IDS_STRING_BIG_NUMBER, MB_ICONINFORMATION);
str.Truncate(2467);
}
UpdateData(true);
SetDlgItemText(IDC_EDIT1, str);
UpdateData(false);
} catch (CFileException *e)
{
e->Delete();
if (buffer) free(buffer);
return;
}
}
/////////////////////////////////////////////////////////////////////////////
//
//
//
int CDlgFactorisationDemo::GetRSAFactorisation(CString &str_p, CString &str_q)
{
int factorCounter = 0;
NumFactor *ndx = factorList;
if ( !ndx ) return NUMBER_NOT_FACTORISED;
while ( ndx )
{
if ( ndx->exponent > 1 || !ndx->isPrime )
{
return NUMBER_NOT_RSA_MODUL;
}
factorCounter++;
if ( 1 == factorCounter )
{
str_p = ndx->factorStr;
}
else if ( 2 == factorCounter )
{
str_q = ndx->factorStr;
}
else
{
break;
}
ndx = ndx->next;
}
if ( factorCounter == 2 )
{
return NUMBER_RSA_MODUL;
}
else
{
return NUMBER_NOT_RSA_MODUL;
}
}
| [
"florian@marchal.de"
] | florian@marchal.de |
b4cbda9313dac1db53c8907c42f35c798d29fbe1 | 625b56ea2aa30484b875c65bf2fc295c0d95e8cb | /Sources/Stats/py_stats.hpp | 32799f97ed9af7364f41f7d28c63a638f4031d9e | [
"Apache-2.0"
] | permissive | ORNL-QCI/netket | 996c981f2c9e854473c6c7d852e67823d90fce6e | 8974f93cf33d8984fb08aafdfe273b2c99a78059 | refs/heads/master | 2022-01-31T05:29:03.750747 | 2019-07-23T02:20:21 | 2019-07-23T02:20:21 | 197,837,025 | 1 | 0 | Apache-2.0 | 2019-07-19T20:22:29 | 2019-07-19T20:22:28 | null | UTF-8 | C++ | false | false | 1,845 | hpp | #ifndef NETKET_PYSTATS_HPP
#define NETKET_PYSTATS_HPP
#include <pybind11/pybind11.h>
#include "common_types.hpp"
#include "obs_manager.hpp"
namespace py = pybind11;
namespace netket {
namespace detail {
py::dict GetItem(const ObsManager& self, const std::string& name) {
py::dict dict;
self.InsertAllStats(name, dict);
return dict;
}
} // namespace detail
void AddStatsModule(py::module& m) {
auto subm = m.def_submodule("stats");
py::class_<ObsManager>(subm, "ObsManager")
.def("__getitem__", &detail::GetItem, py::arg("name"))
.def("__getattr__", &detail::GetItem, py::arg("name"))
.def("__contains__", &ObsManager::Contains, py::arg("name"))
.def("__len__", &ObsManager::Size)
.def("keys", &ObsManager::Names)
.def("__repr__", [](const ObsManager& self) {
std::string s("<netket.stats.ObsManager: size=");
auto size = self.Size();
s += std::to_string(size);
if(size > 0) {
s += " [";
for (const auto& name : self.Names()) {
s += name + ", ";
}
// remove last comma + space:
s.pop_back();
s.pop_back();
s += "]";
}
return s + ">";
});
}
} // namespace netket
// Expose the Stats object to Python as dict
namespace pybind11 {
namespace detail {
using NkStatsType = netket::Binning<double>::Stats;
template <>
struct type_caster<NkStatsType> {
public:
PYBIND11_TYPE_CASTER(NkStatsType, _("_Stats"));
static handle cast(NkStatsType src, return_value_policy /* policy */,
handle /* parent */) {
py::dict dict;
dict["Mean"] = src.mean;
dict["Sigma"] = src.sigma;
dict["Taucorr"] = src.taucorr;
return dict.release();
}
};
} // namespace detail
} // namespace pybind11
#endif // NETKET_PYSTATS_HPP
| [
"damian.hofmann@mpsd.mpg.de"
] | damian.hofmann@mpsd.mpg.de |
39f8113abd3043a1a3ef7a77b5d87de26999bddf | 63f40225cd0b7cea5391efc717984db0a4017854 | /test-suite/generated-src/cpp/test_duration.hpp | 4ea5bcca894a0caa86cbc9ebf63e75d3be9cbada | [
"Apache-2.0"
] | permissive | Wattpad/djinni | 5d78ee51c629bdecf2b219cb5b958b52eedfa9c2 | 9bdbe6b3523ff0f12b5eab3f9122d8388823b04c | refs/heads/master | 2020-04-06T06:33:52.751727 | 2016-05-30T21:44:18 | 2016-05-30T21:44:18 | 28,932,971 | 7 | 0 | null | 2016-05-30T21:44:18 | 2015-01-07T20:37:38 | C++ | UTF-8 | C++ | false | false | 1,949 | hpp | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from duration.djinni
#pragma once
#include <chrono>
#include <cstdint>
#include <experimental/optional>
#include <string>
class TestDuration {
public:
virtual ~TestDuration() {}
static std::string hoursString(std::chrono::duration<int32_t, std::ratio<3600>> dt);
static std::string minutesString(std::chrono::duration<int32_t, std::ratio<60>> dt);
static std::string secondsString(std::chrono::duration<int32_t, std::ratio<1>> dt);
static std::string millisString(std::chrono::duration<int32_t, std::milli> dt);
static std::string microsString(std::chrono::duration<int32_t, std::micro> dt);
static std::string nanosString(std::chrono::duration<int32_t, std::nano> dt);
static std::chrono::duration<int32_t, std::ratio<3600>> hours(int32_t count);
static std::chrono::duration<int32_t, std::ratio<60>> minutes(int32_t count);
static std::chrono::duration<int32_t, std::ratio<1>> seconds(int32_t count);
static std::chrono::duration<int32_t, std::milli> millis(int32_t count);
static std::chrono::duration<int32_t, std::micro> micros(int32_t count);
static std::chrono::duration<int32_t, std::nano> nanos(int32_t count);
static std::chrono::duration<double, std::ratio<3600>> hoursf(double count);
static std::chrono::duration<double, std::ratio<60>> minutesf(double count);
static std::chrono::duration<double, std::ratio<1>> secondsf(double count);
static std::chrono::duration<double, std::milli> millisf(double count);
static std::chrono::duration<double, std::micro> microsf(double count);
static std::chrono::duration<double, std::nano> nanosf(double count);
static std::experimental::optional<std::chrono::duration<int64_t, std::ratio<1>>> box(int64_t count);
static int64_t unbox(std::experimental::optional<std::chrono::duration<int64_t, std::ratio<1>>> dt);
};
| [
"miro.knejp@gmail.com"
] | miro.knejp@gmail.com |
217fb35b7f6a2baf5e8179a73bb5212112e5c0d8 | 865d7a7f4e69d3f2e19a1107ce3ca82be9c7e04b | /哈夫曼编码/哈夫曼编码.cpp | f9d6b8675e0f257f4b4485c05ebca072501a721f | [] | no_license | qinyingwu/Huffman | 261afedfdb3ee329db75fbaa5f6b913d0047b15e | 715a0801ef20d3a53fc77a13b7711e0a05f3e0bd | refs/heads/master | 2020-07-03T09:29:31.190231 | 2019-08-12T06:00:07 | 2019-08-12T06:00:07 | 201,866,680 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,127 | cpp | // 哈夫曼编码.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include<stdlib.h>
#include <queue>
#include <stack>
#include <string>
#include "stdafx.h"
#include <fstream>
using namespace std;
int fff = 0;
string readFileContent(string str) {
std::ifstream fin(str);
if (!fin.is_open())
{
exit(1);
}
string name;
fin >> name;
fin.close();
return name;
}
struct TNode
{
string c;
double f; //出现的频率
int idx; //线性表中的位置索引号
int parents; //父亲标号
int l_child;
int r_child;
TNode() :parents(-1), l_child(-1), r_child(-1), f(0) {}
};
bool operator>(const TNode &x, const TNode &y)
{
return x.f > y.f;
}
void printCode( int n,TNode *t)
{
int sum222 = 0;
int mt = 0;
double xt = 0;
for (int i = 0; i < n;i++)
{ int sum = 0;
cout << t[i].c<<":";
int idx = t[i].idx;
//idx叶子结点索引号
stack <int> s;
while (t[idx].parents != -1)
{
if (idx == t[t[idx].parents].l_child)
{
s.push(0);
}
else
{
s.push(1);
}
idx = t[idx].parents;
}
while (!s.empty())
{
cout << s.top();
sum++;
s.pop();
}
mt = t[i].f*sum;
cout << endl;
sum222 += mt;
}
cout << "哈夫曼压缩率为:" << (((double)sum222 / (fff* 8))*100) << "%" << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
double f[1000];
string a;
a = readFileContent("test.txt");
char charcode[255];
int numcode[255];
for (int i = 0; i < 255; i++) //ASCII码数目统计数组初始化
{
numcode[i] = 0;
}
int index = 0;
for (unsigned int i = 0; i<a.length(); i++)//取出从文件中读出的字符串中的某个字符
{
bool flag = true;
for (int j = 0; j < sizeof(charcode); j++)//和已经存在字符数组中的字符比较,如果已经存在,个数加一,如果不存在,添加到字符数组中
{
if (charcode[j] == a[i])
{
numcode[j]++;
flag = false;
}
}
if (flag)
{
charcode[index] = a[i];
numcode[index] = 1;
index++;
}
}
for (int i = 0; i < index; i++)//输出检索出来的单个字符及其个数
{
if (i % 6 == 0) {
cout << endl;
cout << charcode[i] << ":" << numcode[i] << "个 ";
}
else {
cout << charcode[i] << ":" << numcode[i] << "个 ";
}
}
cout << endl;
cout <<"以下为哈夫曼编码 "<< endl;
int n = index;
TNode *t = new TNode[2*n - 1];
for (int i = 0; i < n; i++)
{
t[i].c = charcode[i];
t[i].f = numcode[i];
fff += numcode[i];
t[i].parents = -1;
t[i].l_child = -1;
t[i].r_child = -1;
t[i].idx = i;
}
std::priority_queue<TNode, std::vector<TNode>, std::greater<TNode> >PQ;
for (int i=0;i<n;i++)
{
PQ.push(t[i]);
}
int next = n; //下一个要生成的结点
while (!PQ.empty())
{
TNode L = PQ.top();
PQ.pop();
TNode R = PQ.top();
PQ.pop();
TNode &P=t[next];
P.l_child= L.idx;
P.r_child = R.idx;
P.f = L.f + R.f;
P.idx = next;
t[next] = P;
t[L.idx].parents = t[R.idx].parents = next;
PQ.push(P);
next++;
if (next ==(2 * n - 1))
{
break;
}
}
printCode(n,t);
int x;
cin >> x;
return 0;
}
| [
"774405003@qq.com"
] | 774405003@qq.com |
d2befca356e91be991770a9ae41e8eb70735e4ac | 707eb97c810fe49094c9b39c3918af73ea3c92a9 | /fboss/agent/hw/sai/store/SaiStore.h | fb4f0148e12939c0f094fdcdb56f6ff28177474f | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | chmodawk/fboss | e178f27c30223bbac466ff536dc3776ed121bf1b | a9b9c054b59b1435e2b7f6ff50cf675c3e2a0ac1 | refs/heads/master | 2023-03-12T10:53:16.469977 | 2021-03-08T11:35:30 | 2021-03-08T11:37:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,829 | h | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include "fboss/agent/hw/sai/api/AdapterKeySerializers.h"
#include "fboss/agent/hw/sai/api/LoggingUtil.h"
#include "fboss/agent/hw/sai/api/SaiApiTable.h"
#include "fboss/agent/hw/sai/api/SaiObjectApi.h"
#include "fboss/agent/hw/sai/api/Traits.h"
#include "fboss/agent/hw/sai/store/LoggingUtil.h"
#include "fboss/agent/hw/sai/store/SaiObject.h"
#include "fboss/agent/hw/sai/store/SaiObjectWithCounters.h"
#include "fboss/agent/hw/sai/store/Traits.h"
#include "fboss/lib/RefMap.h"
#include <folly/dynamic.h>
#include <memory>
#include <optional>
#include <sstream>
#include <type_traits>
extern "C" {
#include <sai.h>
}
namespace facebook::fboss {
inline constexpr auto kAdapterKey2AdapterHostKey = "adapterKey2AdapterHostKey";
template <>
struct AdapterHostKeyWarmbootRecoverable<SaiNextHopGroupTraits>
: std::false_type {};
template <>
struct AdapterHostKeyWarmbootRecoverable<SaiLagTraits> : std::false_type {};
/*
* SaiObjectStore is the critical component of SaiStore,
* it provides the needed operations on a single type of SaiObject
* e.g. Port, Vlan, Route, etc... SaiStore is largely just a collection
* of the SaiObjectStores.
*/
template <typename SaiObjectTraits>
class SaiObjectStore {
public:
using ObjectType = typename std::conditional<
SaiObjectHasStats<SaiObjectTraits>::value,
SaiObjectWithCounters<SaiObjectTraits>,
SaiObject<SaiObjectTraits>>::type;
using ObjectTraits = SaiObjectTraits;
explicit SaiObjectStore(sai_object_id_t switchId) : switchId_(switchId) {}
SaiObjectStore() {}
~SaiObjectStore() {
for (auto iter : warmBootHandles_) {
iter.second->release();
}
}
void setSwitchId(sai_object_id_t switchId) {
switchId_ = switchId;
}
static folly::StringPiece objectTypeName() {
return saiObjectTypeToString(SaiObjectTraits::ObjectType);
}
/*
* This routine will help load sai objects owned by the SAI Adapter.
* For instance, sai queue objects are owned by the adapter and will not be
* loaded during the initial reload. When a port is created, the queues will
* be created by the SDK and the adapter keys for the queue can be retrieved.
* Using the adapter key, the sai store can be populated with its attributes.
*/
std::shared_ptr<ObjectType> loadObjectOwnedByAdapter(
const typename SaiObjectTraits::AdapterKey& adapterKey) {
static_assert(
IsSaiObjectOwnedByAdapter<SaiObjectTraits>::value,
"Only adapter owned SAI objects can be loaded");
return reloadObject(adapterKey);
}
std::shared_ptr<ObjectType> reloadObject(
const typename SaiObjectTraits::AdapterKey& adapterKey) {
ObjectType temporary(adapterKey);
auto adapterHostKey = temporary.adapterHostKey();
auto obj = objects_.ref(adapterHostKey);
if (!obj) {
auto ins =
objects_.refOrInsert(adapterHostKey, std::move(temporary), true);
obj = ins.first;
} else {
// destroy temporary without removing underlying sai object
temporary.release();
}
auto iter = warmBootHandles_.find(adapterHostKey);
if (iter != warmBootHandles_.end()) {
// Adapter keys are discovered by sai store in two ways
// 1. by calling get object keys api which is possible in cold and warm
// boot.
// 2. by looking into saved hw switch state, only possible in warm boot
//
// For objects owned by adapter keys, first is possible ONLY if adapter
// supports get object keys api for a given object type. Unfortunately,
// not all adapters may support get object keys api for all objects. For
// such adapters, warmboot handles may not have this key during cold boot.
// For adapters which support get object keys api, warm boot handles will
// always have this object.
warmBootHandles_.erase(iter);
}
return obj;
}
void reload(
const folly::dynamic* adapterKeysJson,
const folly::dynamic* adapterKeys2AdapterHostKey) {
if (!switchId_) {
XLOG(FATAL)
<< "Attempted to reload() on a SaiObjectStore without a switchId";
}
auto keys = getAdapterKeys(adapterKeysJson);
if constexpr (SaiObjectHasConditionalAttributes<SaiObjectTraits>::value) {
keys.erase(
std::remove_if(
keys.begin(),
keys.end(),
[](auto key) {
auto conditionAttributes =
SaiApiTable::getInstance()
->getApi<typename SaiObjectTraits::SaiApiT>()
.getAttribute(
key,
typename SaiObjectTraits::ConditionAttributes{});
return conditionAttributes !=
SaiObjectTraits::kConditionAttributes;
}),
keys.end());
}
for (const auto k : keys) {
ObjectType obj = getObject(k, adapterKeys2AdapterHostKey);
auto adapterHostKey = obj.adapterHostKey();
XLOGF(DBG5, "SaiStore reloaded {}", obj);
auto ins = objects_.refOrInsert(adapterHostKey, std::move(obj));
if (!ins.second) {
XLOG(FATAL) << "[" << saiObjectTypeToString(SaiObjectTraits::ObjectType)
<< "]"
<< " Unexpected duplicate adapterHostKey";
}
warmBootHandles_.emplace(adapterHostKey, ins.first);
}
}
std::shared_ptr<ObjectType> setObject(
const typename SaiObjectTraits::AdapterHostKey& adapterHostKey,
const typename SaiObjectTraits::CreateAttributes& attributes,
bool notify = true) {
if constexpr (IsObjectPublisher<SaiObjectTraits>::value) {
static_assert(
!IsPublisherKeyCustomType<SaiObjectTraits>::value,
"method not available for objects with publisher attributes of custom types");
}
XLOGF(
DBG5,
"SaiStore setting {} object {}",
objectTypeName(),
adapterHostKey);
auto [object, programmed] = program(adapterHostKey, attributes);
if (notify && programmed) {
if constexpr (IsObjectPublisher<SaiObjectTraits>::value) {
object->notifyAfterCreate(object);
}
}
XLOGF(DBG5, "SaiStore set object {}", *object);
return object;
}
std::shared_ptr<ObjectType> setObject(
const typename SaiObjectTraits::AdapterHostKey& adapterHostKey,
const typename SaiObjectTraits::CreateAttributes& attributes,
const typename PublisherKey<SaiObjectTraits>::custom_type& publisherKey,
bool notify = true) {
static_assert(
IsPublisherKeyCustomType<SaiObjectTraits>::value,
"method available only for objects with publisher attributes of custom types");
XLOGF(
DBG5,
"SaiStore setting {} object {}",
objectTypeName(),
adapterHostKey);
auto [object, programmed] = program(adapterHostKey, attributes);
if (notify && programmed) {
if constexpr (IsObjectPublisher<SaiObjectTraits>::value) {
object->setCustomPublisherKey(publisherKey);
object->notifyAfterCreate(object);
}
}
XLOGF(DBG5, "SaiStore set object {}", *object);
return object;
}
std::shared_ptr<ObjectType> get(
const typename SaiObjectTraits::AdapterHostKey& adapterHostKey) {
XLOGF(DBG5, "SaiStore get object {}", adapterHostKey);
auto itr = warmBootHandles_.find(adapterHostKey);
if (itr != warmBootHandles_.end()) {
return itr->second;
}
return objects_.ref(adapterHostKey);
}
std::shared_ptr<ObjectType> find(
const typename SaiObjectTraits::AdapterKey& adapterKey) {
XLOGF(DBG5, "SaiStore find object {}", adapterKey);
for (auto iter : warmBootHandles_) {
if (iter.second->adapterKey() == adapterKey) {
return iter.second;
}
}
for (auto iter : objects_) {
auto obj = iter.second.lock();
if (obj->adapterKey() == adapterKey) {
return obj;
}
}
return nullptr;
}
void release() {
objects_.clear();
}
folly::dynamic adapterKeysFollyDynamic() const {
folly::dynamic adapterKeys = folly::dynamic::array;
for (const auto& hostKeyAndObj : objects_) {
auto obj = hostKeyAndObj.second.lock();
if (!obj->live()) {
continue;
}
adapterKeys.push_back(toFollyDynamic<SaiObjectTraits>(obj->adapterKey()));
}
return adapterKeys;
}
static std::vector<typename SaiObjectTraits::AdapterKey>
adapterKeysFromFollyDynamic(const folly::dynamic& json) {
std::vector<typename SaiObjectTraits::AdapterKey> adapterKeys;
for (const auto& obj : json) {
adapterKeys.push_back(fromFollyDynamic<SaiObjectTraits>(obj));
}
return adapterKeys;
}
void exitForWarmBoot() {
for (auto itr : objects_) {
if (auto object = itr.second.lock()) {
object->release();
}
}
objects_.clear();
}
const UnorderedRefMap<typename SaiObjectTraits::AdapterHostKey, ObjectType>&
objects() const {
return objects_;
}
uint64_t size() const {
return objects_.size();
}
typename UnorderedRefMap<
typename SaiObjectTraits::AdapterHostKey,
ObjectType>::MapType::const_iterator
begin() const {
return objects_.begin();
}
typename UnorderedRefMap<
typename SaiObjectTraits::AdapterHostKey,
ObjectType>::MapType::const_iterator
end() const {
return objects_.end();
}
void setObjectOwnedByAdapter(bool objectOwnedByAdapter) {
objectOwnedByAdapter_ = objectOwnedByAdapter;
}
bool isObjectOwnedByAdapter() const {
return objectOwnedByAdapter_;
}
size_t warmBootHandlesCount() const {
return warmBootHandles_.size();
}
bool hasUnexpectedUnclaimedWarmbootHandles() const {
bool unclaimedHandles = warmBootHandlesCount() > 0 &&
!(IsSaiObjectOwnedByAdapter<SaiObjectTraits>::value ||
isObjectOwnedByAdapter());
XLOGF(
DBG1,
"unexpected warmboot handles {} entries: {}",
objectTypeName(),
unclaimedHandles);
return unclaimedHandles;
}
void printWarmBootHandles() const {
if (warmBootHandlesCount()) {
XLOGF(DBG1, "unclaimed {} entries", objectTypeName());
}
for (auto iter : warmBootHandles_) {
XLOGF(DBG1, "{}", *iter.second);
}
}
void removeUnexpectedUnclaimedWarmbootHandles() {
if (!hasUnexpectedUnclaimedWarmbootHandles()) {
return;
}
// remove unclaimed objects
warmBootHandles_.clear();
}
private:
template <
typename T = SaiObjectTraits,
typename = std::enable_if_t<std::is_same_v<T, SaiLagTraits>>>
ObjectType getObject(
typename T::AdapterKey key,
const folly::dynamic* adapterKey2AdapterHostKey) {
static_assert(
!AdapterHostKeyWarmbootRecoverable<SaiObjectTraits>::value, "LAG!");
auto ahk = getAdapterHostKey(key, adapterKey2AdapterHostKey);
if (ahk) {
return ObjectType(key, ahk.value());
}
auto label = SaiApiTable::getInstance()->lagApi().getAttribute(
key, SaiLagTraits::Attributes::Label{});
return ObjectType(key, label);
}
template <
typename T = SaiObjectTraits,
typename = std::enable_if_t<!std::is_same_v<T, SaiLagTraits>>>
ObjectType getObject(
typename SaiObjectTraits::AdapterKey key,
const folly::dynamic* adapterKey2AdapterHostKey) {
if constexpr (!AdapterHostKeyWarmbootRecoverable<SaiObjectTraits>::value) {
if (auto ahk = getAdapterHostKey(key, adapterKey2AdapterHostKey)) {
return ObjectType(key, ahk.value());
}
// API tests program using API and reload without json
// such cases has null adapterKeys2AdapterHostKey json
}
return ObjectType(key);
}
std::pair<std::shared_ptr<ObjectType>, bool> program(
const typename SaiObjectTraits::AdapterHostKey& adapterHostKey,
const typename SaiObjectTraits::CreateAttributes& attributes) {
auto existingObj = objects_.ref(adapterHostKey);
auto ins = existingObj
? std::make_pair(existingObj, false)
: objects_.refOrInsert(
adapterHostKey,
ObjectType(adapterHostKey, attributes, switchId_.value()),
true /*force*/);
if (!ins.second) {
ins.first->setAttributes(attributes);
}
auto notify = ins.second;
auto iter = warmBootHandles_.find(adapterHostKey);
if (iter != warmBootHandles_.end()) {
warmBootHandles_.erase(iter);
notify = true;
}
return std::make_pair(ins.first, notify);
}
std::vector<typename SaiObjectTraits::AdapterKey> getAdapterKeys(
const folly::dynamic* adapterKeysJson) const {
return adapterKeysJson ? adapterKeysFromFollyDynamic(*adapterKeysJson)
: getObjectKeys<SaiObjectTraits>(switchId_.value());
}
std::optional<typename SaiObjectTraits::AdapterHostKey> getAdapterHostKey(
const typename SaiObjectTraits::AdapterKey& key,
const folly::dynamic* adapterKeys2AdapterHostKey) {
if (!adapterKeys2AdapterHostKey) {
return std::nullopt;
}
auto iter = adapterKeys2AdapterHostKey->find(folly::to<std::string>(key));
CHECK(iter != adapterKeys2AdapterHostKey->items().end());
return SaiObject<SaiObjectTraits>::follyDynamicToAdapterHostKey(
iter->second);
}
std::optional<sai_object_id_t> switchId_;
bool objectOwnedByAdapter_{false};
UnorderedRefMap<typename SaiObjectTraits::AdapterHostKey, ObjectType>
objects_;
std::unordered_map<
typename SaiObjectTraits::AdapterHostKey,
std::shared_ptr<ObjectType>>
warmBootHandles_;
};
/*
* Specialize SaiSwitchObj to allow for stand alone construction
* since we don't create a object store for SaiSwitchObj
*/
class SaiSwitchObj : public SaiObject<SaiSwitchTraits> {
public:
template <typename... Args>
SaiSwitchObj(Args&&... args)
: SaiObject<SaiSwitchTraits>(std::forward<Args>(args)...) {}
};
/*
* SaiStore represents FBOSS's knowledge of objects and their attributes
* that have been programmed via SAI.
*
*/
class SaiStore {
public:
// Static function for getting the SaiStore folly::Singleton
static std::shared_ptr<SaiStore> getInstance();
SaiStore();
explicit SaiStore(sai_object_id_t switchId);
/*
* Set the switch id on all the SaiObjectStores
* Useful for the singleton mode of operation, which is constructed
* with the default constructor, then after the switch_id is ready, that
* is set on the SaiStore
*/
void setSwitchId(sai_object_id_t switchId);
/*
* Reload the SaiStore from the current SAI state via SAI api calls.
*/
void reload(
const folly::dynamic* adapterKeys = nullptr,
const folly::dynamic* adapterKeys2AdapterHostKey = nullptr);
/*
*
*/
void release();
template <typename SaiObjectTraits>
SaiObjectStore<SaiObjectTraits>& get() {
return std::get<SaiObjectStore<SaiObjectTraits>>(stores_);
}
template <typename SaiObjectTraits>
const SaiObjectStore<SaiObjectTraits>& get() const {
return std::get<SaiObjectStore<SaiObjectTraits>>(stores_);
}
std::string storeStr(sai_object_type_t objType) const;
folly::dynamic adapterKeysFollyDynamic() const;
void exitForWarmBoot();
folly::dynamic adapterKeys2AdapterHostKeysFollyDynamic() const;
void checkUnexpectedUnclaimedWarmbootHandles() const;
void removeUnexpectedUnclaimedWarmbootHandles();
void printWarmbootHandles() const;
private:
sai_object_id_t switchId_{};
std::tuple<
SaiObjectStore<SaiAclTableGroupTraits>,
SaiObjectStore<SaiAclTableGroupMemberTraits>,
SaiObjectStore<SaiAclTableTraits>,
SaiObjectStore<SaiAclEntryTraits>,
SaiObjectStore<SaiAclCounterTraits>,
SaiObjectStore<SaiBridgeTraits>,
SaiObjectStore<SaiBridgePortTraits>,
SaiObjectStore<SaiBufferPoolTraits>,
SaiObjectStore<SaiBufferProfileTraits>,
SaiObjectStore<SaiDebugCounterTraits>,
SaiObjectStore<SaiPortTraits>,
SaiObjectStore<SaiVlanTraits>,
SaiObjectStore<SaiVlanMemberTraits>,
SaiObjectStore<SaiRouteTraits>,
SaiObjectStore<SaiRouterInterfaceTraits>,
SaiObjectStore<SaiFdbTraits>,
SaiObjectStore<SaiVirtualRouterTraits>,
SaiObjectStore<SaiNextHopGroupMemberTraits>,
SaiObjectStore<SaiNextHopGroupTraits>,
SaiObjectStore<SaiIpNextHopTraits>,
SaiObjectStore<SaiLocalMirrorTraits>,
SaiObjectStore<SaiEnhancedRemoteMirrorTraits>,
#if SAI_API_VERSION >= SAI_VERSION(1, 7, 0)
SaiObjectStore<SaiSflowMirrorTraits>,
#endif
SaiObjectStore<SaiMplsNextHopTraits>,
SaiObjectStore<SaiNeighborTraits>,
SaiObjectStore<SaiHostifTrapGroupTraits>,
SaiObjectStore<SaiHostifTrapTraits>,
SaiObjectStore<SaiQueueTraits>,
SaiObjectStore<SaiSchedulerTraits>,
SaiObjectStore<SaiSamplePacketTraits>,
SaiObjectStore<SaiHashTraits>,
SaiObjectStore<SaiInSegTraits>,
SaiObjectStore<SaiQosMapTraits>,
SaiObjectStore<SaiPortSerdesTraits>,
SaiObjectStore<SaiWredTraits>,
SaiObjectStore<SaiTamReportTraits>,
SaiObjectStore<SaiTamEventActionTraits>,
SaiObjectStore<SaiTamEventTraits>,
SaiObjectStore<SaiTamTraits>,
SaiObjectStore<SaiLagTraits>,
SaiObjectStore<SaiLagMemberTraits>>
stores_;
};
template <typename SaiObjectTraits>
std::vector<typename SaiObjectTraits::AdapterKey>
keysForSaiObjStoreFromStoreJson(const folly::dynamic& json) {
return SaiObjectStore<SaiObjectTraits>::adapterKeysFromFollyDynamic(
json[saiObjectTypeToString(SaiObjectTraits::ObjectType)]);
}
} // namespace facebook::fboss
namespace fmt {
template <typename SaiObjectTraits>
struct formatter<facebook::fboss::SaiObjectStore<SaiObjectTraits>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(
const facebook::fboss::SaiObjectStore<SaiObjectTraits>& store,
FormatContext& ctx) {
std::stringstream ss;
ss << "Object type: "
<< facebook::fboss::saiObjectTypeToString(SaiObjectTraits::ObjectType)
<< std::endl;
const auto& objs = store.objects();
for (const auto& [key, object] : objs) {
std::ignore = key;
ss << fmt::format("{}", *object.lock()) << std::endl;
}
return format_to(ctx.out(), "{}", ss.str());
}
};
template <typename T, typename Char>
struct is_range<facebook::fboss::SaiObjectStore<T>, Char> : std::false_type {};
} // namespace fmt
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
c7ce7232bbfe16a2d360a4e5d84a164673f22210 | a09400aa22a27c7859030ec470b5ddee93e0fdf0 | /stalkersoc/source/control_run_attack.cpp | e4808af10277491d23581512be5215bc655b88fb | [] | no_license | BearIvan/Stalker | 4f1af7a9d6fc5ed1597ff13bd4a34382e7fdaab1 | c0008c5103049ce356793b37a9d5890a996eed23 | refs/heads/master | 2022-04-04T02:07:11.747666 | 2020-02-16T10:51:57 | 2020-02-16T10:51:57 | 160,668,112 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,503 | cpp | #include "StdAfx.h"
#include "ai/monsters/control_run_attack.h"
#include "ai/monsters/BaseMonster/base_monster.h"
#include "ai/monsters/monster_velocity_space.h"
#include "ai/monsters/control_animation_base.h"
#include "ai/monsters/control_direction_base.h"
#include "ai/monsters/control_movement_base.h"
void CControlRunAttack::load(LPCSTR section)
{
read_distance (section,"Run_Attack_Dist", m_min_dist, m_max_dist);
read_delay (section,"Run_Attack_Delay", m_min_delay, m_max_delay);
}
void CControlRunAttack::reinit()
{
CControl_ComCustom<>::reinit();
m_time_next_attack = 0;
}
void CControlRunAttack::activate()
{
m_man->capture_pure (this);
m_man->subscribe (this, ControlCom::eventAnimationEnd);
m_man->subscribe (this, ControlCom::eventAnimationStart);
m_man->path_stop (this);
m_man->move_stop (this);
//////////////////////////////////////////////////////////////////////////
SControlDirectionData *ctrl_dir = (SControlDirectionData*)m_man->data(this, ControlCom::eControlDir);
VERIFY (ctrl_dir);
ctrl_dir->heading.target_speed = 3.f;
ctrl_dir->heading.target_angle = m_man->direction().angle_to_target(m_object->EnemyMan.get_enemy()->Position());
//////////////////////////////////////////////////////////////////////////
SControlAnimationData *ctrl_anim = (SControlAnimationData*)m_man->data(this, ControlCom::eControlAnimation);
VERIFY (ctrl_anim);
ctrl_anim->global.motion = smart_cast<IKinematicsAnimated*>(m_object->Visual())->ID_Cycle_Safe("stand_attack_run_0");
ctrl_anim->global.actual = false;
}
void CControlRunAttack::on_release()
{
m_man->unlock (this, ControlCom::eControlPath);
m_man->release_pure (this);
m_man->unsubscribe (this, ControlCom::eventAnimationEnd);
m_man->unsubscribe (this, ControlCom::eventAnimationStart);
}
bool CControlRunAttack::check_start_conditions()
{
if (is_active()) return false;
if (m_man->is_captured_pure()) return false;
const CEntityAlive *enemy = m_object->EnemyMan.get_enemy();
if (!enemy) return false;
// check if faced enemy
if (!m_man->direction().is_face_target(enemy, XrMath::PI_DIV_6)) return false;
float dist = enemy->Position().distance_to(m_object->Position());
// check distance to enemy
if ((dist > m_max_dist) || (dist < m_min_dist)) return false;
// check if run state, speed
SVelocityParam &velocity_run = m_object->move().get_velocity(MonsterMovement::eVelocityParameterRunNormal);
if (!XrMath::fsimilar(m_man->movement().velocity_current(), velocity_run.velocity.linear, 2.f)) return false;
if (m_time_next_attack > time()) return false;
return true;
}
void CControlRunAttack::on_event(ControlCom::EEventType type, ControlCom::IEventData *dat)
{
switch (type) {
case ControlCom::eventAnimationEnd:
m_time_next_attack = time() + Random.randI(m_min_delay,m_max_delay);
m_man->notify (ControlCom::eventRunAttackEnd, 0);
break;
case ControlCom::eventAnimationStart: // handle blend params
{
// set animation speed
SControlAnimationData *ctrl_data_anim = (SControlAnimationData*)m_man->data(this, ControlCom::eControlAnimation);
VERIFY (ctrl_data_anim);
CBlend *blend = m_man->animation().current_blend();
VERIFY (blend);
// animation time
float anim_time = blend->timeTotal / blend->speed;
// run velocity
u32 velocity_mask = MonsterMovement::eVelocityParameterRunNormal;
SVelocityParam &velocity = m_object->move().get_velocity(velocity_mask);
// distance
float path_dist = anim_time * velocity.velocity.linear;
Fvector dir;
dir.sub (m_object->EnemyMan.get_enemy()->Position(), m_object->Position());
dir.normalize_safe ();
Fvector target_position;
target_position.mad (m_object->Position(), dir, path_dist);
if (!m_man->build_path_line (this, target_position, u32(-1), velocity_mask | MonsterMovement::eVelocityParameterStand)) {
m_man->notify (ControlCom::eventRunAttackEnd, 0);
} else {
// enable path
SControlPathBuilderData *ctrl_path = (SControlPathBuilderData*)m_man->data(this, ControlCom::eControlPath);
VERIFY (ctrl_path);
ctrl_path->enable = true;
m_man->lock (this, ControlCom::eControlPath);
SControlMovementData *ctrl_move = (SControlMovementData*)m_man->data(this, ControlCom::eControlMovement);
VERIFY (ctrl_move);
ctrl_move->velocity_target = velocity.velocity.linear;
ctrl_move->acc = flt_max;
}
}
break;
}
}
| [
"i-sobolevskiy@mail.ru"
] | i-sobolevskiy@mail.ru |
752860344eaee86ca519a859f5caa132aff6f87c | aa903ef99df7b688e2639f304550bb96a57ea7af | /Day6_IntermediateCPP/Project1/String.cpp | ac37e8f957508e00c5aecdf79f07eaa0fedec43b | [] | no_license | Ashish-Surve/Learn_C-CPP | f4a4f98b33d775362beebb4aeb91b7407124e18c | 9e7cd7239a96d7af70b10f5b3d19dac58a8ce7d5 | refs/heads/master | 2020-12-13T20:00:10.478308 | 2020-02-13T12:17:35 | 2020-02-13T12:17:35 | 234,510,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | cpp | #include"String.h"
#include<iostream>
using namespace std;
String::String(const char * c)
{
cout << "inside String parameterised" << endl;
Len = strlen(c);
Name = new char[Len + 1];
strcpy_s(Name, Len + 1, c);
}
String::String()
{
cout << "inside String default" << endl;
Len = 0;
Name = new char[1];
*Name = '\0';
}
String::~String()
{
cout << "inside String dtor" << endl;
if (Name != nullptr)
delete[]Name;
Name = nullptr;
}
void String::operator=(const String &s)
{
cout << "inside String overloaded =" << endl;
if (this == nullptr)
return;
else
{
if (Name != nullptr)
delete[]Name;
Len = s.Len;
Name = new char[Len + 1];
strcpy_s(Name, Len + 1, s.Name);
}
}
String::String(const String &s)
{
cout << "String Copy Constructor" << endl;
this->Len = s.Len;
this->Name = new char[s.Len + 1];
strcpy_s(this->Name, s.Len + 1, s.Name);
}
void String::Display()const
{
cout << "inside String display" << endl;
if (Name == nullptr)
return;
cout << Name << endl;
} | [
"ashish.surve@outlook.in"
] | ashish.surve@outlook.in |
ff7ac10c40d066e0c16d55faaf308f14b834d0dd | 0f52b2074afa3f1a99942ad5473da3786bf4f4cf | /lab2/timeit.cpp | f54ea72f9be1c3d2aae18946d2ce23564ed1eb1d | [] | no_license | pokachopotun/msu_m118_ivanov | 350a5f9000565a1b3739b6ffcd4ec7c68150cf78 | 2a58e006c174f59b94e2b4582943ebf3adc4a9bd | refs/heads/master | 2022-12-12T22:44:13.440398 | 2020-09-04T10:08:07 | 2020-09-04T10:08:07 | 149,507,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | cpp | #include <papi.h>
#include <iostream>
#include <memory>
#include <testsized.h>
#include <chrono>
using namespace std;
typedef std::chrono::high_resolution_clock Clock;
const int numEvents = 1;
const int reps = 1;
void timeit(int mSize, int bSize, const string& mode){
double worktime = 0;
for(int i=0 ;i < reps; i++){
unique_ptr< TestSized > a( new TestSized(mSize) );
// a->Print();
auto t1 = Clock::now();
a->Multiply(bSize, mode);
auto t2 = Clock::now();
double s = std::chrono::duration_cast<chrono::milliseconds>(t2 - t1).count();
worktime += s;
}
// printf("Size %d Block %d Mode %s Time %6.1f ms\n", mSize, bSize, mode.c_str(), time);
printf("Size %d Block %d Mode %s Time %6.1f ms\n", mSize, bSize, mode.c_str(), worktime);
}
int main(int argc, char * argv[]) {
if(argc < 4){
cout << "use ./timeit mSize bSize ijk" << endl;
return 0;
}
const int mSize = atoi(argv[1]);
const int bSize = atoi(argv[2]);
const string mode(argv[3]);
timeit(mSize, bSize, mode);
return 0;
}
| [
"mr.salixnew@gmail.com"
] | mr.salixnew@gmail.com |
852380c69990d02376f8afb85a852ebc807dac44 | a18898bce8afba8ff6107413745239c447ee55b5 | /04/ex03/IMateriaSource.hpp | 75ce52cfd412c4ba07523e88b040aa90f9459364 | [] | no_license | nesvoboda/piscine_cpp | 7d19b6783b51787fbc4f5085fb71a6ae407f93f0 | 854cb7062b175c6631147a95a954de8cfe0bdeeb | refs/heads/master | 2022-12-30T21:25:06.599826 | 2020-10-20T10:42:42 | 2020-10-20T10:42:42 | 286,800,642 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,193 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* IMateriaSource.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ashishae <ashishae@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/06 10:58:35 by ashishae #+# #+# */
/* Updated: 2020/09/06 12:03:49 by ashishae ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef IMATERIASOURCE_HPP
# define IMATERIASOURCE_HPP
# include <iostream>
# include <string>
# include "AMateria.hpp"
class IMateriaSource
{
public:
virtual ~IMateriaSource() {}
virtual void learnMateria(AMateria*) = 0;
virtual AMateria* createMateria(std::string const & type) = 0;
};
#endif | [
"ashishae@student.42.fr"
] | ashishae@student.42.fr |
3621fa8e950d50a8adcad8c32e052778a79e8413 | 8501c150e044c0d9fa72be9f2d583f8ca4188b69 | /libs/common/delay.hpp | 1a4fd75ebb238bac99e277c4b150efdb407be49b | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | utsavjnn/iroha | 7234fc88eacff8a3e265928fe2eff0c8c629eda0 | 072bf4d0fb0fc505feb4b102944c6bd89830a50c | refs/heads/master | 2022-12-06T19:49:54.911117 | 2020-07-09T18:40:20 | 2020-07-10T19:22:03 | 278,109,080 | 4 | 0 | Apache-2.0 | 2020-07-08T14:18:44 | 2020-07-08T14:18:43 | null | UTF-8 | C++ | false | false | 6,853 | hpp | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_DELAY_HPP
#define IROHA_DELAY_HPP
#include <rxcpp/operators/rx-delay.hpp>
namespace iroha {
/**
* This class is mostly the same as rxcpp::operators::delay,
* the only change is that it accepts a selector lambda which generates
* a duration based on observable value instead of a fixed duration
* Return an observable that emits each item emitted by the source observable
* after the specified delay
* Delay is generated with selector from the last received value
* @tparam T value type
* @tparam Selector the type of the transforming function
* which returns time interval
* @tparam Coordination the type of the scheduler
*/
template <class T, class Selector, class Coordination>
struct delay {
typedef rxcpp::util::decay_t<T> source_value_type;
typedef rxcpp::util::decay_t<Coordination> coordination_type;
typedef typename coordination_type::coordinator_type coordinator_type;
typedef rxcpp::util::decay_t<Selector> select_type;
struct delay_values {
delay_values(select_type s, coordination_type c)
: selector(std::move(s)), coordination(c) {}
select_type selector;
coordination_type coordination;
};
delay_values initial;
delay(select_type s, coordination_type coordination)
: initial(std::move(s), coordination) {}
template <class Subscriber>
struct delay_observer {
typedef delay_observer<Subscriber> this_type;
typedef rxcpp::util::decay_t<T> value_type;
typedef rxcpp::util::decay_t<Subscriber> dest_type;
typedef rxcpp::observer<T, this_type> observer_type;
struct delay_subscriber_values : public delay_values {
delay_subscriber_values(rxcpp::composite_subscription cs,
dest_type d,
delay_values v,
coordinator_type c)
: delay_values(v),
cs(std::move(cs)),
dest(std::move(d)),
coordinator(std::move(c)),
worker(coordinator.get_worker()),
expected(worker.now()) {}
rxcpp::composite_subscription cs;
dest_type dest;
coordinator_type coordinator;
rxcpp::schedulers::worker worker;
rxcpp::schedulers::scheduler::clock_type::time_point expected;
};
std::shared_ptr<delay_subscriber_values> state;
delay_observer(rxcpp::composite_subscription cs,
dest_type d,
delay_values v,
coordinator_type c)
: state(std::make_shared<delay_subscriber_values>(
delay_subscriber_values(
std::move(cs), std::move(d), v, std::move(c)))) {
auto localState = state;
auto disposer = [=](const rxcpp::schedulers::schedulable &) {
localState->cs.unsubscribe();
localState->dest.unsubscribe();
localState->worker.unsubscribe();
};
auto selectedDisposer = on_exception(
[&]() { return localState->coordinator.act(disposer); },
localState->dest);
if (selectedDisposer.empty()) {
return;
}
localState->dest.add(
[=]() { localState->worker.schedule(selectedDisposer.get()); });
localState->cs.add(
[=]() { localState->worker.schedule(selectedDisposer.get()); });
}
template <class Value>
void on_next(Value &&v) const {
auto localState = state;
auto selected = on_exception(
[&]() { return localState->selector(std::forward<Value>(v)); },
localState->dest);
if (selected.empty()) {
return;
}
auto work = [v, localState](const rxcpp::schedulers::schedulable &) {
localState->dest.on_next(v);
};
auto selectedWork =
on_exception([&]() { return localState->coordinator.act(work); },
localState->dest);
if (selectedWork.empty()) {
return;
}
localState->worker.schedule(localState->worker.now() + selected.get(),
selectedWork.get());
}
void on_error(std::exception_ptr e) const {
auto localState = state;
auto work = [e, localState](const rxcpp::schedulers::schedulable &) {
localState->dest.on_error(e);
};
auto selectedWork =
on_exception([&]() { return localState->coordinator.act(work); },
localState->dest);
if (selectedWork.empty()) {
return;
}
localState->worker.schedule(selectedWork.get());
}
void on_completed() const {
auto localState = state;
auto work = [localState](const rxcpp::schedulers::schedulable &) {
localState->dest.on_completed();
};
auto selectedWork =
on_exception([&]() { return localState->coordinator.act(work); },
localState->dest);
if (selectedWork.empty()) {
return;
}
localState->worker.schedule(selectedWork.get());
}
static rxcpp::subscriber<T, observer_type> make(dest_type d,
delay_values v) {
auto cs = rxcpp::composite_subscription();
auto coordinator = v.coordination.create_coordinator();
return rxcpp::make_subscriber<T>(
cs,
observer_type(this_type(
cs, std::move(d), std::move(v), std::move(coordinator))));
}
};
template <class Subscriber>
auto operator()(Subscriber dest) const
-> decltype(delay_observer<Subscriber>::make(std::move(dest),
initial)) {
return delay_observer<Subscriber>::make(std::move(dest), initial);
}
};
template <typename T,
typename Selector,
typename Coordination,
class ResolvedSelector = rxcpp::util::decay_t<Selector>,
class Duration = decltype(std::declval<ResolvedSelector>()(
(std::declval<std::decay_t<T>>()))),
class Enabled = rxcpp::util::enable_if_all_true_type_t<
rxcpp::is_coordination<Coordination>,
rxcpp::util::is_duration<Duration>>,
class Delay =
delay<T, ResolvedSelector, rxcpp::util::decay_t<Coordination>>>
static auto makeDelay(Selector &&s, Coordination &&cn) {
return Delay(std::forward<Selector>(s), std::forward<Coordination>(cn));
}
} // namespace iroha
#endif // IROHA_DELAY_HPP
| [
"andrei@soramitsu.co.jp"
] | andrei@soramitsu.co.jp |
cf0ad796dd2f30bd540b99da475364647bfad7b2 | db96b049c8e27f723fcb2f3a99291e631f1a1801 | /src/algo/sequence/unit_test/unit_test_align_cleanup.cpp | 8a982d117fc74de00e311446c70bd0cd43c0a97e | [] | no_license | Watch-Later/ncbi-cxx-toolkit-public | 1c3a2502b21c7c5cee2c20c39e37861351bd2c05 | 39eede0aea59742ca4d346a6411b709a8566b269 | refs/heads/master | 2023-08-15T14:54:41.973806 | 2021-10-04T04:03:02 | 2021-10-04T04:03:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,828 | cpp | /* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Vyacheslav Chetvernin
*
* File Description:
*
* ===========================================================================
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbiapp.hpp>
// #include <corelib/ncbiargs.hpp>
// #include <corelib/ncbienv.hpp>
#include <corelib/test_boost.hpp>
#include <objmgr/object_manager.hpp>
#include <objtools/data_loaders/genbank/gbloader.hpp>
// #include <objmgr/scope.hpp>
#include <serial/serial.hpp>
#include <serial/objistr.hpp>
#include <serial/objostr.hpp>
#include <algo/sequence/align_cleanup.hpp>
USING_NCBI_SCOPE;
USING_SCOPE(objects);
NCBITEST_INIT_CMDLINE(arg_desc)
{
// Here we make descriptions of command line parameters that we are
// going to use.
}
NCBITEST_AUTO_INIT()
{
CRef<CObjectManager> om = CObjectManager::GetInstance();
CGBDataLoader::RegisterInObjectManager(*om);
}
void check_no_overlaps(CAlignCleanup::TAligns& cleaned_aligns)
{
vector<CRef<CSeq_loc> > combined_row(2);
combined_row[0].Reset(new CSeq_loc);
combined_row[1].Reset(new CSeq_loc);
ITERATE (CAlignCleanup::TAligns, align, cleaned_aligns) {
cerr << MSerial_AsnText << **align;
for (int row = 0; row < 2; ++row) {
CRef<CSeq_loc> seq_loc = (*align)->CreateRowSeq_loc(row);
CRef<CSeq_loc> intersection = combined_row[row]->Intersect(*seq_loc, CSeq_loc::fStrand_Ignore, NULL);
// cerr << MSerial_AsnText << *seq_loc;
BOOST_CHECK(intersection->GetTotalRange().GetLength()==0);
combined_row[row]->Add(*seq_loc);
}
}
}
BOOST_AUTO_TEST_CASE(Test1)
{
CRef<CObjectManager> om = CObjectManager::GetInstance();
CScope scope(*om);
scope.AddDefaults();
string buf = " \
Seq-align ::= { \
type partial, \
dim 2, \
score { \
{ \
id str \"score\", \
value int 516 \
}, \
{ \
id str \"num_ident\", \
value int 97 \
}, \
{ \
id str \"num_positives\", \
value int 142 \
}, \
{ \
id str \"pct_identity_gap\", \
value real { 449074074074074, 10, -13 } \
} \
}, \
segs std { \
{ \
dim 2, \
ids { \
gi 489996512, \
gi 407681635 \
}, \
loc { \
int { \
from 2, \
to 217, \
strand unknown, \
id gi 489996512 \
}, \
int { \
from 207988, \
to 208635, \
strand minus, \
id gi 407681635 \
} } } } } \
Seq-align ::= { \
type partial, \
dim 2, \
score { \
{ \
id str \"score\", \
value int 73 \
}, \
{ \
id str \"num_ident\", \
value int 16 \
}, \
{ \
id str \"num_positives\", \
value int 21 \
}, \
{ \
id str \"pct_identity_gap\", \
value real { 5, 10, 1 } \
} \
}, \
segs std { \
{ \
dim 2, \
ids { \
gi 489996512, \
gi 407681635 \
}, \
loc { \
int { \
from 252, \
to 283, \
strand unknown, \
id gi 489996512 \
}, \
int { \
from 173613, \
to 173708, \
strand minus, \
id gi 407681635 \
} } } } } \
";
CNcbiIstrstream istrs(buf);
unique_ptr<CObjectIStream> istr(CObjectIStream::Open(eSerial_AsnText, istrs));
CAlignCleanup::TAligns orig_aligns;
while (!istr->EndOfData()) {
CRef<CSeq_align> align(new CSeq_align);
*istr >> *align;
orig_aligns.push_back(align);
}
CAlignCleanup cln(scope);
cln.SortInputsByScore(true);
CAlignCleanup::TAligns cleaned_aligns;
cln.Cleanup(orig_aligns, cleaned_aligns, CAlignCleanup::eAlignVec);
check_no_overlaps(cleaned_aligns);
}
/*
BOOST_AUTO_TEST_CASE(TestTwoSubjects)
{
CRef<CObjectManager> om = CObjectManager::GetInstance();
CScope scope(*om);
scope.AddDefaults();
string buf = " \
Seq-align ::= { \
type partial, \
dim 2, \
score { \
{ \
id str \"score\", \
value int 434 \
} \
}, \
segs std { \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} \
}, \
loc { \
int { \
from 1, \
to 11, \
strand unknown, \
id gi 446035996 \
}, \
int { \
from 11324, \
to 11356, \
strand plus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} } } }, \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} \
}, \
loc { \
empty gi 446035996, \
int { \
from 11357, \
to 11362, \
strand plus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} } } }, \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} \
}, \
loc { \
int { \
from 12, \
to 81, \
strand unknown, \
id gi 446035996 \
}, \
int { \
from 11363, \
to 11572, \
strand plus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} } } }, \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} \
}, \
loc { \
empty gi 446035996, \
int { \
from 11573, \
to 11575, \
strand plus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} } } }, \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} \
}, \
loc { \
int { \
from 82, \
to 163, \
strand unknown, \
id gi 446035996 \
}, \
int { \
from 11576, \
to 11821, \
strand plus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_106\" \
} } } } } } \
Seq-align ::= { \
type partial, \
dim 2, \
score { \
{ \
id str \"score\", \
value int 440 \
} \
}, \
segs std { \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_29\" \
} \
}, \
loc { \
int { \
from 3, \
to 80, \
strand unknown, \
id gi 446035996 \
}, \
int { \
from 71709, \
to 71942, \
strand minus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_29\" \
} } } }, \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_29\" \
} \
}, \
loc { \
empty gi 446035996, \
int { \
from 71706, \
to 71708, \
strand minus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_29\" \
} } } }, \
{ \
dim 2, \
ids { \
gi 446035996, \
general { \
db \"PRJNA248255\", \
tag str \"seq_29\" \
} \
}, \
loc { \
int { \
from 81, \
to 163, \
strand unknown, \
id gi 446035996 \
}, \
int { \
from 71457, \
to 71705, \
strand minus, \
id general { \
db \"PRJNA248255\", \
tag str \"seq_29\" \
} } } } } } \
";
CNcbiIstrstream istrs(buf.c_str());
unique_ptr<CObjectIStream> istr(CObjectIStream::Open(eSerial_AsnText, istrs));
CAlignCleanup::TAligns orig_aligns;
while (!istr->EndOfData()) {
CRef<CSeq_align> align(new CSeq_align);
*istr >> *align;
orig_aligns.push_back(align);
}
CAlignCleanup cln;
cln.SortInputsByScore(true);
CAlignCleanup::TAligns cleaned_aligns;
cln.CleanupByQuery(orig_aligns, cleaned_aligns);
check_no_overlaps(cleaned_aligns);
}
*/
| [
"ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03"
] | ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03 |
5daac50b096a5af8a014fe80355914922d3c6769 | 91fd8f1aeecdf3b619c2b59e23d7261d51a046c1 | /프로그래머스/2017 팁스타운/예상 대진표.cpp | eceab1972a047175f0d40fdab47c4bb1d7ef1302 | [
"MIT"
] | permissive | jm199seo/coding-test-practice | d1f2dab03b5a8873dc2eb4d6a2de1d84c6c01bf0 | e18f9b0636f870047f04d0579aa42a20fe8153a8 | refs/heads/master | 2023-01-03T06:58:52.299338 | 2020-10-22T20:04:12 | 2020-10-22T20:04:12 | 297,982,850 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp | #include <bits/stdc++.h>
using namespace std;
// https://programmers.co.kr/learn/courses/30/lessons/12985
int solution(int n, int a, int b)
{
int answer = 1;
if (a > b) {
int temp = b;
b = a;
a = temp;
}
while (n / 2 > 1) {
n = n / 2;
if (b - a < 2) {
if (a % 2 == 0) {
a = ceil(float(a) / 2);
b = ceil(float(b) / 2);
answer++;
}
else {
return answer;
}
}
else {
a = ceil(float(a) / 2);
b = ceil(float(b) / 2);
answer++;
}
}
return answer;
}
int main() {
int answer = solution(8, 4, 7);
cout << "answer: " << answer << endl;
}
| [
"jm199seo@vt.edu"
] | jm199seo@vt.edu |
26226bf6bd1eecc86d2a0e4c867d0895b6c09049 | 3bea155d88e1bf4984795153b0f365e4eeaeb455 | /src/users/customer.cpp | 06e7583f8bd968f7fe2a10c6cd2017d3a690b6e6 | [] | no_license | youssef7ussien/ECommerceSystem-Cpp | c0a43f7695eafcd059b0e1ce1429e2d519a231e8 | 6ea92b068479245aa12fc6dc43da5e7b770665ce | refs/heads/master | 2023-04-01T23:31:10.827893 | 2021-03-31T01:06:12 | 2021-03-31T01:06:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,128 | cpp | #include "customer.h"
#include <ctime>
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
PurchaseData::PurchaseData()
{
name=address=phoneNumber=email=country="";
}
string PurchaseData::getName() const
{
return name;
}
void PurchaseData::setName(string name)
{
this->name=name;
}
string PurchaseData::getAddress() const
{
return address;
}
void PurchaseData::setAddress(string address)
{
this->address=address;
}
string PurchaseData::getEmail() const
{
return email;
}
void PurchaseData::setEmail(string email)
{
this->email=email;
}
string PurchaseData::getPhoneNumber() const
{
return phoneNumber;
}
void PurchaseData::setPhoneNumber(string phoneNumber)
{
this->phoneNumber=phoneNumber;
}
string PurchaseData::getCountry() const
{
return country;
}
void PurchaseData::setCountry(string country)
{
this->country=country;
}
double PurchaseData::shippingExpenses(double price) const
{
return 0.05*price;
}
double PurchaseData::totalPrice(double price) const
{
return price+shippingExpenses(price);
}
string PurchaseData::getDate()
{
time_t now=time(0);
string date=ctime(&now);
/* date(0,2) = date.substr(0,3) -> day name
* date(4,6) = date.substr(4,3) -> month
* date(8,9) = date.substr(8,2) -> day number
* date(11,18) = date.substr(11,8) -> clock
* date(20,23) = date.substr(20,4) -> year
*/
return date.substr(0,3)+", "+date.substr(8,2)+" "+date.substr(4,3)
+" "+date.substr(20,4)+", at "+date.substr(11,8);
}
// **********************************************************************************
Customer::Customer()
{
name="";
}
Customer::Customer(string name)
{
this->name=name;
}
string Customer::getName() const
{
return name;
}
int Customer::cartLength() const
{
return cart.getLength();
}
Queue<Product> Customer::getCart() const
{
return cart;
}
void Customer::clearCart()
{
cart.clear();
}
PurchaseData Customer::getPurchaseData() const
{
return this->PD;
}
void Customer::createPurchaseData(PurchaseData PD)
{
this->PD=PD;
}
void Customer::addToCart(const Product& product)
{
cart.enqueue(product);
}
Product Customer::removeFromCart()
{
return cart.dequeue();
}
string createFileName(const string& fileName)
{
string newName=fileName+"-invoice.txt";
ifstream file(newName);
for(int i=1 ; i>0 ; i++)
{
if(file)
{
file.close();
newName=fileName+" - invoice ("+to_string(i)+").txt";
file.open(newName);
}
else
{
file.close();
return newName;
}
}
return newName;
}
void line(ofstream &invoiceFile,int length)
{
while(length--)
invoiceFile<<"-";
invoiceFile<<endl;
}
void Customer::printPurchaseData(Queue<Product> products)
{
ofstream invoiceFile(createFileName(PD.getName()));
if(!invoiceFile.is_open())
{
return;
}
line(invoiceFile,90);
invoiceFile<<"Order Date : "<<PD.getDate()<<endl;
line(invoiceFile,90);
invoiceFile<<endl<<"Customer Information : "<<endl;
invoiceFile<<"\t"; line(invoiceFile,70);
invoiceFile<<"\t "<<setw(20)<<left<<"* Name"<<setw(40)<<left<<PD.getName()<<endl;
invoiceFile<<"\t"; line(invoiceFile,70);
invoiceFile<<"\t "<<setw(20)<<left<<"* Phone Number"<<setw(40)<<left<<PD.getPhoneNumber()<<endl;
invoiceFile<<"\t"; line(invoiceFile,70);
invoiceFile<<"\t "<<setw(20)<<left<<"* Email"<<setw(40)<<left<<PD.getEmail()<<endl;
invoiceFile<<"\t"; line(invoiceFile,70);
invoiceFile<<"\t "<<setw(20)<<left<<"* Country"<<setw(40)<<left<<PD.getCountry()<<endl;
invoiceFile<<"\t"; line(invoiceFile,70);
invoiceFile<<"\t "<<setw(20)<<left<<"* Address"<<setw(40)<<left<<PD.getAddress()<<endl;
invoiceFile<<"\t"; line(invoiceFile,70);
line(invoiceFile,90);
invoiceFile<<"\nProducts :"<<endl;
invoiceFile<<" "; line(invoiceFile,79);
invoiceFile<<"\t";
invoiceFile<<setw(10)<<left<<"Number";
invoiceFile<<setw(33)<<left<<"Name";
invoiceFile<<setw(18)<<left<<"Category";
invoiceFile<<setw(13)<<left<<"price";
invoiceFile<<endl;
invoiceFile<<" "; line(invoiceFile,79);
double price=0.0;
for(int i=0; products.getLength() ; i++)
{
Product product=products.dequeue();
invoiceFile<<"\t";
invoiceFile<<left;
invoiceFile<<setw(7)<<i+1<<" ";
invoiceFile<<setw(30)<<product.getName()<<" ";
invoiceFile<<setw(15)<<product.getCategoryName()<<" ";
invoiceFile<<setw(10)<<right<<product.getPrice()<<" $"<<endl;
price+=product.getPrice();
}
invoiceFile<<" "; line(invoiceFile,79);
invoiceFile<<"\tshippingExpenses : "<<setw(52)<<right<<PD.shippingExpenses(price)<<" $"<<endl;
invoiceFile<<" "; line(invoiceFile,79);
invoiceFile<<"\tTotal Price : "<<setw(57)<<right<<PD.totalPrice(price)<<" $"<<endl;
invoiceFile<<" "; line(invoiceFile,79);
line(invoiceFile,90);
invoiceFile.close();
}
| [
"youssef12468@gmail.com"
] | youssef12468@gmail.com |
cf9561ee08400fcd438aae4a31f9416daf68c5a2 | c3e8096995748151e010ef3984418e30dce25e0e | /testing/share/Testing/test_data/HronTurekFsi/fluid/0/motionU | 28420096889162c0bff3662601d3169fcd6f7f1c | [
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
] | permissive | anilkunwar/ElmerFoamFSI | ebf26615930d25710330abd700e52cb5273672da | b042d74cd42aa80f58c6d5c605b0e46d92258fcf | refs/heads/master | 2020-06-28T21:02:57.870856 | 2016-09-24T01:00:22 | 2016-09-24T01:00:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,612 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | foam-extend: Open Source CFD |
| \\ / O peration | Version: 3.1 |
| \\ / A nd | Web: http://www.extend-project.de |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class tetPointVectorField;
location "0";
object motionU;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField uniform (0 0 0);
boundaryField
{
plate
{
type fixedValue;
value uniform (0 0 0);
}
outlet
{
type fixedValue;
value uniform (0 0 0);
}
inlet
{
type fixedValue;
value uniform (0 0 0);
}
cylinder
{
type fixedValue;
value uniform (0 0 0);
}
bottom
{
type fixedValue;
value uniform (0 0 0);
}
top
{
type fixedValue;
value uniform (0 0 0);
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"mtcampbe@illinoisrocstar.com"
] | mtcampbe@illinoisrocstar.com | |
926142994f1d7be3dc4a7f408f5cb7ca07613d75 | 6732486464a2cdcb0816180badeac6a49ca5cc2d | /differential_amplifier_LGT8F328P/differential_amplifier_LGT8F328P.ino | 6fd3357298a2983103f15baa61f326f88f17419c | [] | no_license | spiderock98/Arduino | 5de2664fe4c7bf00915a5249d75e6e8e6808b064 | 7d64ab1f165edc1e199e6d47f8725d598d3f4c9f | refs/heads/master | 2022-04-29T13:42:27.742269 | 2021-05-22T14:52:18 | 2021-05-22T14:52:18 | 140,645,921 | 0 | 0 | null | 2022-03-27T16:18:02 | 2018-07-12T01:40:49 | C++ | UTF-8 | C++ | false | false | 638 | ino | //============================================
// Differential Amplifier demo for LGT8F328x
// by dbuezas
// Using new differential_amplifier library.
// Differential read from all analog pin combinations
//============================================
#include "differential_amplifier.h"
void setup() {
Serial.begin(230400);
// analogReference(DEFAULT); // 5v
}
void loop() {
int value = analogDiffRead(A0, A1, GAIN_1);
if (value < 0) {
Serial.println("[ERROR] Cannot combine these PINs");
return;
}
Serial.print((value*1.0 / 819));
Serial.print("V\t");
Serial.print(value);
Serial.println();
delay(100);
}
| [
"5751062057@st.utc2.edu.vn"
] | 5751062057@st.utc2.edu.vn |
3aa98708060f6484261e91e9993f5a13a664ae66 | 65f427dad9fedca750aad7dcfeff3840d5f0c1e2 | /CH13.35/StrVector.h | 0dc40ed120d5764e6fffd639346588086a49f7ff | [] | no_license | wuzhipeng2014/CPP-Primer | 412b8f44d70dc6cb0aa1f217f1e1050c0cee1107 | ff8d90f1fb78680c415c18a64f0b2ae5eacb11f8 | refs/heads/master | 2020-06-12T13:40:06.357780 | 2015-07-14T01:59:33 | 2015-07-14T01:59:33 | 39,045,880 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,226 | h | #pragma once
#define _SCL_SECURE_NO_WARNINGS
#include <string>
#include <memory>
using namespace std;
class StrVector
{
public:
StrVector();
~StrVector();
//拷贝控制成员
StrVector(const StrVector &); //拷贝构造函数
StrVector& operator=(const StrVector &); //拷贝赋值运算符
StrVector(StrVector &&); //移动构造函数
StrVector& operator=(StrVector &&); //移动赋值运算符
void push_back(const string &);
void push_back(string &&);
size_t size() const
{
return first_free - elements;
}
size_t capacity() const
{
return cap - elements;
}
string * begin() const
{
return elements;
}
string *end() const
{
return first_free;
}
private:
static allocator<string> alloc;
void chk_n_alloc()
{
if (size()==capacity())
{
reallocate();
}
}
//开辟更多的空间,
pair<string*, string*> alloc_n_copy(const string*, const string*);
void free(); //销毁元素并释放内存
void reallocate(); //获取更多的空间,并拷贝已有的元素
string * elements; //指向strVector的首元素
string * first_free; //指向strvector第一个空闲的位置
string * cap; //指向分配的内存之后的位置
};
| [
"798288416@qq.com"
] | 798288416@qq.com |
c444e1c88ff65b39f5f70a026eb2a30e9dfb2983 | cf9c4f10e2db6508a4784eb56d63c87000047e78 | /src/SOFilterDebuger/DebugModule.cpp | 11f60c0d54a45ecedcc577074febc432807c3450 | [
"MIT"
] | permissive | wakare/Leviathan | 86f578bebb0b9100920d981ef6c67672a241b94b | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | refs/heads/master | 2021-06-26T17:25:28.927589 | 2020-10-11T15:12:53 | 2020-10-11T15:12:53 | 151,736,145 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | #include "DebugModule.h"
namespace SOFilter
{
DebugModule::DebugModule()
: m_debug_state(EDS_UNKNOWN)
{
auto _debug_task = [this](CoPullType<int>& sink)
{
};
DoAsyncTask(_debug_task);
}
void DebugModule::DebugStart()
{
_debugStateChange(EDS_START);
}
void DebugModule::DebugStop()
{
_debugStateChange(EDS_STOP);
}
void DebugModule::DebugTick()
{
_debugStateChange(EDS_TICK);
}
void DebugModule::DebugRollback()
{
_debugStateChange(EDS_ROLLBACK);
}
void DebugModule::Update()
{
_tick();
}
void DebugModule::_debugStateChange(DebugState state)
{
auto _state_change = [this, state](CoPullType<int>& sink)
{
};
DoAsyncTask(_state_change);
}
}
| [
"wakarenokaze@gmail.com"
] | wakarenokaze@gmail.com |
47b6d0cf84d8df3d4d5d53bc77eaa177009f74f3 | 691d74ae7d6b6769fead7d2a95f94b8453a4acd2 | /Learn Advanced C++ Programming/Operator Overloading/Overloading Plus/Complex.cpp | acc6f5ebe766ab3e2aeeadab17c6b6b4fd0cd790 | [] | no_license | karlit0/Learn-Advanced-C-Programming---John-Purcell | fc91dc95e87b6fd318b2d60b8e148b00c40a410a | 3319810e2207e127182619015675df8b19b8fc14 | refs/heads/master | 2023-01-20T04:32:20.584933 | 2020-11-25T19:44:41 | 2020-11-25T19:44:41 | 305,679,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include "Complex.h"
ostream& operator<<(ostream& Out, const Complex& C)
{
Out << "(" << C.GetReal() << ", " << C.GetImaginary() << ")";
return Out;
}
Complex operator+(const Complex& C1, const Complex& C2)
{
return Complex(C1.GetReal() + C2.GetReal(), C1.GetImaginary() + C2.GetImaginary());
}
Complex operator+(const Complex& C1, double D)
{
return Complex(C1.GetReal() + D, C1.GetImaginary());
}
Complex operator+(double D, const Complex& C1)
{
return Complex(C1.GetReal() + D, C1.GetImaginary());
}
Complex::Complex() : Real(0), Imaginary(0)
{
}
Complex::Complex(double Real, double Imaginary) : Real(Real), Imaginary(Imaginary)
{
}
Complex::Complex(const Complex& Other)
{
Real = Other.Real;
Imaginary = Other.Imaginary;
}
const Complex& Complex::operator=(const Complex& Other)
{
Real = Other.Real;
Imaginary = Other.Imaginary;
return *this;
}
| [
"astipanovic23@gmail.com"
] | astipanovic23@gmail.com |
a086b59bc164d637928e9b7c747e8abd5fd65c0d | c6fa53212eb03017f9e72fad36dbf705b27cc797 | /DQM/TrackerCommon/plugins/DetectorStateFilter.h | ec4afd2e280b491bf9bd29ae84eade87ff8edf7a | [] | no_license | gem-sw/cmssw | a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608 | 5893ef29c12b2718b3c1385e821170f91afb5446 | refs/heads/CMSSW_6_2_X_SLHC | 2022-04-29T04:43:51.786496 | 2015-12-16T16:09:31 | 2015-12-16T16:09:31 | 12,892,177 | 2 | 4 | null | 2018-11-22T13:40:31 | 2013-09-17T10:10:26 | C++ | UTF-8 | C++ | false | false | 521 | h | #ifndef DetectorStateFilter_H
#define DetectorStateFilter_H
#include "FWCore/Framework/interface/EDFilter.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
class DetectorStateFilter : public edm::EDFilter {
public:
DetectorStateFilter( const edm::ParameterSet & );
~DetectorStateFilter();
private:
bool filter( edm::Event &, edm::EventSetup const& );
uint64_t nEvents_, nSelectedEvents_;
bool verbose_;
bool detectorOn_;
std::string detectorType_;
edm:: InputTag dcsStatusLabel_;
};
#endif
| [
"sha1-66dec20152d9caa90fb44e3138a83d284b0c6de4@cern.ch"
] | sha1-66dec20152d9caa90fb44e3138a83d284b0c6de4@cern.ch |
0eb376b6a05fd8f6fed11eee5cda3226cdc942de | c74e77aed37c97ad459a876720e4e2848bb75d60 | /0-99/3/(6461331)[OK]A[ b'Shortest path of the king' ].cpp | 15f263a5ce7c8ba0fbc0d37c7c16d4ea53a685b9 | [] | no_license | yashar-sb-sb/my-codeforces-submissions | aebecf4e906a955f066db43cb97b478d218a720e | a044fccb2e2b2411a4fbd40c3788df2487c5e747 | refs/heads/master | 2021-01-21T21:06:06.327357 | 2017-11-14T21:20:28 | 2017-11-14T21:28:39 | 98,517,002 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 709 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<map>
#include<cmath>
#include<queue>
#include<stack>
#include<sstream>
#include<iomanip>
#include<bitset>
#include<string>
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
typedef long double ldb;
typedef pair<int,int> pii;
int main()
{
ios_base::sync_with_stdio(0);
char c,d;
int h1,v1,h2,v2;
cin>>c>>v1;
h1 = c-'a';
cin>>c>>v2;
h2 = c-'a';
h1=h2-h1;
v1-=v2;
c=h1>0?'R':'L';
d=v1>0?'D':'U';
h1=abs(h1);
v1=abs(v1);
cout<<max(h1,v1)<<'\n';
for(;h1>0||v1>0;--h1,--v1)
{
if(h1>0)cout<<c;
if(v1>0)cout<<d;
cout<<'\n';
}
return 0;
} | [
"yashar_sb_sb@yahoo.com"
] | yashar_sb_sb@yahoo.com |
3994e94f11225efda520bb8065135e1a3c6a4d87 | 2a985fd5bfce31e0d41706b4d0df2071ff84ecc9 | /POJ/2381/9333395_WA.cpp | f8c19b5c855c4b029d10aa9ce11a6799a241789a | [] | no_license | liuguojun/OnlineJudge | 527d6ecd1c879ff6c5be838c08ae2283e479c2c9 | 06fe122ce5551ca36107f05ec2e9da8ccfde59ed | refs/heads/master | 2021-01-22T11:11:33.576712 | 2012-10-15T14:36:34 | 2012-10-15T14:36:34 | 5,849,474 | 0 | 1 | null | 2014-10-13T17:04:19 | 2012-09-18T00:50:26 | C++ | UTF-8 | C++ | false | false | 796 | cpp | #include <iostream>
#include <bitset>
using namespace std;
int flag[16000010] = {0};
int main()
{
int a, c, m, R0;
cin >> a >> c >> m >> R0;
int max = -1, R1, i;
while( true )
{
R1 = (a*R0 + c) % m;
if( flag[R1] )
break;
else {
flag[R1] = 1;
R0 = R1;
}
}
int last = -1, curr = -1;
for( i = 0; i < 16000001; i++ )
{
if(flag[i])
{
if( last==-1 && curr==-1)
curr = i;
else{
last = curr;
curr = i;
if(max < curr - last)
max = curr - last;
}
}
}
cout << max <<endl;
return 0;
}
| [
"liuguojun.pku@gmail.com"
] | liuguojun.pku@gmail.com |
ea8c05f620bbc3063c8cb5db61dca8d91b8b2c41 | 5c519a25471506c2a84546367c2569fb2d01b6b6 | /math/primitives.h | ecc54017109ca09e6b8c8e7dc759e8861edd164e | [] | no_license | MightyPowerNuke/math | 4ebf5420e90c2b2aad6d72e666a29e8a9025091d | 4e33e2bc9d325841318195fdcaa4889e4ad2522b | refs/heads/master | 2023-08-15T21:47:31.127708 | 2021-10-11T19:57:18 | 2021-10-11T19:57:18 | 400,864,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,365 | h | #pragma once
#include <array>
#include "vector.h"
#include "point.h"
namespace geom {
/*Line value struct. Contains a point (origin point) P and a direction vector v.*/
struct Line {
::mpn::Point3 P;
::mpn::Vector3 v;
constexpr Line() noexcept : P(0,0,0), v(0,0,0) { }
constexpr Line(const ::mpn::Point3& _P, const ::mpn::Vector3& _v) noexcept : P(_P), v(_v) {}
};
/*2D rectangle value class. Stores the top left and bottom right coordinates.*/
template<typename T>
class RectangleArea final {
public:
constexpr RectangleArea() : x0(-1), y0(-1), x1(+1), y1(+1) {}
constexpr RectangleArea(T _x0, T _y0, T _x1, T _y1) : x0(_x0), y0(_y0), x1(_x1), y1(_y1) {}
constexpr T left() const { return x0; }
constexpr T right() const { return x1; }
constexpr T top() const { return y0; }
constexpr T bottom() const { return y1; }
constexpr T width() const { return x1 - x0; }
constexpr T height() const { return y1 - y0; }
constexpr T area() const { return width() * height(); }
private:
T x0, y0, x1, y1;
};
using Rectangle2D = RectangleArea<float>;
/*Converts pixel size coordinates into device coordinates.
- coords: pixel size coordinates.
- w: screen width.
- h: screen height.
Result is a Rectangle2D with coordinates in range [-1,+1]. */
//Rectangle2D coords2device(const Rectangle2D& coords, float w, float h);
/*Converts device coordinates into pixel size coordinates.
- coords: device coordinates.
- w: screen width
- h: screen height
Result is a Rectangle2D with coordinates in range [0,w) and [0,h) respectively.*/
//Rectangle2D device2coords(const Rectangle2D& dev, float w, float h);
constexpr const float INVALID_DISTANCE = -1;
struct Triangle
{
::std::array<::mpn::Point3, 3> vertices;
constexpr Triangle(::std::array<::mpn::Point3, 3>&& vertices) : vertices(vertices) {};
constexpr Triangle(::mpn::Point3 p0, ::mpn::Point3 p1, ::mpn::Point3 p2) : vertices{ p0, p1, p2 } {};
float intersect(const geom::Line& line) const noexcept;
::mpn::Point3 getCenter() const;
};
static_assert(sizeof(Triangle) <= 64, "Triangle not lightweight enough");
struct AABB
{
::mpn::Point3 minCoords;
::mpn::Point3 maxCoords;
AABB() = default;
AABB(::mpn::Point3 minCoords, ::mpn::Point3 maxCoords) : minCoords(minCoords), maxCoords(maxCoords)
{
if (!(minCoords[0] <= maxCoords[0] && minCoords[1] <= maxCoords[1] && minCoords[2] <= maxCoords[2]))
{
throw ::std::invalid_argument("Min coords must store the smaller coordinate for each dimensions");
}
}
bool intersect(const geom::Line& line) const noexcept;
inline ::mpn::Point3 getCenter() const noexcept {
return ::mpn::Point3(
(minCoords[0] + maxCoords[0]) / 2.0f,
(minCoords[1] + maxCoords[1]) / 2.0f,
(minCoords[2] + maxCoords[2]) / 2.0f
);
}
bool contains(const AABB& other) const noexcept
{
return minCoords[0] <= other.minCoords[0]
&& minCoords[1] <= other.minCoords[1]
&& minCoords[2] <= other.minCoords[2]
&& maxCoords[0] >= other.maxCoords[0]
&& maxCoords[1] >= other.maxCoords[1]
&& maxCoords[2] >= other.maxCoords[2];
}
static AABB _union(const AABB& left, const AABB& right);
};
AABB createAABB(const Triangle& triangle);
AABB createAABB(std::vector<Triangle>::const_iterator begin, std::vector<Triangle>::const_iterator end);
}
| [
"vsomos@gmail.com"
] | vsomos@gmail.com |
39e5ef583f532ccd37f5a3813dc6b5773d8b4ec9 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14171/function14171_schedule_3/function14171_schedule_3_wrapper.cpp | cc0b44c904387dedbdf075a4840dbee386368cfe | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,473 | cpp | #include "Halide.h"
#include "function14171_schedule_3_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(64);
Halide::Buffer<int32_t> buf01(64);
Halide::Buffer<int32_t> buf02(64);
Halide::Buffer<int32_t> buf03(64, 128, 64);
Halide::Buffer<int32_t> buf04(64, 128);
Halide::Buffer<int32_t> buf05(64);
Halide::Buffer<int32_t> buf06(64, 128);
Halide::Buffer<int32_t> buf07(64, 64, 128);
Halide::Buffer<int32_t> buf08(64, 64);
Halide::Buffer<int32_t> buf0(64, 64, 128, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14171_schedule_3(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf08.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14171/function14171_schedule_3/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
094bf81ad9e729074398df2f43e07377a8ca0b80 | bf2536ee42d1104ef8f8f986093c751fc4b12f82 | /On-Line_Game-master/OnlineTagGame/PacketStream.cpp | 8b7f65beadd5831292d48e8d1d834a05ac63d54a | [] | no_license | ahmada505/OnlineGaming | 3af6efc4c62f615395527ca5480d1c898d00b731 | b45b850dad71165eb5f11fd567b5a0e046ec3f71 | refs/heads/master | 2020-04-25T05:09:04.417158 | 2019-02-25T15:37:17 | 2019-02-25T15:37:17 | 172,532,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 668 | cpp | #include "PacketStream.h"
void PacketStream::writeInt(int dataIn)
{
outputStream << dataIn << "";
}
void PacketStream::readInt(int &dataOut)
{
inputStream >> dataOut;
}
void PacketStream::writeString(std::string dataIn)
{
outputStream << dataIn << "";
}
void PacketStream::readString(std::string &dataOut)
{
inputStream >> dataOut;
}
void PacketStream::toCharArray(char* arrayIn)
{
std::string s = outputStream.str();
memcpy(arrayIn,s.c_str(), s.length());
outputStream.str("" );
}
void PacketStream::fromCharArray(char* arrayIn)
{
inputStream.str(""); // clear the old stream
inputStream.str(arrayIn);//populate inputStream
}
| [
"anessahmad20@gmail.com"
] | anessahmad20@gmail.com |
1dc8f1b2b67210244dd3f761ae8f82fea3c74bca | e5ac268ec52905657c0b916ebb7ffaf74888871b | /dx11tut10/dx11tut10/Engine/Engine/d3dclass.h | f9dce9d2a37134c19a7a7e4fa228fb08e9ca78f4 | [] | no_license | sungjae96/directx | 8fb53fd6571c5eadde51649f0cff4d431c35bfb6 | 1c0510672e59861f6592f2acd35203ee915ba691 | refs/heads/master | 2020-07-26T21:33:17.543520 | 2019-10-27T09:24:42 | 2019-10-27T09:24:42 | 208,770,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,026 | h | ////////////////////////////////////////////////////////////////////////////////
// Filename: d3dclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _D3DCLASS_H_
#define _D3DCLASS_H_
/////////////
// LINKING //
/////////////
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dx11.lib")
#pragma comment(lib, "d3dx10.lib")
//////////////
// INCLUDES //
//////////////
#include <dxgi.h>
#include <d3dcommon.h>
#include <d3d11.h>
#include <d3dx10math.h>
////////////////////////////////////////////////////////////////////////////////
// Class name: D3DClass
////////////////////////////////////////////////////////////////////////////////
class D3DClass
{
public:
D3DClass();
D3DClass(const D3DClass&);
~D3DClass();
bool Initialize(int, int, bool, HWND, bool, float, float);
void Shutdown();
void BeginScene(float, float, float, float);
void EndScene();
ID3D11Device* GetDevice();
ID3D11DeviceContext* GetDeviceContext();
void GetProjectionMatrix(D3DXMATRIX&);
void GetWorldMatrix(D3DXMATRIX&);
void GetOrthoMatrix(D3DXMATRIX&);
void GetVideoCardInfo(char*, int&);
void TurnZBufferOn();
void TurnZBufferOff();
void TurnOnAlphaBlending();
void TurnOffAlphaBlending();
void TurnOnCulling();
void TurnOffCulling();
private:
bool m_vsync_enabled;
int m_videoCardMemory;
char m_videoCardDescription[128];
IDXGISwapChain* m_swapChain;
ID3D11Device* m_device;
ID3D11DeviceContext* m_deviceContext;
ID3D11RenderTargetView* m_renderTargetView;
ID3D11Texture2D* m_depthStencilBuffer;
ID3D11DepthStencilState* m_depthStencilState;
ID3D11DepthStencilView* m_depthStencilView;
ID3D11RasterizerState* m_rasterState;
D3DXMATRIX m_projectionMatrix;
D3DXMATRIX m_worldMatrix;
D3DXMATRIX m_orthoMatrix;
ID3D11DepthStencilState* m_depthDisabledStencilState;
ID3D11BlendState* m_alphaEnableBlendingState;
ID3D11BlendState* m_alphaDisableBlendingState;
ID3D11RasterizerState* m_rasterStateNoCulling;
};
#endif | [
"suungjae9612@naver.com"
] | suungjae9612@naver.com |
b43c457b595ee900e826571a09a84d7820c25755 | d03d052c0ca220d06ec17d170e2b272f4e935a0c | /gen/mojo/services/files/interfaces/ioctl.mojom-common.h | 22b54dd94dd11ab64fa3950c13e11ca7c9b6d0ed | [
"Apache-2.0"
] | permissive | amplab/ray-artifacts | f7ae0298fee371d9b33a40c00dae05c4442dc211 | 6954850f8ef581927df94be90313c1e783cd2e81 | refs/heads/master | 2023-07-07T20:45:43.526694 | 2016-08-06T19:53:55 | 2016-08-06T19:53:55 | 65,099,400 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,907 | h | // NOTE: This file was generated by the Mojo bindings generator.
#ifndef MOJO_SERVICES_FILES_INTERFACES_IOCTL_MOJOM_COMMON_H_
#define MOJO_SERVICES_FILES_INTERFACES_IOCTL_MOJOM_COMMON_H_
#include <stdint.h>
#include <iosfwd>
#include "mojo/public/cpp/bindings/array.h"
#include "mojo/public/cpp/bindings/callback.h"
#include "mojo/public/cpp/bindings/interface_handle.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/bindings/map.h"
#include "mojo/public/cpp/bindings/message_validator.h"
#include "mojo/public/cpp/bindings/string.h"
#include "mojo/public/cpp/bindings/struct_ptr.h"
#include "mojo/public/cpp/system/buffer.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/handle.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "mojo/services/files/interfaces/ioctl.mojom-internal.h"
namespace mojo {
namespace files {
// --- Interface Forward Declarations ---
// --- Struct Forward Declarations ---
// --- Union Forward Declarations ---
// --- Enums Declarations ---
// --- Constants ---
const uint32_t kIoctlInvalid = 0U;
const uint32_t kIoctlTerminal = 1U;
// --- Interface declarations ---
} // namespace files
} // namespace mojo
// --- Internal Template Specializations ---
namespace mojo {
namespace internal {
} // internal
} // mojo
namespace mojo {
namespace files {
// --- Interface Request Validators ---
// --- Interface Response Validators ---
// --- Interface enum operators ---
// --- Unions ---
// Unions must be declared first because they can be members of structs.
// --- Inlined structs ---
// --- Non-inlined structs ---
// --- Struct serialization helpers ---
// --- Union serialization helpers ---
// --- Request and response parameter structs for Interface methods ---
} // namespace files
} // namespace mojo
#endif // MOJO_SERVICES_FILES_INTERFACES_IOCTL_MOJOM_COMMON_H_
| [
"pcmoritz@gmail.com"
] | pcmoritz@gmail.com |
03bd663dd764890be2987024d02a74536802651e | 483b059128e71bbb158443da0bf95ce2ecff92e7 | /de_stroyer/hooks.h | 063bff220cb32e0f22fe168f701f7e42f0f4e9a0 | [] | no_license | txz62582/niger | ecbbac53556ce7edb18bd5a6fbd781e35698f3d6 | 44b30659c77f5a1c40ce1faa11cad73525a5f343 | refs/heads/master | 2021-01-18T18:36:29.830853 | 2017-06-17T07:49:22 | 2017-06-17T07:49:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | h | #pragma once
typedef bool( __stdcall *CreateMoveFn )(float, CUserCmd*);
extern CreateMoveFn oCreateMove;
enum ClientFrameStage_t
{
FRAME_UNDEFINED = -1,
FRAME_START,
FRAME_NET_UPDATE_START,
FRAME_NET_UPDATE_POSTDATAUPDATE_START,
FRAME_NET_UPDATE_POSTDATAUPDATE_END,
FRAME_NET_UPDATE_END,
FRAME_RENDER_START,
FRAME_RENDER_END
};
typedef void( __stdcall* FrameStageNotifyFn )(ClientFrameStage_t);
extern FrameStageNotifyFn oFrameStageNotify;
typedef void( __fastcall *PaintTraverseFn )(void*, void*, unsigned int, bool, bool);
extern PaintTraverseFn oPaintTraverse;
typedef void( __stdcall *OverrideViewFn )(CViewSetup*);
extern OverrideViewFn oOverrideView;
namespace Hooks
{
extern bool __stdcall CreateMove( float flInputSampleTime, CUserCmd* cmd );
extern void __stdcall FrameStageNotify( ClientFrameStage_t stage );
extern bool __stdcall InPrediction( void );
extern void __fastcall PaintTraverse( void* _this, void* _edx, unsigned int panel, bool forceRepaint, bool allowForce );
extern void __stdcall OverrideView( CViewSetup* vsView );
} | [
"noreply@github.com"
] | noreply@github.com |
55436291ea8b1e89369fc3ddc0807668c8d23389 | 5e9e0adef44a1618af987f07bf4363842660277a | /AngryBirds/source/AngryBirds.Desktop.OpenGL/Button.cpp | d8d573f490281d2e92bb1afb27e75b790adf47ca | [] | no_license | rodrigobmg/Angry-Birds | cf7462c5c38d9b3074f1753d96390a22f5e5ddda | 0625646bc1e1d131a05e395bda60471eb4f74d04 | refs/heads/master | 2020-11-29T12:57:48.601554 | 2016-03-11T03:43:01 | 2016-03-11T03:43:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,302 | cpp | #include "stdafx.h"
#include "Button.h"
/**
* @method Button::init()
* @desc inititalizes the button renderer and screen space coordinates
*/
void Button::init(TiXmlElement *buttonElement)
{
buttonElement->QueryFloatAttribute("screenX", &x);
buttonElement->QueryFloatAttribute("screenY", &y);
float imgWid, imgHt;
buttonElement->QueryFloatAttribute("imgWidth", &imgWid);
buttonElement->QueryFloatAttribute("imgHeight", &imgHt);
buttonRenderer = new Renderer();
buttonRenderer->init(buttonElement->Attribute("src"), 1, imgWid, imgHt);
float screenX = x, screenY = y;
TiXmlElement *buttonSpriteElement = buttonElement->FirstChildElement()->FirstChildElement();
buttonSpriteElement->QueryFloatAttribute("spriteWidth", &width);
buttonSpriteElement->QueryFloatAttribute("spriteHeight", &height);
float spritePosX, spritePosY;
buttonSpriteElement->QueryFloatAttribute("uPosLeft", &spritePosX);
buttonSpriteElement->QueryFloatAttribute("vPosTop", &spritePosY);
buttonRenderer->setUTextureLeft(0, spritePosX);
buttonRenderer->setUTextureRight(0, spritePosX + width);
buttonRenderer->setVTextureTop(0, spritePosY);
buttonRenderer->setVTextureBottom(0, spritePosY + height);
buttonRenderer->setXPositionLeft(screenX);
buttonRenderer->setXPositionRight(screenX + width);
buttonRenderer->setYPositionTop(screenY);
buttonRenderer->setYPositionBottom(screenY + height);
mButtonPressed = false;
}
/**
* @method Button::update()
* @desc called every frame, checks if button was pressed or not
*/
void Button::update()
{
mButtonPressed = false;
if (InputManagerC::GetInstance()->isMouseClicked())
{
float mousex = InputManagerC::GetInstance()->getMouseX();
float mousey = InputManagerC::GetInstance()->getMouseY();
if (mousex > x && mousex < (x + width))
{
if (mousey > y && mousey < (y + height))
{
mButtonPressed = true;
}
}
}
}
/**
* @method Button::render()
* @desc renders the button sprite
*/
void Button::render()
{
buttonRenderer->render();
}
/**
* @method Button::isButtonPressed()
* @desc getter for button pressed state
*/
bool Button::isButtonPressed()
{
return mButtonPressed;
}
/**
* @method Button::~Button()
* @desc destructor to free up heap allocated memory
*/
Button::~Button()
{
delete buttonRenderer;
} | [
"njain@fiea.ucf.edu"
] | njain@fiea.ucf.edu |
11d140982d873ebf0da6bf5a4486a9e892cff891 | 899516cf6838c9b9e2397fb17b2d4040757835e0 | /filetreeview.cpp | 11a218862fbcb73414e9b9f13d856339acbce42f | [
"MIT"
] | permissive | Liyinghui1/videoWidget | b3f81332828831f1311b3d60aab2e79f9d9e3662 | dae03c3e7b4c1b18f25343d16139e1a729003cb6 | refs/heads/master | 2021-05-23T00:09:40.142019 | 2020-04-05T11:56:31 | 2020-04-05T11:56:31 | 253,149,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | #include "FileTreeView.h"
#include<QPushButton>
#include<QMouseEvent>
#include<QDebug>
#include<QFileInfo>
#include<QFileSystemModel>
CFileTreeView::CFileTreeView()
{
model= new QFileSystemModel;
model->setRootPath("C:\\");
this->setModel(model);
}
void CFileTreeView::mousePressEvent(QMouseEvent *event)
{
QPoint point = event->pos();
QModelIndex modelIndex = this->indexAt(point);
if(event->button() == Qt::LeftButton)
{
if(modelIndex.isValid())
{
QString filePath = model->filePath(modelIndex);
emit signalFilePathSelected(filePath);
}
}
QTreeView::mousePressEvent(event);
}
| [
"noreply@github.com"
] | noreply@github.com |
8daee52f3fd88a3134f9c46ccf2f4c7c49e072bc | 38e46b75230bebc8212626d3debefaa7c0cfd0bc | /src/array4d.cpp | 84456ccb539da5f4362baed9e28ea7d8515af726 | [] | no_license | vcmman/libcnn | 0a052f99ff8679d80ef6786bc241bc84b08b9051 | 43f418715810822de6860ca578c0f177b3d1a486 | refs/heads/master | 2021-01-18T00:09:17.200212 | 2015-11-16T08:04:24 | 2015-11-16T08:04:24 | 49,413,537 | 0 | 1 | null | 2016-01-11T08:50:34 | 2016-01-11T08:50:31 | null | UTF-8 | C++ | false | false | 3,028 | cpp | #include <iostream>
#include "array4d.hpp"
#include "inst_template.hpp"
using namespace libcnn;
namespace libcnn {
/* default constructor */
template<typename DT>
Array4D<DT>::Array4D():
value_(nullptr), shape_(std::vector<int>(4, 0)),
dim0_(0), dim1_(0), dim2_(0), dim3_(0) {}
/* copy construnctor */
template<typename DT>
Array4D<DT>::Array4D(const Array4D& src):
shape_(src.shape_),
dim0_(src.dim0_), dim1_(src.dim1_), dim2_(src.dim2_), dim3_(src.dim3_) {
// allocate memory
value_ = new DT[src.get_size()];
// iteratively copy value from source
for(int i = 0; i < src.get_size(); ++i) {
value_[i] = src.value_[i];
}
}
/* constructor */
template<typename DT>
Array4D<DT>::Array4D(const vector<int>& shape):
shape_(shape),
dim0_(shape[0]), dim1_(shape[1]), dim2_(shape[2]), dim3_(shape[3]) {
// allocate memory
value_ = new DT[shape[0]*shape[1]*shape[2]*shape[3]];
}
/* constructor (overloaded) */
template<typename DT>
Array4D<DT>::Array4D(const vector<int>& shape, DT* const value):
shape_(shape),
dim0_(shape[0]), dim1_(shape[1]), dim2_(shape[2]), dim3_(shape[3]) {
// assume that shape and size of value matches
value_ = value;
}
/* destructor */
template<typename DT>
Array4D<DT>::~Array4D() {
delete []value_;
}
/* get value */
template<typename DT>
DT* Array4D<DT>::get_value() const {
return value_;
}
/* get shape */
template<typename DT>
vector<int> Array4D<DT>::get_shape() const {
return shape_;
}
/* get dimemsion */
template<typename DT>
int Array4D<DT>::get_dim(const int axes) const {
switch(axes) {
case 0: return dim0_;
case 1: return dim1_;
case 2: return dim2_;
case 3: return dim3_;
}
}
/* get size */
template<typename DT>
int Array4D<DT>::get_size() const {
return shape_[0]*shape_[1]*shape_[2]*shape_[3];
}
/* set value, tested */
template<typename DT>
void Array4D<DT>::set_value(DT* const new_value, const int new_size) {
// allocate memory
value_ = new DT[new_size];
value_ = new_value;
}
/* set shape */
template<typename DT>
void Array4D<DT>::set_shape(const vector<int>& new_shape) {
shape_ = new_shape;
}
/* overload operator = */
template<typename DT>
Array4D<DT>& Array4D<DT>::operator=(const Array4D<DT>& src) {
shape_ = src.shape_;
int size = get_size();
value_ = new DT[size];
for(int i = 0; i < size; ++i) {
value_[i] = src.value_[i];
}
return *this;
}
/* overload operator + */
template<typename DT>
Array4D<DT>& Array4D<DT>::operator+(const Array4D<DT>& src) {
// assume that their shape matches
int size = get_size();
for(int i = 0; i < size; ++i) {
value_[i] += src.value_[i];
}
return *this;
}
/* overload operator - */
template<typename DT>
Array4D<DT>& Array4D<DT>::operator-(const Array4D<DT>& src) {
// assume that their shape matches
int size = get_size();
for(int i = 0; i < size; ++i) {
value_[i] -= src.value_[i];
}
return *this;
}
INST_CLASS(Array4D); // instantiate class Array4D
} // namespace libcnn
| [
"lsh@lsh-ubuntu-laptop.(none)"
] | lsh@lsh-ubuntu-laptop.(none) |
ab23d0201a2d7f94289387d6b4f4c7b4b58649b0 | c7c77ecdb2a33ee387147f068a6772961a5adc78 | /stromx/cvimgproc/WarpAffine.cpp | c2111497699440fe346f69a2aabc06f4bec0bb0f | [
"Apache-2.0"
] | permissive | uboot/stromx-opencv | b38d8a3a192f3ed1f1d9d87341f0817024debf32 | c7de6353905fee8870f8bf700363e0868ab17b78 | refs/heads/master | 2020-05-22T01:31:04.138296 | 2018-02-08T15:19:05 | 2018-02-08T15:19:05 | 52,387,716 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,201 | cpp | #include "stromx/cvimgproc/WarpAffine.h"
#include "stromx/cvimgproc/Locale.h"
#include "stromx/cvimgproc/Utility.h"
#include <stromx/cvsupport/Image.h>
#include <stromx/cvsupport/Matrix.h>
#include <stromx/cvsupport/Utilities.h>
#include <stromx/runtime/DataContainer.h>
#include <stromx/runtime/DataProvider.h>
#include <stromx/runtime/Id2DataComposite.h>
#include <stromx/runtime/Id2DataPair.h>
#include <stromx/runtime/ReadAccess.h>
#include <stromx/runtime/VariantComposite.h>
#include <stromx/runtime/WriteAccess.h>
#include <opencv2/imgproc/imgproc.hpp>
namespace stromx
{
namespace cvimgproc
{
const std::string WarpAffine::PACKAGE(STROMX_CVIMGPROC_PACKAGE_NAME);
const runtime::Version WarpAffine::VERSION(STROMX_CVIMGPROC_VERSION_MAJOR, STROMX_CVIMGPROC_VERSION_MINOR, STROMX_CVIMGPROC_VERSION_PATCH);
const std::string WarpAffine::TYPE("WarpAffine");
WarpAffine::WarpAffine()
: runtime::OperatorKernel(TYPE, PACKAGE, VERSION, setupInitParameters()),
m_affineM(cvsupport::Matrix::eye(2, 3, runtime::Matrix::FLOAT_32)),
m_dsizex(),
m_dsizey(),
m_dataFlow()
{
}
const runtime::DataRef WarpAffine::getParameter(unsigned int id) const
{
switch(id)
{
case PARAMETER_AFFINE_M:
return m_affineM;
case PARAMETER_DSIZEX:
return m_dsizex;
case PARAMETER_DSIZEY:
return m_dsizey;
case PARAMETER_DATA_FLOW:
return m_dataFlow;
default:
throw runtime::WrongParameterId(id, *this);
}
}
void WarpAffine::setParameter(unsigned int id, const runtime::Data& value)
{
try
{
switch(id)
{
case PARAMETER_AFFINE_M:
{
const runtime::Matrix & castedValue = runtime::data_cast<runtime::Matrix>(value);
if(! castedValue.variant().isVariant(runtime::Variant::FLOAT_MATRIX))
{
throw runtime::WrongParameterType(parameter(id), *this);
}
cvsupport::checkMatrixValue(castedValue, m_affineMParameter, *this);
m_affineM = castedValue;
}
break;
case PARAMETER_DSIZEX:
{
const runtime::UInt32 & castedValue = runtime::data_cast<runtime::UInt32>(value);
if(! castedValue.variant().isVariant(runtime::Variant::UINT_32))
{
throw runtime::WrongParameterType(parameter(id), *this);
}
cvsupport::checkNumericValue(castedValue, m_dsizexParameter, *this);
m_dsizex = castedValue;
}
break;
case PARAMETER_DSIZEY:
{
const runtime::UInt32 & castedValue = runtime::data_cast<runtime::UInt32>(value);
if(! castedValue.variant().isVariant(runtime::Variant::UINT_32))
{
throw runtime::WrongParameterType(parameter(id), *this);
}
cvsupport::checkNumericValue(castedValue, m_dsizeyParameter, *this);
m_dsizey = castedValue;
}
break;
case PARAMETER_DATA_FLOW:
{
const runtime::Enum & castedValue = runtime::data_cast<runtime::Enum>(value);
if(! castedValue.variant().isVariant(runtime::Variant::ENUM))
{
throw runtime::WrongParameterType(parameter(id), *this);
}
cvsupport::checkEnumValue(castedValue, m_dataFlowParameter, *this);
m_dataFlow = castedValue;
}
break;
default:
throw runtime::WrongParameterId(id, *this);
}
}
catch(runtime::BadCast&)
{
throw runtime::WrongParameterType(parameter(id), *this);
}
}
const std::vector<const runtime::Parameter*> WarpAffine::setupInitParameters()
{
std::vector<const runtime::Parameter*> parameters;
m_dataFlowParameter = new runtime::EnumParameter(PARAMETER_DATA_FLOW);
m_dataFlowParameter->setAccessMode(runtime::Parameter::NONE_WRITE);
m_dataFlowParameter->setTitle(L_("Data flow"));
m_dataFlowParameter->add(runtime::EnumDescription(runtime::Enum(MANUAL), L_("Manual")));
m_dataFlowParameter->add(runtime::EnumDescription(runtime::Enum(ALLOCATE), L_("Allocate")));
parameters.push_back(m_dataFlowParameter);
return parameters;
}
const std::vector<const runtime::Parameter*> WarpAffine::setupParameters()
{
std::vector<const runtime::Parameter*> parameters;
switch(int(m_dataFlow))
{
case(MANUAL):
{
m_affineMParameter = new runtime::MatrixParameter(PARAMETER_AFFINE_M, runtime::Variant::FLOAT_MATRIX);
m_affineMParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_affineMParameter->setTitle(L_("Affine transformation"));
m_affineMParameter->setRows(2);
m_affineMParameter->setCols(3);
parameters.push_back(m_affineMParameter);
m_dsizexParameter = new runtime::NumericParameter<runtime::UInt32>(PARAMETER_DSIZEX);
m_dsizexParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_dsizexParameter->setTitle(L_("Size X"));
parameters.push_back(m_dsizexParameter);
m_dsizeyParameter = new runtime::NumericParameter<runtime::UInt32>(PARAMETER_DSIZEY);
m_dsizeyParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_dsizeyParameter->setTitle(L_("Size Y"));
parameters.push_back(m_dsizeyParameter);
}
break;
case(ALLOCATE):
{
m_affineMParameter = new runtime::MatrixParameter(PARAMETER_AFFINE_M, runtime::Variant::FLOAT_MATRIX);
m_affineMParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_affineMParameter->setTitle(L_("Affine transformation"));
m_affineMParameter->setRows(2);
m_affineMParameter->setCols(3);
parameters.push_back(m_affineMParameter);
m_dsizexParameter = new runtime::NumericParameter<runtime::UInt32>(PARAMETER_DSIZEX);
m_dsizexParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_dsizexParameter->setTitle(L_("Size X"));
parameters.push_back(m_dsizexParameter);
m_dsizeyParameter = new runtime::NumericParameter<runtime::UInt32>(PARAMETER_DSIZEY);
m_dsizeyParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_dsizeyParameter->setTitle(L_("Size Y"));
parameters.push_back(m_dsizeyParameter);
}
break;
}
return parameters;
}
const std::vector<const runtime::Input*> WarpAffine::setupInputs()
{
std::vector<const runtime::Input*> inputs;
switch(int(m_dataFlow))
{
case(MANUAL):
{
m_srcDescription = new runtime::Input(INPUT_SRC, runtime::Variant::IMAGE);
m_srcDescription->setTitle(L_("Source"));
inputs.push_back(m_srcDescription);
m_dstDescription = new runtime::Input(INPUT_DST, runtime::Variant::IMAGE);
m_dstDescription->setTitle(L_("Destination"));
inputs.push_back(m_dstDescription);
}
break;
case(ALLOCATE):
{
m_srcDescription = new runtime::Input(INPUT_SRC, runtime::Variant::IMAGE);
m_srcDescription->setTitle(L_("Source"));
inputs.push_back(m_srcDescription);
}
break;
}
return inputs;
}
const std::vector<const runtime::Output*> WarpAffine::setupOutputs()
{
std::vector<const runtime::Output*> outputs;
switch(int(m_dataFlow))
{
case(MANUAL):
{
runtime::Output* dst = new runtime::Output(OUTPUT_DST, runtime::Variant::IMAGE);
dst->setTitle(L_("Destination"));
outputs.push_back(dst);
}
break;
case(ALLOCATE):
{
runtime::Output* dst = new runtime::Output(OUTPUT_DST, runtime::Variant::IMAGE);
dst->setTitle(L_("Destination"));
outputs.push_back(dst);
}
break;
}
return outputs;
}
void WarpAffine::initialize()
{
runtime::OperatorKernel::initialize(setupInputs(), setupOutputs(), setupParameters());
}
void WarpAffine::execute(runtime::DataProvider & provider)
{
switch(int(m_dataFlow))
{
case(MANUAL):
{
runtime::Id2DataPair srcInMapper(INPUT_SRC);
runtime::Id2DataPair dstInMapper(INPUT_DST);
provider.receiveInputData(srcInMapper && dstInMapper);
const runtime::Data* srcData = 0;
runtime::Data* dstData = 0;
runtime::ReadAccess srcReadAccess;
runtime::DataContainer inContainer = dstInMapper.data();
runtime::WriteAccess writeAccess(inContainer);
dstData = &writeAccess.get();
if(srcInMapper.data() == inContainer)
{
throw runtime::InputError(INPUT_SRC, *this, "Can not operate in place.");
}
else
{
srcReadAccess = runtime::ReadAccess(srcInMapper.data());
srcData = &srcReadAccess.get();
}
if(! srcData->variant().isVariant(m_srcDescription->variant()))
{
throw runtime::InputError(INPUT_SRC, *this, "Wrong input data variant.");
}
if(! dstData->variant().isVariant(m_dstDescription->variant()))
{
throw runtime::InputError(INPUT_DST, *this, "Wrong input data variant.");
}
const runtime::Image* srcCastedData = runtime::data_cast<runtime::Image>(srcData);
runtime::Image * dstCastedData = runtime::data_cast<runtime::Image>(dstData);
int width = int(m_dsizex);
int height = int(m_dsizey);
dstCastedData->initializeImage(width, height, width * srcCastedData->pixelSize(), dstCastedData->data(), srcCastedData->pixelType());
cv::Mat srcCvData = cvsupport::getOpenCvMat(*srcCastedData);
cv::Mat dstCvData = cvsupport::getOpenCvMat(*dstCastedData);
cv::Mat affineMCvData = cvsupport::getOpenCvMat(m_affineM);
int dsizexCvData = int(m_dsizex);
int dsizeyCvData = int(m_dsizey);
cv::warpAffine(srcCvData, dstCvData, affineMCvData, cv::Size(dsizexCvData, dsizeyCvData));
runtime::DataContainer dstOutContainer = inContainer;
runtime::Id2DataPair dstOutMapper(OUTPUT_DST, dstOutContainer);
provider.sendOutputData(dstOutMapper);
}
break;
case(ALLOCATE):
{
runtime::Id2DataPair srcInMapper(INPUT_SRC);
provider.receiveInputData(srcInMapper);
const runtime::Data* srcData = 0;
runtime::ReadAccess srcReadAccess;
srcReadAccess = runtime::ReadAccess(srcInMapper.data());
srcData = &srcReadAccess.get();
if(! srcData->variant().isVariant(m_srcDescription->variant()))
{
throw runtime::InputError(INPUT_SRC, *this, "Wrong input data variant.");
}
const runtime::Image* srcCastedData = runtime::data_cast<runtime::Image>(srcData);
cv::Mat srcCvData = cvsupport::getOpenCvMat(*srcCastedData);
cv::Mat dstCvData;
cv::Mat affineMCvData = cvsupport::getOpenCvMat(m_affineM);
int dsizexCvData = int(m_dsizex);
int dsizeyCvData = int(m_dsizey);
cv::warpAffine(srcCvData, dstCvData, affineMCvData, cv::Size(dsizexCvData, dsizeyCvData));
runtime::Image* dstCastedData = new cvsupport::Image(dstCvData);
runtime::DataContainer dstOutContainer = runtime::DataContainer(dstCastedData);
runtime::Id2DataPair dstOutMapper(OUTPUT_DST, dstOutContainer);
dstCastedData->initializeImage(dstCastedData->width(), dstCastedData->height(), dstCastedData->stride(), dstCastedData->data(), srcCastedData->pixelType());
provider.sendOutputData(dstOutMapper);
}
break;
}
}
} // cvimgproc
} // stromx
| [
"matz.fuchs@gmx.at"
] | matz.fuchs@gmx.at |
f84595fffe2751ec157d2d96842553bdace40f45 | be821060cc8c977d9d873a4c78635a8f21df8ee4 | /in_one_weekend+multithreading/material.h | 707c6a8c6aa5b9688cec5833dbf36b554c856bdc | [] | no_license | scriobhh/raytracing_in_one_weekend | d354e9773632a1788fa05ffeb5e4c79ae3d37c24 | 2cd3f3f5f00ce5a0d70328c82593c44916848537 | refs/heads/master | 2023-08-24T15:30:34.400123 | 2021-10-12T14:19:12 | 2021-10-12T14:19:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,329 | h | #ifndef MATERIALH
#define MATERIALH
#include "hitable.h"
#include "util.h"
class material
{
public:
virtual bool scatter(const ray& r_in, const hit_record& rec, rgb& attenuation, ray& scattered) const = 0;
};
point reflect(const point& v, const point& normal)
{
// the normal is the midpoint of the angle of reflection
// dot(v,normal) gives the magnitude of the vector mapped onto the normal
// dot(v,normal)*normal gives a vector in the direction of the normal with the magnitude of dot(v,normal)
// v hits at point on the surface and continues below the surface
// v - dot(v,normal)*normal gives a vector that is parallel to the surface
// v - 2*dot(v,normal)*normal gives a vector that is reflected off the surface
return v - 2*dot(v,normal)*normal;
}
// snell's law is used to determine the direction of the refracted ray
static bool refract(const point& v, const point& normal, float ni_over_nt, point& refracted)
{
// https://viclw17.github.io/2018/08/05/raytracting-dielectric-materials/
// the following maths is figured out by taking the equation R = A + B where:
// R is the refracted vector
// A is the component vector of R that is perpendicular to the normal
// B is the component vector of R that is parallel to the normal
// the equation is then re-arranged and substituted until the equation is in terms of the incoming vector, the normal and the refraction index
point uv = unit_vector(v);
float dt = dot(uv, normal);
// dt represents the steepness of the angle of the incoming vector
// the disciminant is larger for larger values of dt and smaller refractive indexes
// a refractive index of 1 or lower means refraction is guaranteed
float discriminant = 1.0 - ni_over_nt*ni_over_nt*(1-dt*dt);
// discriminant values:
// >0 means the ray is refracted
// 0 means the ray is parallel to the surface
// <0 means the ray is not refracted
if (discriminant > 0)
{
refracted = ni_over_nt*(uv - normal*dt) - normal*sqrt(discriminant);
return true;
}
else
return false;
}
// this is called Schlick's approximation
// it is a simple approximation of the reflection coefficient of the boundary of 2 mediums
// the reflection coefficient is used with the boundary of 2 mediums to calculate the amount of light that is reflected off the boundary
// of the incoming light that bounces off the boundary, a certain amount is reflected and the rest is refracted
// the reflectance of the boundary and angle is the ratio of the imcoing light that is reflected
// the ratio of incoming light that is refracted can be calculated by (1 - reflectance)
// e.g. if 80% of the energy of the incoming light is reflected, then schlick() should approximately return 0.8
// in that case the amount of light that is refracted would be 20%, and the ratio of incoming light to refracted light would be 0.2
// note that the reflection coefficient changes with angle (cosine)
static float schlick(float cosine, float ref_idx)
{
float r0 = (1-ref_idx) / (1+ref_idx);
r0 = r0*r0;
return r0 + (1-r0)*pow((1-cosine), 5);
}
// diffuse materials cause rays to bounce in random directions, called 'diffuse reflection'
class lambertian : public material
{
public:
lambertian(const rgb& a) : albedo(a) {}
virtual bool scatter(const ray& r_in, const hit_record& rec, rgb& attenuation, ray& scattered) const
{
// target is the point the ray will bounce to, it is calculated by:
// take the hitpoint
// add the tangent (which is a unit vector) to get a point that is 1 magnitude away from the surface of the sphere and perpendicular to the surface
// add a random point on a unit circle
point target = rec.hit_point + rec.normal + random_in_unit_sphere();
scattered = ray(rec.hit_point, target-rec.hit_point);
attenuation = albedo;
return true;
}
rgb albedo;
};
// metal materials reflect rays in a predictable way called 'specular reflection'
class metal : public material
{
public:
metal(const rgb& a, float f) : albedo(a) { if (f < 1) fuzz = f; else fuzz = 1; }
virtual bool scatter(const ray& r_in, const hit_record& rec, rgb& attenuation, ray& scattered) const
{
point reflected = reflect(unit_vector(r_in.direction()), rec.normal);
// fuzz is used to add a certain amount of randomness to the direction of the reflection, giving the appearance of a rough or fuzzy surface
scattered = ray(rec.hit_point, reflected + fuzz*random_in_unit_sphere());
attenuation = albedo;
// returns false if the reflected ray is parallel to the surface or goes below the surface
return (dot(scattered.direction(), rec.normal) > 0);
}
rgb albedo;
float fuzz;
};
// dielectric materials are transparent materials that reflect and refract rays
// in real life they produce both a reflected and refracted ray at the same time
// a certain amount of the light is reflected and the remaining amount is refracted
// the amount that is reflected vs refracted depends on the viewing angle, and there are angles where no refraction or no reflection take place
// see: snell's law, refractive index, critical angle, fresnel equations, reflection coefficient, schlick's approximation, brewster's angle, total internal reflection
// a design decision was made here to only account for one of the rays and randomly decide if the reflected ray or refracted ray should be returned
class dielectric : public material
{
public:
dielectric(float ri) : ref_idx(ri) {}
virtual bool scatter(const ray& r_in, const hit_record& rec, rgb& attenuation, ray& scattered) const
{
point outward_normal;
point reflected = reflect(r_in.direction(), rec.normal);
float ni_over_nt;
attenuation = rgb(1.0, 1.0, 1.0); // the glass surface absorbs nothing
point refracted;
float reflect_prob;
float cosine;
if(dot(r_in.direction(), rec.normal) > 0) // ray comes from inside the object
{
outward_normal = -rec.normal;
ni_over_nt = ref_idx;
// NOTE cosine is calculated slightly differently (see the commented out line below this) in the book, the * ref_idx part doesn't make any sense to me because it can result in cosine values that are >1 which doesn't make any sense, I changed it to not include the * ref_idx and the picture is almost the same, just that glass is slightly more reflective (I also changed the way the maths is written to make it slightly easier to read)
// see the no_ref_idx and with_ref_idx files in the build/ file
//cosine = ref_idx * dot(r_in.direction(), rec.normal) / r_in.direction().length();
cosine = dot(unit_vector(r_in.direction()), rec.normal);
}
else // ray comes from outside the object
{
outward_normal = rec.normal;
ni_over_nt = 1.0 / ref_idx;
cosine = -dot(r_in.direction(), rec.normal) / r_in.direction().length();
}
if(refract(r_in.direction(), outward_normal, ni_over_nt, refracted))
{
reflect_prob = schlick(cosine, ref_idx); // schlick() returns the ratio of incoming light that is reflected off the surface, e.g. if 80% of the energy of the incoming light is reflected, then schlick should approximately return 0.8
}
else
{
//scattered = ray(rec.hit_point, reflected);
reflect_prob = 1.0;
}
if(my_rand() < reflect_prob)
{
scattered = ray(rec.hit_point, reflected);
}
else
{
scattered = ray(rec.hit_point, refracted);
}
return true;
}
float ref_idx;
};
#endif
| [
"darren.delaney.2018@mumail.ie"
] | darren.delaney.2018@mumail.ie |
b79af887e96bc9088abfd818737529a2647a6547 | 046ef54cc9fd54d4dcccd6255684edce28d0afab | /src/fastqreader.h | 9275b27aa8b7816630db3526b99feaf6d8144b48 | [
"MIT"
] | permissive | OpenGene/defastq | d7510c2a1a58d0e2e173b6e9a0cf2ec2663f1bba | d037affcdc28463dc670ea773846d795fc6e586b | refs/heads/main | 2023-08-11T07:24:30.123071 | 2021-09-28T01:49:33 | 2021-09-28T01:49:33 | 398,289,322 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,176 | h | /*
MIT License
Copyright (c) 2021 Shifu Chen <chen@haplox.com>
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 FASTQ_READER_H
#define FASTQ_READER_H
#include <stdio.h>
#include <stdlib.h>
#include "simpleread.h"
#include "common.h"
#include <iostream>
#include <fstream>
#include "igzip_lib.h"
class FastqReader{
public:
FastqReader(string filename);
~FastqReader();
bool isZipped();
//this function is not thread-safe
//do not call read() of a same FastqReader object from different threads concurrently
SimpleRead* read();
bool eof();
public:
static bool isZipFastq(string filename);
static bool isFastq(string filename);
static bool test();
private:
void init();
void close();
void clearLineBreaks(char* line);
void readToBuf();
void readToBufIgzip();
bool bufferFinished();
private:
string mFilename;
struct isal_gzip_header mGzipHeader;
struct inflate_state mGzipState;
unsigned char *mGzipInputBuffer;
unsigned char *mGzipOutputBuffer;
size_t mGzipInputBufferSize;
size_t mGzipOutputBufferSize;
FILE* mFile;
bool mZipped;
char* mFastqBuf;
int mBufDataLen;
int mBufUsedLen;
bool mStdinMode;
bool mHasNoLineBreakAtEnd;
long mCounter;
};
#endif
| [
"chen@haplox.com"
] | chen@haplox.com |
0bcfd70283a39b26344ad3d934f53ee5349c4163 | 15a35df4de841aa5c504dc4f8778581c00397c87 | /Server1/Engine/Log/Logger.cpp | 4df293558c1ae2a2fefed13dc1afc70ff61edd14 | [] | no_license | binbin88115/server | b6197fef8f35276ff7bdf471a025091d65f96fa9 | e3c178db3b6c6552c60b007cac8ffaa6d3c43c10 | refs/heads/master | 2021-01-15T13:49:38.647852 | 2014-05-05T12:47:20 | 2014-05-05T12:47:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,248 | cpp | #include "Logger.h"
#include <stdarg.h>
#include <string>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
#define msgFormatA(buf,msg)\
do{\
va_list ap;\
va_start(ap, msg);\
vsprintf_s(buf,sizeof(buf),msg,ap);\
va_end(ap);\
}while(0)
class Log4xcc_Logger:public LoggerInterface{
public:
LoggerPtr rootLogger;
Log4xcc_Logger()
{
rootLogger = Logger::getRootLogger();
log4cxx::PropertyConfigurator::configure("log4cxx.properties");
}
virtual void debug(const char * pattern, ...)
{
char buf[1024] = {0};
msgFormatA(buf,pattern);
LOG4CXX_DEBUG(rootLogger,buf);
}
virtual void info(const char * pattern, ...)
{
char buf[1024] = {0};
msgFormatA(buf,pattern);
LOG4CXX_INFO(rootLogger,buf);
}
virtual void error(const char * pattern, ...)
{
char buf[1024] = {0};
msgFormatA(buf, pattern);
LOG4CXX_ERROR(rootLogger,buf);
}
virtual void warn(const char * pattern, ...)
{
char buf[1024] = {0};
msgFormatA(buf, pattern);
LOG4CXX_WARN(rootLogger,buf);
}
};
Log4xcc_Logger logger;
LoggerInterface * GetLogger()
{
return &logger;
} | [
"jjl_2009_hi@163.com"
] | jjl_2009_hi@163.com |
d7f28899b0f7b19b6fea0736cba35dab17d06ce3 | cf6c6ffd42d8186c842c80238ce42479807a8c15 | /src/Game/GameActor.cpp | 52ae984495528d476751921dc63ca70d37cf0581 | [] | no_license | schlenkibus/Always-On-Static-2D | fbe13f820cc4384a29acee290cedbc1d70d81878 | f4bad6d6a5be9bc972f4c1c0fe167986e3a8f292 | refs/heads/master | 2021-09-06T20:01:07.954608 | 2018-02-10T18:26:38 | 2018-02-10T18:26:38 | 118,633,698 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,604 | cpp | #include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Window/Keyboard.hpp>
#include <iostream>
#include "GameActor.h"
#include "../Box2D/PhysicsWorld.h"
GameActor::GameActor(PhysicsWorld& w, sf::Texture& tex, sf::Vector2f pos, std::string name, bool staticActor) :
m_texture{tex},
m_ActorName{std::move(name)},
m_bodyDef{}, m_shape{}, m_position{pos} {
//Graphics
m_sprite.setPosition(m_position.getAsSFML());
m_sprite.setTexture(tex);
//Physics
m_shape.SetAsBox(tex.getSize().x, tex.getSize().y / 2);
if(staticActor) {
m_bodyDef.type = b2_staticBody;
} else {
m_bodyDef.type = b2_dynamicBody;
}
m_bodyDef.position.Set(m_position.getAsBox2D().x, m_position.getAsBox2D().y);
m_body = w.getWorld()->CreateBody(&m_bodyDef);
m_fixture = m_body->CreateFixture(&m_shape, 0.005f);
m_body->SetBullet(true);
}
GameActor::~GameActor() {
}
std::string GameActor::getName() {
return m_ActorName;
}
void GameActor::update(double deltaTime) {
m_position = m_body->GetPosition();
m_sprite.setPosition(m_position.getAsSFML().x, m_position.getAsSFML().y - m_sprite.getTexture()->getSize().y / 2);
m_sprite.setRotation(m_body->GetAngle());
}
void GameActor::draw(sf::RenderWindow& window) {
window.draw(m_sprite);
}
b2Body* GameActor::getBody() {
return m_body;
}
sf::Sprite& GameActor::getSprite() {
return m_sprite;
} | [
"justus.scheil@parteimail.de"
] | justus.scheil@parteimail.de |
b75288b97b0b640959dea89cd98ad7cd29f987a6 | 78bec4bf1516360edb966c653fd5b68e4b20e57a | /Mercado/src/Estabelecimento.cpp | 968d7f871d0bf1c82193de17b0747ae340dd5cd8 | [] | no_license | artoop/LP1IMD | ae18a8942af8623f24600259b832a9988994a7ed | 622829d09e97a25cd3c3f1e63fdbc4759cd5c4ce | refs/heads/master | 2022-11-20T21:34:52.340801 | 2020-07-20T13:47:18 | 2020-07-20T13:47:18 | 272,798,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,743 | cpp | #include "Estabelecimento.hpp"
#include <iostream>
#include <iomanip>
Estabelecimento::Estabelecimento()
{
}
Estabelecimento::Estabelecimento(const std::string& arquivo)
{
this->arquivo = arquivo;
ler_arquivo();
}
Estabelecimento::~Estabelecimento()
{
}
std::string Estabelecimento::unidade_to_string(UnidadeMedida unidade)
{
switch(unidade)
{
case pacote: return "Pacote"; break;
case lata: return "Lata"; break;
case quilo: return "Quilo"; break;
case desconhecido: return "desconhecido"; break;
default: return "desconhecido"; break;
}
}
UnidadeMedida Estabelecimento::str_to_unidade(std::string str_unidade)
{
if(str_unidade.compare("Pacote") == 0)
{
return pacote;
}
else if(str_unidade.compare("Lata") == 0)
{
return lata;
}
else if(str_unidade.compare("Quilo") == 0)
{
return quilo;
}
else return desconhecido;
}
double Estabelecimento::str_to_double(std::string str_double)
{
str_double = str_double.substr(4, str_double.length()-5);
return stod(str_double);
}
void Estabelecimento::ler_arquivo()
{
std::ifstream arquivo_entrada(arquivo);
std::string linha;
if(arquivo_entrada.fail())
{
std::cout << "Arquivo inexistente." << std::endl;
}
else
{
std::string cod, nome, unidadeMed, preco, qtd;
std::getline(arquivo_entrada, linha);
while(std::getline(arquivo_entrada, linha))
{
std::stringstream stream(linha);
std::getline(stream, cod, ',' );
std::getline(stream, nome, ',' );
std::getline(stream, unidadeMed, ',');
std::getline(stream, preco, ',');
std::getline(stream, qtd);
produtos.push_back(Produto(cod, nome,str_to_unidade(unidadeMed), str_to_double(preco)));
estoque[cod] = stoi(qtd);
}
}
arquivo_entrada.close();
}
void Estabelecimento::listar()
{
system("clear");
std::cout << "::::::::::::PRODUTOS DISPONIVEIS:::::::::::: " << std::endl << std::endl;
for(auto& p : produtos)
{
int qtd = estoque[p.getCodigo()];
if(qtd > 0)
{
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << "- cod: " << p.getCodigo() << " | " << p.getNome()
<< " - R$ " << p.getPreco() << "/" << unidade_to_string(p.getUnidade()) << " | qtd: " << qtd << std::endl;
}
}
}
bool Estabelecimento::em_estoque(std::string codigo, int quantidade)
{
return estoque[codigo] >= quantidade;
}
Produto* Estabelecimento::busca(std::string codigo)
{
for(auto& c : produtos)
{
if (codigo == c.getCodigo())
{
return &c;
}
}
return nullptr;
}
void Estabelecimento::caixa()
{
std::ofstream arquivo_caixa("caixa.csv");
double total_vendas = 0;
arquivo_caixa << ":::::::PRODUTOS VENDIDOS::::::: " << std::endl << std::endl;
for (auto& v : produtos)
{
total_vendas += v.getPreco()*vendas[v.getCodigo()];
if(vendas[v.getCodigo()] > 0)
{
arquivo_caixa << "cod: " << v.getCodigo() << " | prod: " << v.getNome()
<< " | preco: " << v.getPreco() << "/" << unidade_to_string(v.getUnidade())
<< " | qtd: " << vendas[v.getCodigo()] << " | total: R$ "
<< (vendas[v.getCodigo()])*(v.getPreco()) << std::endl;
}
}
arquivo_caixa << std::endl << "Faturamento total: R$ " << total_vendas << std::endl;
}
void Estabelecimento::venda(std::string codigo, int quantidade)
{
estoque[codigo] -= quantidade;
vendas[codigo] += quantidade;
} | [
"arturbprocopio@gmail.com"
] | arturbprocopio@gmail.com |
ee72525adf8f367aa11cbd53f79a1de4db32498b | 41f9175f449a5a1f1e45339d92f1f74476e37d1e | /C-C/lanqiao/判断闰年.cpp | 11976d0bda4b4e11315aed4c79394e03a2b68f16 | [] | no_license | Vicebery/Algorithm-Programs | 10753b6344156c42d8673bc0196fb475626dd327 | 80628aabcd2a203907ccb645984b92c1e05eddfc | refs/heads/master | 2021-06-02T21:42:58.696910 | 2020-08-21T03:06:05 | 2020-08-21T03:06:05 | 58,551,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | #include"iostream"
using namespace std;
int main()
{
int y;
cin>>y;
if(y%400==0||(y%4==0&&y%100!=0))
cout<<"yes";
else
cout<<"no";
return 0;
}
| [
"Vicebery@163.com"
] | Vicebery@163.com |
83c285c655d10cb0ff1405015092a760b1a17ea0 | 3900a8feacf56a2db64c631f822c44191a714dc4 | /Examples/SDKLibrary/interface/server/portable/events/data_types/alarm_condition_type_data_t.cpp | 123748cbc5ecc34ef14669a653b53cccbdb4da4c | [
"MIT"
] | permissive | JayeshThamke/robot-examples | fc45f61d638001f2358a1b08c7543aa4f3b10664 | afc6b8b10809988b03663d703203625927e66e8f | refs/heads/master | 2020-03-08T17:18:09.409824 | 2018-03-29T20:41:10 | 2018-03-29T20:41:10 | 128,265,254 | 1 | 0 | null | 2018-04-05T21:16:55 | 2018-04-05T21:16:55 | null | UTF-8 | C++ | false | false | 15,491 | cpp |
/* ------------------------------------------------------------------------------------------------------------------
COPYRIGHT (c) 2009 - 2017
HONEYWELL INC.,
ALL RIGHTS RESERVED
This software is a copyrighted work and/or information protected as a trade
secret. Legal rights of Honeywell Inc. in this software are distinct from
ownership of any medium in which the software is embodied. Copyright or trade
secret notices included must be reproduced in any copies authorized by
Honeywell Inc. The information in this software is subject to change without
notice and should not be considered as a commitment by Honeywell Inc.
--------------------------------------------------------------------------------------------------------------------- */
#include "alarm_condition_type_data_t.h"
#if ((UASDK_INCLUDE_EVENTS > 0) && (UASDK_INCLUDE_ALARMS_AND_CONDITIONS > 0))
#include "opcua_node_id_numeric_t.h"
#include "opcua_server_state_t.h"
namespace uasdk
{
UA_DEFINE_RUNTIME_TYPE(AlarmConditionTypeData_t, AcknowledgeableConditionTypeData_t);
AlarmConditionTypeData_t::AlarmConditionTypeData_t()
{
}
AlarmConditionTypeData_t::~AlarmConditionTypeData_t()
{
}
bool AlarmConditionTypeData_t::IsOfType(const uint32_t typeId, uint16_t namespaceindex) const
{
if(namespaceindex != 0) return false;
return typeId == 2915 || AcknowledgeableConditionTypeData_t::IsOfType(typeId, namespaceindex);
}
Status_t AlarmConditionTypeData_t::Initialise()
{
Status_t rtnStatus = OpcUa_Good;
browseName = new SafeRefCount_t<String_t>();
UASDK_RETURN_OUT_OF_MEMORY_IF_NULL(browseName);
rtnStatus = browseName->CopyFrom("AlarmConditionType");
UASDK_RETURN_STATUS_ONLY_IF_BAD(rtnStatus.Value());
inputNode.reset();
suppressedOrShelved.reset();
maxTimeShelved.reset();
ShelvingState_unshelveTime.reset();
return AcknowledgeableConditionTypeData_t::Initialise();
}
uint32_t AlarmConditionTypeData_t::TypeId(uint16_t& namespaceIndex) const
{
namespaceIndex = 0;
return AlarmConditionTypeData_t::TYPE_ID;
}
IntrusivePtr_t<BaseDataType_t> AlarmConditionTypeData_t::AttributeValue(const uint32_t& typeId, const ArrayUA_t<QualifiedName_t>&browsePath, const uint32_t &_attributeId, const String_t& _indexRange, const ArrayUA_t<String_t> & locales, Status_t &result)
{
UASDK_UNUSED(_indexRange);
result = OpcUa_BadInvalidArgument;
IntrusivePtr_t<BaseDataType_t> emptyResult;
emptyResult.reset();
uint16_t namespaceIndex = 0;
if (!IsOfType(typeId, namespaceIndex))
{
return emptyResult;
}
char nameStr[1024] = { 0 };
char *loc = &nameStr[0];
uint32_t nameStrSize = static_cast<uint32_t>(sizeof(nameStr));
for (uint32_t index = 0; index < browsePath.Count() && static_cast<uint32_t>(loc - nameStr) < (nameStrSize - 2); ++index)
{
UASDK_strncat(loc, nameStrSize - (loc - nameStr), (char*)(browsePath[index]->Name().Payload().Data()), browsePath[index]->Name().Payload().Length());
loc += browsePath[index]->Name().Payload().Length();
if (index < (browsePath.Count() - 1) && static_cast<uint32_t>(loc - nameStr) < (nameStrSize - 2))
{
*loc = '.';
++loc;
*loc = '\0';
}
nameStrSize = static_cast<uint32_t>(sizeof(nameStr));
}
/* Start class specific attributes */
if(UASDK_strcmp(nameStr, "InputNode") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return inputNode;
};
if(UASDK_strcmp(nameStr, "SuppressedOrShelved") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return suppressedOrShelved;
};
if(UASDK_strcmp(nameStr, "MaxTimeShelved") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return maxTimeShelved;
};
if(UASDK_strcmp(nameStr, "ActiveState") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 11
{
result = OpcUa_Good;
IntrusivePtr_t<LocalizedText_t> localizedText;
localizedText = new SafeRefCount_t<LocalizedText_t>();
if (localizedText.is_set())
{
if (activeState.is_set() && activeState->Value().is_set())
{
localizedText->CopyFrom(*activeState->Value()->GetLocalizedText(locales, result));
}
}
else
{
result = OpcUa_BadOutOfMemory;
}
return localizedText;
}
if(UASDK_strcmp(nameStr, "ActiveState.Id") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->Id();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ActiveState.EffectiveDisplayName") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->EffectiveDisplayName();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ActiveState.TransitionTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->TransitionTime();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ActiveState.EffectiveTransitionTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->EffectiveTransitionTime();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "SuppressedState") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 11
{
result = OpcUa_Good;
IntrusivePtr_t<LocalizedText_t> localizedText;
localizedText = new SafeRefCount_t<LocalizedText_t>();
if (localizedText.is_set())
{
if (suppressedState.is_set() && suppressedState->Value().is_set())
{
localizedText->CopyFrom(*suppressedState->Value()->GetLocalizedText(locales, result));
}
}
else
{
result = OpcUa_BadOutOfMemory;
}
return localizedText;
}
if(UASDK_strcmp(nameStr, "SuppressedState.Id") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(SuppressedState().is_set())
{
result = OpcUa_Good;
return SuppressedState()->Id();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "SuppressedState.TransitionTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(SuppressedState().is_set())
{
result = OpcUa_Good;
return SuppressedState()->TransitionTime();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ShelvingState.UnshelveTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return ShelvingState_unshelveTime;
};
/* end class specific attributes */
return AcknowledgeableConditionTypeData_t::AttributeValue(typeId, browsePath, _attributeId, _indexRange, locales, result);
}
IntrusivePtr_t<const BaseDataType_t> AlarmConditionTypeData_t::AttributeValue(const uint32_t& typeId, const ArrayUA_t<QualifiedName_t>&browsePath, const uint32_t &_attributeId, const String_t& _indexRange, const ArrayUA_t<String_t> & locales, Status_t &result) const
{
UASDK_UNUSED(_indexRange);
IntrusivePtr_t<BaseDataType_t> emptyResult;
emptyResult.reset();
result = OpcUa_BadInvalidArgument;
uint16_t namespaceIndex = 0;
if (!IsOfType(typeId, namespaceIndex))
{
return emptyResult;
}
char nameStr[1024] = { 0 };
char *loc = &nameStr[0];
uint32_t nameStrSize = static_cast<uint32_t>(sizeof(nameStr));
for (uint32_t index = 0; index < browsePath.Count() && static_cast<uint32_t>(loc - nameStr) < (nameStrSize - 2); ++index)
{
UASDK_strncat(loc, nameStrSize - (loc - nameStr), (char*)(browsePath[index]->Name().Payload().Data()), browsePath[index]->Name().Payload().Length());
loc += browsePath[index]->Name().Payload().Length();
if (index < (browsePath.Count() - 1) && static_cast<uint32_t>(loc - nameStr) < (nameStrSize - 2))
{
*loc = '.';
++loc;
*loc = '\0';
}
nameStrSize = static_cast<uint32_t>(sizeof(nameStr));
}
/* Start class specific attributes */
if(UASDK_strcmp(nameStr, "InputNode") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return inputNode;
};
if(UASDK_strcmp(nameStr, "SuppressedOrShelved") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return suppressedOrShelved;
};
if(UASDK_strcmp(nameStr, "MaxTimeShelved") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return maxTimeShelved;
};
if(UASDK_strcmp(nameStr, "ActiveState") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 11
{
result = OpcUa_Good;
IntrusivePtr_t<LocalizedText_t> localizedText;
localizedText = new SafeRefCount_t<LocalizedText_t>();
if (localizedText.is_set())
{
if (activeState.is_set() && activeState->Value().is_set())
{
localizedText->CopyFrom(*activeState->Value()->GetLocalizedText(locales, result));
}
}
else
{
result = OpcUa_BadOutOfMemory;
}
return localizedText;
}
if(UASDK_strcmp(nameStr, "ActiveState.Id") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->Id();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ActiveState.EffectiveDisplayName") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->EffectiveDisplayName();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ActiveState.TransitionTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->TransitionTime();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ActiveState.EffectiveTransitionTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(ActiveState().is_set())
{
result = OpcUa_Good;
return ActiveState()->EffectiveTransitionTime();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "SuppressedState") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 11
{
result = OpcUa_Good;
IntrusivePtr_t<LocalizedText_t> localizedText;
localizedText = new SafeRefCount_t<LocalizedText_t>();
if (localizedText.is_set())
{
if (suppressedState.is_set() && suppressedState->Value().is_set())
{
localizedText->CopyFrom(*suppressedState->Value()->GetLocalizedText(locales, result));
}
}
else
{
result = OpcUa_BadOutOfMemory;
}
return localizedText;
}
if(UASDK_strcmp(nameStr, "SuppressedState.Id") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(SuppressedState().is_set())
{
result = OpcUa_Good;
return SuppressedState()->Id();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "SuppressedState.TransitionTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
if(SuppressedState().is_set())
{
result = OpcUa_Good;
return SuppressedState()->TransitionTime();
}
result = OpcUa_BadAttributeIdInvalid;
return emptyResult;
};
if(UASDK_strcmp(nameStr, "ShelvingState.UnshelveTime") == 0 && _attributeId == AttributeId_t::ATTRIBUTE_ID_VALUE) //From 4
{
result = OpcUa_Good;
return ShelvingState_unshelveTime;
};
/* end class specific attributes */
return AcknowledgeableConditionTypeData_t::AttributeValue(typeId, browsePath, _attributeId, _indexRange, locales, result);
}
Status_t AlarmConditionTypeData_t::CopyTo(IntrusivePtr_t<BaseDataType_t>& destination) const
{
return CopyToDestination(*this, destination);
}
Status_t AlarmConditionTypeData_t::CopyFrom(const BaseDataType_t& source)
{
IntrusivePtr_t<const AlarmConditionTypeData_t> ptr = RuntimeCast<const AlarmConditionTypeData_t*>(source);
if (!ptr.is_set())
{
return OpcUa_BadTypeMismatch;
}
return CopyFrom(*ptr);
}
Status_t AlarmConditionTypeData_t::CopyFrom(const AlarmConditionTypeData_t& source)
{
Status_t result = OpcUa_Good;
inputNode.reset();
if(source.inputNode.is_set())
{
result = source.inputNode->CopyToNodeId(inputNode);
if(result.IsBad())
{
return result;
}
}
suppressedOrShelved.reset();
if(source.suppressedOrShelved.is_set())
{
suppressedOrShelved = new SafeRefCount_t<Boolean_t>();
if(!suppressedOrShelved.is_set())
{
return OpcUa_BadOutOfMemory;
}
result = suppressedOrShelved->CopyFrom(*source.SuppressedOrShelved());
if(result.IsBad())
{
return result;
}
}
maxTimeShelved.reset();
if(source.maxTimeShelved.is_set())
{
maxTimeShelved = new SafeRefCount_t<Duration_t>();
if(!maxTimeShelved.is_set())
{
return OpcUa_BadOutOfMemory;
}
result = maxTimeShelved->CopyFrom(*source.MaxTimeShelved());
if(result.IsBad())
{
return result;
}
}
activeState.reset();
if(source.activeState.is_set())
{
result = source.activeState->CopyTo(activeState);
if(result.IsBad())
{
return result;
}
}
suppressedState.reset();
if(source.suppressedState.is_set())
{
result = source.suppressedState->CopyTo(suppressedState);
if(result.IsBad())
{
return result;
}
}
ShelvingState_unshelveTime.reset();
if(source.ShelvingState_unshelveTime.is_set())
{
ShelvingState_unshelveTime = new SafeRefCount_t<Duration_t>();
if(!ShelvingState_unshelveTime.is_set())
{
return OpcUa_BadOutOfMemory;
}
result = ShelvingState_unshelveTime->CopyFrom(*source.ShelvingState_UnshelveTime());
if(result.IsBad())
{
return result;
}
}
result = AcknowledgeableConditionTypeData_t::CopyFrom(source);
return result;
}
} // namespace
#endif //((UASDK_INCLUDE_EVENTS > 0) && (UASDK_INCLUDE_ALARMS_AND_CONDITIONS > 0))
| [
"Andrew.Cullen@beeond.net"
] | Andrew.Cullen@beeond.net |
6f274f8f9d2030c600b3bf32721b123f2e085b5b | be4fd7c1bf5b5d6a998e31ebf00194e25100b662 | /landTest.cpp | 2951d84d7d753064a0d066157894330c661ce779 | [] | no_license | kirkosyn/C-project | 53de1c442888c6ffcc78707e7ccb59c50c19c977 | 0d2070b2844e1d49d7e4146401c0599ea89d4f88 | refs/heads/master | 2020-03-11T16:02:04.085184 | 2018-04-18T18:19:58 | 2018-04-18T18:19:58 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 4,714 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "GeographicArea.h"
#include "WaterArea.h"
#include "LandArea.h"
#include "Country.h"
#include "Tests.h"
///funkcja zapisująca stan obiektu klasy WaterArea do pliku
void writeToFileTests::waterAreaTest()
{
std::fstream file;
file.open("plikwater.txt", std::ios::out | std::ios::app);
WaterArea sea;
sea.setObject();
file << sea;
file.close();
}
///funkcja zapisująca stan obiektu klasy LandArea do pliku
void writeToFileTests::landAreaTest()
{
std::fstream file;
file.open("plikland.txt", std::ios::out | std::ios::app);
LandArea land;
land.setObject();
file << land;
file.close();
}
///funkcja wczytująca stan obiektu klasy WaterArea z pliku
void readFromFileTests::waterAreaTest()
{
std::fstream file;
file.open("plikwater.txt", std::ios::in);
if (!file.good())
{
std::cout << "File doesn't exist!\n";
return;
}
WaterArea sea;
std::vector<WaterArea> vectorsea;
std::vector<WaterArea>::iterator it;
while (!file.eof())
{
file.seekg(file.tellg());
file >> sea;
vectorsea.push_back(sea);
}
unsigned int i = 0;
for (it = vectorsea.begin(); i < (vectorsea.size() - 1); it++, i++)
(*it).showArea();
file.close();
}
///funkcja wczytująca stan obiektu klasy LandArea z pliku
void readFromFileTests::landAreaTest()
{
std::fstream file;
file.open("plikland.txt", std::ios::in);
if (!file.good())
{
std::cout << "File doesn't exist!\n";
return;
}
LandArea land;
std::vector<LandArea> vectorland;
std::vector<LandArea>::iterator it;
while (!file.eof())
{
file.seekg(file.tellg());
file >> land;
vectorland.push_back(land);
}
unsigned int i = 0;
for (it = vectorland.begin(); i < (vectorland.size() - 1); it++, i++)
(*it).showArea();
file.close();
}
///funkcja testująca automatyczne obiekty klasy WaterArea
void automaticTests::waterAreaTest()
{
WaterArea reservoir;
reservoir.showArea();
// setting object
reservoir.setTypeOfWater("Sweet_water");
reservoir.assignArea(991.14, 11.55);
reservoir.setHemisphere("NW");
reservoir.setLatitude(89);
reservoir.setLongitude(11);
std::cout << "reservoir latitude: " << reservoir.getLatitude() << std::endl;
std::cout << "reservoir longitude: " << reservoir.getLongitude() << std::endl << std::endl;
reservoir.setLandform(BAY);
reservoir.setLatitude(23);
reservoir.setLongitude(122);
reservoir.showArea();
// setting random values
reservoir.setObject();
reservoir.showArea();
}
///funkcja testująca automatyczne obiekty klasy LandArea
void automaticTests::landAreaTest()
{
LandArea land;
land.showArea();
// setting object
land.assignArea(200.13, 66.3);
land.setHemisphere("NE");
land.setLandform(TUNDRA);
land.setLatitude(55);
land.setLongitude(99);
std::cout << "land latitude: " << land.getLatitude() << std::endl;
std::cout << "land longitude: " << land.getLongitude() << std::endl << std::endl;
land.setContinent("Asia");
land.setBorders(9191);
land.setLatitude(3);
land.setLongitude(150);
land.showArea();
// setting random values
land.setObject();
land.showArea();
}
///funkcja testująca obiekty klas WaterArea, LandArea, GeographicArea, Country
void automaticTests::allClassesTest()
{
GeographicArea *areas[3];
LandArea land;
WaterArea reservoir;
Country country;
areas[0] = &land;
areas[1] = &reservoir;
areas[2] = &country;
for (int i = 0; i < 3; i++)
{
areas[i]->assignArea(911.1, 41.55);
areas[i]->setHemisphere("SW");
areas[i]->setLatitude(41);
areas[i]->setLongitude(111);
areas[i]->showArea();
}
std::cout << "\n****\n";
for (int i = 0; i < 3; i++)
{
areas[i]->setObject();
areas[i]->showArea();
}
std::vector<Country> countries;
std::vector<LandArea> lands;
std::vector<WaterArea> reservoirs;
std::vector<Country>::iterator itc;
std::vector<LandArea>::iterator itl;
std::vector<WaterArea>::iterator itr;
countries.push_back(Country());
countries.push_back(Country("Norway", 138.14, PartnerCountry()));
countries.push_back(Country("Sweden", 4434.55, PartnerCountry(516,"Denmark", "Pears")));
lands.push_back(LandArea());
lands.push_back(land);
reservoirs.push_back(WaterArea());
reservoirs.push_back(reservoir);
std::cout << "\n****";
std::cout << "\nCountry vector\n\n";
for (itc = countries.begin(); itc != countries.end(); itc++)
{
(*itc).setObject();
(*itc).showCountry();
(*itc).showArea();
}
std::cout << "\n****";
std::cout << "\nLandArea vector\n\n";
for (itl = lands.begin(); itl != lands.end(); itl++)
(*itl).showArea();
std::cout << "\n****";
std::cout << "\nWaterArea vector\n\n";
for (itr = reservoirs.begin(); itr != reservoirs.end(); itr++)
(*itr).showArea();
} | [
"kokoska300@op.pl"
] | kokoska300@op.pl |
7a1c859f8cfa6af53276b5498fcc39b08760f9ee | f90920085074e79a37048155750b80e5e884c5d2 | /tsrc/testdriver/siptester/src/TCmdSendReferWithinDialog.cpp | d5753157735bdc1a393e91b8514132696fadda71 | [] | no_license | piashishi/mce | fec6847fc9b4e01c43defdedf62ef68f55deba8e | 8c0f20e0ebd607fb35812fd02f63a83affd37d74 | refs/heads/master | 2021-01-25T06:06:18.042653 | 2016-08-13T15:38:09 | 2016-08-13T15:38:09 | 26,538,858 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,337 | cpp | /*
* Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Implementation
*
*/
#include <sipclienttransaction.h>
#include <sipmessageelements.h>
#include <sipclienttransaction.h>
#include <sipreferdialogassoc.h>
#include <sipnotifydialogassoc.h>
#include "TCmdSendReferWithinDialog.h"
#include "SIPConstants.h"
/**
* INPUT:
* Headers: Contact*, Content-Type*, Content-Encoding*, Route*
* Parameters: Content*
* IDs: NotifyDialogId*, ReferDialogId*
*
* OUTPUT:
* Parameters: -
* IDs: TransactionId, ReferDialogId
*/
void TCmdSendReferWithinDialog::ExecuteL()
{
// -- Setup ---------------------------------------------------------------
// Get SIP objects from registry
CSIPDialogAssocBase* dialogAssoc = GetAnyDialogAssocL();
// Extract required headers
CSIPReferToHeader* referToHeader = ExtractReferToHeaderLC();
// Create a new dialog association
CSIPReferDialogAssoc* newdialogAssoc =
CSIPReferDialogAssoc::NewL( dialogAssoc->Dialog(),
referToHeader );
CleanupStack::Pop( referToHeader );
CleanupStack::PushL( newdialogAssoc );
// Extract both headers (that are still left) and content.
CSIPMessageElements* elements = ExtractHeadersAndContentLC();
// -- Execution -----------------------------------------------------------
// Start SIP refer transaction.
CSIPClientTransaction* transaction =
newdialogAssoc->SendReferL( elements );
CleanupStack::Pop( elements );
// -- Response creation ---------------------------------------------------
AddIdResponseL( KTransactionId, transaction );
CleanupStack::Pop( newdialogAssoc );
AddIdResponseL( KReferDialogId, newdialogAssoc );
}
TBool TCmdSendReferWithinDialog::Match( const TTcIdentifier& aId )
{
return TTcSIPCommandBase::Match( aId, _L8("SendReferWithinDialog") );
}
TTcCommandBase* TCmdSendReferWithinDialog::CreateL( MTcTestContext& aContext )
{
return new( ELeave ) TCmdSendReferWithinDialog( aContext );
}
| [
"piashishi@qq.com"
] | piashishi@qq.com |
d1f191bcf2cbcbec6a62c49c986591250a6c68db | b3656c674b8c55f10586a63e7ba0da1c89b6087b | /lscvm/lscvm-mem.cpp | db94f80343f67c147d5ef20f98303a71fa56a976 | [] | no_license | zhiayang/cddc19 | e30975413643c7ebfd82d55564b138dc1515df24 | c1374630d61865a641d2788c8efdff9608b004c3 | refs/heads/master | 2020-05-30T14:40:54.098874 | 2019-06-15T01:42:37 | 2019-06-15T01:42:37 | 189,796,877 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,830 | cpp | // lscvm-memoryinator.cpp
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <map>
#include <vector>
#include <string>
#include <iostream>
std::string createNumber(int num)
{
if(num < 0)
{
return "a" + createNumber(-num) + "S";
}
else if(num < 10)
{
return std::string(1, (char) (num + 'a'));
}
else if(num == 10)
{
return "cfM";
}
else
{
switch(num)
{
case 11: return "fgA";
case 12: return "ggA";
case 13: return "ghA";
case 14: return "hhA";
case 15: return "hiA";
case 16: return "iiA";
case 17: return "ijA";
case 18: return "jjA";
case 19: return "jjAbA";
case 20: return "efM";
case 21: return "dhM";
case 22: return "efMcA";
case 23: return "efMdA";
case 24: return "diM";
case 25: return "ffM";
case 26: return "ffMbA";
case 27: return "djM";
case 28: return "ehM";
case 29: return "ehMbA";
case 30: return "fgM";
case 31: return "fgMbA";
case 32: return "eiM";
case 'a': return "jjMjAhA";
case 'b': return "hhAhM";
case 'c': return "jcAjM";
case 'd': return "effMM";
case 'e': return "effMMbA";
case 'f': return "jiAgM";
case 'g': return "hhAhMfA";
case 'h': return "jeAiM";
case 'i': return "hdfMM";
case 'j': return "hdfMMbA";
case 'A': return "iiMbA";
case 'B': return "iiMcA";
case 'C': return "iiMdA";
case 'D': return "iiMeA";
case 'E': return "iiMfA";
case 'F': return "iiMgA";
case 'G': return "iiMhA";
case 'H': return "iiMiA";
case 'I': return "iiMjA";
case 'J': return "ijMcA";
case 'K': return "ijMdA";
case 'M': return "ijMfA";
case 'P': return "ijMiA";
case 'R': return "jjMbA";
case 'S': return "jjMcA";
case 'V': return "jjMfA";
case 'Z': return "jjMjA";
// if we run into code size problems, i'm sure this algo can be optimised.
default: {
std::string ret;
int x = num / 9;
ret = createNumber(x) + "jM";
int y = num % 9;
if(y > 0) ret += createNumber(y) + "A";
return ret;
} break;
}
}
}
int main(int argc, char** argv)
{
bool squeeze = false;
std::string input;
if(argc > 1)
{
if(strcmp("--squeeze", argv[1]) == 0)
{
squeeze = true;
}
else
{
fprintf(stderr, "unknown option '%s'\n", argv[1]);
exit(-1);
}
}
while(true)
{
printf("string: ");
std::getline(std::cin, input);
printf("address: ");
std::string ofs;
std::getline(std::cin, ofs);
int offset = 0;
if(!ofs.empty()) offset = std::stol(ofs);
std::string output;
std::map<char, size_t> offsets;
if(squeeze)
{
// dump all the characters out.
std::vector<char> chars = {
'Z', 'V', 'S', 'R', 'K', 'J', 'I', 'H', 'G', 'E', 'D', 'C', 'B',
'M', 'A', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a', 'F', 'P'
};
for(auto thechar : chars)
{
output += createNumber(thechar);
offsets.insert(std::make_pair(thechar, chars.size() - offsets.size()));
}
}
// write the offset once
output += createNumber(offset);
for(size_t i = 0; i < input.size(); i++)
{
if(squeeze)
{
// see if we will benefit from fetching.
auto _fetchOfs = offsets[input[i]];
assert(_fetchOfs > 0);
// get how many chars it takes to fetch the thing from stack
auto fetchOfs = createNumber(_fetchOfs) + "F";
auto number = createNumber(input[i]);
if(fetchOfs.size() < number.size())
output += fetchOfs;
else
output += number;
}
else
{
output += createNumber(input[i]); // this is the value
}
// K writes to memory. format: [value] [address] K
output += "bF"; // fetch the offset
output += "K";
// add one
if(i + 1 < input.size())
output += "bA";
}
printf("\n\noutput (%zu chars):\n", output.size());
printf("\n%s\n\n", output.c_str());
}
}
| [
"zhiayang@gmail.com"
] | zhiayang@gmail.com |
a2e7b2452bab0d31f25f727b8ecee039acc83e99 | b2f864c29fceeb2ba4371ede89dfaab898bd588b | /FORTRESS/shlee_fortress.cpp | 16edf961d16be2666ec9db0f54ba2d1f3ebbe094 | [] | no_license | kdw808/algorithm-study | 6d13e7da8bdef9ee964b9c57f37e829b1675610b | cdf49c68f642df58c261cc29ed4ec28b03407755 | refs/heads/master | 2020-05-22T07:00:24.338378 | 2017-01-08T01:10:59 | 2017-01-08T01:10:59 | 60,958,955 | 5 | 5 | null | 2016-11-21T16:07:17 | 2016-06-12T09:33:02 | Java | UTF-8 | C++ | false | false | 2,058 | cpp | #include <stdbool.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
#define N_MAX 100
#define R_MAX 20000
struct wall_t
{
float x;
float y;
float r;
int height;
vector<wall_t> childs;
void add(wall_t rhs) {
for (vector<wall_t>::size_type i = 0, n = childs.size(); i < n; i++) {
if (childs[i].contain(rhs)) {
childs[i].add(rhs);
return;
} else if (rhs.contain(childs[i])) {
wall_t t = childs[i];
childs.erase(childs.begin() + i);
rhs.childs.push_back(t);
childs.push_back(rhs);
return;
}
}
childs.push_back(rhs);
}
bool contain(const wall_t& rhs) {
return (r > rhs.r) && distance(rhs) <= abs(r - rhs.r);
}
float distance(const wall_t& rhs)
{
return sqrt((x - rhs.x)*(x - rhs.x) + (y - rhs.y)*(y - rhs.y));
}
};
int C;
int N;
int solution = 0;
int build_height(wall_t& wall)
{
int height = 0;
for (auto it = wall.childs.begin(); it != wall.childs.end(); ++it) {
height = max(height, build_height(*it));
}
wall.height = height + 1;
return wall.height;
}
void find_solution(wall_t& wall)
{
if (wall.childs.size() >= 2) {
int max1 = 0;
int max2 = 0;
for (auto it = wall.childs.begin(); it != wall.childs.end(); ++it) {
if (it->height > max1) {
max2 = max1;
max1 = it->height;
}
else if (it->height > max2) {
max2 = it->height;
}
}
int candidate = max1 + max2;
if (solution < candidate) {
solution = candidate;
}
}
for (auto it = wall.childs.begin() ; it != wall.childs.end(); ++it) {
find_solution(*it);
}
}
int main()
{
int C;
cin >> C;
for (int c = 0; c < C; c++) {
wall_t root;
root.x = root.y = 0;
root.r = R_MAX;
int N;
cin >> N;
for (int n = 0; n < N; n++) {
wall_t wall;
cin >> wall.x >> wall.y >> wall.r;
root.add(wall);
}
build_height(root.childs[0]);
solution = 0;
find_solution(root);
if (root.childs[0].height - 1 > solution)
solution = root.childs[0].height - 1;
cout << solution << endl;
}
return 0;
} | [
"shlee.mars@gmail.com"
] | shlee.mars@gmail.com |
e99a443d3e43d686742a291f1ccee330295ac48b | 0c420e8b97af7a1dacb668b1b8ef1180a8d47588 | /Backup2306/EvCoreHeaders/EvFramework/PropertyGridProperty.h | 33fdbe7a782b4a4e32c84fb100a638ae0c71e71b | [] | no_license | Spritutu/Halcon_develop | 9da18019b3fefac60f81ed94d9ce0f6b04ce7bbe | f2ea3292e7a13d65cab5cb5a4d507978ca593b66 | refs/heads/master | 2022-11-04T22:17:35.137845 | 2020-06-22T17:30:19 | 2020-06-22T17:30:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | h | /// PropertyGridProperty.h : interface of the CPropertyGridProperty
/// Udupa; April'2012
#pragma once
#include "AfxPropertyGridCtrl.h"
class CPropertyGridProperty : public CMFCPropertyGridProperty
{
public:
CPropertyGridProperty(const CString& strGroupName, DWORD_PTR dwData=0, BOOL bIsValueList=FALSE);
CPropertyGridProperty(const CString& strName, const _variant_t& varValue, LPCTSTR lpszDescr=NULL,
DWORD_PTR dwData=0, LPCTSTR lpszEditMask=NULL, LPCTSTR lpszEditTemplate=NULL, LPCTSTR lpszValidChars=NULL);
CString m_strFormat;
//virtual BOOL TextToVar(const CString& strText);
virtual CString FormatProperty();
virtual BOOL OnEndEdit();
void SetLimits(int nMin, int nMax);
protected:
int m_nMin;
int m_nMax;
};
| [
"huynhbuutu@gmail.com"
] | huynhbuutu@gmail.com |
80f7a54b461c1601fe995e680dfbd20ebbd0821f | 7033873dd70098ef984893db807626f8b3b69516 | /Tombol.cpp | 79f23089171729ae5f67adfa24a95bea191d55b8 | [] | no_license | anung-git/cpp_class | 4b7d150167be5c5a6f68361c2056bd5509c356ce | 40048a0b8cb8fb6fe41374037f5d2e5de51ead1e | refs/heads/master | 2021-01-16T04:19:46.112862 | 2020-02-25T15:44:12 | 2020-02-25T15:44:12 | 242,974,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cpp |
#include <Arduino.h>
Tombol::Tombol(const int up, const int down, const int menu)
{
pinMode(up,INPUT_PULLUP);
pinMode(down,INPUT_PULLUP);
pinMode(menu,INPUT_PULLUP);
Tombol::down=down;
Tombol::up=up;
Tombol::menu=menu;
}
Tombol::~Tombol()
{
}
| [
"anung93@ymail.com"
] | anung93@ymail.com |
e559400451f690666d447461cc0e5855cc57579c | 8ab4d1ac3e46c132530a5f37595b2d28fd5e394b | /source/server/admin/stats_handler.cc | 0a9bd56257a438e118e923ec401bad264e4db8c1 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | apurvsibal/envoy | 1a4ac01f214320d78fd0a7981e0141590d19383b | 4533ea1897c278477836c72ad5a124148aff4d10 | refs/heads/main | 2023-05-27T23:36:25.262312 | 2021-06-18T21:45:11 | 2021-06-18T21:45:11 | 378,596,727 | 2 | 0 | Apache-2.0 | 2021-06-20T08:35:17 | 2021-06-20T08:35:17 | null | UTF-8 | C++ | false | false | 11,767 | cc | #include "source/server/admin/stats_handler.h"
#include "envoy/admin/v3/mutex_stats.pb.h"
#include "source/common/common/empty_string.h"
#include "source/common/html/utility.h"
#include "source/common/http/headers.h"
#include "source/common/http/utility.h"
#include "source/server/admin/prometheus_stats.h"
#include "source/server/admin/utils.h"
namespace Envoy {
namespace Server {
const uint64_t RecentLookupsCapacity = 100;
StatsHandler::StatsHandler(Server::Instance& server) : HandlerContextBase(server) {}
Http::Code StatsHandler::handlerResetCounters(absl::string_view, Http::ResponseHeaderMap&,
Buffer::Instance& response, AdminStream&) {
for (const Stats::CounterSharedPtr& counter : server_.stats().counters()) {
counter->reset();
}
server_.stats().symbolTable().clearRecentLookups();
response.add("OK\n");
return Http::Code::OK;
}
Http::Code StatsHandler::handlerStatsRecentLookups(absl::string_view, Http::ResponseHeaderMap&,
Buffer::Instance& response, AdminStream&) {
Stats::SymbolTable& symbol_table = server_.stats().symbolTable();
std::string table;
const uint64_t total =
symbol_table.getRecentLookups([&table](absl::string_view name, uint64_t count) {
table += fmt::format("{:8d} {}\n", count, name);
});
if (table.empty() && symbol_table.recentLookupCapacity() == 0) {
table = "Lookup tracking is not enabled. Use /stats/recentlookups/enable to enable.\n";
} else {
response.add(" Count Lookup\n");
}
response.add(absl::StrCat(table, "\ntotal: ", total, "\n"));
return Http::Code::OK;
}
Http::Code StatsHandler::handlerStatsRecentLookupsClear(absl::string_view, Http::ResponseHeaderMap&,
Buffer::Instance& response, AdminStream&) {
server_.stats().symbolTable().clearRecentLookups();
response.add("OK\n");
return Http::Code::OK;
}
Http::Code StatsHandler::handlerStatsRecentLookupsDisable(absl::string_view,
Http::ResponseHeaderMap&,
Buffer::Instance& response,
AdminStream&) {
server_.stats().symbolTable().setRecentLookupCapacity(0);
response.add("OK\n");
return Http::Code::OK;
}
Http::Code StatsHandler::handlerStatsRecentLookupsEnable(absl::string_view,
Http::ResponseHeaderMap&,
Buffer::Instance& response, AdminStream&) {
server_.stats().symbolTable().setRecentLookupCapacity(RecentLookupsCapacity);
response.add("OK\n");
return Http::Code::OK;
}
Http::Code StatsHandler::handlerStats(absl::string_view url,
Http::ResponseHeaderMap& response_headers,
Buffer::Instance& response, AdminStream& admin_stream) {
if (server_.statsConfig().flushOnAdmin()) {
server_.flushStats();
}
Http::Code rc = Http::Code::OK;
const Http::Utility::QueryParams params = Http::Utility::parseAndDecodeQueryString(url);
const bool used_only = params.find("usedonly") != params.end();
absl::optional<std::regex> regex;
if (!Utility::filterParam(params, response, regex)) {
return Http::Code::BadRequest;
}
std::map<std::string, uint64_t> all_stats;
for (const Stats::CounterSharedPtr& counter : server_.stats().counters()) {
if (shouldShowMetric(*counter, used_only, regex)) {
all_stats.emplace(counter->name(), counter->value());
}
}
for (const Stats::GaugeSharedPtr& gauge : server_.stats().gauges()) {
if (shouldShowMetric(*gauge, used_only, regex)) {
ASSERT(gauge->importMode() != Stats::Gauge::ImportMode::Uninitialized);
all_stats.emplace(gauge->name(), gauge->value());
}
}
std::map<std::string, std::string> text_readouts;
for (const auto& text_readout : server_.stats().textReadouts()) {
if (shouldShowMetric(*text_readout, used_only, regex)) {
text_readouts.emplace(text_readout->name(), text_readout->value());
}
}
if (const auto format_value = Utility::formatParam(params)) {
if (format_value.value() == "json") {
response_headers.setReferenceContentType(Http::Headers::get().ContentTypeValues.Json);
response.add(
statsAsJson(all_stats, text_readouts, server_.stats().histograms(), used_only, regex));
} else if (format_value.value() == "prometheus") {
return handlerPrometheusStats(url, response_headers, response, admin_stream);
} else {
response.add("usage: /stats?format=json or /stats?format=prometheus \n");
response.add("\n");
rc = Http::Code::NotFound;
}
} else { // Display plain stats if format query param is not there.
for (const auto& text_readout : text_readouts) {
response.add(fmt::format("{}: \"{}\"\n", text_readout.first,
Html::Utility::sanitize(text_readout.second)));
}
for (const auto& stat : all_stats) {
response.add(fmt::format("{}: {}\n", stat.first, stat.second));
}
std::map<std::string, std::string> all_histograms;
for (const Stats::ParentHistogramSharedPtr& histogram : server_.stats().histograms()) {
if (shouldShowMetric(*histogram, used_only, regex)) {
auto insert = all_histograms.emplace(histogram->name(), histogram->quantileSummary());
ASSERT(insert.second); // No duplicates expected.
}
}
for (const auto& histogram : all_histograms) {
response.add(fmt::format("{}: {}\n", histogram.first, histogram.second));
}
}
return rc;
}
Http::Code StatsHandler::handlerPrometheusStats(absl::string_view path_and_query,
Http::ResponseHeaderMap&,
Buffer::Instance& response, AdminStream&) {
const Http::Utility::QueryParams params =
Http::Utility::parseAndDecodeQueryString(path_and_query);
const bool used_only = params.find("usedonly") != params.end();
absl::optional<std::regex> regex;
if (!Utility::filterParam(params, response, regex)) {
return Http::Code::BadRequest;
}
PrometheusStatsFormatter::statsAsPrometheus(server_.stats().counters(), server_.stats().gauges(),
server_.stats().histograms(), response, used_only,
regex);
return Http::Code::OK;
}
// TODO(ambuc) Export this as a server (?) stat for monitoring.
Http::Code StatsHandler::handlerContention(absl::string_view,
Http::ResponseHeaderMap& response_headers,
Buffer::Instance& response, AdminStream&) {
if (server_.options().mutexTracingEnabled() && server_.mutexTracer() != nullptr) {
response_headers.setReferenceContentType(Http::Headers::get().ContentTypeValues.Json);
envoy::admin::v3::MutexStats mutex_stats;
mutex_stats.set_num_contentions(server_.mutexTracer()->numContentions());
mutex_stats.set_current_wait_cycles(server_.mutexTracer()->currentWaitCycles());
mutex_stats.set_lifetime_wait_cycles(server_.mutexTracer()->lifetimeWaitCycles());
response.add(MessageUtil::getJsonStringFromMessageOrError(mutex_stats, true, true));
} else {
response.add("Mutex contention tracing is not enabled. To enable, run Envoy with flag "
"--enable-mutex-tracing.");
}
return Http::Code::OK;
}
std::string
StatsHandler::statsAsJson(const std::map<std::string, uint64_t>& all_stats,
const std::map<std::string, std::string>& text_readouts,
const std::vector<Stats::ParentHistogramSharedPtr>& all_histograms,
const bool used_only, const absl::optional<std::regex> regex,
const bool pretty_print) {
ProtobufWkt::Struct document;
std::vector<ProtobufWkt::Value> stats_array;
for (const auto& text_readout : text_readouts) {
ProtobufWkt::Struct stat_obj;
auto* stat_obj_fields = stat_obj.mutable_fields();
(*stat_obj_fields)["name"] = ValueUtil::stringValue(text_readout.first);
(*stat_obj_fields)["value"] = ValueUtil::stringValue(text_readout.second);
stats_array.push_back(ValueUtil::structValue(stat_obj));
}
for (const auto& stat : all_stats) {
ProtobufWkt::Struct stat_obj;
auto* stat_obj_fields = stat_obj.mutable_fields();
(*stat_obj_fields)["name"] = ValueUtil::stringValue(stat.first);
(*stat_obj_fields)["value"] = ValueUtil::numberValue(stat.second);
stats_array.push_back(ValueUtil::structValue(stat_obj));
}
ProtobufWkt::Struct histograms_obj;
auto* histograms_obj_fields = histograms_obj.mutable_fields();
ProtobufWkt::Struct histograms_obj_container;
auto* histograms_obj_container_fields = histograms_obj_container.mutable_fields();
std::vector<ProtobufWkt::Value> computed_quantile_array;
bool found_used_histogram = false;
for (const Stats::ParentHistogramSharedPtr& histogram : all_histograms) {
if (shouldShowMetric(*histogram, used_only, regex)) {
if (!found_used_histogram) {
// It is not possible for the supported quantiles to differ across histograms, so it is ok
// to send them once.
Stats::HistogramStatisticsImpl empty_statistics;
std::vector<ProtobufWkt::Value> supported_quantile_array;
for (double quantile : empty_statistics.supportedQuantiles()) {
supported_quantile_array.push_back(ValueUtil::numberValue(quantile * 100));
}
(*histograms_obj_fields)["supported_quantiles"] =
ValueUtil::listValue(supported_quantile_array);
found_used_histogram = true;
}
ProtobufWkt::Struct computed_quantile;
auto* computed_quantile_fields = computed_quantile.mutable_fields();
(*computed_quantile_fields)["name"] = ValueUtil::stringValue(histogram->name());
std::vector<ProtobufWkt::Value> computed_quantile_value_array;
for (size_t i = 0; i < histogram->intervalStatistics().supportedQuantiles().size(); ++i) {
ProtobufWkt::Struct computed_quantile_value;
auto* computed_quantile_value_fields = computed_quantile_value.mutable_fields();
const auto& interval = histogram->intervalStatistics().computedQuantiles()[i];
const auto& cumulative = histogram->cumulativeStatistics().computedQuantiles()[i];
(*computed_quantile_value_fields)["interval"] =
std::isnan(interval) ? ValueUtil::nullValue() : ValueUtil::numberValue(interval);
(*computed_quantile_value_fields)["cumulative"] =
std::isnan(cumulative) ? ValueUtil::nullValue() : ValueUtil::numberValue(cumulative);
computed_quantile_value_array.push_back(ValueUtil::structValue(computed_quantile_value));
}
(*computed_quantile_fields)["values"] = ValueUtil::listValue(computed_quantile_value_array);
computed_quantile_array.push_back(ValueUtil::structValue(computed_quantile));
}
}
if (found_used_histogram) {
(*histograms_obj_fields)["computed_quantiles"] = ValueUtil::listValue(computed_quantile_array);
(*histograms_obj_container_fields)["histograms"] = ValueUtil::structValue(histograms_obj);
stats_array.push_back(ValueUtil::structValue(histograms_obj_container));
}
auto* document_fields = document.mutable_fields();
(*document_fields)["stats"] = ValueUtil::listValue(stats_array);
return MessageUtil::getJsonStringFromMessageOrDie(document, pretty_print, true);
}
} // namespace Server
} // namespace Envoy
| [
"noreply@github.com"
] | noreply@github.com |
793493b13a0fdd548d28c5c139ccab635e1a344f | a4055bb38028fdce22a1939bc12c89572ded2f2d | /ESPixelStick/src/output/OutputTM1814Uart.hpp | 96a54b2b52ac16cf75dbb18b771a144fda81d8eb | [] | no_license | aaronmefford/ESPixelStick | f1add1b66ef2988b3481685ee77844722652979e | 76d60f089f8446db4ddcd24a3a30aad493510362 | refs/heads/master | 2022-08-11T18:32:14.779996 | 2022-07-19T00:06:38 | 2022-07-19T00:06:38 | 112,758,010 | 0 | 0 | null | 2022-07-19T00:06:39 | 2017-12-01T15:54:10 | C++ | UTF-8 | C++ | false | false | 2,495 | hpp | #pragma once
/*
* OutputTM1814Uart.h - TM1814 driver code for ESPixelStick UART
*
* Project: ESPixelStick - An ESP8266 / ESP32 and E1.31 based pixel driver
* Copyright (c) 2015, 2022 Shelby Merrick
* http://www.forkineye.com
*
* This program is provided free for you to use in any way that you wish,
* subject to the laws and regulations where you are using it. Due diligence
* is strongly suggested before using this code. Please give credit where due.
*
* The Author makes no warranty of any kind, express or implied, with regard
* to this program or the documentation contained in this document. The
* Author shall not be liable in any event for incidental or consequential
* damages in connection with, or arising out of, the furnishing, performance
* or use of these programs.
*
* This is a derived class that converts data in the output buffer into
* pixel intensities and then transmits them through the configured serial
* interface.
*
*/
#include "../ESPixelStick.h"
#if defined(SUPPORT_OutputType_TM1814) && defined(SUPPORT_UART_OUTPUT)
#include "OutputTM1814.hpp"
#include "OutputUart.hpp"
class c_OutputTM1814Uart : public c_OutputTM1814
{
public:
// These functions are inherited from c_OutputCommon
c_OutputTM1814Uart (c_OutputMgr::e_OutputChannelIds OutputChannelId,
gpio_num_t outputGpio,
uart_port_t uart,
c_OutputMgr::e_OutputType outputType);
virtual ~c_OutputTM1814Uart ();
// functions to be provided by the derived class
// functions to be provided by the derived class
void Begin (); ///< set up the operating environment based on the current config (or defaults)
void Render (); ///< Call from loop(), renders output data
void PauseOutput (bool State);
bool SetConfig (ArduinoJson::JsonObject& jsonConfig);
void GetConfig (ArduinoJson::JsonObject& jsonConfig);
void GetStatus (ArduinoJson::JsonObject& jsonStatus);
private:
c_OutputUart Uart;
#define TM1814_DATA_RATE (800000.0)
#define TM1814_NUM_DATA_BITS_PER_INTENSITY_BIT 11
#define TM1814_NUM_DATA_BYTES_PER_INTENSITY_BYTE 8
#define TM1814_BAUD_RATE int(TM1814_DATA_RATE * TM1814_NUM_DATA_BITS_PER_INTENSITY_BIT)
}; // c_OutputTM1814Uart
#endif // defined(SUPPORT_OutputType_TM1814) && defined(SUPPORT_UART_OUTPUT)
| [
"MartinMueller2003@yahoo.com"
] | MartinMueller2003@yahoo.com |
1b624912610c6a14df9f9edc3540b4d940166840 | 5e669e02bb0e685df1f4d52f9f68c8f2045e7e74 | /goteras-reto/main.cpp | 960b2f8dc8c6663ebf19bd6d21ae3b3bf21f2118 | [] | no_license | kgrafico/problema-goteras-c | 759ead494f9dfcbb406a0a2dd930e5fd5e0e65b3 | fcd90a0e0f82102bda1f191de841fbdfac17aa6f | refs/heads/master | 2022-03-09T09:59:39.813977 | 2019-10-03T10:34:57 | 2019-10-03T10:34:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | cpp | // Problema <216> <goteras>
//
// https://www.aceptaelreto.com
//
// <Carolina Chamorro Saldaña>
//---------------------------------------------------------
#include <iostream>
using namespace std;
void casoDePrueba() {
int seconds, hours, min, sec;
cout << "1: " << endl;
cin >> seconds;
hours = seconds / 3600;
min = ((seconds - hours*3600)/60);
sec = seconds % 60;
printf("%02d:%02d:%02d\n", hours, min, sec);
} // casoDePrueba
//---------------------------------------------------------
int main() {
unsigned int numCasos, i;
cin >> numCasos;
for (i = 0; i < numCasos; ++i) {
casoDePrueba();
}
return 0;
} // main
| [
"carolina.chamorro@securitasdirect.es"
] | carolina.chamorro@securitasdirect.es |
a6998c4a6d80c2eee962efc8ad4394638cc4dd7d | 395d1860e82bc75ccc04b91c4b9a8fa46276d9bb | /Source/Vision/Runtime/EnginePlugins/Havok/HavokPhysicsEnginePlugin/vHavokSerialize.cpp | 7f271a621082c2edabf1f6847b4a11389dbf05e9 | [] | no_license | Hakhyun-Kim/projectanarchy | 28ba7370050000a12e4305faa11d5deb77c330a1 | ccea719afcb03967a68a169730b59e8a8a6c45f8 | refs/heads/master | 2021-06-03T04:41:22.814866 | 2013-11-07T07:21:03 | 2013-11-07T07:21:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,672 | cpp | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#include <Vision/Runtime/EnginePlugins/Havok/HavokPhysicsEnginePlugin/HavokPhysicsEnginePluginPCH.h>
#include <Common/Base/Config/hkConfigVersion.h>
#if (HAVOK_SDK_VERSION_MAJOR >= 2010)
// Serialization and patches
#include <Common/Base/KeyCode.h>
#define HK_EXCLUDE_FEATURE_SerializeDeprecatedPre700
//#define HK_EXCLUDE_FEATURE_MemoryTracker
//#define HK_EXCLUDE_FEATURE_RegisterVersionPatches
// Plugins have to reg thier own classes, always, even if not a dll.
#undef HAVOK_ANIMATION_KEYCODE
#undef HK_FEATURE_PRODUCT_ANIMATION
#undef HAVOK_BEHAVIOR_KEYCODE
#undef HK_FEATURE_PRODUCT_BEHAVIOR
#undef HAVOK_CLOTH_KEYCODE
#undef HK_FEATURE_PRODUCT_CLOTH
#undef HAVOK_DESTRUCTION_2012_KEYCODE
#undef HK_FEATURE_PRODUCT_DESTRUCTION_2012
#undef HAVOK_AI_KEYCODE
#undef HK_FEATURE_PRODUCT_AI
#undef HAVOK_PHYSICS_KEYCODE
#undef HK_FEATURE_PRODUCT_PHYSICS
#undef HAVOK_DESTRUCTION_KEYCODE
#undef HK_FEATURE_PRODUCT_DESTRUCTION
#undef HAVOK_SIMULATION_KEYCODE
#undef HK_FEATURE_PRODUCT_MILSIM
#include <Common/Base/Config/hkProductFeatures.cxx>
#else // 7.1 etc
// Register Havok classes that are appropriate for the current keycode strings
#include <Common/Base/KeyCode.h>
#define HK_CLASSES_FILE <Common/Serialize/Classlist/hkKeyCodeClasses.h>
#include <Common/Serialize/Util/hkBuiltinTypeRegistry.cxx>
// Register versioning information.
// If you don't want the ability to load previous Havok versions then use hkCompat_None instead to reduce code size
#define HK_COMPAT_FILE <Common/Compat/hkCompat.h>
#endif
/*
* Havok SDK - Base file, BUILD(#20131019)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from salesteam@havok.com.
*
*/
| [
"joel.van.eenwyk@havok.com"
] | joel.van.eenwyk@havok.com |
2a8587aca04b97ff71d6643424586f7f155bdae6 | 7d6e81d77da55dce2e895d7d787f9a529039995b | /array1.cpp | 4f370cbaaf0f80aaba4af22e5ee0d3b698a2a862 | [] | no_license | andyanidas/TeachingMgl | 65dc88088ecc2ad6529b96c674fcdd09f42801f5 | 1305923c9e43789db09b1ec520139db21811cc3a | refs/heads/main | 2023-04-24T19:08:04.587445 | 2021-05-20T16:14:59 | 2021-05-20T16:14:59 | 331,643,983 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 775 | cpp | #include<iostream>
using namespace std;
//array
int main(){
int arr[5] = {1,2}; //toonii tsugluulga {1,2,3,4,5}
cout<<arr[2]<<endl;
// '\0' -> null element buyu hooson
char ug[5] = {'H','e','l','o'};
cout<<ug[0];
cout<<ug[1];
ug[2] = 'm'; //{'H','e','m','o'};
cout<<ug[2];
cout<<ug[2];
cout<<ug[3]<<endl;
int arr1[10];
for(int i = 0 ; i<10 ; i++){
arr1[i] = i*10;
}
cout<<"arr1[] = ";
for(int i = 0; i<10; i++){
cout<<arr1[i]<<" ";
}
cout<<endl;
//----------------------------------------
string words[5];
cout<<"Enter some words :";
for(int i = 0 ; i<5 ; i++){
cin>>words[i];
}
cout<<"4 dugeer ug n: "<<words[3]<<endl;
for(int i = 0 ; i<5 ; i++){
cout<<words[i]<<" ";
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
f0de5ae4e8071f61edae613bca76a65ea7686528 | 97d6161b8bd9dbe5d8a2610bf2428355b25117ad | /NodeMCU2AllJoyn/MQTTDSB/BridgeRT/WidgetAction.cpp | 69d2983389de2a5a719035bc0ac84f579ce12c23 | [
"MIT"
] | permissive | JohnMasen/NodeMCU-WindowsIoT-AllJoyn | fe96319e23f787bd7dbceee90de8655c0f6c677f | c130158ffdf67a485b562d0db15f062514fd42fe | refs/heads/master | 2021-01-22T04:48:44.011785 | 2015-09-16T10:20:02 | 2015-09-16T10:20:02 | 42,281,761 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,788 | cpp | //
// Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include "pch.h"
#include "WidgetConsts.h"
#include "WidgetAction.h"
using namespace BridgeRT;
const char CP_ACTION_INTERFACE_NAME[] = "org.alljoyn.ControlPanel.Action";
const char METHOD_EXEC_STR[] = "Exec";
const uint16_t ACTION_BUTTON = 1;
WidgetAction::THandlerMap WidgetAction::s_execHandlerMap;
//**************************************************************************************************************************************
//
// WidgetAction Constructor. (This creates a button on the Control Panel Controller)
//
// pControlPanel Control Panel that hosts this action (this Control Panel Button)
// pCallback Callback to invoke when Control Panel Button is pressed
//
//**************************************************************************************************************************************
WidgetAction::WidgetAction(_In_ ControlPanel* pControlPanel, _In_ WidgetActionCallback pCallback)
: Widget(pControlPanel)
, m_pActionCallback(pCallback)
{
}
//**************************************************************************************************************************************
//
// Destructor
//
//**************************************************************************************************************************************
WidgetAction::~WidgetAction()
{
}
//**************************************************************************************************************************************
//
// AllJoyn Interface Name for this Widget Type
//
//**************************************************************************************************************************************
const char* WidgetAction::GetInterfaceName()
{
return CP_ACTION_INTERFACE_NAME;
}
//**************************************************************************************************************************************
//
// Action Handler Callback. This static function is invoked when a Control Panel's button is pressed.
// Looks up the WidgetAction that the Exec call is intended for and invokes the Action Handler's Exec method
//
// busObject The Bus Object that the Control Panel invoked.
// member The interface description member that was invoked.
// message The message arguments. This is not used for WidgetActions.
//
//**************************************************************************************************************************************
void WidgetAction::ExecHandler(
alljoyn_busobject busObject,
const alljoyn_interfacedescription_member* member,
alljoyn_message message)
{
UNREFERENCED_PARAMETER(message);
QStatus status = ER_BUS_OBJ_NOT_FOUND;
auto busObjectActionPair = s_execHandlerMap.find(busObject);
if (busObjectActionPair != s_execHandlerMap.end())
{
status = busObjectActionPair->second->Exec(busObject, member);
}
alljoyn_busobject_methodreply_status(busObject, message, status);
}
QStatus WidgetAction::Exec(alljoyn_busobject bus, const alljoyn_interfacedescription_member* member)
{
UNREFERENCED_PARAMETER(bus);
UNREFERENCED_PARAMETER(member);
return (*m_pActionCallback)(GetControlPanel());
}
//**************************************************************************************************************************************
//
// Helper method that adds custom properties/methods or signals for this Widget type to the businterface.
// The Base class implements the standard properties
//
// busInterface The Bus Interface to add this Widget's custom properties to
//
//**************************************************************************************************************************************
QStatus WidgetAction::AddCustomInterfaces(_In_ alljoyn_interfacedescription busInterface)
{
QStatus status = ER_OK;
// Add alljoyn method to the interface
CHK_AJSTATUS(alljoyn_interfacedescription_addmethod(busInterface, METHOD_EXEC_STR, ARG_NONE_STR, ARG_NONE_STR, ARG_NONE_STR, 0, nullptr));
leave:
return status;
}
//**************************************************************************************************************************************
//
// Helper method that adds custom properties/methods or signals for this Widget type to the businterface.
// The Base class implements the standard properties
//
// busInterface The Bus Interface to add this Widget's custom properties to
//
//**************************************************************************************************************************************
QStatus WidgetAction::AddCustomInterfaceHandlers(_In_ alljoyn_busobject busObject, _In_ alljoyn_interfacedescription busInterface)
{
QStatus status = ER_OK;
QCC_BOOL bFound = QCC_FALSE;
alljoyn_interfacedescription_member execMember = { 0 };
// Get member description
bFound = alljoyn_interfacedescription_getmember(busInterface, METHOD_EXEC_STR, &execMember);
if (bFound != QCC_TRUE)
{
status = ER_INVALID_DATA;
goto leave;
}
CHK_AJSTATUS(alljoyn_busobject_addmethodhandler(
busObject,
execMember,
reinterpret_cast<alljoyn_messagereceiver_methodhandler_ptr>(&WidgetAction::ExecHandler),
this));
s_execHandlerMap.insert(std::make_pair(busObject, this));
leave:
return status;
}
//**************************************************************************************************************************************
//
// Gets the specified property valuename
//
// interfaceName Not used. Required by AllJoyn
// propName Name of property to read
// val MsgArg value to return to the caller. The Property data.
//
//**************************************************************************************************************************************
QStatus WidgetAction::Get(_In_z_ const char* interfaceName, _In_z_ const char* propName, _Out_ alljoyn_msgarg val) const
{
QStatus status = ER_OK;
UNREFERENCED_PARAMETER(interfaceName);
// Handle the Optional Parameters if requested
if (strcmp(propName, PROPERTY_OPTPARAMS_STR) == 0)
{
uint16_t keys[] = { LABEL_KEY, BGCOLOR_KEY, HINT_KEY };
// Set of optional parameters
uint16_t actionHints[] = { ACTION_BUTTON };
// Create an array of Variant Type-Data value pairs
alljoyn_msgarg values = alljoyn_msgarg_array_create(_countof(keys));
CHK_POINTER(values);
// Set each Variant "Type-Data Pair"
CHK_AJSTATUS(alljoyn_msgarg_set(alljoyn_msgarg_array_element(values, LABEL_KEY), ARG_STRING_STR, GetLabel()));
CHK_AJSTATUS(alljoyn_msgarg_set(alljoyn_msgarg_array_element(values, BGCOLOR_KEY), ARG_UINT32_STR, GetBgColor()));
CHK_AJSTATUS(alljoyn_msgarg_set(alljoyn_msgarg_array_element(values, HINT_KEY), ARG_UINT16_ARRY_STR, _countof(actionHints), actionHints));
// Create an array of Dictionary Entries
alljoyn_msgarg dictEntries = alljoyn_msgarg_array_create(_countof(keys));
CHK_POINTER(dictEntries);
// Load the Dictionary Entries into the array of dictionary entries where the Keys are Number values that map to Variant Type-Data pairs
for (int idx = 0; idx < _countof(keys); idx++)
{
CHK_AJSTATUS(alljoyn_msgarg_set(
alljoyn_msgarg_array_element(dictEntries, idx),
ARG_DICT_ITEM_STR,
keys[idx],
alljoyn_msgarg_array_element(values, keys[idx])));
}
// Return the array of dictionary entries for the Optional Parameters Output Property
CHK_AJSTATUS(alljoyn_msgarg_set(val, ARG_DICT_STR, _countof(keys), dictEntries));
alljoyn_msgarg_stabilize(val);
}
// The Properties are unknown, hand them up to the base Widget to process.
else
{
CHK_AJSTATUS(Widget::Get(interfaceName, propName, val));
}
leave:
return status;
} | [
"bucherjiang@msn.com"
] | bucherjiang@msn.com |
0cd124a5947c64a75bbe528a3a41afb4d39846fb | b888cb86601a4e28a033386bc1c8516318528f52 | /BattleTank/Source/BattleTank/TankPlayerController.cpp | da4ac8f152ca06e24b814362d798e8a32fb93c57 | [] | no_license | Skyrix012/BattleTank_04 | 84d25da9f224cdf35641e280325cf14cebeb80d7 | 7d2f260bbc1b8996d0a0c040d3b8cdf4d0e9280e | refs/heads/master | 2020-03-08T12:35:10.722978 | 2018-05-03T22:54:27 | 2018-05-03T22:54:27 | 128,130,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankPlayerController.h"
#include "BattleTank.h"
void ATankPlayerController::BeginPlay()
{
Super::BeginPlay();
auto ControlledTank = GetControlledTank();
if (!ControlledTank)
{
UE_LOG(LogTemp, Warning, TEXT("PLayerController not possesing a tank"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("PlayerController possessing %s"), *(ControlledTank->GetName()));
}
}
void ATankPlayerController::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
AimTowardsCrosshair();
}
ATank* ATankPlayerController::GetControlledTank() const
{
return Cast<ATank>(GetPawn());
}
void ATankPlayerController::AimTowardsCrosshair()
{
if (!GetControlledTank()) { return; }
FVector HitLocation; //Out Parameter
if (GetSightRayHitLocation(HitLocation)) //Has "side-effect", is going to line trace
{
//UE_LOG(LogTemp, Warning, TEXT("HitLocation: %s"), *HitLocation.ToString());
//TODO Tell controlled tank to aim at this point
}
}
//Get world location with linetrace through crosshair, true if hits landscape
bool ATankPlayerController::GetSightRayHitLocation(FVector & HitLocation) const
{
int32 ViewportSizeX, ViewportSizeY;
GetViewportSize(ViewportSizeX, ViewportSizeY);
auto ScreenLocation = FVector2D(ViewportSizeX * CrosshairXLocation, ViewportSizeY * CrosshairYLocation);
//"De-project" the screen position of the crosshair to a world direction
FVector LookDirection;
if (GetLookDirection(ScreenLocation, LookDirection))
{
UE_LOG(LogTemp, Warning, TEXT("Look direction: %s"), *LookDirection.ToString());
}
return true;
}
bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector & LookDirection) const
{
FVector CameraWorldLocation; //To be discarded
return DeprojectScreenPositionToWorld(ScreenLocation.X, ScreenLocation.Y, CameraWorldLocation, LookDirection);
}
| [
"jk-012@hotmail.com"
] | jk-012@hotmail.com |
82c7c54b67f2cfad70c4eee22475d2ddbc7d0063 | f8f14b69daa92751826d6cc9843773dbb372fcb3 | /maemo/gui/libmobkvmsg.cpp | 3cbeffc0eb76f9d40e0956b4e957397622dc9632 | [] | no_license | nickjalbert/rage | bfcda8b362d6b0c423006b2d51438d54978fe5de | 7677f9d4fbb6b5020a7ef7c3357e9dba9c1ad313 | refs/heads/master | 2021-05-26T13:02:42.044440 | 2010-05-17T21:41:19 | 2010-05-17T21:41:19 | 603,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,893 | cpp | #include "libmobkvmsg.h"
#ifdef __MAEMO5__
void ConnectionEventCallback(ConIcConnection* /*connection*/,
ConIcConnectionEvent* event, gpointer user_data)
{
ConnectionType *data = (ConnectionType*)user_data;
bool connected = (con_ic_connection_event_get_status(event) ==
CON_IC_STATUS_CONNECTED);
if (connected)
{
const gchar* bearer = con_ic_event_get_bearer_type(CON_IC_EVENT(event));
if (strcmp(bearer,CON_IC_BEARER_WLAN_ADHOC) == 0 ||
strcmp(bearer,CON_IC_BEARER_WLAN_INFRA) == 0)
*data = CONN_TYPE_WIFI;
else if (strcmp(bearer,"GPRS") == 0)
*data = CONN_TYPE_CELLULAR;
}
}
#endif /* __MAEMO5__ */
// TODO: pass in the header?
MobKVMessage::MobKVMessage(QUrl url, QObject *parent) : QObject(parent)
{
this->url = url;
connect(&net_man, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
// TODO: want a better post variable?
buf.append("incident=<incident>");
#ifdef __MAEMO5__
/* Init and start a request for the network type */
con_type = CONN_TYPE_INIT;
ConIcConnection *connection = con_ic_connection_new();
g_object_ref_sink(connection);
g_signal_connect(G_OBJECT(connection), "connection-event",
G_CALLBACK(ConnectionEventCallback), &con_type);
con_ic_connection_connect(connection,
CON_IC_CONNECT_FLAG_AUTOMATICALLY_TRIGGERED);
/* somewhat ugly, spin til there's a response to the connection */
while (con_type == CONN_TYPE_INIT)
QCoreApplication::instance()->processEvents();
#else
con_type = CONN_TYPE_WIFI;
#endif /* __MAEMO5__ */
}
MobKVMessage::~MobKVMessage(void)
{
}
int MobKVMessage::addKeyValue(QString key, QString value, int flags)
{
buf.append("<" + key + ">");
buf.append(value);
buf.append("</" + key + ">");
return 0;
}
int MobKVMessage::addKeyValue(QString key, QByteArray blob, int flags)
{
return -1;
}
void MobKVMessage::send(void)
{
buf.append("</incident>");
/* 1 = Wifi, 2 = Cell, 0 = nothing */
printf("Connection status is %d\n", con_type);
net_man.post(QNetworkRequest(url), buf);
}
/* TODO: how about a diff way to check on progress?, signals, etc. can't just
* call this at any point in time, and we probably want to just destruct it.*/
void MobKVMessage::close(void)
{
// this->deleteLater();
}
void MobKVMessage::replyFinished(QNetworkReply *reply)
{
#if 0
printf("Got reply from %s\n", reply->url().toString().toAscii().data());
printf("Error: %d\n", reply->error());
QList<QByteArray> list = reply->rawHeaderList();
printf("%d headers:\n", list.count());
for (int i = 0; i < list.size(); i++) {
printf("%s: ", list.at(i).data());
printf("%s\n", reply->rawHeader(list.at(i)).data());
}
#endif
reply->close();
reply->deleteLater();
/* Cleanup ourselves too. Don't want to do this unless we're completely
* done. */
this->deleteLater();
}
| [
"brho@cs.berkeley.edu"
] | brho@cs.berkeley.edu |
47711bffdd4fc16afa5639c9180ce5073b8dbbbe | e016b0b04a6db80b0218a4f095e6aa4ea6fcd01c | /Classes/Native/mscorlib_System_Predicate_1_gen3989486669.h | 78722cc43518b01faf7b586be10904e45cc5b650 | [
"MIT"
] | permissive | rockarts/MountainTopo3D | 5a39905c66da87db42f1d94afa0ec20576ea68de | 2994b28dabb4e4f61189274a030b0710075306ea | refs/heads/master | 2021-01-13T06:03:01.054404 | 2017-06-22T01:12:52 | 2017-06-22T01:12:52 | 95,056,244 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 851 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_MulticastDelegate3201952435.h"
// Mapbox.VectorTile.Geometry.InteralClipperLib.InternalClipper/OutRec
struct OutRec_t1251549258;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Object
struct Il2CppObject;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Predicate`1<Mapbox.VectorTile.Geometry.InteralClipperLib.InternalClipper/OutRec>
struct Predicate_1_t3989486669 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"stevenrockarts@gmail.com"
] | stevenrockarts@gmail.com |
cfb7e948eb2f93bcb935ca44d521098894692e7b | ac68e95eef155951a5ec57abb2e6432ea451ff30 | /boyview.cpp | 75b8f015650498ee592680edc551868d0d023933 | [] | no_license | nazib07/RestaurantManagement | 601f3a4a84e0e74485d6ee002f965494eced5fb8 | f4921a7b6112a648b096702d6c619d9cca41649b | refs/heads/master | 2020-05-22T01:17:31.409310 | 2018-12-27T16:39:23 | 2018-12-27T16:39:23 | 24,441,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | cpp | #include "boyview.h"
#include "ui_boyview.h"
boyView::boyView(QWidget *parent) :
QWidget(parent),
ui(new Ui::boyView)
{
ui->setupUi(this);
}
boyView::~boyView()
{
delete ui;
}
void boyView::setBoy(Boys *boy)
{
ui->lbl_address->setText(boy->getAddress());
ui->lbl_mobile->setText(boy->getMobile());
ui->lbl_name->setText(boy->getName());
ui->lbl_Photo->setPixmap(QPixmap::fromImage(QImage(boy->getPhoto())));
}
| [
"nazib.cse@gmail.com"
] | nazib.cse@gmail.com |
90f8de86c441c9e5c921576b04d3922ea0818b7f | 235b388c17045e2ddb118f27a6efd6baf9a62a35 | /ogl-master/tutorial10_transparency/tutorial10.cpp | 078696b72177ee57b016af48678181abdf84fb10 | [] | no_license | Enmoren/SoftSys3DGraphics | 8e26cb609d06fa0d5308386700e712101cdff027 | 6a894569205d6c539ea084dee2cdf7cba2e7cd39 | refs/heads/master | 2020-05-04T04:30:09.289900 | 2019-05-09T16:28:57 | 2019-05-09T16:28:57 | 178,966,553 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,227 | cpp | // Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <vector>
// Include GLEW
#include <GL/glew.h>
// Include GLFW
#include <GLFW/glfw3.h>
GLFWwindow* window;
// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;
#include <common/shader.hpp>
#include <common/texture.hpp>
#include <common/controls.hpp>
#include <common/objloader.hpp>
#include <common/vboindexer.hpp>
int main( void )
{
// Initialise GLFW
if( !glfwInit() )
{
fprintf( stderr, "Failed to initialize GLFW\n" );
getchar();
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Open a window and create its OpenGL context
window = glfwCreateWindow( 1024, 768, "Tutorial 10 - Transparency", NULL, NULL);
if( window == NULL ){
fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
getchar();
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
getchar();
glfwTerminate();
return -1;
}
// Ensure we can capture the escape key being pressed below
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
// Hide the mouse and enable unlimited mouvement
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// Set the mouse at the center of the screen
glfwPollEvents();
glfwSetCursorPos(window, 1024/2, 768/2);
// Dark blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
// Cull triangles which normal is not towards the camera
//glEnable(GL_CULL_FACE); // Not this time !
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// Create and compile our GLSL program from the shaders
GLuint programID = LoadShaders( "StandardShading.vertexshader", "StandardTransparentShading.fragmentshader" );
// Get a handle for our "MVP" uniform
GLuint MatrixID = glGetUniformLocation(programID, "MVP");
GLuint ViewMatrixID = glGetUniformLocation(programID, "V");
GLuint ModelMatrixID = glGetUniformLocation(programID, "M");
// Load the texture
GLuint Texture = loadDDS("uvmap.DDS");
// Get a handle for our "myTextureSampler" uniform
GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler");
// Read our .obj file
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
bool res = loadOBJ("suzanne.obj", vertices, uvs, normals);
std::vector<unsigned short> indices;
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_uvs;
std::vector<glm::vec3> indexed_normals;
indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs, indexed_normals);
// Load it into a VBO
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW);
GLuint uvbuffer;
glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW);
GLuint normalbuffer;
glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW);
// Generate a buffer for the indices as well
GLuint elementbuffer;
glGenBuffers(1, &elementbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);
// Get a handle for our "LightPosition" uniform
glUseProgram(programID);
GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace");
// For speed computation
double lastTime = glfwGetTime();
int nbFrames = 0;
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
do{
// Measure speed
double currentTime = glfwGetTime();
nbFrames++;
if ( currentTime - lastTime >= 1.0 ){ // If last prinf() was more than 1sec ago
// printf and reset
printf("%f ms/frame\n", 1000.0/double(nbFrames));
nbFrames = 0;
lastTime += 1.0;
}
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Use our shader
glUseProgram(programID);
// Compute the MVP matrix from keyboard and mouse input
computeMatricesFromInputs();
glm::mat4 ProjectionMatrix = getProjectionMatrix();
glm::mat4 ViewMatrix = getViewMatrix();
glm::mat4 ModelMatrix = glm::mat4(1.0);
glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
glm::vec3 lightPos = glm::vec3(4,4,4);
glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);
// Bind our texture in Texture Unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Texture);
// Set our "myTextureSampler" sampler to use Texture Unit 0
glUniform1i(TextureID, 0);
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glVertexAttribPointer(
1, // attribute
2, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 3rd attribute buffer : normals
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glVertexAttribPointer(
2, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
// Draw the triangles !
glDrawElements(
GL_TRIANGLES, // mode
indices.size(), // count
GL_UNSIGNED_SHORT, // type
(void*)0 // element array buffer offset
);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0 );
// Cleanup VBO and shader
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &uvbuffer);
glDeleteBuffers(1, &normalbuffer);
glDeleteBuffers(1, &elementbuffer);
glDeleteProgram(programID);
glDeleteTextures(1, &Texture);
glDeleteVertexArrays(1, &VertexArrayID);
// Close OpenGL window and terminate GLFW
glfwTerminate();
return 0;
}
| [
"enmo.ren@students.olin.edu"
] | enmo.ren@students.olin.edu |
793b3cb84983a721be7f29b5cd9b01a7417e63a7 | eab2bb94baabfc5c36266e0cfa2950d90988b094 | /Land/main.cpp | dd1dcd9b74d59aeca93a1299bec4d4473fd2b071 | [] | no_license | EmbeddedSystemClass/Land_Meter_C | 129dffba988da243a84b3f6cbf7820ca1a1a3d6e | fc4ac382bc1c8310acd4ef969a08b1c9e453770a | refs/heads/master | 2021-01-04T19:35:51.483089 | 2018-09-05T21:11:17 | 2018-09-05T21:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: zls
*
* Created on May 12, 2017, 10:13 AM
*/
#include <cstdlib>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
return 0;
}
| [
"jackw2050@gmail.com"
] | jackw2050@gmail.com |
d67fb33e5c39c2f2b2f37fb22b42038a56798836 | afe94d3675f1d4ad2274cfd5f9eab0f378877bf1 | /lesson_03/12_OOP_Simplest/main.cpp | 9a665fe59cfc339a307257d2fd53711dee43b90f | [] | no_license | Chuvi-w/cpp | d807f51fcc9431997dbe97244b4ebf5c177e3258 | be3066bfa4844f4bc08bac981f51f3ce628a4f2a | refs/heads/master | 2021-01-17T21:39:26.340626 | 2015-08-29T10:47:13 | 2015-08-29T10:47:13 | 42,061,059 | 1 | 0 | null | 2015-09-07T15:38:46 | 2015-09-07T15:38:45 | null | UTF-8 | C++ | false | false | 2,191 | cpp | // Объявление класса
// -----------------
#include <iostream>
// c++ 11 M_PI не определена в режиме __STRICT_ANSI__
//#undef __STRICT_ANSI__
//const double M_PI = 4.0 * atan(1);
#include <cmath>
//#include <math.h>
// Храним координаты точек как
// 2 отдельных массива
//-->
const int POINTS = 100;
double x[POINTS], y[POINTS];
//<--
// Создали структуру точка
//-->
struct Point {
double x, y;
};
// Массив из точек
Point p[140];
// Обращение к элементам массива:
// p[0].x, p[0].y
//<--
// Класс = данные + методы работы
//-->
class Point2D {
public:
double x, y;
void move(double dx, double dy) {
x += dx;
y += dy;
}
// Повернуть точку относительно
// начала координат
// angle - в градусах
void rotate(double angle) {
// Перевод из градусов в радианы
// a - угол в радианах
double a = angle * M_PI / 180.0;
double
nx = x * cos(a) - y * sin(a);
double
ny = x * sin(a) + y * cos(a);
x = nx;
y = ny;
}
};
//<--
// Модификаторы доступа: public / private / protected
using namespace std;
Point2D pointsStatic[1000];
// Создание экземпляра
// -------------------
// Пример использования:
//-->
int main() {
// Два отдельных массива
x[0] = 1;
y[0] = 2;
// ООП
p[0].x = 1;
p[0].y = 2;
Point p1;
p1.x = 2;
Point2D p2;
p2.x = 2;
Point2D points[100];
points[10].x = 10.1;
points[10].y = 10.3;
points[0].move(1, 2);
points[1].rotate(1.2);
Point2D A, B, C;
A.move(10, 2);
/* x[10] = 1;
y[20] = 2;
move_point(10, 10, 2); */
// Динамическая память
Point2D* p;
//...
p = new Point2D;
p->x = 2;
p->move(10, 11);
(*p).move(1, 2);
delete p;
// Создаю массив объектов в
// динамической памяти
Point2D* pp = new Point2D[10];
// Удаляю
delete[] pp;
return 0;
}
//<--
| [
"super.denis@gmail.com"
] | super.denis@gmail.com |
25b1185fdee39bb7d96f86c3297577a0fba9d35c | f7dc806f341ef5dbb0e11252a4693003a66853d5 | /core/os/time_enums.h | a61bdaa73cc5c0991ba635a235f77b5ff655fe42 | [
"LicenseRef-scancode-free-unknown",
"MIT",
"CC-BY-4.0",
"OFL-1.1",
"Bison-exception-2.2",
"CC0-1.0",
"LicenseRef-scancode-nvidia-2002",
"LicenseRef-scancode-other-permissive",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clau... | permissive | godotengine/godot | 8a2419750f4851d1426a8f3bcb52cac5c86f23c2 | 970be7afdc111ccc7459d7ef3560de70e6d08c80 | refs/heads/master | 2023-08-21T14:37:00.262883 | 2023-08-21T06:26:15 | 2023-08-21T06:26:15 | 15,634,981 | 68,852 | 18,388 | MIT | 2023-09-14T21:42:16 | 2014-01-04T16:05:36 | C++ | UTF-8 | C++ | false | false | 2,819 | h | /**************************************************************************/
/* time_enums.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 TIME_ENUMS_H
#define TIME_ENUMS_H
#include <cstdint>
enum Month {
/// Start at 1 to follow Windows SYSTEMTIME structure
/// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx
MONTH_JANUARY = 1,
MONTH_FEBRUARY,
MONTH_MARCH,
MONTH_APRIL,
MONTH_MAY,
MONTH_JUNE,
MONTH_JULY,
MONTH_AUGUST,
MONTH_SEPTEMBER,
MONTH_OCTOBER,
MONTH_NOVEMBER,
MONTH_DECEMBER,
};
enum Weekday : uint8_t {
WEEKDAY_SUNDAY,
WEEKDAY_MONDAY,
WEEKDAY_TUESDAY,
WEEKDAY_WEDNESDAY,
WEEKDAY_THURSDAY,
WEEKDAY_FRIDAY,
WEEKDAY_SATURDAY,
};
#endif // TIME_ENUMS_H
| [
"arnfranke@yahoo.com"
] | arnfranke@yahoo.com |
05ab6892178ed7178b59137f53aac5466853459b | ad39d17ee31f015502be9c61c890899b84767f8e | /InputMethod/frminput.h | 1b15f53649eea4c6e9b33d37dbcef93dc4f4db08 | [] | no_license | radtek/CombineAuthenticateHost | 9e8c7c1be9d16c8076cb0dd156cdcdf080a27854 | d158dc633caaf7fd3b1e081d3b13334d9ff73a9b | refs/heads/master | 2021-05-29T05:41:37.719860 | 2015-06-17T05:23:22 | 2015-06-17T05:23:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,836 | h | #ifndef FRMINPUT_H
#define FRMINPUT_H
#include <QWidget>
#include <QMouseEvent>
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QTextEdit>
#include <QPlainTextEdit>
#include <QTextBrowser>
#include <QtSql>
#include <QPushButton>
#include <QTimer>
namespace Ui
{
class frmInput;
}
class frmInput : public QWidget
{
Q_OBJECT
public:
explicit frmInput(QWidget *parent = 0);
~frmInput();
//单例模式,保证一个程序只存在一个输入法实例对象
static frmInput *Instance() {
if (!_instance) {
_instance = new frmInput;
}
return _instance;
}
//初始化面板状态,包括字体大小
void Init(QString position, QString style, int fontSize);
protected:
//事件过滤器,处理鼠标在汉字标签处单击操作
bool eventFilter(QObject *obj, QEvent *event);
//鼠标拖动事件
void mouseMoveEvent(QMouseEvent *e);
//鼠标按下事件
void mousePressEvent(QMouseEvent *e);
//鼠标松开事件
void mouseReleaseEvent(QMouseEvent *);
private slots:
//焦点改变事件槽函数处理
void focusChanged(QWidget *oldWidget, QWidget *nowWidget);
//输入法面板按键处理
void btn_clicked();
//改变输入法面板样式
void changeStyle(QString topColor, QString bottomColor,
QString borderColor, QString textColor);
//定时器处理退格键
void reClicked();
private:
Ui::frmInput *ui;
static frmInput *_instance; //实例对象
int deskWidth; //桌面宽度
int deskHeight; //桌面高度
int frmWidth; //窗体宽度
int frmHeight; //窗体高度
QPoint mousePoint; //鼠标拖动自定义标题栏时的坐标
bool mousePressed; //鼠标是否按下
bool isPress; //是否长按退格键
QPushButton *btnPress; //长按按钮
QTimer *timerPress; //退格键定时器
bool checkPress(); //校验当前长按的按钮
bool isFirst; //是否首次加载
void InitForm(); //初始化窗体数据
void InitProperty(); //初始化属性
void ChangeStyle(); //改变样式
QWidget *currentWidget; //当前焦点的对象
QLineEdit *currentLineEdit; //当前焦点的单行文本框
QTextEdit *currentTextEdit; //当前焦点的多行文本框
QPlainTextEdit *currentPlain; //当前焦点的富文本框
QTextBrowser *currentBrowser; //当前焦点的文本浏览框
QString currentEditType; //当前焦点控件的类型
QString currentPosition; //当前输入法面板位置类型
QString currentStyle; //当前输入法面板样式
int currentFontSize; //当前输入法面板字体大小
void insertValue(QString value);//插入值到当前焦点控件
void deleteValue(); //删除当前焦点控件的一个字符
QString currentType; //当前输入法类型
void changeType(QString type); //改变输入法类型
void changeLetter(bool isUpper);//改变字母大小写
QList<QLabel *>labCh; //汉字标签数组
QStringList allPY; //所有拼音链表
QStringList currentPY; //当前拼音链表
int currentPY_index; //当前拼音索引
int currentPY_count; //当前拼音数量
void selectChinese(); //查询汉字
void showChinese(); //显示查询到的汉字
void setChinese(int index); //设置当前汉字
void clearChinese(); //清空当前汉字信息
};
#endif // FRMINPUT_H
| [
"1274388603@qq.com"
] | 1274388603@qq.com |
e1d7d38db72bc5b9a9c65d61504cafeffefd4264 | 948d555823c2d123601ff6c149869be377521282 | /SDK/SoT_BP_FishingFish_WildSplash_05_parameters.hpp | 17cc324bfac7fa2d634cd376d8afd0f572a074ef | [] | no_license | besimbicer89/SoT-SDK | 2acf79303c65edab01107ab4511e9b9af8ab9743 | 3a4c6f3b77c1045b7ef0cddd064350056ef7d252 | refs/heads/master | 2022-04-24T01:03:37.163407 | 2020-04-27T12:45:47 | 2020-04-27T12:45:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | hpp | #pragma once
// SeaOfThieves (1.6.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function BP_FishingFish_WildSplash_05.BP_FishingFish_WildSplash_05_C.UserConstructionScript
struct ABP_FishingFish_WildSplash_05_C_UserConstructionScript_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"getpeyton@gmail.com"
] | getpeyton@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.