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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
42e9d095a92d1086601cf4797025fa40f16e2a25 | 6693c202f4aa960b05d7dfd0ac8e19a0d1199a16 | /COJ/eliogovea-cojAC/eliogovea-p3272-Accepted-s868998.cpp | 67c7f31de5a01dcde293a09a81264e18c3b0bdc2 | [] | no_license | eliogovea/solutions_cp | 001cf73566ee819990065ea054e5f110d3187777 | 088e45dc48bfb4d06be8a03f4b38e9211a5039df | refs/heads/master | 2020-09-11T11:13:47.691359 | 2019-11-17T19:30:57 | 2019-11-17T19:30:57 | 222,045,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 20;
int t;
double pv, pm;
double dp[N + 5][N + 5][N + 5];
bool primo(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
bool p[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
//freopen("dat.txt", "r", stdin);
for (int i = 2; i <= N; i++) {
p[i] = primo(i);
}
cin >> t;
while (t--) {
cin >> pv >> pm;;
pv /= 100.0;
pm /= 100.0;
for (int i = 0; i <= N; i++) {
for (int j = 0; j <= N; j++) {
for (int k = 0; k <= N; k++) {
dp[i][j][k] = 0;
}
}
}
dp[0][0][0] = 1.0;
for (int i = 0; i < 18; i++) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
dp[i + 1][j][k] += dp[i][j][k] * (1.0 - pv) * (1.0 - pm);
dp[i + 1][j + 1][k] += dp[i][j][k] * pv * (1.0 - pm);
dp[i + 1][j][k + 1] += dp[i][j][k] * (1.0 - pv) * pm;
dp[i + 1][j + 1][k + 1] += dp[i][j][k] * pv * pm;
}
}
}
double ans = 0.0;
for (int i = 0; i <= 18; i++) {
for (int j = 0; j <= 18; j++) {
if (p[i] || p[j]) {
ans += dp[18][i][j];
}
}
}
cout.precision(10);
cout << fixed << ans << "\n";
}
}
| [
"eliogovea1993@gmail.com"
] | eliogovea1993@gmail.com |
8398f9fbce8f56f93daf304d2dd24917d34593c4 | 3df1fd5834a0f3a00412ab944f47c1c60fee7a71 | /p_10267/p_10267/p_10267.cpp | 56aca659779aca61817938043349d8ef3476756f | [] | no_license | RATIONAL331/Programming-Challenges | 336b0285f8720cdeb347875be579fe96b4a976aa | 00239a241efa04f77016053e6d2394086bd124d2 | refs/heads/master | 2020-04-07T05:43:13.419765 | 2019-01-08T17:05:49 | 2019-01-08T17:05:49 | 158,107,154 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,507 | cpp |
/* @JUDGE_ID: RATIONAL331 10267 C++ */
/* @BEGIN_OF_SOURCE_CODE */
#include<iostream>
#include<string>
#include<fstream>
void deleteBoard(char**, int);
void fill(char**, int, int, int, int, int, int, char);
void printBoard(char** , int, int);
void calculateBoard(char**, int, int, int, int, char, char);
int main() {
// first_command는 들어오는 줄에서 명령을 담당하는 첫번째 문자
char first_command;
// 각종 칠하는데 사용하는 변수들
int m, n, x, y, x1, x2, y1, y2; char c; std::string name;
// board는 그림판을 나타내기 위한 변수;
char** board = nullptr;
//std::ofstream outFile("ouput.txt");
while (true) {
std::cin >> first_command;
if (std::cin.eof() && board != nullptr) {
deleteBoard(board, n);
//outFile.close();
return 0;
}
switch (first_command) {
// x*y 이미지를 새로 만든다.
case 'I':
if (board != nullptr) {
deleteBoard(board, n);
}
std::cin >> m >> n;
board = new char*[n];
for (int i = 0; i < n; i++) board[i] = new char[m];
fill(board, m, n, 0, m - 1, 0, n - 1, 'O');
break;
// 모든 픽셀을 흰색으로 칠한다.
case 'C':
if (board != nullptr) {
fill(board, m, n, 0, m-1, 0, n-1, 'O');
}
break;
// (x,y)를 c로 칠한다.
case 'L':
if (board != nullptr) {
std::cin >> x >> y >> c;
fill(board, m, n, x-1, x-1, y-1, y-1, c);
}
break;
// x열에 y1행부터 y2행까지 수직으로 c로 칠함
case 'V':
if (board != nullptr) {
std::cin >> x >> y1 >> y2 >> c;
fill(board, m, n, x-1, x-1, y1-1, y2-1, c);
}
break;
// x1열부터 x2열 까지 y열에 수평으로 c로 칠함
case 'H':
if (board != nullptr) {
std::cin >> x1 >> x2 >> y >> c;
fill(board, m, n, x1-1, x2-1, y-1, y-1, c);
}
break;
// (x1,y1) 부터 (x2,y2)로 표현된 직사각형을 c로 칠함
case 'K':
if (board != nullptr) {
std::cin >> x1 >> y1 >> x2 >> y2 >> c;
fill(board, m, n, x1-1, x2-1, y1-1, y2-1, c);
}
break;
// (x,y)와 같은 색깔을 가진 부분을 c로 칠하기(재귀)
case 'F':
if (board != nullptr) {
std::cin >> x >> y >> c;
int tempX = x - 1; int tempY = y - 1;
char originalC = board[tempY][tempX];
calculateBoard(board, m, n, tempX, tempY, originalC, c);
}
break;
// 파일명 + 배열 출력
case 'S':
if (board != nullptr) {
std::cin >> name;
std::cout << name << std::endl;
printBoard(board, m, n);
/*
outFile << name << std::endl;
for (int yIdx = 0; yIdx < n; yIdx++) {
for (int xIdx = 0; xIdx < m; xIdx++) {
outFile << board[yIdx][xIdx];
}
outFile << std::endl;
}
*/
}
else {
std::cin >> name;
std::cout << name << std::endl;
//outFile << name << std::endl;
}
break;
// 세션 종료
case 'X':
if (board != nullptr) {
deleteBoard(board, n);
}
//outFile.close();
return 0;
}
}
return 0;
}
void deleteBoard(char** board, int m) {
for (int i = 0; i < m; i++) delete[] board[i];
delete[] board;
}
void fill(char** board, int m, int n, int x1, int x2, int y1, int y2, char c) {
if (x1 > x2) std::swap(x1, x2);
if (y1 > y2) std::swap(y1, y2);
if (x1 < 0 || y1 < 0 || x2 >= m || y2 >= n) return;
for (int yIdx = y1; yIdx <= y2; yIdx++) {
for (int xIdx = x1; xIdx <= x2; xIdx++) {
board[yIdx][xIdx] = c;
}
}
return;
}
void printBoard(char** board, int m, int n) {
for (int yIdx = 0; yIdx < n; yIdx++) {
for (int xIdx = 0; xIdx < m; xIdx++) {
std::cout << board[yIdx][xIdx];
}
std::cout << std::endl;
}
}
void calculateBoard(char** board, int m, int n, int tempX, int tempY, char originalC, char c) {
if (tempX < 0 || tempY < 0 || tempX >= m || tempY >= n) return;
if (originalC == c) return; //이 부분을 처리하지 않으면 무한반복에 걸린다 (갔던 곳을 또 갔다옴)
fill(board, m, n, tempX, tempX, tempY, tempY, c);
if (tempX - 1 >= 0) if(board[tempY][tempX - 1] == originalC) calculateBoard(board, m, n, tempX - 1, tempY, originalC, c);
if (tempY - 1 >= 0) if(board[tempY - 1][tempX] == originalC) calculateBoard(board, m, n, tempX, tempY - 1, originalC, c);
if (tempX + 1 <= m - 1) if (board[tempY][tempX + 1] == originalC) calculateBoard(board, m, n, tempX + 1, tempY, originalC, c);
if (tempY + 1 <= n - 1) if (board[tempY + 1][tempX] == originalC) calculateBoard(board, m, n, tempX, tempY + 1, originalC, c);
return;
}
/* @BEGIN_OF_SOURCE_CODE */
| [
"rational331@gmail.com"
] | rational331@gmail.com |
7f09baa542eb827feea82108cae90ead1a08903a | 94f87ab18725a7a5b2a04552fd8eeafa948a8105 | /XiaCaoJun_Teacher/src/Audio_Video_Rtmp_class/XAudioRecord.h | 66382ef5693530f33533f8cf170a0e87b1396272 | [] | no_license | jiaquan11/2020VSPro | 9aeece5951cc46e55f5bd2ad6bce566a4f1fa653 | f78554e8d8141a0c56eb9aca230b77cbb44af1b2 | refs/heads/master | 2021-07-07T14:32:08.740843 | 2021-04-15T15:12:15 | 2021-04-15T15:12:15 | 237,612,013 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | h | #pragma once
#include "XDataThread.h"
enum XAUDIOTYPE
{
X_AUDIO_QT
};
class XAudioRecord : public XDataThread
{
public:
int channels = 2;//声道数
int sampleRate = 44100;//样本率
int sampleByte = 2;//样本字节大小
int nbSamples = 1024;//一帧音频每个通道的样本数量
public:
virtual ~XAudioRecord();
static XAudioRecord* Get(XAUDIOTYPE type = X_AUDIO_QT, int index = 0);
//开始录制
virtual bool Init() = 0;
//停止录制
virtual void Stop() = 0;
protected:
XAudioRecord();
};
| [
"913882743@qq.com"
] | 913882743@qq.com |
38ce1bf20ee445ec96edc530ba5489512021814b | 8566300b105f1560c4534441904783fb9d187a46 | /sword.cpp | b9504af46edad17015e0a09c646304a64ad1b3fc | [] | no_license | wayneIsGod/Augmented-reality-cv-2- | f851d251e3b111d0a1257939ef384b39cca50d20 | ac70f3f3a74667f0adfdac0ed5b0f655c6398033 | refs/heads/master | 2020-07-22T18:42:49.591173 | 2019-09-09T11:35:38 | 2019-09-09T11:35:38 | 207,292,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | cpp | #include "sword.h"
sword::sword(){}
sword::sword(int x, int y, int xEnd, int yEnd, int xSpeed, int ySpeed, int swordSize):
m_x(x), m_y(y), m_xEnd(xEnd), m_yEnd(yEnd), m_xSpeed(xSpeed), m_ySpeed(ySpeed), m_swordSize(swordSize)
{
srand(time(NULL)*1000*x);
m_swordID = rand() % 3;
}
sword::~sword()
{
}
int sword::get_x()
{
return m_x;
}
int sword::get_y()
{
return m_y;
}
int sword::get_xSpeed()
{
return m_xSpeed;
}
int sword::get_ySpeed()
{
return m_ySpeed;
}
int sword::get_swordID()
{
return m_swordID;
}
void sword::walk()
{
m_x = m_x + m_xSpeed;
m_y = m_y + m_ySpeed;
}
void sword::print(Mat show_img, Mat* sword)
{
Mat temp = backgroundClear(sword[m_swordID], show_img, m_x, m_y);
pictback(temp, show_img, m_x, m_y);
} | [
"wayne.860116@gmail.com"
] | wayne.860116@gmail.com |
8f38fda0620634738645b4c357516b9bd2117f92 | fb70e6a3c45c70e8bfff62ea12b259a6b4fcd672 | /src_main/public/tier2/p4helpers.h | d08cdf42181d5034dddb21b69f6728af773569d4 | [] | no_license | TrentSterling/D0G | 263ba85123567939de1de3fac6de850b2b106445 | bb42185ab815af441cff08eeeb43524160a447cf | refs/heads/master | 2021-01-17T20:09:10.149287 | 2014-03-26T11:26:39 | 2014-03-26T11:26:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,157 | h | //===== Copyright © 1996-2013, Valve Corporation, All rights reserved. ======//
//============= D0G modifications © 2013, SiPlus, MIT licensed. =============//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#if !defined(P4HELPERS_H) && !defined(__ANDROID__)
#define P4HELPERS_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlstring.h"
#include "tier1/smartptr.h"
//
// Class representing file operations
//
class CP4File
{
public:
explicit CP4File( char const *szFilename );
virtual ~CP4File();
public:
// Opens the file for edit
virtual bool Edit( void );
// Opens the file for add
virtual bool Add( void );
// Is the file in perforce?
virtual bool IsFileInPerforce();
protected:
// The filename that this class instance represents
CUtlString m_sFilename;
};
//
// An override of CP4File performing no Perforce interaction
//
class CP4File_Dummy : public CP4File
{
public:
explicit CP4File_Dummy( char const *szFilename ) : CP4File( szFilename ) {}
public:
virtual bool Edit( void ) { return true; }
virtual bool Add( void ) { return true; }
virtual bool IsFileInPerforce() { return false; }
};
//
// Class representing a factory for creating other helper objects
//
class CP4Factory
{
public:
CP4Factory();
~CP4Factory();
public:
// Sets whether dummy objects are created by the factory.
// Returns the old state of the dummy mode.
bool SetDummyMode( bool bDummyMode );
public:
// Sets the name of the changelist to open files under,
// NULL for "Default" changelist.
void SetOpenFileChangeList( const char *szChangeListName );
public:
// Creates a file access object for the given filename.
CP4File *AccessFile( char const *szFilename ) const;
protected:
// Whether the factory is in the "dummy mode" and is creating dummy objects
bool m_bDummyMode;
};
// Default p4 factory
extern CP4Factory *g_p4factory;
//
// CP4AutoEditFile - edits the file upon construction
//
class CP4AutoEditFile
{
public:
explicit CP4AutoEditFile( char const *szFilename ) : m_spImpl( g_p4factory->AccessFile( szFilename ) ) { m_spImpl->Edit(); }
CP4File * File() const { return m_spImpl.Get(); }
protected:
CPlainAutoPtr< CP4File > m_spImpl;
};
//
// CP4AutoAddFile - adds the file upon construction
//
class CP4AutoAddFile
{
public:
explicit CP4AutoAddFile( char const *szFilename ) : m_spImpl( g_p4factory->AccessFile( szFilename ) ) { m_spImpl->Add(); }
CP4File * File() const { return m_spImpl.Get(); }
protected:
CPlainAutoPtr< CP4File > m_spImpl;
};
//
// CP4AutoEditAddFile - edits the file upon construction / adds upon destruction
//
class CP4AutoEditAddFile
{
public:
explicit CP4AutoEditAddFile( char const *szFilename ) : m_spImpl( g_p4factory->AccessFile( szFilename ) )
{
m_spImpl->Edit();
}
~CP4AutoEditAddFile( void ) { m_spImpl->Add(); }
CP4File * File() const { return m_spImpl.Get(); }
protected:
CPlainAutoPtr< CP4File > m_spImpl;
};
#endif // #ifndef P4HELPERS_H
| [
"hwguy.siplus@gmail.com"
] | hwguy.siplus@gmail.com |
4116ed1067ec1834dc87a52d57651161de5ddf73 | d316848f3dbd902a5d6b5d5f30a54e369bb3fd79 | /IrisLangLibrary/include/IrisExportAPIs/IrisExportForCpp.h | 0924db17dc0018b81ca25557b8f51ae3ef60b1d3 | [
"Apache-2.0"
] | permissive | yuwenhuisama/Iris-Language | 7898cc7a4854073342072bb95fd84ba87076005b | d2cabe4bb89628a33bc34e429d1fdce6f3f076e6 | refs/heads/iris_stable | 2021-01-19T02:36:04.930074 | 2017-02-24T18:41:23 | 2017-02-24T18:41:23 | 53,872,799 | 14 | 5 | null | 2017-02-02T17:33:46 | 2016-03-14T16:30:16 | C++ | UTF-8 | C++ | false | false | 8,023 | h | /*
* Development APIs exported using C++ ABI.
* C++ API will provide APIs of style :
* IrisDevUtil::<FunctionName>(Object, parameter);
*/
#ifndef _H_IRISEXPROTFORCPP_
#define _H_IRISEXPROTFORCPP_
#ifdef IRISLANGLIBRARY_EXPORTS
#define IRISLANGLIBRARY_API __declspec(dllexport)
#else
#define IRISLANGLIBRARY_API __declspec(dllimport)
#endif
#include "IrisUnil/IrisValue.h"
#include "IrisInterfaces/IIrisClass.h"
#include "IrisInterfaces/IIrisClosureBlock.h"
#include "IrisInterfaces/IIrisContextEnvironment.h"
#include "IrisInterfaces/IIrisInterface.h"
#include "IrisInterfaces/IIrisModule.h"
#include "IrisInterfaces/IIrisObject.h"
#include "IrisInterfaces/IIrisValues.h"
namespace IrisDev {
typedef IrisValue(*IrisNativeFunction)(IrisValue&, IIrisValues*, IIrisValues*, IIrisContextEnvironment*);
#define DECLARE_IRISDEV_CLASS_CHECK(klass) IRISLANGLIBRARY_API bool CheckClassIs##klass(const IrisValue& ivValue);
DECLARE_IRISDEV_CLASS_CHECK(Class)
DECLARE_IRISDEV_CLASS_CHECK(Module)
DECLARE_IRISDEV_CLASS_CHECK(Interface)
DECLARE_IRISDEV_CLASS_CHECK(Object)
DECLARE_IRISDEV_CLASS_CHECK(String)
DECLARE_IRISDEV_CLASS_CHECK(UniqueString)
DECLARE_IRISDEV_CLASS_CHECK(Integer)
DECLARE_IRISDEV_CLASS_CHECK(Float)
DECLARE_IRISDEV_CLASS_CHECK(Array)
DECLARE_IRISDEV_CLASS_CHECK(Hash)
DECLARE_IRISDEV_CLASS_CHECK(Range)
DECLARE_IRISDEV_CLASS_CHECK(Block)
IRISLANGLIBRARY_API void* _InnerGetNativePointer(const IrisValue& ivValue);
IRISLANGLIBRARY_API void* _InnerGetNativePointer(IIrisObject* pObject);
#ifndef _IRIS_LIB_DEFINE_
#define _IRIS_LIB_DEFINE_
template<class T>
T GetNativePointer(const IrisValue& ivValue) {
return static_cast<T>(_InnerGetNativePointer(ivValue));
}
template<class T>
T GetNativePointer(IIrisObject* pObject) {
return static_cast<T>(_InnerGetNativePointer(pObject));
}
#endif
IRISLANGLIBRARY_API bool CheckClass(const IrisValue& ivValue, const char* szClassName);
IRISLANGLIBRARY_API bool CheckClassIsStringOrUniqueString(const IrisValue& ivValue);
IRISLANGLIBRARY_API void GroanIrregularWithString(const char* szIrregularString);
IRISLANGLIBRARY_API int GetInt(const IrisValue& ivValue);
IRISLANGLIBRARY_API double GetFloat(const IrisValue& ivValue);
IRISLANGLIBRARY_API const char* GetString(const IrisValue& ivValue);
IRISLANGLIBRARY_API IrisValue CallMethod(const IrisValue& ivObj, const char* szMethodName, IIrisValues* pParameters);
IRISLANGLIBRARY_API IrisValue CallClassClassMethod(IIrisClass* pClass, const char* szMethodName, IIrisValues* pParameters);
IRISLANGLIBRARY_API IrisValue CallClassModuleMethod(IIrisModule* pModule, const char* szMethodName, IIrisValues* pParameters);
IRISLANGLIBRARY_API IIrisClass* GetClass(const char* strClassPathName);
IRISLANGLIBRARY_API IIrisModule* GetModule(const char* strClassPathName);
IRISLANGLIBRARY_API IIrisInterface* GetInterface(const char* strClassPathName);
IRISLANGLIBRARY_API bool ObjectIsFixed(const IrisValue& ivObj);
IRISLANGLIBRARY_API IIrisClosureBlock* GetClosureBlock(IIrisContextEnvironment* pContextEnvironment);
IRISLANGLIBRARY_API IrisValue ExcuteClosureBlock(IIrisClosureBlock* pClosureBlock, IIrisValues* pParameters);
IRISLANGLIBRARY_API void ContextEnvironmentSetClosureBlock(IIrisContextEnvironment* pContextEnvironment, IIrisClosureBlock* pBlock);
IRISLANGLIBRARY_API IIrisObject* GetNativeObjectPointer(const IrisValue& ivObj);
IRISLANGLIBRARY_API int GetObjectID(const IrisValue& ivObj);
IRISLANGLIBRARY_API IIrisClass* GetClassOfObject(const IrisValue& ivObj);
IRISLANGLIBRARY_API const char* GetNameOfClass(IIrisClass* pClass);
IRISLANGLIBRARY_API const char* GetNameOfModule(IIrisModule* pModule);
IRISLANGLIBRARY_API const char* GetNameOfInterface(IIrisInterface* pInterface);
IRISLANGLIBRARY_API void MarkObject(const IrisValue& ivObject);
IRISLANGLIBRARY_API void MarkClosureBlock(IIrisClosureBlock* pClosureBlock);
IRISLANGLIBRARY_API const IrisValue& Nil();
IRISLANGLIBRARY_API const IrisValue& False();
IRISLANGLIBRARY_API const IrisValue& True();
IRISLANGLIBRARY_API bool RegistClass(const char* szPath, IIrisClass* pClass);
IRISLANGLIBRARY_API bool RegistModule(const char* szPath, IIrisModule* pModule);
IRISLANGLIBRARY_API bool RegistInterface(const char* szPath, IIrisInterface* pInterface);
//IRISLANGLIBRARY_API bool AddClass(IIrisModule* pModule, IIrisClass* pClass);
IRISLANGLIBRARY_API void AddInstanceMethod(IIrisClass* pClass, const char* szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter);
IRISLANGLIBRARY_API void AddClassMethod(IIrisClass* pClass, const char* szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter);
IRISLANGLIBRARY_API void AddInstanceMethod(IIrisModule* pModule, const char* szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter);
IRISLANGLIBRARY_API void AddClassMethod(IIrisModule* pModule, const char* szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter);
IRISLANGLIBRARY_API void AddGetter(IIrisClass* pClass, const char* szInstanceVariableName, IrisNativeFunction pfFunction);
IRISLANGLIBRARY_API void AddSetter(IIrisClass* pClass, const char* szInstanceVariableName, IrisNativeFunction pfFunction);
IRISLANGLIBRARY_API void AddConstance(IIrisClass* pClass, const char* szConstanceName, const IrisValue& ivValue);
IRISLANGLIBRARY_API void AddConstance(IIrisModule* pModule, const char* szConstanceName, const IrisValue& ivValue);
IRISLANGLIBRARY_API void AddClassVariable(IIrisClass* pClass, const char* szVariableName, const IrisValue& ivValue);
IRISLANGLIBRARY_API void AddClassVariable(IIrisModule* pModule, const char* szVariableName, const IrisValue& ivValue);
IRISLANGLIBRARY_API void AddModule(IIrisClass* pClass, IIrisModule* pTargetModule);
IRISLANGLIBRARY_API void AddModule(IIrisModule* pModule, IIrisModule* pTargetModule);
IRISLANGLIBRARY_API IrisValue CreateNormalInstance(IIrisClass* pClass, IIrisValues* ivsParams, IIrisContextEnvironment* pContexEnvironment);
IRISLANGLIBRARY_API IrisValue CreateInstanceByInstantValue(const char* szString);
IRISLANGLIBRARY_API IrisValue CreateInstanceByInstantValue(double dFloat);
IRISLANGLIBRARY_API IrisValue CreateInstanceByInstantValue(int nInteger);
IRISLANGLIBRARY_API IrisValue CreateUniqueStringInstanceByUniqueIndex(size_t nIndex);
IRISLANGLIBRARY_API void SetObjectInstanceVariable(IrisValue& ivObj, char* szInstanceVariableName, const IrisValue& ivValue);
IRISLANGLIBRARY_API IrisValue GetObjectInstanceVariable(IrisValue& ivObj, char* szInstanceVariableName);
IRISLANGLIBRARY_API bool IrregularHappened();
IRISLANGLIBRARY_API bool FatalErrorHappened();
IRISLANGLIBRARY_API IIrisValues* CreateIrisValuesList(size_t nSize);
IRISLANGLIBRARY_API const IrisValue& GetValue(IIrisValues* pValues, size_t nIndex);
IRISLANGLIBRARY_API void SetValue(IIrisValues* pValues, size_t nIndex, const IrisValue& ivValue);
IRISLANGLIBRARY_API void ReleaseIrisValuesList(IIrisValues* pValues);
};
#ifndef _IRIS_INITIALIZE_STRUCT_DEFINED_
#define _IRIS_INITIALIZE_STRUCT_DEFINED_
typedef void(*FatalErrorMessageFunctionForCpp)(const char* pMessage);
typedef bool(*ExitConditionFunctionForCpp)();
typedef struct IrisInitializeStructForCpp_tag {
FatalErrorMessageFunctionForCpp m_pfFatalErrorMessageFunction;
ExitConditionFunctionForCpp m_pfExitConditionFunction;
} IrisInitializeStructForCpp, *PIrisInitializeStructForCpp;
#endif // ! _IRIS_INITIALIZE_STRUCT_DEFINED_
IRISLANGLIBRARY_API bool IR_Initialize(PIrisInitializeStructForCpp pInitializeStruct);
IRISLANGLIBRARY_API bool IR_Run();
IRISLANGLIBRARY_API bool IR_ShutDown();
IRISLANGLIBRARY_API bool IR_LoadScriptFromPath(const char* pScriptFilePath);
IRISLANGLIBRARY_API bool IR_LoadScriptFromVirtualPathAndText(const char* pPath, const char * pScriptText);
IRISLANGLIBRARY_API bool IR_LoadExtention(const char* pExtentionPath);
#endif | [
"1026121287@qq.com"
] | 1026121287@qq.com |
2994cae3780a70de8d75e55ccdfed138627b1f3d | db952eee0a7bea52d8f8767dd32aff57a66146e6 | /CommandsReader/main.cpp | 99dc5a2e12de9fe1217a5917136d8178ddba8954 | [] | no_license | mkowalik/ImageSaver_Mudita | 12bbde52fafb91b420c8ce7fc8407837880221ac | 5a7be764055c10e38c73187383b4fd71a23de67c | refs/heads/master | 2023-01-18T20:10:46.899038 | 2020-11-16T00:25:30 | 2020-11-16T00:28:43 | 312,069,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,109 | cpp | // Michal Kowalik <kowalik.michal1@gmail.com>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <memory>
#include <sys/wait.h>
#include <unistd.h>
#include "../common/ip_communication_fifo.h"
#include "log_saver.h"
#include "commands_reader.h"
constexpr char logFileName[] = "log.txt";
constexpr char ImageWriterPath[] = "./ImageWriter/image_writer.out";
pid_t imageWriterPID;
std::unique_ptr<CommandsReader> getCommandsReader(int argc, char* argv[]){
if (argc > 1){
return std::unique_ptr<CommandsReader>(new FileCommandsReader("test.in"));
} else {
return std::unique_ptr<CommandsReader>(new CINCommandsReader());
}
}
std::unique_ptr<LogSaver> getLogSaver(){
return std::unique_ptr<LogSaver>(new FileLogSaver(logFileName));
}
std::unique_ptr<IPCommunication> getIPCommunication(){
return std::unique_ptr<IPCommunication>(new IPCommunicationFIFO(IPCommunication::Role::CommandsReader));
}
void runImageWriterProc(){
imageWriterPID = fork(); //< create child process
if (imageWriterPID == -1){ //< error
throw std::runtime_error("Error while trying to fork.");
} else if (imageWriterPID == 0){ //< child process
execl(ImageWriterPath, "");
throw std::runtime_error("Error while trying to run ImageWriter.");
}
//< return to parent (CommandsReader) process
}
void waitForImageWriter(){
int status;
waitpid(imageWriterPID, &status, 0);
}
int main(int argc, char* argv[]){
runImageWriterProc();
auto ipCom = getIPCommunication();
auto comReader = getCommandsReader(argc, argv);
auto logSaver = getLogSaver();
while (true){
IPCommunication::Request req = comReader->readCommand();
IPCommunication::Response resp = ipCom->sendRequest(req);
if (resp.getType() == IPCommunication::Response::ResponseType::ERROR){
logSaver->log(resp.getMessage(), LogSaver::LogType::ERROR);
} else if (resp.getType() == IPCommunication::Response::ResponseType::ACK_FINISH){
break;
}
}
waitForImageWriter();
return 0;
} | [
"kowalik.michal1@gmail.com"
] | kowalik.michal1@gmail.com |
6e4338b2abacecd6e91638ab1ec1ed464742a280 | b8499de1a793500b47f36e85828f997e3954e570 | /v2_3/build/Android/Preview/app/src/main/include/Fuse.Triggers.WhileLoading.h | 6f033f645231fcd443bed6d7bd4e69c5be7a98c8 | [] | no_license | shrivaibhav/boysinbits | 37ccb707340a14f31bd57ea92b7b7ddc4859e989 | 04bb707691587b253abaac064317715adb9a9fe5 | refs/heads/master | 2020-03-24T05:22:21.998732 | 2018-07-26T20:06:00 | 2018-07-26T20:06:00 | 142,485,250 | 0 | 0 | null | 2018-07-26T20:03:22 | 2018-07-26T19:30:12 | C++ | UTF-8 | C++ | false | false | 1,136 | h | // This file was generated based on 'C:/Users/hp laptop/AppData/Local/Fusetools/Packages/Fuse.Triggers/1.9.0/WhileLoading.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IBase-d3bd6f2e.h>
#include <Fuse.Animations.IUnwr-594abe9.h>
#include <Fuse.Binding.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ISourceLocation.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.IBusyHandler.h>
#include <Fuse.Triggers.WhileBusy.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
namespace g{namespace Fuse{namespace Triggers{struct WhileLoading;}}}
namespace g{
namespace Fuse{
namespace Triggers{
// public sealed class WhileLoading :32
// {
::g::Fuse::Triggers::WhileBusy_type* WhileLoading_typeof();
void WhileLoading__ctor_7_fn(WhileLoading* __this);
void WhileLoading__New3_fn(WhileLoading** __retval);
struct WhileLoading : ::g::Fuse::Triggers::WhileBusy
{
void ctor_7();
static WhileLoading* New3();
};
// }
}}} // ::g::Fuse::Triggers
| [
"shubhamanandoist@gmail.com"
] | shubhamanandoist@gmail.com |
da3adbc16a45773ca5a57d9e43c835674dc9f8cb | 5ff250fabc22281747677eda00406dfa6d8dae2b | /Codinginterview/8.3.cpp | 786785b02094d0a8450642e0f6b0f7d449e84510 | [] | no_license | TreeHU/Codinginterview | 03f58481d934a5ab26ad0d32d66f267ea00c137e | daa68744c308cbae4ef0bc26b66a60bee6fd11fc | refs/heads/master | 2022-11-13T15:47:47.098146 | 2020-06-28T14:12:09 | 2020-06-28T14:12:09 | 260,079,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | cpp | #include<iostream>
using namespace std;
bool findMagicnum(int * arr, int begin, int end, int &ans) {
if (end < begin) {
return false;
}
int mid = (begin + end) / 2;
if (arr[mid] == mid) {
ans = mid;
return true;
}
if (findMagicnum(arr, begin, mid -1, ans) || findMagicnum(arr, mid +1 , end, ans)) {
return true;
}
}
int findMagicnum(int* arr, int size) {
int ans = -1;
if (findMagicnum(arr, 0, size - 1, ans)) {
return ans;
}
}
int main() {
int arr[11] = { -40,-20,-1,1,2,3,5,7,9,12,13 };
cout << findMagicnum(arr, 11) << endl;
return 0;
} | [
"thegns@naver.com"
] | thegns@naver.com |
24f93c7425814d01a2e8a1bcfd2604ec5568c839 | 429d499fe1ca850762d49e46b87f5552284332d0 | /tensorflow/compiler/mlir/tensorflow/transforms/xla_rewrite.cc | b724f620b190d8c827e0c1267f3319d3b5bbc6ec | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | huaxz1986/tensorflow | a594ba79343d04c41c9ea76d779aeb6f741008b5 | b3ec1fdccf17781936553c29abb2cf19b5fa2324 | refs/heads/master | 2023-06-07T22:11:50.677231 | 2023-06-05T11:23:43 | 2023-06-05T11:28:30 | 109,361,013 | 1 | 1 | Apache-2.0 | 2018-04-27T09:49:28 | 2017-11-03T06:35:42 | C++ | UTF-8 | C++ | false | false | 4,865 | cc | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This transformation pass converts stateful and stateless partitioned calls
// with _xla_compile_device_type attribute to XLA launch ops.
#include <stack>
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/call_graph_util.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/attribute_utils.h"
#define DEBUG_TYPE "tf-xla-rewrite"
namespace mlir {
namespace {
#define GEN_PASS_DEF_XLAREWRITEPASS
#include "tensorflow/compiler/mlir/tensorflow/transforms/tf_device_passes.h.inc"
struct XlaRewritePass : public impl::XlaRewritePassBase<XlaRewritePass> {
void runOnOperation() override;
};
void MoveResourceArgsToEnd(func::FuncOp callee) {
llvm::DenseMap<BlockArgument, BlockArgument> mapping;
unsigned num_params = callee.getNumArguments();
llvm::BitVector removed_params(num_params);
// Copy the resource-type parameters to the end.
for (unsigned i = 0; i < num_params; ++i) {
BlockArgument param = callee.getArgument(i);
if (getElementTypeOrSelf(param.getType())
.template isa<TF::ResourceType>()) {
removed_params.set(i);
callee.getBody().addArgument(param.getType(), param.getLoc());
param.replaceAllUsesWith(callee.getArguments().back());
removed_params.push_back(false);
}
}
// Remove old resource-type parameters.
callee.getBody().front().eraseArguments(removed_params);
// Update function type.
callee.setFunctionType(FunctionType::get(callee.getContext(),
callee.getBody().getArgumentTypes(),
callee.getResultTypes()));
}
void RewriteCall(tf_device::ClusterFuncOp cluster_func_op, SymbolTable &symtab,
OpBuilder &builder) {
llvm::SmallVector<Value> non_resource_args, resource_args;
bool has_resources = false, in_order = true;
for (const Value &arg : cluster_func_op.getOperands()) {
if (!getElementTypeOrSelf(arg.getType()).template isa<TF::ResourceType>()) {
non_resource_args.push_back(arg);
if (has_resources) in_order = false;
} else {
resource_args.push_back(arg);
has_resources = true;
}
}
if (!in_order) {
// Functions do not get reused in practice, so skip the check for if the
// callee has been updated.
StringAttr callee_sym = cluster_func_op.getFuncAttr().getAttr();
MoveResourceArgsToEnd(symtab.lookup<func::FuncOp>(callee_sym));
}
builder.setInsertionPoint(cluster_func_op);
auto xla_launch_op = builder.create<TF::XlaLaunchOp>(
cluster_func_op.getLoc(), cluster_func_op.getResultTypes(),
/*constants=*/ValueRange({}), ValueRange(non_resource_args),
ValueRange(resource_args), cluster_func_op.getFuncAttr());
CopyDeviceAndUnderscoredAttributes(cluster_func_op, xla_launch_op);
cluster_func_op.replaceAllUsesWith(xla_launch_op.getResults());
cluster_func_op.erase();
}
void XlaRewritePass::runOnOperation() {
ModuleOp module = getOperation();
SymbolTable symtab(module);
OpBuilder builder(&getContext());
module.walk([&](tf_device::ClusterFuncOp cluster_func_op) {
RewriteCall(cluster_func_op, symtab, builder);
});
// Verify that there are no nested XLA launch ops.
module.walk([&](TF::XlaLaunchOp xla_launch_op) {
llvm::SmallVector<mlir::Operation *> nested_launch_ops;
func::FuncOp root = symtab.lookup<func::FuncOp>(
xla_launch_op.getFunctionAttr().getRootReference());
if (failed(GetOutermostOpsOfType<TF::XlaLaunchOp>(root, symtab,
nested_launch_ops)))
return signalPassFailure();
if (!nested_launch_ops.empty()) {
xla_launch_op.emitError() << "Nested XLA launch ops detected";
return signalPassFailure();
}
});
}
} // namespace
namespace TFDevice {
std::unique_ptr<OperationPass<ModuleOp>> CreateXlaRewritePass() {
return std::make_unique<XlaRewritePass>();
}
} // namespace TFDevice
} // namespace mlir
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
1b0f0014de653a63e750514deec3872e5bbe363a | 702010848952ab40204abdbc654442affcf67473 | /src/GeoGabTimeEvent.h | 19b010d879015816613335a0e3ed965ed9b8673a | [
"MIT"
] | permissive | gsieben/GeoGab-TimeEvent | be9a25ed9f6a1dea51ac97c03a877732f0606170 | a89fcb397cb327669a56a15f6cbf0bc72ae69c68 | refs/heads/main | 2023-03-13T03:07:10.460395 | 2021-03-04T19:14:41 | 2021-03-04T19:14:41 | 341,347,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,467 | h | /**
* @file TimeEvent.h
* @author Gabriel A. Sieben (gsieben@geogab.net)
* @brief
* @version 1.0.4
* @date 19-February-2021
*
* @copyright (c) 2021 - MIT License (see license file)
*
*/
#ifndef GeoGabTimeEvent_h
#define GeoGabTimeEvent_h
#include <Arduino.h> // Standard Library
#include <functional> // To overhand a "function" to another as parameter
#include <vector> // Vector Library
using namespace std;
#define TIMEEVENT_VERSION "1.0.4"
enum {
TE_ERROR_NONE=0, // 0000 0000: Perfect :-)
TE_ERROR_NO_SLOTS_FREE=1 // 0000 0001: Reverse more slots on init
};
class TimeEvent {
public:
uint8_t error; // Error Number
uint8_t SlotIndex=0; // Index of the actual slot
vector<uint32_t> Runtime; // Init: 1 - Previous runtime of the slot
TimeEvent(uint8_t size); // Constructor with timer slots
void Reset();
bool Check(const uint32_t &every, const uint32_t &offset, function<void (void)> funct);
bool Check(const uint32_t &every, const uint32_t &offset);
private:
uint8_t SlotMax; // Init: 2 - Maximal Slots available (must be defined while object creation)
vector<uint32_t> PrevStamp; // Init: 3 - Previous runtime of the slot
uint32_t ActStamp; // actual loop time stamp
};
#endif
| [
"gsieben@geogab.net"
] | gsieben@geogab.net |
ca9f4b1d21d68be5bf062f24b0d7d9bdb7726f4b | a7a20574ffb80b80f5ad942a966c2af6948f4cd9 | /src/Geo/transofrom.cc | 8eecd4c943402d7811f4a645338bf45e410a4a1b | [] | no_license | marcomanno/mesh_sweep | f3a905e676e877766c5b5d9185bd930b882a4ba6 | 8ab3f332df2e86c1ee52fdab81fd0279c3bbe6bf | refs/heads/master | 2020-05-22T05:31:42.783455 | 2019-07-14T18:35:58 | 2019-07-14T18:35:58 | 186,237,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,007 | cc | #include "transofrom.hh"
#ifdef QUATERNION
#include <Eigen/Geometry>
using Quat = Eigen::Quaternion<double>;
#endif
namespace Geo {
Transform& Transform::operator+=(const Transform & _oth)
{
origin_ += _oth.origin_;
delta_ += _oth.delta_;
axis_ += _oth.axis_;
return *this;
}
Transform& Transform::operator-=(const Transform& _oth)
{
origin_ -= _oth.origin_;
delta_ -= _oth.delta_;
axis_ -= _oth.axis_;
return *this;
}
Transform& Transform::operator*=(double _coeff)
{
origin_ *= _coeff;
delta_ *= _coeff;
axis_ *= _coeff;
return *this;
}
Transform& Transform::operator/=(double _coeff)
{
origin_ /= _coeff;
delta_ /= _coeff;
axis_ /= _coeff;
return *this;
}
VectorD<3> Transform::operator()(const VectorD<3>& _pos)
{
auto p = _pos - origin_;
VectorD<3> rot_v(p);
auto axis = axis_;
auto len = normalize(axis);
if (len != 0)
{
auto alpha = len;
auto z_dir = (p * axis) * axis;
auto x_dir = p - z_dir;
auto y_dir = axis % x_dir;
rot_v = z_dir + x_dir * cos(alpha) + y_dir * sin(alpha);
}
return origin_ + delta_ + rot_v;
}
Transform Transform::interpolate(
const Transform& _start, const Transform& _end, double _par, Transform* _d_trnsf)
{
if (_d_trnsf != nullptr)
* _d_trnsf = _end - _start;
return Geo::interpolate(_start, _end, _par);
}
VectorD<3> Transform::rotation_axis(const VectorD<3>& _direction, double angle)
{
if (angle < 1e-12)
return { };
auto len = length(_direction);
if (len < 1e-12)
throw "Undefined direction";
return sqrt(angle) / len * _direction;
}
struct Trajectory : public ITrajectory
{
const Interval<double>& range() const override { return range_; }
Interval<double> range_;
};
struct TrajectoryLinear : public Trajectory
{
Transform transform(double _par, Transform* _d_transf = nullptr) const override
{
auto t = (_par - range_[0]) / range_.length();
auto result = Transform::interpolate(start_, end_, t, _d_transf);
if (_d_transf != nullptr)
* _d_transf /= range_.length();
return result;
}
VectorD<3> evaluate(double _par, const VectorD<3>& _pos, VectorD<3>* _dir = nullptr) const override
{
Transform d_transf;
auto trnsf = transform(_par, &d_transf);
auto new_pos = trnsf(_pos);
if (_dir != nullptr)
{
*_dir = d_transf.get_rotation_origin() + d_transf.get_translation();
auto& ax = trnsf.get_rotation_axis();
auto ax_len_sq = length_square(ax);
auto& dax = d_transf.get_rotation_axis();
auto p = _pos - trnsf.get_rotation_origin();
auto ax_len = sqrt(ax_len_sq);
auto alpha = ax_len;
double ca = cos(alpha), sa = sin(alpha);
if (ax_len_sq > 1e-24)
{
auto dalpha = (ax * dax) / ax_len;
auto ax_n = ax / ax_len;
auto dax_n = (dax - ax * ((ax * dax) / ax_len_sq)) / ax_len;
auto tz = (p * ax_n) * ax_n;
auto dtz = (p * dax_n) * ax_n + (p * ax_n) * dax_n;
auto tx = p - tz;
auto dtx = -dtz;
auto ty = ax_n % tx;
auto dty = ax_n % dtx + dax_n % tx;
*_dir += dtz + dtx * ca + dty * sa + dalpha * (ty * ca - tx * sa);
}
else
{
auto da_lensq = Geo::length_square(dax);
auto da_len = sqrt(da_lensq);
auto dalpha = da_len;
auto tz = ((p * dax) / da_lensq) * dax;
auto tx = p - tz;
auto ty = (dax % tx) / da_len;
*_dir += (ty * ca - tx * sa) * dalpha;
}
}
return new_pos;
}
Transform start_, end_;
Interval<double> range_;
};
std::unique_ptr<ITrajectory>
ITrajectory::make_linear(const Interval<double>& _interv,
const Transform& _start, const Transform& _end)
{
auto res = std::make_unique<TrajectoryLinear>();
res->range_ = _interv;
res->start_ = _start;
res->end_ = _end;
return res;
}
} // nemespace Geo
| [
"guzel.gala@outlook.com"
] | guzel.gala@outlook.com |
5ed000be28cead2bb48db4dbe01570d75ef4375c | 5889bdb7327b7ca3bce4417df4bcdb81b4425fa7 | /twrpTar.cpp | 5a9340a25cf7cd9cc42d0b5007f834b2ec2f1d03 | [
"Apache-2.0"
] | permissive | maximik1980/TWRP-2.6.1.0-u8186 | 62d035c31e93bfbd9d475c49e8a9c044cb238b7c | 5892bf8e8cb6b1fa619c24c793098f80740e7124 | refs/heads/master | 2020-06-08T19:00:14.847025 | 2013-09-23T08:18:12 | 2013-09-23T08:18:12 | 13,030,434 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,692 | cpp | /*
Copyright 2012 bigbiff/Dees_Troy TeamWin
This file is part of TWRP/TeamWin Recovery Project.
TWRP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TWRP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with TWRP. If not, see <http://www.gnu.org/licenses/>.
*/
extern "C" {
#include "libtar/libtar.h"
#include "twrpTar.h"
#include "tarWrite.h"
#include "libcrecovery/common.h"
}
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <dirent.h>
#include <sys/mman.h>
#include "twrpTar.hpp"
#include "twcommon.h"
#include "data.hpp"
#include "variables.h"
#include "twrp-functions.hpp"
using namespace std;
twrpTar::twrpTar(void) {
use_encryption = 0;
userdata_encryption = 0;
use_compression = 0;
split_archives = 0;
has_data_media = 0;
pigz_pid = 0;
oaes_pid = 0;
}
twrpTar::~twrpTar(void) {
// Do nothing
}
void twrpTar::setfn(string fn) {
tarfn = fn;
}
void twrpTar::setdir(string dir) {
tardir = dir;
}
void twrpTar::setexcl(string exclude) {
tarexclude.push_back(exclude);
}
int twrpTar::createTarFork() {
int status = 0;
pid_t pid, rc_pid;
if ((pid = fork()) == -1) {
LOGINFO("create tar failed to fork.\n");
return -1;
}
if (pid == 0) {
// Child process
if (use_encryption || userdata_encryption) {
LOGINFO("Using encryption\n");
DIR* d;
struct dirent* de;
unsigned long long regular_size = 0, encrypt_size = 0, target_size = 0, core_count = 1;
unsigned enc_thread_id = 1, regular_thread_id = 0, i, start_thread_id = 1;
int item_len, ret, thread_error = 0;
std::vector<TarListStruct> RegularList;
std::vector<TarListStruct> EncryptList;
string FileName;
struct TarListStruct TarItem;
twrpTar reg, enc[9];
struct stat st;
pthread_t enc_thread[9];
pthread_attr_t tattr;
void *thread_return;
core_count = sysconf(_SC_NPROCESSORS_CONF);
if (core_count > 8)
core_count = 8;
LOGINFO(" Core Count : %llu\n", core_count);
Archive_Current_Size = 0;
d = opendir(tardir.c_str());
if (d == NULL) {
LOGERR("error opening '%s'\n", tardir.c_str());
_exit(-1);
}
// Figure out the size of all data to be encrypted and create a list of unencrypted files
while ((de = readdir(d)) != NULL) {
FileName = tardir + "/";
FileName += de->d_name;
if (has_data_media == 1 && FileName.size() >= 11 && strncmp(FileName.c_str(), "/data/media", 11) == 0)
continue; // Skip /data/media
if (de->d_type == DT_BLK || de->d_type == DT_CHR)
continue;
if (de->d_type == DT_DIR && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0 && strcmp(de->d_name, "lost+found") != 0) {
item_len = strlen(de->d_name);
if (userdata_encryption && ((item_len >= 3 && strncmp(de->d_name, "app", 3) == 0) || (item_len >= 6 && strncmp(de->d_name, "dalvik", 6) == 0))) {
if (Generate_TarList(FileName, &RegularList, &target_size, ®ular_thread_id) < 0) {
LOGERR("Error in Generate_TarList with regular list!\n");
closedir(d);
_exit(-1);
}
regular_size += TWFunc::Get_Folder_Size(FileName, false);
} else {
encrypt_size += TWFunc::Get_Folder_Size(FileName, false);
}
} else if (de->d_type == DT_REG) {
stat(FileName.c_str(), &st);
encrypt_size += (unsigned long long)(st.st_size);
}
}
closedir(d);
target_size = encrypt_size / core_count;
target_size++;
LOGINFO(" Unencrypted size: %llu\n", regular_size);
LOGINFO(" Encrypted size : %llu\n", encrypt_size);
LOGINFO(" Target size : %llu\n", target_size);
if (!userdata_encryption) {
enc_thread_id = 0;
start_thread_id = 0;
core_count--;
}
Archive_Current_Size = 0;
d = opendir(tardir.c_str());
if (d == NULL) {
LOGERR("error opening '%s'\n", tardir.c_str());
_exit(-1);
}
// Divide up the encrypted file list for threading
while ((de = readdir(d)) != NULL) {
FileName = tardir + "/";
FileName += de->d_name;
if (has_data_media == 1 && FileName.size() >= 11 && strncmp(FileName.c_str(), "/data/media", 11) == 0)
continue; // Skip /data/media
if (de->d_type == DT_BLK || de->d_type == DT_CHR)
continue;
if (de->d_type == DT_DIR && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0 && strcmp(de->d_name, "lost+found") != 0) {
item_len = strlen(de->d_name);
if (userdata_encryption && ((item_len >= 3 && strncmp(de->d_name, "app", 3) == 0) || (item_len >= 6 && strncmp(de->d_name, "dalvik", 6) == 0))) {
// Do nothing, we added these to RegularList earlier
} else {
FileName = tardir + "/";
FileName += de->d_name;
if (Generate_TarList(FileName, &EncryptList, &target_size, &enc_thread_id) < 0) {
LOGERR("Error in Generate_TarList with encrypted list!\n");
closedir(d);
_exit(-1);
}
}
} else if (de->d_type == DT_REG || de->d_type == DT_LNK) {
stat(FileName.c_str(), &st);
if (de->d_type == DT_REG)
Archive_Current_Size += (unsigned long long)(st.st_size);
TarItem.fn = FileName;
TarItem.thread_id = enc_thread_id;
EncryptList.push_back(TarItem);
}
}
closedir(d);
if (enc_thread_id != core_count) {
LOGERR("Error dividing up threads for encryption, %i threads for %i cores!\n", enc_thread_id, core_count);
if (enc_thread_id > core_count)
_exit(-1);
else
LOGERR("Continuining anyway.");
}
if (userdata_encryption) {
// Create a backup of unencrypted data
reg.setfn(tarfn);
reg.ItemList = &RegularList;
reg.thread_id = 0;
reg.use_encryption = 0;
reg.use_compression = use_compression;
LOGINFO("Creating unencrypted backup...\n");
if (createList((void*)®) != 0) {
LOGERR("Error creating unencrypted backup.\n");
_exit(-1);
}
}
if (pthread_attr_init(&tattr)) {
LOGERR("Unable to pthread_attr_init\n");
_exit(-1);
}
if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE)) {
LOGERR("Error setting pthread_attr_setdetachstate\n");
_exit(-1);
}
if (pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM)) {
LOGERR("Error setting pthread_attr_setscope\n");
_exit(-1);
}
/*if (pthread_attr_setstacksize(&tattr, 524288)) {
LOGERR("Error setting pthread_attr_setstacksize\n");
_exit(-1);
}*/
// Create threads for the divided up encryption lists
for (i = start_thread_id; i <= core_count; i++) {
enc[i].setdir(tardir);
enc[i].setfn(tarfn);
enc[i].ItemList = &EncryptList;
enc[i].thread_id = i;
enc[i].use_encryption = use_encryption;
enc[i].use_compression = use_compression;
LOGINFO("Start encryption thread %i\n", i);
ret = pthread_create(&enc_thread[i], &tattr, createList, (void*)&enc[i]);
if (ret) {
LOGINFO("Unable to create %i thread for encryption! %i\nContinuing in same thread (backup will be slower).", i, ret);
if (createList((void*)&enc[i]) != 0) {
LOGERR("Error creating encrypted backup %i.\n", i);
_exit(-1);
} else {
enc[i].thread_id = i + 1;
}
}
usleep(100000); // Need a short delay before starting the next thread or the threads will never finish for some reason.
}
if (pthread_attr_destroy(&tattr)) {
LOGERR("Failed to pthread_attr_destroy\n");
}
for (i = start_thread_id; i <= core_count; i++) {
if (enc[i].thread_id == i) {
if (pthread_join(enc_thread[i], &thread_return)) {
LOGERR("Error joining thread %i\n", i);
_exit(-1);
} else {
LOGINFO("Joined thread %i.\n", i);
ret = (int)thread_return;
if (ret != 0) {
thread_error = 1;
LOGERR("Thread %i returned an error %i.\n", i, ret);
_exit(-1);
}
}
} else {
LOGINFO("Skipping joining thread %i because of pthread failure.\n", i);
}
}
if (thread_error) {
LOGERR("Error returned by one or more threads.\n");
_exit(-1);
}
LOGINFO("Finished encrypted backup.\n");
_exit(0);
} else {
if (create() != 0)
_exit(-1);
else
_exit(0);
}
} else {
if (TWFunc::Wait_For_Child(pid, &status, "createTarFork()") != 0)
return -1;
}
return 0;
}
int twrpTar::extractTarFork() {
int status = 0;
pid_t pid, rc_pid;
pid = fork();
if (pid >= 0) // fork was successful
{
if (pid == 0) // child process
{
if (TWFunc::Path_Exists(tarfn)) {
LOGINFO("Single archive\n");
if (extract() != 0)
_exit(-1);
else
_exit(0);
} else {
LOGINFO("Multiple archives\n");
string temp;
char actual_filename[255];
twrpTar tars[9];
pthread_t tar_thread[9];
pthread_attr_t tattr;
int thread_count = 0, i, start_thread_id = 1, ret, thread_error = 0;
void *thread_return;
basefn = tarfn;
temp = basefn + "%i%02i";
tarfn += "000";
if (!TWFunc::Path_Exists(tarfn)) {
LOGERR("Unable to locate '%s' or '%s'\n", basefn.c_str(), tarfn.c_str());
_exit(-1);
}
if (TWFunc::Get_File_Type(tarfn) != 2) {
LOGINFO("First tar file '%s' not encrypted\n", tarfn.c_str());
tars[0].basefn = basefn;
tars[0].thread_id = 0;
if (extractMulti((void*)&tars[0]) != 0) {
LOGERR("Error extracting split archive.\n");
_exit(-1);
}
} else {
start_thread_id = 0;
}
// Start threading encrypted restores
if (pthread_attr_init(&tattr)) {
LOGERR("Unable to pthread_attr_init\n");
_exit(-1);
}
if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE)) {
LOGERR("Error setting pthread_attr_setdetachstate\n");
_exit(-1);
}
if (pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM)) {
LOGERR("Error setting pthread_attr_setscope\n");
_exit(-1);
}
/*if (pthread_attr_setstacksize(&tattr, 524288)) {
LOGERR("Error setting pthread_attr_setstacksize\n");
_exit(-1);
}*/
for (i = start_thread_id; i < 9; i++) {
sprintf(actual_filename, temp.c_str(), i, 0);
if (TWFunc::Path_Exists(actual_filename)) {
thread_count++;
tars[i].basefn = basefn;
tars[i].thread_id = i;
LOGINFO("Creating extract thread ID %i\n", i);
ret = pthread_create(&tar_thread[i], &tattr, extractMulti, (void*)&tars[i]);
if (ret) {
LOGINFO("Unable to create %i thread for extraction! %i\nContinuing in same thread (restore will be slower).", i, ret);
if (extractMulti((void*)&tars[i]) != 0) {
LOGERR("Error extracting backup in thread %i.\n", i);
_exit(-1);
} else {
tars[i].thread_id = i + 1;
}
}
usleep(100000); // Need a short delay before starting the next thread or the threads will never finish for some reason.
} else {
break;
}
}
for (i = start_thread_id; i < thread_count + start_thread_id; i++) {
if (tars[i].thread_id == i) {
if (pthread_join(tar_thread[i], &thread_return)) {
LOGERR("Error joining thread %i\n", i);
_exit(-1);
} else {
LOGINFO("Joined thread %i.\n", i);
ret = (int)thread_return;
if (ret != 0) {
thread_error = 1;
LOGERR("Thread %i returned an error %i.\n", i, ret);
_exit(-1);
}
}
} else {
LOGINFO("Skipping joining thread %i because of pthread failure.\n", i);
}
}
if (thread_error) {
LOGERR("Error returned by one or more threads.\n");
_exit(-1);
}
LOGINFO("Finished encrypted backup.\n");
_exit(0);
}
}
else // parent process
{
if (TWFunc::Wait_For_Child(pid, &status, "extractTarFork()") != 0)
return -1;
}
}
else // fork has failed
{
LOGINFO("extract tar failed to fork.\n");
return -1;
}
return 0;
}
int twrpTar::splitArchiveFork() {
int status = 0;
pid_t pid, rc_pid;
pid = fork();
if (pid >= 0) // fork was successful
{
if (pid == 0) // child process
{
if (Split_Archive() <= 0)
_exit(-1);
else
_exit(0);
}
else // parent process
{
if (TWFunc::Wait_For_Child(pid, &status, "splitArchiveFork()") != 0)
return -1;
}
}
else // fork has failed
{
LOGINFO("split archive failed to fork.\n");
return -1;
}
return 0;
}
int twrpTar::Generate_TarList(string Path, std::vector<TarListStruct> *TarList, unsigned long long *Target_Size, unsigned *thread_id) {
DIR* d;
struct dirent* de;
struct stat st;
string FileName;
struct TarListStruct TarItem;
string::size_type i;
bool skip;
if (has_data_media == 1 && Path.size() >= 11 && strncmp(Path.c_str(), "/data/media", 11) == 0)
return 0; // Skip /data/media
d = opendir(Path.c_str());
if (d == NULL) {
LOGERR("error opening '%s' -- error: %s\n", Path.c_str(), strerror(errno));
closedir(d);
return -1;
}
while ((de = readdir(d)) != NULL) {
// Skip excluded stuff
if (split.size() > 0) {
skip = false;
for (i = 0; i < split.size(); i++) {
if (strcmp(de->d_name, split[i].c_str()) == 0) {
LOGINFO("excluding %s\n", de->d_name);
skip = true;
break;
}
}
if (skip)
continue;
}
FileName = Path + "/";
FileName += de->d_name;
if (has_data_media == 1 && FileName.size() >= 11 && strncmp(FileName.c_str(), "/data/media", 11) == 0)
continue; // Skip /data/media
if (de->d_type == DT_BLK || de->d_type == DT_CHR)
continue;
TarItem.fn = FileName;
TarItem.thread_id = *thread_id;
if (de->d_type == DT_DIR && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0 && strcmp(de->d_name, "lost+found") != 0) {
TarList->push_back(TarItem);
if (Generate_TarList(FileName, TarList, Target_Size, thread_id) < 0)
return -1;
} else if (de->d_type == DT_REG || de->d_type == DT_LNK) {
stat(FileName.c_str(), &st);
TarList->push_back(TarItem);
if (de->d_type == DT_REG)
Archive_Current_Size += st.st_size;
if (Archive_Current_Size != 0 && *Target_Size != 0 && Archive_Current_Size > *Target_Size) {
*thread_id = *thread_id + 1;
Archive_Current_Size = 0;
}
}
}
closedir(d);
return 0;
}
int twrpTar::Generate_Multiple_Archives(string Path) {
DIR* d;
struct dirent* de;
struct stat st;
string FileName;
char actual_filename[255];
string::size_type i;
bool skip;
if (has_data_media == 1 && Path.size() >= 11 && strncmp(Path.c_str(), "/data/media", 11) == 0)
return 0; // Skip /data/media
LOGINFO("Path: '%s', archive filename: '%s'\n", Path.c_str(), tarfn.c_str());
d = opendir(Path.c_str());
if (d == NULL)
{
LOGERR("error opening '%s' -- error: %s\n", Path.c_str(), strerror(errno));
closedir(d);
return -1;
}
while ((de = readdir(d)) != NULL) {
// Skip excluded stuff
if (split.size() > 0) {
skip = false;
for (i = 0; i < split.size(); i++) {
if (strcmp(de->d_name, split[i].c_str()) == 0) {
LOGINFO("excluding %s\n", de->d_name);
skip = true;
break;
}
}
if (skip) {
continue;
}
}
FileName = Path + "/";
FileName += de->d_name;
if (has_data_media == 1 && FileName.size() >= 11 && strncmp(FileName.c_str(), "/data/media", 11) == 0)
continue; // Skip /data/media
if (de->d_type == DT_BLK || de->d_type == DT_CHR)
continue;
if (de->d_type == DT_DIR && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0 && strcmp(de->d_name, "lost+foud") != 0)
{
unsigned long long folder_size = TWFunc::Get_Folder_Size(FileName, false);
if (Archive_Current_Size + folder_size > MAX_ARCHIVE_SIZE) {
LOGINFO("Calling Generate_Multiple_Archives\n");
if (Generate_Multiple_Archives(FileName) < 0)
return -1;
} else {
//FileName += "/";
LOGINFO("Adding folder '%s'\n", FileName.c_str());
tardir = FileName;
if (tarDirs(true) < 0)
return -1;
Archive_Current_Size += folder_size;
}
}
else if (de->d_type == DT_REG || de->d_type == DT_LNK)
{
stat(FileName.c_str(), &st);
if (de->d_type != DT_LNK) {
if (Archive_Current_Size != 0 && Archive_Current_Size + st.st_size > MAX_ARCHIVE_SIZE) {
LOGINFO("Closing tar '%s', ", tarfn.c_str());
closeTar();
if (TWFunc::Get_File_Size(tarfn) == 0) {
LOGERR("Backup file size for '%s' is 0 bytes.\n", tarfn.c_str());
return -1;
}
Archive_File_Count++;
if (Archive_File_Count > 999) {
LOGERR("Archive count is too large!\n");
return -1;
}
string temp = basefn + "%03i";
sprintf(actual_filename, temp.c_str(), Archive_File_Count);
tarfn = actual_filename;
Archive_Current_Size = 0;
LOGINFO("Creating tar '%s'\n", tarfn.c_str());
gui_print("Creating archive %i...\n", Archive_File_Count + 1);
if (createTar() != 0)
return -1;
}
}
LOGINFO("Adding file: '%s'... ", FileName.c_str());
if (addFile(FileName, true) < 0)
return -1;
if (de->d_type != DT_LNK) {
Archive_Current_Size += st.st_size;
}
LOGINFO("added successfully, archive size: %llu\n", Archive_Current_Size);
if (de->d_type != DT_LNK) {
if (st.st_size > 2147483648LL)
LOGERR("There is a file that is larger than 2GB in the file system\n'%s'\nThis file may not restore properly\n", FileName.c_str());
}
}
}
closedir(d);
return 0;
}
int twrpTar::Split_Archive()
{
string temp = tarfn + "%03i";
char actual_filename[255];
string tarsplit;
basefn = tarfn;
Archive_File_Count = 0;
Archive_Current_Size = 0;
sprintf(actual_filename, temp.c_str(), Archive_File_Count);
tarfn = actual_filename;
for (int i = 0; i < tarexclude.size(); ++i) {
tarsplit = tarexclude[i];
tarsplit += " ";
}
if (!tarexclude.empty())
split = TWFunc::split_string(tarsplit, ' ', true);
createTar();
DataManager::GetValue(TW_HAS_DATA_MEDIA, has_data_media);
gui_print("Creating archive 1...\n");
if (Generate_Multiple_Archives(tardir) < 0) {
LOGERR("Error generating multiple archives\n");
return -1;
}
closeTar();
LOGINFO("Done, created %i archives.\n", (++Archive_File_Count));
return (Archive_File_Count);
}
int twrpTar::extractTar() {
char* charRootDir = (char*) tardir.c_str();
if (openTar() == -1)
return -1;
if (tar_extract_all(t, charRootDir) != 0) {
LOGERR("Unable to extract tar archive '%s'\n", tarfn.c_str());
return -1;
}
if (tar_close(t) != 0) {
LOGERR("Unable to close tar file\n");
return -1;
}
return 0;
}
int twrpTar::extract() {
Archive_Current_Type = TWFunc::Get_File_Type(tarfn);
if (Archive_Current_Type == 1) {
//if you return the extractTGZ function directly, stack crashes happen
LOGINFO("Extracting gzipped tar\n");
int ret = extractTar();
return ret;
} else if (Archive_Current_Type == 2) {
string Password;
DataManager::GetValue("tw_restore_password", Password);
int ret = TWFunc::Try_Decrypting_File(tarfn, Password);
if (ret < 1) {
LOGERR("Failed to decrypt tar file '%s'\n", tarfn.c_str());
return -1;
}
if (ret == 1) {
LOGERR("Decrypted file is not in tar format.\n");
return -1;
}
if (ret == 3) {
LOGINFO("Extracting encrypted and compressed tar.\n");
Archive_Current_Type = 3;
} else
LOGINFO("Extracting encrypted tar.\n");
return extractTar();
} else {
LOGINFO("Extracting uncompressed tar\n");
return extractTar();
}
}
int twrpTar::tarDirs(bool include_root) {
DIR* d;
string mainfolder = tardir + "/", subfolder;
string tarsplit;
char buf[PATH_MAX], charTarPath[PATH_MAX];
string excl;
string::size_type i;
bool skip;
//set exclude directories for libtar
for (int i = 0; i < tarexclude.size(); ++i) {
excl += tarexclude.at(i);
tarsplit = tarexclude.at(i);
excl += " ";
tarsplit += " ";
}
d = opendir(tardir.c_str());
if (d != NULL) {
if (!tarsplit.empty()) {
split = TWFunc::split_string(tarsplit, ' ', true);
}
struct dirent* de;
while ((de = readdir(d)) != NULL) {
#ifdef RECOVERY_SDCARD_ON_DATA
if ((tardir == "/data" || tardir == "/data/") && strcmp(de->d_name, "media") == 0) continue;
#endif
if (de->d_type == DT_BLK || de->d_type == DT_CHR || strcmp(de->d_name, "..") == 0 || strcmp(de->d_name, "lost+found") == 0)
continue;
// Skip excluded stuff
if (split.size() > 0) {
skip = false;
for (i = 0; i < split.size(); i++) {
if (strcmp(de->d_name, split[i].c_str()) == 0) {
LOGINFO("excluding %s\n", de->d_name);
skip = true;
break;
}
}
if (skip) {
continue;
}
}
subfolder = mainfolder;
if (strcmp(de->d_name, ".") != 0) {
subfolder += de->d_name;
} else {
LOGINFO("addFile '%s' including root: %i\n", buf, include_root);
if (addFile(subfolder, include_root) != 0)
return -1;
continue;
}
strcpy(buf, subfolder.c_str());
if (de->d_type == DT_DIR) {
if (include_root) {
charTarPath[0] = NULL;
LOGINFO("tar_append_tree '%s' as NULL\n", buf, charTarPath);
if (tar_append_tree(t, buf, NULL, &excl[0]) != 0) {
LOGERR("Error appending '%s' to tar archive '%s'\n", buf, tarfn.c_str());
return -1;
}
} else {
string temp = Strip_Root_Dir(buf);
strcpy(charTarPath, temp.c_str());
LOGINFO("tar_append_tree '%s' as '%s'\n", buf, charTarPath);
if (tar_append_tree(t, buf, charTarPath, &excl[0]) != 0) {
LOGERR("Error appending '%s' to tar archive '%s'\n", buf, tarfn.c_str());
return -1;
}
}
} else if (tardir != "/" && (de->d_type == DT_REG || de->d_type == DT_LNK)) {
LOGINFO("addFile '%s' including root: %i\n", buf, include_root);
if (addFile(buf, include_root) != 0)
return -1;
}
fflush(NULL);
}
closedir(d);
}
return 0;
}
int twrpTar::tarList(bool include_root, std::vector<TarListStruct> *TarList, unsigned thread_id) {
struct stat st;
char buf[PATH_MAX];
int list_size = TarList->size(), i = 0, archive_count = 0;
string temp;
char actual_filename[PATH_MAX];
basefn = tarfn;
temp = basefn + "%i%02i";
sprintf(actual_filename, temp.c_str(), thread_id, archive_count);
tarfn = actual_filename;
if (createTar() != 0) {
LOGERR("Error creating tar '%s' for thread %i\n", tarfn.c_str(), thread_id);
return -2;
}
Archive_Current_Size = 0;
while (i < list_size) {
if (TarList->at(i).thread_id == thread_id) {
strcpy(buf, TarList->at(i).fn.c_str());
stat(buf, &st);
if (st.st_mode & S_IFREG) { // item is a regular file
if (Archive_Current_Size + (unsigned long long)(st.st_size) > MAX_ARCHIVE_SIZE) {
if (closeTar() != 0) {
LOGERR("Error closing '%s' on thread %i\n", tarfn.c_str(), thread_id);
return -3;
}
archive_count++;
LOGINFO("Splitting thread ID %i into archive %i\n", thread_id, archive_count);
if (archive_count > 99) {
LOGINFO("BLAH!\n");
LOGERR("Too many archives for thread %i\n", thread_id);
return -4;
}
sprintf(actual_filename, temp.c_str(), thread_id, archive_count);
tarfn = actual_filename;
if (createTar() != 0) {
LOGERR("Error creating tar '%s' for thread %i\n", tarfn.c_str(), thread_id);
return -2;
}
Archive_Current_Size = 0;
}
Archive_Current_Size += (unsigned long long)(st.st_size);
}
if (addFile(buf, include_root) != 0) {
LOGERR("Error adding file '%s' to '%s'\n", buf, tarfn.c_str());
return -1;
}
}
i++;
}
if (closeTar() != 0) {
LOGERR("Error closing '%s' on thread %i\n", tarfn.c_str(), thread_id);
return -3;
}
LOGINFO("Thread id %i tarList done, %i archives.\n", thread_id, archive_count, i, list_size);
return 0;
}
int twrpTar::create() {
init_libtar_buffer(0);
if (createTar() == -1)
return -1;
if (tarDirs(false) == -1)
return -1;
if (closeTar() == -1)
return -1;
free_libtar_buffer();
return 0;
}
void* twrpTar::createList(void *cookie) {
twrpTar* threadTar = (twrpTar*) cookie;
if (threadTar->tarList(true, threadTar->ItemList, threadTar->thread_id) == -1) {
LOGINFO("ERROR tarList for thread ID %i\n", threadTar->thread_id);
return (void*)-2;
}
LOGINFO("Thread ID %i finished successfully.\n", threadTar->thread_id);
return (void*)0;
}
void* twrpTar::extractMulti(void *cookie) {
twrpTar* threadTar = (twrpTar*) cookie;
int archive_count = 0;
string temp = threadTar->basefn + "%i%02i";
char actual_filename[255];
sprintf(actual_filename, temp.c_str(), threadTar->thread_id, archive_count);
while (TWFunc::Path_Exists(actual_filename)) {
threadTar->tarfn = actual_filename;
if (threadTar->extract() != 0) {
LOGINFO("Error extracting '%s' in thread ID %i\n", actual_filename, threadTar->thread_id);
return (void*)-2;
}
archive_count++;
if (archive_count > 99)
break;
sprintf(actual_filename, temp.c_str(), threadTar->thread_id, archive_count);
}
LOGINFO("Thread ID %i finished successfully.\n", threadTar->thread_id);
return (void*)0;
}
int twrpTar::addFilesToExistingTar(vector <string> files, string fn) {
char* charTarFile = (char*) fn.c_str();
if (tar_open(&t, charTarFile, NULL, O_RDONLY | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) == -1)
return -1;
removeEOT(charTarFile);
if (tar_open(&t, charTarFile, NULL, O_WRONLY | O_APPEND | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) == -1)
return -1;
for (unsigned int i = 0; i < files.size(); ++i) {
char* file = (char*) files.at(i).c_str();
if (tar_append_file(t, file, file) == -1)
return -1;
}
if (tar_append_eof(t) == -1)
return -1;
if (tar_close(t) == -1)
return -1;
return 0;
}
int twrpTar::createTar() {
char* charTarFile = (char*) tarfn.c_str();
char* charRootDir = (char*) tardir.c_str();
static tartype_t type = { open, close, read, write_tar };
string Password;
if (use_encryption && use_compression) {
// Compressed and encrypted
Archive_Current_Type = 3;
LOGINFO("Using encryption and compression...\n");
DataManager::GetValue("tw_backup_password", Password);
int i, pipes[4];
if (pipe(pipes) < 0) {
LOGERR("Error creating first pipe\n");
return -1;
}
if (pipe(pipes + 2) < 0) {
LOGERR("Error creating second pipe\n");
return -1;
}
pigz_pid = fork();
if (pigz_pid < 0) {
LOGERR("pigz fork() failed\n");
for (i = 0; i < 4; i++)
close(pipes[i]); // close all
return -1;
} else if (pigz_pid == 0) {
// pigz Child
close(pipes[1]);
close(pipes[2]);
close(0);
dup2(pipes[0], 0);
close(1);
dup2(pipes[3], 1);
if (execlp("pigz", "pigz", "-", NULL) < 0) {
LOGERR("execlp pigz ERROR!\n");
close(pipes[0]);
close(pipes[3]);
_exit(-1);
}
} else {
// Parent
oaes_pid = fork();
if (oaes_pid < 0) {
LOGERR("openaes fork() failed\n");
for (i = 0; i < 4; i++)
close(pipes[i]); // close all
return -1;
} else if (oaes_pid == 0) {
// openaes Child
int output_fd = open(tarfn.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (output_fd < 0) {
LOGERR("Failed to open '%s'\n", tarfn.c_str());
for (i = 0; i < 4; i++)
close(pipes[i]); // close all
return -1;
}
close(pipes[0]);
close(pipes[1]);
close(pipes[3]);
close(0);
dup2(pipes[2], 0);
close(1);
dup2(output_fd, 1);
if (execlp("openaes", "openaes", "enc", "--key", Password.c_str(), NULL) < 0) {
LOGERR("execlp openaes ERROR!\n");
close(pipes[2]);
close(output_fd);
_exit(-1);
}
} else {
// Parent
close(pipes[0]);
close(pipes[2]);
close(pipes[3]);
fd = pipes[1];
if(tar_fdopen(&t, fd, charRootDir, NULL, O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) != 0) {
close(fd);
LOGERR("tar_fdopen failed\n");
return -1;
}
return 0;
}
}
} else if (use_compression) {
// Compressed
Archive_Current_Type = 1;
LOGINFO("Using compression...\n");
int pigzfd[2];
if (pipe(pigzfd) < 0) {
LOGERR("Error creating pipe\n");
return -1;
}
pigz_pid = fork();
if (pigz_pid < 0) {
LOGERR("fork() failed\n");
close(pigzfd[0]);
close(pigzfd[1]);
return -1;
} else if (pigz_pid == 0) {
// Child
close(pigzfd[1]); // close unused output pipe
int output_fd = open(tarfn.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (output_fd < 0) {
LOGERR("Failed to open '%s'\n", tarfn.c_str());
close(pigzfd[0]);
_exit(-1);
}
dup2(pigzfd[0], 0); // remap stdin
dup2(output_fd, 1); // remap stdout to output file
if (execlp("pigz", "pigz", "-", NULL) < 0) {
LOGERR("execlp pigz ERROR!\n");
close(output_fd);
close(pigzfd[0]);
_exit(-1);
}
} else {
// Parent
close(pigzfd[0]); // close parent input
fd = pigzfd[1]; // copy parent output
if(tar_fdopen(&t, fd, charRootDir, NULL, O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) != 0) {
close(fd);
LOGERR("tar_fdopen failed\n");
return -1;
}
}
} else if (use_encryption) {
// Encrypted
Archive_Current_Type = 2;
LOGINFO("Using encryption...\n");
DataManager::GetValue("tw_backup_password", Password);
int oaesfd[2];
pipe(oaesfd);
oaes_pid = fork();
if (oaes_pid < 0) {
LOGERR("fork() failed\n");
close(oaesfd[0]);
close(oaesfd[1]);
return -1;
} else if (oaes_pid == 0) {
// Child
close(oaesfd[1]); // close unused
int output_fd = open(tarfn.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (output_fd < 0) {
LOGERR("Failed to open '%s'\n", tarfn.c_str());
_exit(-1);
}
dup2(oaesfd[0], 0); // remap stdin
dup2(output_fd, 1); // remap stdout to output file
if (execlp("openaes", "openaes", "enc", "--key", Password.c_str(), NULL) < 0) {
LOGERR("execlp openaes ERROR!\n");
close(output_fd);
close(oaesfd[0]);
_exit(-1);
}
} else {
// Parent
close(oaesfd[0]); // close parent input
fd = oaesfd[1]; // copy parent output
if(tar_fdopen(&t, fd, charRootDir, NULL, O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) != 0) {
close(fd);
LOGERR("tar_fdopen failed\n");
return -1;
}
return 0;
}
} else {
// Not compressed or encrypted
init_libtar_buffer(0);
if (tar_open(&t, charTarFile, &type, O_WRONLY | O_CREAT | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) == -1) {
LOGERR("tar_open error opening '%s'\n", tarfn.c_str());
return -1;
}
}
return 0;
}
int twrpTar::openTar() {
char* charRootDir = (char*) tardir.c_str();
char* charTarFile = (char*) tarfn.c_str();
string Password;
if (Archive_Current_Type == 3) {
LOGINFO("Opening encrypted and compressed backup...\n");
DataManager::GetValue("tw_restore_password", Password);
int i, pipes[4];
if (pipe(pipes) < 0) {
LOGERR("Error creating first pipe\n");
return -1;
}
if (pipe(pipes + 2) < 0) {
LOGERR("Error creating second pipe\n");
return -1;
}
oaes_pid = fork();
if (oaes_pid < 0) {
LOGERR("pigz fork() failed\n");
for (i = 0; i < 4; i++)
close(pipes[i]); // close all
return -1;
} else if (oaes_pid == 0) {
// openaes Child
close(pipes[0]); // Close pipes that are not used by this child
close(pipes[2]);
close(pipes[3]);
int input_fd = open(tarfn.c_str(), O_RDONLY | O_LARGEFILE);
if (input_fd < 0) {
LOGERR("Failed to open '%s'\n", tarfn.c_str());
close(pipes[1]);
_exit(-1);
}
close(0);
dup2(input_fd, 0);
close(1);
dup2(pipes[1], 1);
if (execlp("openaes", "openaes", "dec", "--key", Password.c_str(), NULL) < 0) {
LOGERR("execlp openaes ERROR!\n");
close(input_fd);
close(pipes[1]);
_exit(-1);
}
} else {
// Parent
pigz_pid = fork();
if (pigz_pid < 0) {
LOGERR("openaes fork() failed\n");
for (i = 0; i < 4; i++)
close(pipes[i]); // close all
return -1;
} else if (pigz_pid == 0) {
// pigz Child
close(pipes[1]); // Close pipes not used by this child
close(pipes[2]);
close(0);
dup2(pipes[0], 0);
close(1);
dup2(pipes[3], 1);
if (execlp("pigz", "pigz", "-d", "-c", NULL) < 0) {
LOGERR("execlp pigz ERROR!\n");
close(pipes[0]);
close(pipes[3]);
_exit(-1);
}
} else {
// Parent
close(pipes[0]); // Close pipes not used by parent
close(pipes[1]);
close(pipes[3]);
fd = pipes[2];
if(tar_fdopen(&t, fd, charRootDir, NULL, O_RDONLY | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) != 0) {
close(fd);
LOGERR("tar_fdopen failed\n");
return -1;
}
}
}
} else if (Archive_Current_Type == 2) {
LOGINFO("Opening encrypted backup...\n");
DataManager::GetValue("tw_restore_password", Password);
int oaesfd[2];
pipe(oaesfd);
oaes_pid = fork();
if (oaes_pid < 0) {
LOGERR("fork() failed\n");
close(oaesfd[0]);
close(oaesfd[1]);
return -1;
} else if (oaes_pid == 0) {
// Child
close(oaesfd[0]); // Close unused pipe
int input_fd = open(tarfn.c_str(), O_RDONLY | O_LARGEFILE);
if (input_fd < 0) {
LOGERR("Failed to open '%s'\n", tarfn.c_str());
close(oaesfd[1]);
_exit(-1);
}
close(0); // close stdin
dup2(oaesfd[1], 1); // remap stdout
dup2(input_fd, 0); // remap input fd to stdin
if (execlp("openaes", "openaes", "dec", "--key", Password.c_str(), NULL) < 0) {
LOGERR("execlp openaes ERROR!\n");
close(input_fd);
close(oaesfd[1]);
_exit(-1);
}
} else {
// Parent
close(oaesfd[1]); // close parent output
fd = oaesfd[0]; // copy parent input
if(tar_fdopen(&t, fd, charRootDir, NULL, O_RDONLY | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) != 0) {
close(fd);
LOGERR("tar_fdopen failed\n");
return -1;
}
}
} else if (Archive_Current_Type == 1) {
LOGINFO("Opening as a gzip...\n");
int pigzfd[2];
pipe(pigzfd);
pigz_pid = fork();
if (pigz_pid < 0) {
LOGERR("fork() failed\n");
close(pigzfd[0]);
close(pigzfd[1]);
return -1;
} else if (pigz_pid == 0) {
// Child
close(pigzfd[0]);
int input_fd = open(tarfn.c_str(), O_RDONLY | O_LARGEFILE);
if (input_fd < 0) {
LOGERR("Failed to open '%s'\n", tarfn.c_str());
_exit(-1);
}
dup2(input_fd, 0); // remap input fd to stdin
dup2(pigzfd[1], 1); // remap stdout
if (execlp("pigz", "pigz", "-d", "-c", NULL) < 0) {
close(pigzfd[1]);
close(input_fd);
LOGERR("execlp openaes ERROR!\n");
_exit(-1);
}
} else {
// Parent
close(pigzfd[1]); // close parent output
fd = pigzfd[0]; // copy parent input
if(tar_fdopen(&t, fd, charRootDir, NULL, O_RDONLY | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) != 0) {
close(fd);
LOGERR("tar_fdopen failed\n");
return -1;
}
}
} else if (tar_open(&t, charTarFile, NULL, O_RDONLY | O_LARGEFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, TAR_GNU) != 0) {
LOGERR("Unable to open tar archive '%s'\n", charTarFile);
return -1;
}
return 0;
}
string twrpTar::Strip_Root_Dir(string Path) {
string temp;
size_t slash;
if (Path.substr(0, 1) == "/")
temp = Path.substr(1, Path.size() - 1);
else
temp = Path;
slash = temp.find("/");
if (slash == string::npos)
return temp;
else {
string stripped;
stripped = temp.substr(slash, temp.size() - slash);
return stripped;
}
return temp;
}
int twrpTar::addFile(string fn, bool include_root) {
char* charTarFile = (char*) fn.c_str();
if (include_root) {
if (tar_append_file(t, charTarFile, NULL) == -1)
return -1;
} else {
string temp = Strip_Root_Dir(fn);
char* charTarPath = (char*) temp.c_str();
if (tar_append_file(t, charTarFile, charTarPath) == -1)
return -1;
}
return 0;
}
int twrpTar::closeTar() {
flush_libtar_buffer(t->fd);
if (tar_append_eof(t) != 0) {
LOGERR("tar_append_eof(): %s\n", strerror(errno));
tar_close(t);
return -1;
}
if (tar_close(t) != 0) {
LOGERR("Unable to close tar archive: '%s'\n", tarfn.c_str());
return -1;
}
if (Archive_Current_Type > 0) {
close(fd);
int status;
if (pigz_pid > 0 && TWFunc::Wait_For_Child(pigz_pid, &status, "pigz") != 0)
return -1;
if (oaes_pid > 0 && TWFunc::Wait_For_Child(oaes_pid, &status, "openaes") != 0)
return -1;
}
free_libtar_buffer();
return 0;
}
int twrpTar::removeEOT(string tarFile) {
char* charTarFile = (char*) tarFile.c_str();
off_t tarFileEnd;
while (th_read(t) == 0) {
if (TH_ISREG(t))
tar_skip_regfile(t);
tarFileEnd = lseek(t->fd, 0, SEEK_CUR);
}
if (tar_close(t) == -1)
return -1;
if (truncate(charTarFile, tarFileEnd) == -1)
return -1;
return 0;
}
int twrpTar::entryExists(string entry) {
char* searchstr = (char*)entry.c_str();
int ret;
Archive_Current_Type = TWFunc::Get_File_Type(tarfn);
if (openTar() == -1)
ret = 0;
else
ret = tar_find(t, searchstr);
if (closeTar() != 0)
LOGINFO("Unable to close tar after searching for entry.\n");
return ret;
}
unsigned long long twrpTar::uncompressedSize() {
int type = 0;
unsigned long long total_size = 0;
string Tar, Command, result;
vector<string> split;
Tar = TWFunc::Get_Filename(tarfn);
type = TWFunc::Get_File_Type(tarfn);
if (type == 0)
total_size = TWFunc::Get_File_Size(tarfn);
else {
Command = "pigz -l " + tarfn;
/* if we set Command = "pigz -l " + tarfn + " | sed '1d' | cut -f5 -d' '";
we get the uncompressed size at once. */
TWFunc::Exec_Cmd(Command, result);
if (!result.empty()) {
/* Expected output:
compressed original reduced name
95855838 179403776 -1.3% data.yaffs2.win
^
split[5]
*/
split = TWFunc::split_string(result, ' ', true);
if (split.size() > 4)
total_size = atoi(split[5].c_str());
}
}
LOGINFO("%s's uncompressed size: %llu bytes\n", Tar.c_str(), total_size);
return total_size;
}
extern "C" ssize_t write_tar(int fd, const void *buffer, size_t size) {
return (ssize_t) write_libtar_buffer(fd, buffer, size);
}
| [
"maximik@list.ru"
] | maximik@list.ru |
86686e144b7cfb4a00e18654dbaad6b7349512f8 | 5a60acb7da51b8493c7699e4222f484ad633ca7f | /branches/map65/astro.cpp | f861a6ce22ac958624ed5ffed1d6cf4c1a2390fe | [
"BSD-2-Clause",
"BSD-2-Clause-Views"
] | permissive | BackupTheBerlios/wsjt-svn | 447db90ba48af2a43e0c244f4873224c987a4d2d | a76ef285f8b7305f92c79ce8eebf1bd1831a1fa2 | refs/heads/master | 2021-01-02T22:51:37.851022 | 2014-02-09T11:27:11 | 2014-02-09T11:27:11 | 40,800,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,833 | cpp | #include "astro.h"
#include "ui_astro.h"
#include <QDebug>
#include <QFile>
#include <QMessageBox>
#include <stdio.h>
#include "commons.h"
Astro::Astro(QWidget *parent) :
QWidget(parent),
ui(new Ui::Astro)
{
ui->setupUi(this);
ui->astroTextBrowser->setStyleSheet(
"QTextBrowser { background-color : cyan; color : black; }");
ui->astroTextBrowser->clear();
}
Astro::~Astro()
{
delete ui;
}
void Astro::astroUpdate(QDateTime t, QString mygrid, QString hisgrid,
int fQSO, int nsetftx, int ntxFreq, QString azelDir)
{
static int ntxFreq0=-99;
static bool astroBusy=false;
char cc[300];
double azsun,elsun,azmoon,elmoon,azmoondx,elmoondx;
double ramoon,decmoon,dgrd,poloffset,xnr;
int ntsky,ndop,ndop00;
QString date = t.date().toString("yyyy MMM dd");
QString utc = t.time().toString();
int nyear=t.date().year();
int month=t.date().month();
int nday=t.date().day();
int nhr=t.time().hour();
int nmin=t.time().minute();
double sec=t.time().second() + 0.001*t.time().msec();
int isec=sec;
double uth=nhr + nmin/60.0 + sec/3600.0;
int nfreq=(int)datcom_.fcenter;
if(nfreq<10 or nfreq > 50000) nfreq=144;
if(!astroBusy) {
astroBusy=true;
astrosub_(&nyear, &month, &nday, &uth, &nfreq, mygrid.toAscii(),
hisgrid.toAscii(), &azsun, &elsun, &azmoon, &elmoon,
&azmoondx, &elmoondx, &ntsky, &ndop, &ndop00,&ramoon, &decmoon,
&dgrd, &poloffset, &xnr, 6, 6);
astroBusy=false;
}
sprintf(cc,
"Az: %6.1f\n"
"El: %6.1f\n"
"MyDop: %6d\n"
"DxAz: %6.1f\n"
"DxEl: %6.1f\n"
"DxDop: %6d\n"
"Dec: %6.1f\n"
"SunAz: %6.1f\n"
"SunEl: %6.1f\n"
"Tsky: %6d\n"
"MNR: %6.1f\n"
"Dgrd: %6.1f",
azmoon,elmoon,ndop00,azmoondx,elmoondx,ndop,decmoon,azsun,elsun,
ntsky,xnr,dgrd);
ui->astroTextBrowser->setText(" "+ date + "\nUTC: " + utc + "\n" + cc);
QString fname=azelDir+"/azel.dat";
QFile f(fname);
if(!f.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox mb;
mb.setText("Cannot open " + fname);
mb.exec();
return;
}
int ndiff=0;
if(ntxFreq != ntxFreq0) ndiff=1;
ntxFreq0=ntxFreq;
QTextStream out(&f);
sprintf(cc,"%2.2d:%2.2d:%2.2d,%5.1f,%5.1f,Moon\n"
"%2.2d:%2.2d:%2.2d,%5.1f,%5.1f,Sun\n"
"%2.2d:%2.2d:%2.2d,%5.1f,%5.1f,Source\n"
"%4d,%6d,Doppler\n"
"%3d,%1d,fQSO\n"
"%3d,%1d,fQSO2\n",
nhr,nmin,isec,azmoon,elmoon,
nhr,nmin,isec,azsun,elsun,
nhr,nmin,isec,0.0,0.0,
nfreq,ndop,
fQSO,nsetftx,
ntxFreq,ndiff);
out << cc;
f.close();
}
void Astro::setFontSize(int n)
{
ui->astroTextBrowser->setFontPointSize(n);
}
| [
"k1jt@b3ca0830-8508-0410-8253-dac51d8a7955"
] | k1jt@b3ca0830-8508-0410-8253-dac51d8a7955 |
ee233fc727c8747a369d9289e806b9dcf3c1ba84 | a5f34d9ded886e3161cb9f259c39de5cd489f9b0 | /objects/xVDashboardView.h | bd650a2a1c2d73b7804f44fe141b3e349e0f2ae0 | [] | no_license | CDullin/xVTK | a9cdee0668aec0c4ea80829e9ea0d2bc880aaed3 | c18b989284b397b58a8bcf948e4a2d779dea76ac | refs/heads/main | 2023-06-27T23:40:52.912622 | 2021-07-29T09:38:07 | 2021-07-29T09:38:07 | 345,925,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 943 | h | #ifndef XVDASHBOARDVIEW_H
#define XVDASHBOARDVIEW_H
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItemGroup>
#include <QGraphicsPixmapItem>
#include <QGraphicsRectItem>
#include "xVCustomGraphicItems.h"
#include "xVTypes.h"
class xVDashboardView: public QGraphicsView
{
Q_OBJECT
public:
xVDashboardView(QWidget *parent = nullptr);
public slots:
void updateMap();
void moveScrollArea(QPointF);
void KSlot(const SIG_TYPE& t,void *pData=nullptr);
protected slots:
void switchPosition();
void deselectAll();
void rDblClickInScene();
signals:
void KSignal(const SIG_TYPE& t,void *pData=nullptr);
protected:
QGraphicsView *pMapView = nullptr;
xGroupItem *pMapGrpItem = nullptr;
QGraphicsPixmapItem *pMapPixItem = nullptr;
QGraphicsRectItem *pFrameItem = nullptr;
xRectItem *pViewportRectItem = nullptr;
bool _topRight = true;
};
#endif // XVDASHBOARDVIEW_H
| [
"christian.dullin@protonmail.com"
] | christian.dullin@protonmail.com |
5ef74688989eecc75001def3b0ffadff17cede78 | 01fc4fad267a64afe431447f0091db638ec9fb24 | /TreeReaderTests/TextTreeVisitorTests.cpp | 495b89764cbdb4fd9cd81841446603a2111c00b2 | [] | no_license | Qt-Widgets/TreeReader | f8bd2588af312ace96ba352e3b44d3cd229bcd37 | f0e6f84a1f8837d37eab7cd2732db54aa0c3abe2 | refs/heads/master | 2021-03-08T15:11:42.414363 | 2020-03-10T16:21:17 | 2020-03-10T16:21:17 | 246,354,184 | 1 | 0 | null | 2020-03-10T16:37:24 | 2020-03-10T16:37:24 | null | UTF-8 | C++ | false | false | 1,921 | cpp | #include "TextTreeVisitor.h"
#include "TreeReaderTestHelpers.h"
#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
using namespace TreeReader;
namespace TreeReaderTests
{
TEST_CLASS(TextTreeVisitorTests)
{
public:
TEST_METHOD(VisitEmptyTree)
{
size_t visits = 0;
VisitInOrder(TextTree(), FunctionTreeVisitor([&visits](const TextTree& tree, const TextTree::Node& node, size_t level)
{
visits += 1;
return TreeVisitor::Result();
}));
Assert::AreEqual<size_t>(0, visits);
}
TEST_METHOD(VisitSimpleTree)
{
size_t visits = 0;
VisitInOrder(CreateSimpleTree(), FunctionTreeVisitor([&visits](const TextTree& tree, const TextTree::Node& node, size_t level)
{
visits += 1;
return TreeVisitor::Result();
}));
Assert::AreEqual<size_t>(8, visits);
}
TEST_METHOD(VisitSimpleTreeWithDelegate)
{
size_t visits = 0;
auto visitor = make_shared<FunctionTreeVisitor>([&visits](const TextTree& tree, const TextTree::Node& node, size_t level)
{
visits += 1;
return TreeVisitor::Result();
});
VisitInOrder(CreateSimpleTree(), DelegateTreeVisitor(visitor));
Assert::AreEqual<size_t>(8, visits);
}
TEST_METHOD(VisitSimpleTreeWithAbort)
{
size_t visits = 0;
auto visitor = make_shared<FunctionTreeVisitor>([&visits](const TextTree& tree, const TextTree::Node& node, size_t level)
{
visits += 1;
return TreeVisitor::Result();
});
CanAbortTreeVisitor abort(visitor);
abort.Abort = true;
VisitInOrder(CreateSimpleTree(), abort);
Assert::AreEqual<size_t>(0, visits);
}
};
}
| [
"pierrebai@hotmail.com"
] | pierrebai@hotmail.com |
a5eced76d97f4af53196b73d035966f8909618d6 | 0901e36429c0f9aeedfba15e8bf20f44b03f0a52 | /Framework/EventFramework/ControllerEvent.h | de86d7d4f853b485f08e56439a49fcf1b80a1742 | [
"BSD-3-Clause"
] | permissive | SergeyIvanov87/TTL | 84fb7771fb4b40f86529e0ddd38652a121caa876 | 442633703dafac28c499bb0b76afe51ae87a12bf | refs/heads/master | 2023-05-02T09:55:01.121003 | 2023-04-22T21:36:47 | 2023-04-22T21:36:47 | 138,077,585 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,148 | h | #ifndef CONTROLLER_EVENT_H
#define CONTROLLER_EVENT_H
#include <variant>
#include <memory>
#include "EventTypeTraitsDeclaration.h"
//Common template controller event, for all registered ControlEventID ID
template<class ...EventTypes>
struct CommonControllerEvent
{
//variant stores all registered ControlEventID appropriated classes, using traits
using EventTypeHolderList = std::tuple<
//std::nullptr_t,
typename EventTypeTraits<EventTypes>::EventTypeUniquePtr ...>;
using EventTypeHolderImpl = std::variant<
//std::nullptr_t,
typename EventTypeTraits<EventTypes>::EventTypeUniquePtr ...>;
CommonControllerEvent() = default;
template<class SpecificEventPtr, typename = std::enable_if_t
<
std::is_constructible
<
EventTypeHolderImpl, SpecificEventPtr
>::value
>
>
CommonControllerEvent(SpecificEventPtr &&eventPtr) :
m_eventHolder(std::forward<SpecificEventPtr>(eventPtr))
{
}
CommonControllerEvent(CommonControllerEvent &&eventPtr) = default;
ControlEventID getEventType() const;
EventTypeHolderImpl m_eventHolder;
/* int getButton() const
{
switch(m_eventHolder.index())
{
case ControlEventID::MOUSE_EVENT:
return static_cast<int>(std::get<ControlEventID::MOUSE_EVENT>(m_eventHolder)->getEventTypeCtrlId());
case ControlEventID::KEYBOARD_EVENT:
return static_cast<int>(std::get<ControlEventID::KEYBOARD_EVENT>(m_eventHolder)->getEventTypeCtrlId().key);
default:
//TODO
assert(false);
}
}*/
};
#endif //CONTROLLER_EVENT_H
| [
"sergius140608@rambler.ru"
] | sergius140608@rambler.ru |
4208f1b55b7df0d8b221a997b2a0d8dc4d7c3f1d | 757ef734d0abe7156b8da6d53749058f9d6c93dc | /Firmware/source/src/controls/control.cpp | 5708ad06d9cd28dda3ba380ac8471278b63b7397 | [
"MIT"
] | permissive | WPI-AIM/AutoBVM | e674091be7798e2cc780c986e6e307f1487d3586 | 38aa8c50d74af872d0b5bbefa0d30b00e5c05d19 | refs/heads/master | 2023-05-26T15:20:04.475752 | 2023-05-20T00:25:27 | 2023-05-20T00:25:27 | 249,450,286 | 4 | 1 | MIT | 2023-05-20T00:25:29 | 2020-03-23T14:16:18 | C++ | UTF-8 | C++ | false | false | 18,286 | cpp | #include "control.h"
#include <display/main_display.h>
#include <utilities/util.h>
#include "../config/uvent_conf.h"
#include "actuators/actuator.h"
#include "eeprom/storage.h"
#include "sensors/pressure_sensor.h"
#include "waveform.h"
#include "alarm/alarm.h"
#include <AccelStepper.h>
#include <DueTimer.h>
#include <ams_as5048b.h>
#include <display/screens/screen.h>
#include <display/layouts/layouts.h>
// Instance to control the paddle
Actuator actuator;
// Storage instance
Storage storage;
// Gauge Pressure Sensor instance
PressureSensor gauge_sensor = {PRESSURE_GAUGE_PIN};
// Differential Pressure Sensor instance
PressureSensor diff_sensor = {PRESSURE_DIFF_PIN};
// Waveform instance
Waveform waveform;
uint32_t cycle_count = 0;
// Alarms
AlarmManager alarm_manager{SPEAKER_PIN, &cycle_count};
/* State machine instance. Takes in a pointer to actuator
* as there are actuator commands within the state machine.
*/
Machine machine(States::ST_STARTUP, &actuator, &waveform, &gauge_sensor, &alarm_manager, &cycle_count);
// Bool to keep track of the alert box
static bool alert_box_already_visible = false;
void loop_test_readout(lv_timer_t* timer)
{
static bool timer_delay_complete = false;
// Internal timers, components might have different refresh times
static uint32_t last_readout_refresh = 0;
// Don't poll the sensors before we're sure everything's had a chance to init
if (!timer_delay_complete && (millis() >= SENSOR_POLL_STARTUP_DELAY)) {
timer_delay_complete = true;
// Set some dummy alarms
cycle_count++;
alarm_manager.badPlateau(true);
alarm_manager.lowPressure(true);
alarm_manager.noTidalPres(true);
alarm_manager.update();
}
if (!timer_delay_complete) {
LV_LOG_TRACE("Timer is not ready yet, returning (%d)", millis());
return;
}
// If verbose data polling is off, polling / updates won't be done if the state machine is off
// If in debug screen mode, it won't be done if we're in startup state either
#if VERBOSE_DATA_POLLING == 0
States cur_state = control_get_state();
if (cur_state == States::ST_OFF || (!ENABLE_CONTROL && cur_state == States::ST_STARTUP)) {
return;
}
#endif
// Main screen, passed through via user data in main.cpp
auto* screen = static_cast<MainScreen*>(timer->user_data);
// Check for errors
handle_alerts();
// Poll gauge sensor, add point to graph and update readout obj.
// Will not refresh until explicitly told
static double cur_pressure = -2;
screen->get_chart(CHART_IDX_PRESSURE)->add_data_point(cur_pressure);
set_readout(AdjValueType::CUR_PRESSURE, cur_pressure);
screen->get_chart(CHART_IDX_FLOW)->add_data_point(cur_pressure);
set_readout(AdjValueType::PLAT_PRESSURE, cur_pressure);
cur_pressure += 1;
cur_pressure += random(100) / 100.0;
if (cur_pressure > 40) {
cur_pressure -= 42;
}
// Poll vT sensor, add point to graph and update readout obj.
// Will not refresh until explicitly told
static int16_t test2 = 0;
double cur_tidal_volume = test2;
set_readout(AdjValueType::TIDAL_VOLUME, cur_tidal_volume);
test2 += 50;
if (test2 > 1000) {
test2 -= 1002;
}
set_readout(RESPIRATION_RATE, 30);
set_readout(PEEP, 30);
set_readout(PIP, 30);
// Check to see if it's time to refresh the readout boxes
if (has_time_elapsed(&last_readout_refresh, READOUT_REFRESH_INTERVAL)) {
// Refresh all of the readout labels
for (auto& value : adjustable_values) {
if (!value.is_dirty()) {
continue;
}
value.refresh_readout();
value.clear_dirty();
}
}
screen->try_refresh_charts();
}
void loop_update_readouts(lv_timer_t* timer)
{
static bool timer_delay_complete = false;
// Internal timers, components might have different refresh times
static uint32_t last_readout_refresh = 0;
// Don't poll the sensors before we're sure everything's had a chance to init
if (!timer_delay_complete && (millis() >= SENSOR_POLL_STARTUP_DELAY)) {
timer_delay_complete = true;
}
if (!timer_delay_complete) {
LV_LOG_TRACE("Timer is not ready yet, returning (%d)", millis());
return;
}
// If verbose data polling is off, polling / updates won't be done if the state machine is off
// If in debug screen mode, it won't be done if we're in startup state either
#if VERBOSE_DATA_POLLING == 0
States cur_state = control_get_state();
if (cur_state == States::ST_OFF || (!ENABLE_CONTROL && cur_state == States::ST_STARTUP)) {
return;
}
#endif
// Main screen, passed through via user data in main.cpp
auto* screen = static_cast<MainScreen*>(timer->user_data);
// Check for errors
handle_alerts();
// Poll gauge sensor, add point to graph and update readout obj.
// Will not refresh until explicitly told
double cur_pressure = control_get_gauge_pressure();
screen->get_chart(CHART_IDX_PRESSURE)->add_data_point(cur_pressure);
set_readout(AdjValueType::CUR_PRESSURE, cur_pressure);
// Poll sensors, update readout obj.
// Will not refresh until explicitly told
// Waveform parameters
waveform_params* p_wave_params = control_get_waveform_params();
set_readout(AdjValueType::TIDAL_VOLUME, p_wave_params->m_tidal_volume);
set_readout(AdjValueType::RESPIRATION_RATE, p_wave_params->m_rr);
set_readout(AdjValueType::IE_RATIO_LEFT, p_wave_params->m_ie_i);
set_readout(AdjValueType::IE_RATIO_RIGHT, p_wave_params->m_ie_e);
set_readout(AdjValueType::PEEP, p_wave_params->m_peep);
set_readout(AdjValueType::PIP, p_wave_params->m_pip);
set_readout(AdjValueType::PLAT_PRESSURE, p_wave_params->m_plateau_press);
double cur_flow = diff_sensor.get_flow(units_flow::lpm, true, Order_type::third);
screen->get_chart(CHART_IDX_FLOW)->add_data_point(cur_flow);
set_readout(AdjValueType::FLOW, cur_flow);
// TODO add more sensors HERE
// Check to see if it's time to refresh the readout boxes
if (has_time_elapsed(&last_readout_refresh, READOUT_REFRESH_INTERVAL)) {
// Refresh all of the readout labels
for (auto& value : adjustable_values) {
if (!value.is_dirty()) {
continue;
}
value.refresh_readout();
value.clear_dirty();
}
}
screen->try_refresh_charts();
}
void handle_alerts()
{
static uint16_t last_alarm_count = 0;
uint16_t alarm_count = control_get_alarm_count();
if (alarm_count <= 0 && alert_box_already_visible) {
alert_box_already_visible = false;
last_alarm_count = 0;
set_alert_count_visual(0);
set_alert_text("");
set_alert_box_visible(false);
return;
}
if (alarm_count > 0 && !alert_box_already_visible) {
alert_box_already_visible = true;
set_alert_box_visible(true);
}
if (last_alarm_count != alarm_count) {
last_alarm_count = alarm_count;
Alarm* alarm_arr = control_get_alarm_list();
String alarm_strings[NUM_ALARMS];
uint16_t buf_size = 0;
uint16_t alarm_list_idx = 0;
for (uint16_t i = 0; i < NUM_ALARMS; i++) {
Alarm* a = &alarm_arr[i];
if (!a->isON()) {
continue;
}
buf_size += a->text().length();
alarm_strings[alarm_list_idx++] = a->text();
}
set_alert_count_visual(alarm_count);
set_alert_text(alarm_strings, alarm_count, buf_size);
}
}
void control_update_waveform_param(AdjValueType type, float new_value)
{
if (type >= AdjValueType::ADJ_VALUE_COUNT) {
return;
}
waveform_params* wave_params = control_get_waveform_params();
switch (type) {
case TIDAL_VOLUME:
wave_params->volume_ml = new_value;
LV_LOG_INFO("Tidal Volume is now %.1f", new_value);
break;
case RESPIRATION_RATE:
wave_params->bpm = (uint16_t) new_value;
LV_LOG_INFO("Respiration Rate is now %.1f", new_value);
break;
case PIP:
wave_params->pip = (uint16_t) new_value;
LV_LOG_INFO("PIP is now %.1f", new_value);
break;
case PEEP:
wave_params->peep = (uint16_t) new_value;
LV_LOG_INFO("PEEP is now %.1f", new_value);
break;
case PLATEAU_TIME:
wave_params->plateau_time = (uint16_t) new_value;
LV_LOG_INFO("PLATEAU TIME is now %.1f", new_value);
break;
case IE_RATIO_LEFT:
wave_params->ie_i = new_value;
LV_LOG_INFO("IE Inspiration is now %.1f", new_value);
break;
case IE_RATIO_RIGHT:
wave_params->ie_e = new_value;
LV_LOG_INFO("IE Expiration is now %.1f", new_value);
break;
default:
break;
}
}
/**
* Loads a target value from EEPROM at startup and sets it to its interface class.
* This function will recalculate the waveform itself, no other action is needed.
* @param value The value we're loading.
* @param settings Pre-Loaded settings object to retrieve from.
*/
static void load_stored_target(AdjustableValue* value, uvent_settings& settings)
{
double val = 0;
switch (value->value_type) {
case TIDAL_VOLUME:
val = settings.tidal_volume;
break;
case RESPIRATION_RATE:
val = settings.respiration_rate;
break;
case PEEP:
val = settings.peep_limit;
break;
case PIP:
val = settings.pip_limit;
break;
case PLATEAU_TIME:
val = settings.plateau_time;
break;
case IE_RATIO_LEFT:
val = settings.ie_ratio_left;
break;
case IE_RATIO_RIGHT:
val = settings.ie_ratio_right;
break;
default:
break;
}
value->set_value_target(val);
control_update_waveform_param(value->value_type, (float) val);
}
void init_adjustable_values()
{
uvent_settings settings{};
storage.get_settings(settings);
for (uint8_t i = 0; i < AdjValueType::ADJ_VALUE_COUNT; i++) {
AdjustableValue* value_class = &adjustable_values[i];
value_class->init(static_cast<AdjValueType>(i));
load_stored_target(value_class, settings);
value_class->set_value_measured(READOUT_VALUE_DEFAULT);
}
adjustable_values[AdjValueType::IE_RATIO_LEFT].set_selected(false);
}
double get_control_target(AdjValueType type)
{
if (type >= AdjValueType::ADJ_VALUE_COUNT) {
return adjustable_values[type].get_settings().default_value;
}
return *adjustable_values[type].get_value_target();
}
void set_readout(AdjValueType type, double val)
{
if (type >= AdjValueType::ADJ_VALUE_COUNT) {
return;
}
adjustable_values[type].set_value_measured(val);
}
double get_readout(AdjValueType type)
{
if (type >= AdjValueType::ADJ_VALUE_COUNT) {
return -1;
}
return *adjustable_values[type].get_value_measured();
}
void control_handler()
{
static bool ledOn = false;
// LED to visually show state machine is running.
digitalWrite(DEBUG_LED, ledOn);
// Toggle the LED.
ledOn = !ledOn;
// Run the state machine
machine.run();
}
/* Interrupt callback to service the actuator
* The actuator, in this case a stepper is serviced periodically
* to "step" the motor.
*/
void actuator_handler()
{
actuator.run();
}
/* Initilaize sub-systems
*/
void control_init()
{
#if ENABLE_CONTROL
// Debug led setup
pinMode(DEBUG_LED, OUTPUT);
// Storage init
storage.init();
// Check EEPROM CRC. Load defaults if CRC fails.
if (!storage.is_crc_ok()) {
Serial.println("CRC failed. Loading defaults.");
// No settings found, or settings corrupted.
storage.load_defaults();
}
// Initialize the actuator
actuator.init();
/* On startup, the angle feedback sensor needs to be programmed with a calibrated
* zero. Usually this is an OTP value burned into the angle register, but it is risky to
* do that, as the magnet may fall or go out-of alignment during transport and the zero cannot
* be programmed again(because OTP).
* To avoid the risk, the EEPROM stores the zero value, which is burned in during manufacture.
* This value can be changed by manually "re-homing" the actuator at the user's discretion.
*
* The below few lines, load the zero value from the EEPROM into the angle sensor register
* at statup. Control can then use the value from the angle sensor to home the actuator.
*/
uvent_settings settings;
storage.get_settings(settings);
actuator.set_zero_position(settings.actuator_home_offset_adc_counts);
// Initialize the Gauge Pressure Sensor
gauge_sensor.init(MAX_GAUGE_PRESSURE, MIN_GAUGE_PRESSURE, RESISTANCE_1, RESISTANCE_2, 0);
// Initialize the Differential Pressure Sensor
if (settings.diff_pressure_type == PRESSURE_SENSOR_TYPE_0) {
diff_sensor.init(MAX_DIFF_PRESSURE_TYPE_0, MIN_DIFF_PRESSURE_TYPE_0, RESISTANCE_1, RESISTANCE_2, 0);
}
else if (settings.diff_pressure_type == PRESSURE_SENSOR_TYPE_1) {
diff_sensor.init(MAX_DIFF_PRESSURE_TYPE_1, MIN_DIFF_PRESSURE_TYPE_1, RESISTANCE_1, RESISTANCE_2, 0);
}
// Initialize the state machine
machine.setup();
/* Setup a timer and a function handler to run
* the state machine.
*/
Timer0.attachInterrupt(control_handler);
Timer0.start(CONTROL_HANDLER_PERIOD_US);
/* Setup a timer and a function handler to run
* the actuation.
*/
Timer1.attachInterrupt(actuator_handler);
Timer1.start(ACTUATOR_HANDLER_PERIOD_US);
#endif
}
/* Called by loop() from main, this function services control
* parametes and functions.
* Since this is called by the loop(), the call interval
* in not periodic.
*/
void control_service()
{
}
/* Get the current angular position of the actuator
*/
double control_get_actuator_position()
{
return actuator.get_position();
}
/* Get the current raw register value of the angle sensor.
* This is a debug stub used to get the offset to set home.
*/
int8_t control_get_actuator_position_raw(double& angle)
{
return actuator.get_position_raw(angle);
}
/**
* DO NOT USE UNLESS ABSOLUTELY NECESSARY
*/
void control_eeprom_write_default()
{
storage.load_defaults();
}
/* Set the current angular position of the actuator as home
*/
void control_zero_actuator_position()
{
uvent_settings settings;
storage.get_settings(settings);
// Zero the angle sensor and write the value to the EEPROM
settings.actuator_home_offset_adc_counts = actuator.set_current_position_as_zero();
// Store this value to the eeprom.
storage.set_settings(settings);
}
void control_write_ventilator_params()
{
uvent_settings settings;
storage.get_settings(settings);
settings.tidal_volume = (uint16_t) get_control_target(TIDAL_VOLUME);
settings.respiration_rate = (uint8_t) get_control_target(RESPIRATION_RATE);
settings.peep_limit = (uint8_t) get_control_target(PEEP);
settings.pip_limit = (uint8_t) get_control_target(PIP);
settings.plateau_time = (uint16_t) get_control_target(PLATEAU_TIME);
settings.ie_ratio_left = get_control_target(IE_RATIO_LEFT);
settings.ie_ratio_right = get_control_target(IE_RATIO_RIGHT);
storage.set_settings(settings);
}
void control_get_serial(char* serial_buffer)
{
uvent_settings settings{};
storage.get_settings(settings);
memcpy(serial_buffer, settings.serial, 12);
}
/* Request to switch the state of the state machine.
*/
void control_change_state(States new_state)
{
machine.change_state(new_state);
}
void control_actuator_manual_move(Tick_Type tt, double angle, double speed)
{
actuator.set_position_relative(tt, angle);
actuator.set_speed(tt, speed);
}
States control_get_state()
{
return machine.get_current_state();
}
const char* control_get_state_string()
{
return machine.get_current_state_string();
}
const char** control_get_state_list(uint8_t* size)
{
return machine.get_state_list(size);
}
void control_display_storage()
{
storage.display_storage();
}
bool control_is_crc_ok()
{
return storage.is_crc_ok();
}
double control_get_degrees_to_volume(C_Stat compliance)
{
return actuator.degrees_to_volume(compliance);
}
double control_get_degrees_to_volume_ml(C_Stat compliance)
{
return actuator.degrees_to_volume(compliance) * 1000;
}
double control_calc_volume_to_degrees(C_Stat compliance, double volume)
{
return actuator.volume_to_degrees(compliance, volume);
}
void control_actuator_set_enable(bool en)
{
actuator.set_enable(en);
}
waveform_params* control_get_waveform_params(void)
{
return (waveform.get_params());
}
void control_calculate_waveform()
{
waveform.calculate_waveform();
}
void control_waveform_display_details()
{
waveform.display_details();
}
double control_get_gauge_pressure()
{
return gauge_sensor.get_pressure(units_pressure::cmH20);
}
double control_get_diff_pressure()
{
return diff_sensor.get_pressure(units_pressure::cmH20);
}
void control_setup_alarm_cb()
{
alarm_manager.set_snooze_cb([]() {
lv_obj_t* mute_button = get_mute_button();
if (!mute_button) {
return;
}
lv_obj_clear_state(mute_button, LV_STATE_CHECKED);
});
}
void control_alarm_snooze()
{
alarm_manager.snooze();
}
void control_set_fault(Fault id)
{
machine.set_fault(id);
}
void control_toggle_alarm_snooze()
{
alarm_manager.toggle_snooze();
}
int16_t control_get_alarm_count()
{
return alarm_manager.numON();
}
String control_get_alarm_text()
{
return (alarm_manager.getText());
}
void control_set_alarm_all_off()
{
alarm_manager.allOff();
}
Alarm* control_get_alarm_list()
{
return alarm_manager.getAlarmList();
}
void control_alarm_test()
{
alarm_manager.overCurrent(true);
} | [
"gfischer@wpi.edu"
] | gfischer@wpi.edu |
40154e51cac80ca9b1a8500ad7ec0ea0768a8f3a | 5a19f0763cccd59abe5617d842301e4e7fe25a13 | /source/houaud/src/hou/aud/stream_audio_source.cpp | d984345e3aefa2c7cbc31687cb6b12b80e85a740 | [
"MIT"
] | permissive | DavideCorradiDev/houzi-game-engine | 6bfec0a8580ff4e33defaa30b1e5b490a4224fba | d704aa9c5b024300578aafe410b7299c4af4fcec | refs/heads/master | 2020-03-09T01:34:13.718230 | 2019-02-02T09:53:24 | 2019-02-02T09:53:24 | 128,518,126 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,713 | cpp | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/aud/stream_audio_source.hpp"
#include "hou/aud/audio_stream_in.hpp"
#include "hou/cor/narrow_cast.hpp"
namespace hou
{
namespace
{
constexpr size_t g_default_buffer_count = 3u;
constexpr size_t g_default_buffer_byte_count = 44100u;
} // namespace
stream_audio_source::stream_audio_source(std::unique_ptr<audio_stream_in> as)
: audio_source()
, m_audio_stream(std::move(as))
, m_buffer_queue(g_default_buffer_count)
, m_looping(false)
, m_processing_buffer_queue(false)
, m_sample_pos(0)
, m_buffers_to_queue_count(0u)
, m_buffer_byte_count(g_default_buffer_byte_count)
{
set_sample_pos_and_stream_cursor(0);
}
stream_audio_source::~stream_audio_source()
{
// The buffer queue will be deleted before the audio source, therefore
// the buffers must be unqueued from the audio source to avoid an OpenAL
// error. To unqueue all buffers, it is sufficient to stop the source first.
// The handle is checked for validity for safety reasons.
if(get_handle().get_name() != 0)
{
stop();
free_buffers();
}
}
void stream_audio_source::set_stream(std::unique_ptr<audio_stream_in> as)
{
stop();
m_audio_stream = std::move(as);
set_sample_pos_and_stream_cursor(0);
}
const audio_stream_in* stream_audio_source::get_stream() const
{
return m_audio_stream.get();
}
void stream_audio_source::set_buffer_count(size_t buffer_count)
{
stop();
free_buffers();
m_buffer_queue = buffer_queue(buffer_count);
}
size_t stream_audio_source::get_buffer_count() const
{
return m_buffer_queue.get_buffer_count();
}
void stream_audio_source::set_buffer_sample_count(size_t buffer_sample_count)
{
stop();
m_buffer_byte_count
= buffer_sample_count * (get_channel_count() * get_bytes_per_sample());
}
size_t stream_audio_source::get_buffer_sample_count() const
{
return m_buffer_byte_count / (get_channel_count() * get_bytes_per_sample());
}
bool stream_audio_source::is_playing() const
{
return m_processing_buffer_queue || audio_source::is_playing();
}
bool stream_audio_source::has_audio() const
{
return m_audio_stream != nullptr;
}
bool stream_audio_source::is_looping() const
{
return m_looping;
}
void stream_audio_source::update_buffer_queue()
{
if(m_processing_buffer_queue)
{
free_buffers();
fill_buffers();
// If the audio source is stopped at this point, it means that the buffer
// queue was not updated fast enough and the audio source automatically
// stopped. In this case force a restart of the audio source with the newly
// added buffers.
if(!audio_source::is_playing())
{
al::play_source(get_handle());
}
}
}
std::vector<uint8_t> stream_audio_source::read_data_chunk(size_t chunk_size)
{
std::vector<uint8_t> data;
if(m_audio_stream != nullptr)
{
data.resize(chunk_size);
m_audio_stream->read(data);
data.resize(m_audio_stream->get_read_byte_count());
}
return data;
}
void stream_audio_source::free_buffers()
{
uint processed_buffers = al::get_source_processed_buffers(get_handle());
if(processed_buffers > 0)
{
std::vector<ALuint> bufferNames(processed_buffers, 0);
al::source_unqueue_buffers(get_handle(),
narrow_cast<ALsizei>(bufferNames.size()), bufferNames.data());
size_t processed_bytes = m_buffer_queue.free_buffers(processed_buffers);
set_sample_pos_variable(normalize_sample_pos(m_sample_pos
+ processed_bytes / (get_channel_count() * get_bytes_per_sample())));
}
}
void stream_audio_source::fill_buffers()
{
while(
m_buffers_to_queue_count > 0u && m_buffer_queue.get_free_buffer_count() > 0)
{
std::vector<uint8_t> data = read_data_chunk(m_buffer_byte_count);
HOU_DEV_ASSERT(!data.empty());
const audio_buffer& buf
= m_buffer_queue.fill_buffer(data, get_format(), get_sample_rate());
ALuint buf_name = buf.get_handle().get_name();
al::source_queue_buffers(get_handle(), 1u, &buf_name);
HOU_DEV_ASSERT(m_buffers_to_queue_count > 0u);
--m_buffers_to_queue_count;
// If looping, reset the stream to the beginning and the number of buffers
// to queue, so that the buffer queueing will continue from the beginning of
// the stream.
if(m_looping && m_buffers_to_queue_count == 0u)
{
HOU_DEV_ASSERT(m_audio_stream != nullptr);
m_audio_stream->set_sample_pos(
narrow_cast<audio_stream::sample_position>(0));
set_buffers_to_queue_count(0u);
// m_sample_pos shouldn't be updated here, it is updated in free_buffers.
}
}
// If the loop ended and the number of buffers to queue is 0, it means that
// the buffer queu processing was ended.
if(m_buffers_to_queue_count == 0u)
{
m_processing_buffer_queue = false;
}
}
stream_audio_source::sample_position stream_audio_source::normalize_sample_pos(
sample_position pos)
{
uint sample_count = get_sample_count();
return sample_count == 0 ? 0 : pos % sample_count;
}
void stream_audio_source::set_sample_pos_variable(sample_position pos)
{
m_sample_pos = pos;
}
void stream_audio_source::set_stream_cursor(sample_position pos)
{
if(m_audio_stream != nullptr)
{
m_audio_stream->set_sample_pos(
narrow_cast<audio_stream::sample_position>(pos));
}
}
void stream_audio_source::set_sample_pos_and_stream_cursor(sample_position pos)
{
pos = normalize_sample_pos(pos);
set_sample_pos_variable(pos);
set_stream_cursor(pos);
}
void stream_audio_source::set_buffers_to_queue_count(uint pos)
{
uint samples_to_end = get_sample_count() - pos;
uint buffer_sample_count = get_buffer_sample_count();
m_buffers_to_queue_count = (samples_to_end > 0u && buffer_sample_count > 0)
? 1u + (samples_to_end - 1u) / buffer_sample_count
: 0u;
}
void stream_audio_source::on_set_looping(bool looping)
{
m_looping = looping;
}
void stream_audio_source::on_set_sample_pos(sample_position value)
{
free_buffers();
set_sample_pos_and_stream_cursor(value);
set_buffers_to_queue_count(m_sample_pos);
fill_buffers();
}
stream_audio_source::sample_position stream_audio_source::on_get_sample_pos()
const
{
uint sample_count = get_sample_count();
return sample_count == 0
? 0
: (m_sample_pos + audio_source::on_get_sample_pos()) % get_sample_count();
}
void stream_audio_source::on_play()
{
m_processing_buffer_queue = true;
}
void stream_audio_source::on_pause()
{
m_processing_buffer_queue = false;
}
audio_buffer_format stream_audio_source::get_format_internal() const
{
HOU_INVARIANT(m_audio_stream != nullptr);
return m_audio_stream->get_format();
}
uint stream_audio_source::get_channel_count_internal() const
{
HOU_INVARIANT(m_audio_stream != nullptr);
return m_audio_stream->get_channel_count();
}
uint stream_audio_source::get_bytes_per_sample_internal() const
{
HOU_INVARIANT(m_audio_stream != nullptr);
return m_audio_stream->get_bytes_per_sample();
}
uint stream_audio_source::get_sample_rate_internal() const
{
HOU_INVARIANT(m_audio_stream != nullptr);
return m_audio_stream->get_sample_rate();
}
uint stream_audio_source::get_sample_count_internal() const
{
HOU_INVARIANT(m_audio_stream != nullptr);
return narrow_cast<uint>(m_audio_stream->get_sample_count());
}
stream_audio_source::buffer_queue::buffer_queue(size_t buffer_count)
: m_buffers(buffer_count)
, m_buffer_sample_counts()
, m_free_buffer_count(buffer_count)
, m_current_index(0u)
{}
size_t stream_audio_source::buffer_queue::free_buffers(size_t count)
{
m_free_buffer_count += count;
HOU_DEV_ASSERT(m_free_buffer_count <= m_buffers.size());
size_t freed_bytes = 0u;
for(uint i = 0; i < count; ++i)
{
freed_bytes += m_buffer_sample_counts.front();
m_buffer_sample_counts.pop();
}
return freed_bytes;
}
const audio_buffer& stream_audio_source::buffer_queue::fill_buffer(
const std::vector<uint8_t>& data, audio_buffer_format format, int sample_rate)
{
HOU_DEV_ASSERT(m_free_buffer_count > 0);
audio_buffer& buffer = m_buffers[m_current_index];
buffer.set_data(data, format, sample_rate);
m_current_index = (m_current_index + 1) % m_buffers.size();
--m_free_buffer_count;
m_buffer_sample_counts.push(data.size());
return buffer;
}
size_t stream_audio_source::buffer_queue::get_free_buffer_count() const
{
return m_free_buffer_count;
}
size_t stream_audio_source::buffer_queue::get_used_buffer_count() const
{
return m_buffers.size() - m_free_buffer_count;
}
size_t stream_audio_source::buffer_queue::get_buffer_count() const
{
return m_buffers.size();
}
} // namespace hou
| [
"davide.corradi.dev@gmail.com"
] | davide.corradi.dev@gmail.com |
0d20b7df02d53b5a888c661c5c1e5c767761bb4a | 560909253e9b44fc361c159c29f9b5e70ff405fe | /doWhile.cpp | 3c62850ca60cfc0d2b2db9dd902f5f2c6fe835eb | [] | no_license | faalbers/CPPNuts | 4c8a693d8bd2bba4e104a3a96a5960249efbfca8 | 949ced3db8c79450ed630e1179764f5e686c2c3b | refs/heads/master | 2023-07-16T20:05:25.358831 | 2021-09-03T18:33:37 | 2021-09-03T18:33:37 | 385,023,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | #include <iostream>
int main()
{
int x = 5;
// entry control loop
while( x > 0 ) {
std::cout << x << std::endl;
x--;
}
x = 5;
// exit control loop
do {
std::cout << x << std::endl;
x--;
} while ( x > 0 );
return 0;
} | [
"chalbers@gmail.com"
] | chalbers@gmail.com |
d247cd6b48f51d043f0d1b14a666c28a438119a3 | e99df5a89a9b5f8a2518bf54c30a0ae2937f8517 | /mycodes/LinkedList/707. Design Linked List.cpp | e3b111a624b31adbfe5dbee3a507a1fe8d800524 | [] | no_license | kumar-sundaram-coder/DSA-1 | aa0c7e2751b259db33c50c1359a4538352234362 | f73420980342a6bf2aa721971be3c9475ce9e3f4 | refs/heads/master | 2023-06-02T04:43:40.327174 | 2020-07-29T09:02:46 | 2020-07-29T09:02:46 | 283,449,553 | 1 | 0 | null | 2020-07-29T08:59:53 | 2020-07-29T08:59:53 | null | UTF-8 | C++ | false | false | 4,493 | cpp | // 707. Design Linked List.===================================
class MyLinkedList {
public:
class Node
{
public:
int val=0;
Node* next=NULL;
Node(int data){
this->val=data;
this->next=NULL;
}
Node(){}
};
Node* head=NULL;
Node*tail=NULL;
int size=0;
/** Initialize your data structure here. */
MyLinkedList() {
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
if(index<0 || index>=size)
return -1;
else
{
Node* curr=head;
while(index-->0){
curr=curr->next;
}
return curr->val;
}
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
void addAtHead(int val) {
Node* node=new Node(val);
if(size==0){
head=node;
tail=node;
}else{
node->next=head;
head=node;
}
size++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
Node* node=new Node(val);
if(size==0){
head=node;
tail=node;
}else{
tail->next=node;
tail=node;
}
size++;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
Node* getNode(int index) {
if(index<0 || index>=size)
return NULL;
else
{
Node* curr=head;
while(index-->0){
curr=curr->next;
}
return curr;
}
}
void addAtIndex(int index, int val) {
if(index >size || index<0)
return;
if(index==0){
return addAtHead(val);
}
else if(index==size){
return addAtTail(val);
}
else{
Node* node=new Node(val);
Node* temp=getNode(index-1);
node->next=temp->next;
temp->next=node;
size++;
}
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteFirst(){
if(size==0) return;
Node* rnode=head;
if(size==1){
head=NULL;
tail=NULL;
}
else{
head=head->next;
rnode->next=NULL;
}
size--;
}
void deleteLast(){
if(size==0) return;
Node* rnode=tail;
if(size==1){
head=NULL;
tail=NULL;
}
else{
Node* secondlastnode=getNode(size-2);
secondlastnode->next=NULL;
tail=secondlastnode;
rnode->next=NULL;
}
size--;
}
void deleteAtIndex(int index) {
if(index>=size || index<0)
return;
if(index==0)
{
return deleteFirst();
}
else if(index==size-1)
{
return deleteLast();
}
else{
Node* temp=getNode(index-1);
Node* rnode=temp->next;
temp->next=temp->next->next;
rnode->next=NULL;
size--;
}
}
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/
// ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
// [[],[1],[3],[1,2],[1],[1],[1]]
// ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
// [[],[1],[3],[1,2],[1],[0],[0]]
// ["MyLinkedList","addAtIndex","addAtIndex","addAtIndex","get"]
// [[],[0,10],[0,20],[1,30],[0]]
// ["MyLinkedList","addAtHead","addAtHead","addAtHead","addAtIndex","deleteAtIndex","addAtHead","addAtTail","get","addAtHead","addAtIndex","addAtHead"]
// [[],[7],[2],[1],[3,0],[2],[6],[4],[4],[4],[5,0],[6]]
| [
"sandyroshan2000@gmail.com"
] | sandyroshan2000@gmail.com |
06db39ce8bc1335aa1a5a285c5f2dabbf5d1cedc | e2119ddc29757a786c983499629c4f92510658ef | /src/Alignment/Multiple/ScoringRefinement.h | 1b84f6a6c42db90ddec1f15c4628dfb0deeaa59a | [] | no_license | refresh-bio/QuickProbs | 623ee08c4143d1d2d5d1260375b401f6ec750378 | 3ec12212ed7268c9b1f54cb0f2fa087e1f54dba1 | refs/heads/master | 2022-06-07T23:05:13.967075 | 2022-05-19T19:17:11 | 2022-05-19T19:17:11 | 48,433,949 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | #pragma once
#include "ColumnRefinement.h"
namespace quickprobs {
class ScoringRefinement : public ColumnRefinement
{
public:
ScoringRefinement(
std::shared_ptr<Configuration> config,
std::shared_ptr<ConstructionStage> constructor) : ColumnRefinement(config, constructor) {}
protected:
virtual bool prepare(
const float *seqsWeights,
const Array<float>& distances,
const Array<SparseMatrixType*> &sparseMatrices,
const ProbabilisticModel &model,
const MultiSequence &alignment);
};
} | [
"adam.gudys@gmail.com"
] | adam.gudys@gmail.com |
82a4c5834ff1aa475e053fe7289941e7eadf86c2 | eda5a416fe0d16d1ac8ac273c6110f2e8c5ed861 | /Mx/Definitions/MxCommonType.h | db885b22cfc11760e915ee4b974c9b1f685d39db | [] | no_license | javier-martinez-palmer/MixEngine | 7eabaf1d8ec0d4e63c29e1fcd7d62ea36287a81e | 351f56ffdf0374b14052fb6ee868cd2ac7cb03ee | refs/heads/master | 2022-02-17T18:33:20.270120 | 2019-09-11T10:42:02 | 2019-09-11T10:42:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,126 | h | #pragma once
#ifndef MX_COMMON_TYPE_H_
#define MX_COMMON_TYPE_H_
#include "../Utils/MxFlags.h"
namespace Mix {
enum class Space {
World,
Self
};
const char* ToString(Space e);
enum class MeshTopology {
Points_List = 1,
Lines_List = 2,
Triangles_List = 3
};
const char* ToString(MeshTopology e);
enum class IndexFormat {
UInt16 = 0x0001,
UInt32 = 0x0002
};
const char* ToString(IndexFormat e);
enum class TextureWrapMode {
Repeat = 0,
ClampToEdge = 1,
Mirror = 2,
};
const char* ToString(TextureWrapMode e);
enum class TextureFilterMode {
Nearest = 0,
Linear = 1
};
const char* ToString(TextureFilterMode e);
enum class TextureMipSampleMode {
Nearest = 0,
Linear = 1
};
const char* ToString(TextureMipSampleMode e);
enum class TextureFormat {
Unknown = 0,
R8G8B8A8_Unorm = 1,
B8G8R8A8_Unorm = 2
};
const char* ToString(TextureFormat e);
enum class TextureType {
Tex_2D = 0,
Cube = 1
};
const char* ToString(TextureType e);
enum class CubeMapFace {
PositiveX = 0,
NegativeX = 1,
PositiveY = 2,
NegativeY = 3,
PositiveZ = 4,
NegativeZ = 5,
};
const char* ToString(CubeMapFace e);
/**
* \brief This enumeration variable provides a simple and commonly used way to set up the layout of vertex data
* So far, Mesh data is set through setxxx(...) function,
* the Mesh arranges the data internally in a specific order,
* and uses a set of VertexAttribute to identify the layout of the vertex data.
* When using a Mesh, a VertexDeclaration is automatically generated so we do not need to set up the VertexDeclaration manually.
*/
enum class VertexAttribute {
Position = 0x0001,
Normal = 0x0002,
Tangent = 0x0004,
UV0 = 0x0008,
UV1 = 0x0010,
Color = 0x0020,
};
const char* ToString(VertexAttribute e);
MX_ALLOW_FLAGS_FOR_ENUM(VertexAttribute);
/**
* \brief This enumeration is used with VertexAttribute to identify a channel of UV.
* UVChannel::UVX has the same vaule as VertexAttribute::UVx
*/
enum class UVChannel {
UV0 = 0x0008,
UV1 = 0x0010
};
const char* ToString(UVChannel e);
}
#endif | [
"x1239392454@outlook.com"
] | x1239392454@outlook.com |
a91af31f91cae3f3789b807a84963d7ef24941b6 | b1b31d91cc189aa8564989951ba3ddb60c3d8d1b | /cradle/src/alia/ui/utilities/dragging.cpp | 08d263130dcd4a54fb2e7c4b6f8b844ed501db32 | [
"BSL-1.0",
"MIT"
] | permissive | dotdecimal/open-cradle | 4a9ce7a7658fc27379aaf3828e5e1eb99ddb215b | a3d3e198ccb64200ff3d820067597b07f1513de1 | refs/heads/master | 2022-07-08T06:37:27.530663 | 2022-06-28T13:11:58 | 2022-06-28T13:11:58 | 107,994,029 | 1 | 5 | MIT | 2022-06-28T13:11:10 | 2017-10-23T14:30:25 | C++ | UTF-8 | C++ | false | false | 3,704 | cpp | #include <alia/ui/utilities/dragging.hpp>
#include <alia/ui/utilities.hpp>
#include <SkDashPathEffect.h>
namespace alia {
void draw_drop_location(dataless_ui_context& ctx, layout_box const& region,
caching_renderer_data& renderer_data, draggable_style const& style)
{
caching_renderer cache(ctx, renderer_data, no_id, region);
if (cache.needs_rendering())
{
skia_renderer renderer(ctx, cache.image(), region.size);
box<2,float> outline_box =
add_border(
box<2,float>(make_vector(0.f, 0.f),
vector<2,float>(region.size)),
-(style.outline_margin + style.outline_width / 2));
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SkFloatToScalar(style.outline_width));
SkScalar dashing[2];
dashing[0] = dashing[1] = SkFloatToScalar(style.outline_dashing);
paint.setPathEffect(SkDashPathEffect::Make(dashing, 2, 0));
set_color(paint, style.outline_color);
draw_rect(renderer.canvas(), paint,
float_box_as_skia_box(outline_box),
resolve_box_corner_sizes(get_layout_traversal(ctx),
style.corner_radii, outline_box.size));
renderer.cache();
cache.mark_valid();
}
cache.draw();
}
void refresh_draggable_style(dataless_ui_context& ctx,
keyed_data<draggable_style>& style_data)
{
if (!is_refresh_pass(ctx))
return;
refresh_keyed_data(style_data, *ctx.style.id);
if (!is_valid(style_data))
{
draggable_style style;
style_path_storage storage;
style_search_path const* path =
add_substyle_to_path(&storage, ctx.style.path, 0, "draggable");
style.outline_width =
resolve_absolute_length(get_layout_traversal(ctx), 0,
get_property(path, "outline-width", UNINHERITED_PROPERTY,
absolute_length(3.f, PIXELS)));
style.outline_margin =
resolve_absolute_length(get_layout_traversal(ctx), 0,
get_property(path, "outline-margin", UNINHERITED_PROPERTY,
absolute_length(0.f, PIXELS)));
style.outline_dashing =
resolve_absolute_length(get_layout_traversal(ctx), 0,
get_property(path, "outline-dashing", UNINHERITED_PROPERTY,
absolute_length(3.f, PIXELS)));
style.outline_color =
get_color_property(path, "outline-color");
style.corner_radii = get_border_radius_property(path);
style.fill_color =
get_property(path, "fill-color", UNINHERITED_PROPERTY,
rgba8(0, 0, 0, 0));
style.fill_size =
resolve_absolute_length(get_layout_traversal(ctx), 0,
get_property(path, "fill-size", UNINHERITED_PROPERTY,
absolute_length(0.f, PIXELS)));
set(style_data, style);
}
}
vector<2,double>
calculate_relative_drag_delta(
dataless_ui_context& ctx, layout_box const& region)
{
vector<2,double> absolute_delta =
get_mouse_position(ctx) - vector<2,double>(region.corner);
vector<2,double> relative_delta;
for (unsigned i = 0; i != 2; ++i)
relative_delta[i] = absolute_delta[i] / region.size[i];
return relative_delta;
}
vector<2,double>
evaluate_relative_drag_delta(
dataless_ui_context& ctx, vector<2,double> const& size,
vector<2,double> const& relative_delta)
{
vector<2,double> absolute_delta;
for (unsigned i = 0; i != 2; ++i)
absolute_delta[i] = relative_delta[i] * size[i];
return get_mouse_position(ctx) - absolute_delta;
}
}
| [
"kerhart@dotdecimal.com"
] | kerhart@dotdecimal.com |
225edc88780be4be50818edc3afd8c7ff9ca7e26 | da707e5c206060bcea26e82e820c8f9adf8d9539 | /lib/sfml/Sloop.cpp | bb0076f809a1ed7d23749b512ef2cea049defe7a | [] | no_license | NicolasAlb/cpp_arcade | 86c62cc1b5e5799de9c18d29c01d365f80acc8c3 | 726d20bbad02596b0df7c16b20286dbee003d34a | refs/heads/master | 2020-03-22T01:57:21.301894 | 2018-07-02T07:46:48 | 2018-07-02T07:46:48 | 139,340,740 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | cpp | //
// EPITECH PROJECT, 2018
// draw_menu_sf
// File description:
// header
//
#include "SMenu.hpp"
extern "C" IGraphics* create()
{
return new SMenu;
}
int SMenu::menu()
{
sf::RenderWindow w(sf::VideoMode(1920, 1080), "ARCADE");
int event = 0;
sf::Music music;
music.openFromFile("ressources/Sirtaki.ogg");
music.play();
this->printAll(w);
while (w.waitEvent(_event)) {
event = this->Kevent(w);
if (event == CHANGE_LIB) {
return (CHANGE_LIB);
}
else if (event == PAC_L || event == NIB_L) {
w.close();
return (event);
}
this->printAll(w);
}
return (0);
}
| [
"nico.975@hotmail.fr"
] | nico.975@hotmail.fr |
866d512299cc0801b627524650344907dccb86b4 | 26598b2ab7026b0a4abf85b8ab8b43adf470b6ff | /Ilya/player.h | 986f90b42cc1908f6a574c71cd75e14f114ce4e1 | [] | no_license | pengnix/Ilya | 531606752ca5796d09a36cae55879babc8c7ec24 | 00b5dc3c705b1fd58fb3336073861928acf35cd6 | refs/heads/master | 2021-01-23T14:47:05.523936 | 2015-02-03T17:49:44 | 2015-02-03T17:49:44 | 24,520,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | h | #ifndef PLAYER_H
#define PLAYER_H
#include <QGraphicsObject>
class Player : public QGraphicsObject
{
// Q_OBJECT
public:
explicit Player();
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QRectF boundingRect() const;
//signals:
//public slots:
void advance();
};
#endif // PLAYER_H
| [
"superpengnix@gmail.com"
] | superpengnix@gmail.com |
c8c09eb3e0485149148f2034658a2ffa6c63ef4f | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/ue/sys/render/I_RenderMatSamplerResource.h | 3cce0dad67d3b3534faecab6e3d16f3d32cec982 | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 301 | h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
namespace ue
{
namespace sys
{
namespace render
{
/** ue::sys::render::I_RenderMatSamplerResource (VTable=0xFFFFFFFF) */
class I_RenderMatSamplerResource
{
public:
};
} // namespace render
} // namespace sys
} // namespace ue
| [
"hopk1nz@gmail.com"
] | hopk1nz@gmail.com |
36efd1a9d130b02de048f5d236d13fdfc2e1c143 | 4611624808ccc2681272cc0847f01e54389490a7 | /build/Android/Debug/app/src/main/include/Fuse.Resources.System-1e583f40.h | 8c4ee155532816334b37132c930d63028b728e50 | [] | no_license | kvitberg/TestCase | 62d6c88e5cab7ac46fd70c29a6e2e695d838f261 | 75c6e7fdf680189e6d6a447c157a07e10218796a | refs/heads/master | 2020-12-02T18:01:51.624735 | 2017-07-06T18:55:24 | 2017-07-06T18:55:24 | 96,462,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | h | // This file was generated based on '../../../Library/Application Support/Fusetools/Packages/Fuse.Common/1.0.5/resources/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.UX.FileSource.h>
namespace g{namespace Fuse{namespace Resources{struct SystemFileSource;}}}
namespace g{namespace Uno{namespace IO{struct Stream;}}}
namespace g{
namespace Fuse{
namespace Resources{
// internal sealed class SystemFileSource :409
// {
::g::Uno::UX::FileSource_type* SystemFileSource_typeof();
void SystemFileSource__ctor_1_fn(SystemFileSource* __this, uString* file);
void SystemFileSource__New1_fn(uString* file, SystemFileSource** __retval);
void SystemFileSource__OpenRead_fn(SystemFileSource* __this, ::g::Uno::IO::Stream** __retval);
struct SystemFileSource : ::g::Uno::UX::FileSource
{
void ctor_1(uString* file);
static SystemFileSource* New1(uString* file);
};
// }
}}} // ::g::Fuse::Resources
| [
"scott.kvitberg@gmail.com"
] | scott.kvitberg@gmail.com |
658460421a2095a2cb8b7bc7041b0e9f2ed34b73 | 8f1b37dd4dfa7899158953c3b49979144e19c21b | /Engine.h | aa17b8dbc603517e797c29f0ab8ff9f838c58002 | [] | no_license | S1mplyD/Non-Gravitar | 24337f50050d0a6d5393eee8deddd645d2b8f94b | 05f6992b4ce67de32db134997ca61d900658fd7a | refs/heads/master | 2021-07-15T03:28:24.219871 | 2021-02-25T19:57:58 | 2021-02-25T19:57:58 | 239,189,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,069 | h | #include "Player.h"
#include "Nemici.h"
#include "Fuel.h"
#include "SFML/Graphics.hpp"
#include "SFML/Window.hpp"
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include "RaggioTraente.h"
#include "Planet.h"
namespace engine {
void Draw(sf::RenderWindow &window, Player &player, std::vector<sf::ConvexShape> &hitbox, sf::VertexArray &lines,Text scoreText, Text fuelText,std::vector<Bunker> &nemici1, std::vector<Bunker2> &nemici2,std::vector<Fuel> &carburante1, std::vector<Fuel2> &carburante2); //Disegna tutti gli oggetti a schermo
void SistemaSparo(char lastdir, Bullet newbullet, Player &player, sf::Sound &shoot_sound, sf::SoundBuffer &buffershoot, int &timerProiettili); //Gestisce il sistema di sparo del player
void PlayerBulletCollision(Player &player, std::vector<Bunker> &nemici1, std::vector<Bunker2> &nemici2, sf::Sound &die_bunker_sound, sf::SoundBuffer &bufferdeath,sf::RenderWindow &window); //Collisione dei proiettili del player con i bunker
void RaggioTraenteCollision(Player &player, sf::RenderWindow &window, std::vector<Fuel> &carburante1, std::vector<Fuel2> &carburante2); //Gestisce collisione tra raggio traente e fuel
void PacmanEffect(Player &player, sf::RenderWindow &window); //Implementa il cosiddetto "Pacman"
void BunkerShootingSystem(std::vector<Bunker> &nemici1, int &timerProiettiliBunker, sf::RenderWindow &window, EnemyBullet bunkerbullet1); //Gestisce lo sparo dei bunker del primo tipo
void Bunker2ShootingSystem(std::vector<Bunker2> &nemici2, int &timerProiettiliBunker2, sf::RenderWindow &window, EnemyBullet2 bunkerbullet2); //Gestisce lo sparo dei bunker del secondo tipo
void BunkerBulletRemove(std::vector<Bunker> &nemici1, std::vector<Bunker2> &nemici2); //Cancella i proiettili dei bunker una volta usciti dallo schermo
void BunkerBulletCollision(std::vector<Bunker> &nemici1, std::vector<Bunker2> &nemici2, Player &player); //Gestisce le collisioni tra proiettili e player
void generateTerrain(int y_punti_terreno[], std::vector<sf::ConvexShape> &v);
};
| [
"lucabennati2k16@gmail.com"
] | lucabennati2k16@gmail.com |
be042eaabf12a0ff4b41fa792dfe846ea6342c9f | a29fc61b2291f3f5ad55d6f2c16168f621452756 | /CruUI/ui/events/ui_event.cpp | 59623bab9a3f287fd1e63847869a3bf762d97959 | [] | no_license | Qazwar/CruUI | 0ced501546f67dea4134c71535b75250baefc68f | f52814a56ec12f0a65390609acb142685e7aed1d | refs/heads/master | 2020-04-29T07:30:10.873179 | 2018-08-31T16:51:08 | 2018-08-31T16:51:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | cpp | #include "ui_event.h"
#include "ui/control.h"
namespace cru
{
namespace ui
{
namespace events
{
Point MouseEventArgs::GetPoint(Control* control) const
{
if (point_.has_value())
return control->AbsoluteToLocal(point_.value());
return Point();
}
}
}
}
| [
"crupest@outlook.com"
] | crupest@outlook.com |
d9bb2f742c934bc69aca287a56d0411707bd3f64 | ec70b2fc804bc2c783c06332b0356ef106d2c059 | /数据结构与算法教材示例源代码/2.12~2.20/Stacktest/LinkQueue.h | 95e1bc4fc0b524c57cf8fa60a2b2aa7d02e81d53 | [] | no_license | StuGRua/ReDS | bd105b5c438045c9c24b45f3bc30b536c6282d6f | 66dc0f5531c7d1744d15a3adface6777af83b94a | refs/heads/master | 2023-02-08T21:53:03.331860 | 2020-12-21T09:52:25 | 2020-12-21T09:52:25 | 300,611,537 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,455 | h | #include <bits/stdc++.h>
using namespace std;
template<class T>
class LinkNode
{
public:
T data; //数据域
LinkNode<T>*link; //指向后继指针的结点
LinkNode(const T&el, LinkNode<T>*ptr = 0){ //构造函数
data=el;
link=ptr;
}
};
template<class T>
class Queue
{
public:
void Clear(); //清空队列
bool EnQueue(const T item); //队列的尾部加入元素item
bool DeQueue(T & item); //取出队列的第一个元素,并删除
bool IsEmpty(); //判断队列是否为空
bool IsFull(); //判断队列是否已满
bool GetFront(T & item); //读取队头元素,但不删除
};
template<class T>
class LinkQueue:public Queue<T>
{
private:
public:
int size; //队列中当前元素的个数
LinkNode<T> * front; //表示队列的头指针
LinkNode<T> * rear; //表示队列的尾指针
LinkQueue() //构造函数,创建队列的实例
{
size = 0;
front = rear = NULL;
}
~LinkQueue() //析构函数
{
Clear();
}
void Clear() //清空队列
{
while(front != NULL)
{
rear = front;
front = front->link;
delete rear;
}
rear = NULL;
size = 0;
}
bool EnQueue(const T item) //item入队,插入队尾
{
if(rear == NULL)
{
front = rear = new LinkNode<T>(item, NULL);
}
else
{
rear->link = new LinkNode<T>(item, NULL);
rear = rear->link;
}
size++;
return true;
}
bool DeQueue(T & item) //读取队头元素并删除
{
LinkNode<T> * temp;
if(size == 0)
{
cout << "empty" << endl;
return false;
}
item = front->data;
temp = front;
front = front->link;
delete temp;
if(front == NULL)
{
rear = NULL;
}
size--;
return true;
}
bool GetFront(T & item) //返回队头元素,但不删除
{
if(size == 0)
{
cout << "empty" << endl;
return false;
}
item = front->data;
return true;
}
void show()
{
while (size!=0)
{
T _tmp;
DeQueue(_tmp);
cout << _tmp << ' ';
}
}
bool IsEmpty()
{
if(size==0) return 1;
else return 0;
}
int getsize()
{
return 0;
}
};
template<typename T>
void connect(LinkQueue<T>& a, LinkQueue<T>& b)
{
if (b.rear == NULL)
return;
if (a.rear != NULL)
a.rear->link = b.front;
else
a.front = b.front;
a.rear = b.rear;
a.size += b.size;
b.front = b.rear = NULL;//避免析构时重复delete
b.size = 0;
} | [
"Stu6@users.noreply.github.com"
] | Stu6@users.noreply.github.com |
a938547bd587b318fc36fff1ddecb48f45cc24d5 | 0a2357ad0098bbb7b74528cb01d6decaab928ed8 | /fhc/test.cpp | 6cff84a5c1323992ddf8506f5686dbc7a919a25b | [] | no_license | touyou/CompetitiveProgramming | 12af9e18f4fe9ce9f08f0a0f2750bcb5d1fc9ce7 | 419f310ccb0f24ff08d3599e5147e5a614071926 | refs/heads/master | 2021-06-18T09:19:01.767323 | 2020-07-16T03:40:08 | 2020-07-16T03:40:08 | 90,118,147 | 0 | 0 | null | 2020-10-13T04:32:19 | 2017-05-03T06:57:58 | C++ | UTF-8 | C++ | false | false | 94 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
cout<<"This is test."<<endl;
}
| [
"fujiyou1121@gmail.com"
] | fujiyou1121@gmail.com |
4e7fa1d7bca54c364000cc5a93b0d91495e5ae4c | b3cea039bfd57377565f9581e3ca2a5971a552f5 | /tensorflow/compiler/xla/mlir_hlo/lib/Dialect/thlo/IR/thlo_ops.cc | 815af6a5a728b93e0be723d7e7ac929842dc05c0 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | mntetai/tensorflow | 0726fef386d2351d6e173650c244fa83c4936c73 | 3020287dbbc016efd4d3b5284c843d248f11c459 | refs/heads/master | 2022-09-29T11:11:11.633298 | 2022-08-31T09:04:46 | 2022-08-31T09:15:00 | 98,040,259 | 0 | 0 | null | 2017-07-22T15:30:55 | 2017-07-22T15:30:55 | null | UTF-8 | C++ | false | false | 33,298 | cc | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "mlir-hlo/Dialect/thlo/IR/thlo_ops.h"
#include <algorithm>
#include <iterator>
#include <memory>
#include <utility>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TypeSwitch.h"
#include "mlir-hlo/Dialect/gml_st/IR/gml_st_ops.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Dialect/Tensor/Utils/Utils.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Interfaces/ViewLikeInterface.h"
namespace mlir {
namespace {
//===----------------------------------------------------------------------===//
// Destination-style ops tools
//===----------------------------------------------------------------------===//
bool hasTensorSemantics(OperandRange operands, unsigned numOutputArgs) {
for (auto operand : operands.drop_back(numOutputArgs)) {
if (!operand.getType().isa<ShapedType>()) continue;
if (!operand.getType().isa<RankedTensorType>()) return false;
}
return llvm::all_of(operands.take_back(numOutputArgs), [](Value operand) {
return operand.getType().isa<RankedTensorType>();
});
}
bool hasBufferSemantics(OperandRange operands) {
return llvm::all_of(operands, [](Value operand) {
return operand.getType().isa<MemRefType>();
});
}
LogicalResult verifyDestinationStyleOp(Operation *op,
unsigned numOutputArgs = 1) {
if (hasBufferSemantics(op->getOperands()))
return success(op->getNumResults() == 0);
if (!hasTensorSemantics(op->getOperands(), numOutputArgs))
return op->emitOpError("expected either buffer or tensor semantics");
if (op->getNumResults() != numOutputArgs) {
return op->emitOpError(
"expected the number of output args to match the number of results");
}
for (auto &en : llvm::enumerate(llvm::zip(
op->getResultTypes(), op->getOperands().take_back(numOutputArgs)))) {
size_t index = en.index();
Type resultType = std::get<0>(en.value());
Type outputOperandType = std::get<1>(en.value()).getType();
if (resultType != outputOperandType)
op->emitOpError() << "type " << resultType << " of result " << index
<< " does not match output operand type "
<< outputOperandType;
}
return success();
}
template <typename DstOpTy>
void printDstStyleOp(
DstOpTy op, OpAsmPrinter &p,
function_ref<SmallVector<StringRef>(DstOpTy op, OpAsmPrinter &)>
printAttrsFn = nullptr) {
if (op.getNumInputs() != 0) {
p << " ins(";
llvm::interleaveComma(
op.getOperands().take_front(op.getNumInputs()), p,
[&](Value input) { p << input << " : " << input.getType(); });
p << ")";
}
p << " outs(";
llvm::interleaveComma(
op.getOperands().take_back(op.getNumOutputs()), p,
[&](Value output) { p << output << " : " << output.getType(); });
p << ")";
// Print attributes with custom printing logic.
SmallVector<StringRef> elidedAttrs;
if (printAttrsFn) elidedAttrs = printAttrsFn(op, p);
p.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
}
ParseResult parseKeywordOperandListWithTypes(
OpAsmParser &parser, OperationState &result, StringRef keyword,
SmallVectorImpl<Type> *operandTypes) {
SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
if (succeeded(parser.parseOptionalKeyword(keyword))) {
SMLoc operandsOperandsLoc = parser.getCurrentLocation();
if (parser.parseCommaSeparatedList(
AsmParser::Delimiter::Paren, [&]() -> ParseResult {
if (parser.parseOperand(operands.emplace_back(),
/*allowResultNumber=*/false) ||
parser.parseColon() ||
parser.parseType(operandTypes->emplace_back())) {
return failure();
}
return success();
}))
return failure();
if (parser.resolveOperands(operands, *operandTypes, operandsOperandsLoc,
result.operands))
return failure();
}
return success();
}
ParseResult parseDstStyleOp(
OpAsmParser &parser, OperationState &result,
function_ref<ParseResult(OpAsmParser &, NamedAttrList &)> parseAttrsFn =
nullptr) {
// Parse `ins` and `outs`.
SmallVector<Type, 4> inputTypes, outputTypes;
if (parseKeywordOperandListWithTypes(parser, result, "ins", &inputTypes) ||
parseKeywordOperandListWithTypes(parser, result, "outs", &outputTypes))
return failure();
// Add result types.
for (Type outputType : outputTypes) {
if (outputType.isa<RankedTensorType>()) result.addTypes(outputType);
}
// Parse required attributes.
if (parseAttrsFn && failed(parseAttrsFn(parser, result.attributes)))
return failure();
// Parse optional attributes.
if (parser.parseOptionalAttrDict(result.attributes)) return failure();
return success();
}
ParseResult parseDenseI64ArrayAttr(OpAsmParser &parser,
NamedAttrList &attributes,
StringRef attributeName) {
if (parser.parseKeyword(attributeName) || parser.parseEqual())
return failure();
attributes.set(attributeName, DenseI64ArrayAttr::parse(parser, Type{}));
return success();
}
void printDenseI64ArrayAttr(OpAsmPrinter &p, StringRef attributeName,
ArrayRef<int64_t> attributeValue) {
p << " " << attributeName << " = [" << attributeValue << "] ";
}
bool dimensionsMatch(int64_t d1, int64_t d2) {
return ShapedType::isDynamic(d1) || ShapedType::isDynamic(d2) || d1 == d2;
}
} // namespace
} // namespace mlir
// Generated dialect definitions.
#include "mlir-hlo/Dialect/thlo/IR/thlo_dialect.cc.inc"
namespace mlir {
namespace thlo {
void THLODialect::initialize() {
addOperations<
#define GET_OP_LIST
#include "mlir-hlo/Dialect/thlo/IR/thlo_ops.cc.inc"
>();
}
//===----------------------------------------------------------------------===//
// ConcatenateOp
//===----------------------------------------------------------------------===//
namespace {
Value fuseConcatenateOpThroughTile(ConcatenateOp op, OpBuilder &builder,
Location loc, Value tile) {
uint64_t concatDim = op.dimension();
auto resultTy = op.getResult().getType().cast<RankedTensorType>();
int64_t rank = resultTy.getRank();
OperandRange allOperands = op.operands();
Value anyOperand = allOperands.front();
// Create the shared tile strides, which are the exact same for every operand
// tile. Also create a basis for the space sizes, tile offsets, and tile
// sizes. These hold the shared values in all non-concat dimensions and can be
// amended in the concat dimension to create the individual operand tiles.
SmallVector<Value> sharedTileStrides(rank);
SmallVector<Value> baseSpaceSizes(rank);
SmallVector<Value> baseTileOffsets(rank);
SmallVector<Value> baseTileSizes(rank);
for (int64_t i = 0; i < rank; ++i) {
Value iCst = builder.create<arith::ConstantIndexOp>(loc, i);
sharedTileStrides[i] = builder.create<gml_st::StrideOp>(loc, tile, iCst);
// The space sizes, tile offsets, and tile sizes differ in the concat
// dimension. Do not populate these.
if (i == static_cast<int64_t>(concatDim)) {
continue;
}
baseSpaceSizes[i] =
builder.createOrFold<tensor::DimOp>(loc, anyOperand, iCst);
baseTileOffsets[i] = builder.create<gml_st::OffsetOp>(loc, tile, iCst);
baseTileSizes[i] = builder.create<gml_st::SizeOp>(loc, tile, iCst);
}
// Some shared values.
ArrayAttr allDynamicStridesOrOffsetsAttr = builder.getI64ArrayAttr(
SmallVector<int64_t>(rank, ShapedType::kDynamicStrideOrOffset));
ArrayAttr allDynamicSizesAttr = builder.getI64ArrayAttr(
SmallVector<int64_t>(rank, ShapedType::kDynamicSize));
Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
Value concatDimCst = builder.create<arith::ConstantIndexOp>(loc, concatDim);
Value maxTileSizeInConcatDim =
builder.create<gml_st::SizeOp>(loc, tile, concatDimCst);
// The remaining tile offset in the concat dimension is subtracted by each
// operand's size in that dimension. We maintain the invariant
// remainingTileOffsetInConcatDim >= 0.
Value remainingTileOffsetInConcatDim =
builder.create<gml_st::OffsetOp>(loc, tile, concatDimCst);
// Create the relevant subsets per operand. These tiles can be empty at
// runtime.
SmallVector<Value> subOperands;
subOperands.reserve(allOperands.size());
for (Value operand : allOperands) {
// Create operand space.
Value operandSizeInConcatDim =
builder.create<tensor::DimOp>(loc, operand, concatDimCst);
baseSpaceSizes[concatDim] = operandSizeInConcatDim;
Value operandSpace = builder.create<gml_st::SpaceOp>(loc, baseSpaceSizes,
allDynamicSizesAttr);
// Find the current operand's tile offset in the concat dimension. This is
// the remaining offset clamped into the bounds of the operand. Note that
// the remaining offset is always >= 0.
Value operandTileOffsetInConcatDim = builder.create<arith::MinUIOp>(
loc, remainingTileOffsetInConcatDim, operandSizeInConcatDim);
baseTileOffsets[concatDim] = operandTileOffsetInConcatDim;
// Find the current operand's tile size in the concat dimension.
Value remainingOperandSizeInConcatDim = builder.create<arith::SubIOp>(
loc, operandSizeInConcatDim, operandTileOffsetInConcatDim);
baseTileSizes[concatDim] = builder.create<arith::MinUIOp>(
loc, remainingOperandSizeInConcatDim, maxTileSizeInConcatDim);
// Create the operand tile and materialize the subset for this operand.
Value tile = builder.create<gml_st::TileOp>(
loc, operandSpace, baseTileOffsets, baseTileSizes, sharedTileStrides,
allDynamicStridesOrOffsetsAttr, allDynamicSizesAttr,
allDynamicStridesOrOffsetsAttr);
subOperands.push_back(
builder.create<gml_st::MaterializeOp>(loc, operand, tile));
// Unless it is the last operand, update the remaining tile offset in the
// concat dimension. The remaining offset is subtracted by the operand's
// size but must remain >= 0.
if (operand != allOperands.back()) {
remainingTileOffsetInConcatDim = builder.create<arith::SelectOp>(
loc,
builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ule,
remainingTileOffsetInConcatDim,
operandSizeInConcatDim),
zeroCst,
builder.create<arith::SubIOp>(loc, remainingTileOffsetInConcatDim,
operandSizeInConcatDim));
}
}
// Create the tiled concat op.
auto tileType = tile.getType().cast<gml_st::TileType>();
Value subInit = builder.create<gml_st::MaterializeOp>(loc, op.init(), tile);
auto subResultType =
RankedTensorType::get(tileType.getShape(), resultTy.getElementType());
return builder.create<thlo::ConcatenateOp>(loc, subResultType, subOperands,
subInit, concatDim);
}
Value fuseConcatenateOpThroughPointRecursively(
OpBuilder &builder, Location loc, RankedTensorType rankedTy,
uint64_t concatDim, SmallVector<Value> &remainingOffsets,
ValueRange remainingOperands) {
// Bail if called for no operands.
if (remainingOperands.empty()) {
return {};
}
Value leadingOperand = remainingOperands.front();
// Terminal case of exactly one operand.
if (remainingOperands.size() == 1) {
// Create operand space.
SmallVector<Value> dynamicDims =
tensor::createDynamicDimValues(builder, loc, leadingOperand);
ArrayAttr staticDims = builder.getI64ArrayAttr(rankedTy.getShape());
Value operandSpace =
builder.create<gml_st::SpaceOp>(loc, dynamicDims, staticDims);
// Create operand point.
SmallVector<int64_t> allDynamicOffsets(rankedTy.getRank(),
ShapedType::kDynamicStrideOrOffset);
Value operandPoint = builder.create<gml_st::PointOp>(
loc, operandSpace, remainingOffsets,
builder.getI64ArrayAttr(allDynamicOffsets));
return builder.create<gml_st::MaterializeOp>(loc, leadingOperand,
operandPoint);
}
// For more than 1 operand, distinguish between the leading operand and the
// remainder.
assert(remainingOperands.size() > 1 &&
"expect more than 1 operand at this point");
Value leadingOperandConcatDim =
builder.create<tensor::DimOp>(loc, leadingOperand, concatDim);
Value leadingOperandPredicate = builder.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::ult, remainingOffsets[concatDim],
leadingOperandConcatDim);
auto ifOp = builder.create<scf::IfOp>(
loc, rankedTy.getElementType(), leadingOperandPredicate,
[&](OpBuilder &builder, Location loc) {
// For the leading operand, recur with the current offsets.
Value fused = fuseConcatenateOpThroughPointRecursively(
builder, loc, rankedTy, concatDim, remainingOffsets,
leadingOperand);
builder.create<scf::YieldOp>(loc, fused);
},
[&](OpBuilder &builder, Location loc) {
// For the remaining operands, substract the leading operand's size from
// the remaining offsets in the concatenation dimension.
SmallVector<Value> thenRemainingOffsets(remainingOffsets.begin(),
remainingOffsets.end());
thenRemainingOffsets[concatDim] = builder.create<arith::SubIOp>(
loc, remainingOffsets[concatDim], leadingOperandConcatDim);
Value fused = fuseConcatenateOpThroughPointRecursively(
builder, loc, rankedTy, concatDim, thenRemainingOffsets,
remainingOperands.drop_front());
builder.create<scf::YieldOp>(loc, fused);
});
return ifOp.getResults().front();
}
Value fuseConcatenateOpThroughPoint(ConcatenateOp op, OpBuilder &builder,
Location loc, Value subset) {
auto resultTy = op.getType().cast<RankedTensorType>();
int64_t resultRank = resultTy.getRank();
uint64_t concatDim = op.dimension();
// Materialize initial offsets.
SmallVector<Value> initialOffsets;
initialOffsets.reserve(resultRank);
for (int64_t i = 0; i < resultRank; ++i) {
initialOffsets.push_back(builder.create<gml_st::OffsetOp>(
loc, subset, builder.create<arith::ConstantIndexOp>(loc, i)));
}
ValueRange initialOperands = op.operands();
return fuseConcatenateOpThroughPointRecursively(
builder, loc, resultTy, concatDim, initialOffsets, initialOperands);
}
} // namespace
Value ConcatenateOp::fuse(Location loc, Value subset, OpBuilder &builder) {
Type subsetTy = subset.getType();
if (subsetTy.isa<gml_st::TileType>()) {
return fuseConcatenateOpThroughTile(*this, builder, loc, subset);
}
if (subsetTy.isa<gml_st::PointType>()) {
return fuseConcatenateOpThroughPoint(*this, builder, loc, subset);
}
return {};
}
ParseResult ConcatenateOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDstStyleOp(parser, result);
}
void ConcatenateOp::print(OpAsmPrinter &p) {
printDstStyleOp(cast<ConcatenateOp>(getOperation()), p);
}
LogicalResult ConcatenateOp::verify() {
return verifyDestinationStyleOp(getOperation(), getNumOutputs());
}
//===----------------------------------------------------------------------===//
// DynamicBroadcastInDimOp
//===----------------------------------------------------------------------===//
ParseResult DynamicBroadcastInDimOp::parse(OpAsmParser &parser,
OperationState &result) {
return parseDstStyleOp(parser, result,
[&](OpAsmParser &parser, NamedAttrList &attributes) {
return parseDenseI64ArrayAttr(
parser, attributes, "broadcast_dimensions");
});
}
void DynamicBroadcastInDimOp::print(OpAsmPrinter &p) {
printDstStyleOp<DynamicBroadcastInDimOp>(
cast<DynamicBroadcastInDimOp>(getOperation()), p,
[](DynamicBroadcastInDimOp op,
OpAsmPrinter &p) -> SmallVector<StringRef> {
printDenseI64ArrayAttr(p, op.broadcast_dimensionsAttrName(),
op.broadcast_dimensions());
return {op.broadcast_dimensionsAttrName()};
});
}
LogicalResult DynamicBroadcastInDimOp::verify() {
return verifyDestinationStyleOp(getOperation(), getNumOutputs());
}
Value DynamicBroadcastInDimOp::fuse(Location loc, Value subset,
OpBuilder &builder) {
Type subsetTy = subset.getType();
auto operandTy = operand().getType().cast<RankedTensorType>();
auto resultTy = getType(0).cast<RankedTensorType>();
int64_t operandRank = operandTy.getRank();
// Create the needed constants only once.
DenseMap<uint64_t, Value> localIndexConstants;
auto getIndexConstant = [&](uint64_t c) -> Value {
auto it = localIndexConstants.find(c);
if (it != localIndexConstants.end()) return it->second;
auto cst = builder.create<arith::ConstantIndexOp>(loc, c);
localIndexConstants[c] = cst;
return cst;
};
// Materialize operand space.
auto operandSpaceTy = builder.getType<gml_st::TileType>(operandTy.getShape());
auto dynamicDims = tensor::createDynamicDimValues(builder, loc, operand());
auto staticDims = builder.getI64ArrayAttr(operandTy.getShape());
Value operandSpace = builder.create<gml_st::SpaceOp>(loc, operandSpaceTy,
dynamicDims, staticDims);
// Materialize operand dimensions.
SmallVector<Value> operandDims;
int64_t dynamicDimsIdx = 0;
operandDims.reserve(operandTy.getRank());
for (const auto &it : llvm::enumerate(operandTy.getShape())) {
int64_t d = it.value();
Value dim = d == ShapedType::kDynamicSize ? dynamicDims[dynamicDimsIdx++]
: getIndexConstant(d);
operandDims.push_back(dim);
}
// Collapse the subset to operate only on corresponding dimensions.
// TODO(frgossen): Only generate this when needed.
auto collapsedSubset = builder.create<gml_st::DropDimsOp>(
loc, subset, broadcast_dimensionsAttr());
// Find the expanding dimensions. If corresponding operand and result
// dimensions are different then the dimension is expanding.
// TODO(frgossen): Use info from known expanding and known non-expanding
// dimensions here.
SmallVector<Value> operandExpandingDims;
for (const auto &it : llvm::enumerate(broadcast_dimensions())) {
auto operandDim = operandDims[it.index()];
auto resultDim = builder.create<tensor::DimOp>(
loc, init(), getIndexConstant(it.value()));
operandExpandingDims.push_back(builder.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::ne, operandDim, resultDim));
}
// Compute operand offsets, which are needed for tile and point subsets.
auto staticOffsets = builder.getI64ArrayAttr(
SmallVector<int64_t>(operandRank, ShapedType::kDynamicStrideOrOffset));
SmallVector<Value> offsets;
Value zero = getIndexConstant(0);
for (int i = 0; i < operandRank; ++i) {
Value isExpanding = operandExpandingDims[i];
Value collapsedSubsetOffset = builder.create<gml_st::OffsetOp>(
loc, collapsedSubset, getIndexConstant(i));
offsets.push_back(builder.create<arith::SelectOp>(loc, isExpanding, zero,
collapsedSubsetOffset));
}
// If the regarded subset is of point type, we can already construct the
// operand point and materialize it.
if (auto pointTy = subsetTy.dyn_cast<gml_st::PointType>()) {
auto operandPoint = builder.create<gml_st::PointOp>(
loc, pointTy, operandSpace, offsets, staticOffsets);
return builder.create<gml_st::MaterializeOp>(
loc, operandTy.getElementType(), operand(), operandPoint);
}
// If the regarded subset is of tile type, we still need the operand tile
// sizes to materialize a fused broadcast.
if (auto tileTy = subsetTy.dyn_cast<gml_st::TileType>()) {
// Compute operand tile sizes.
auto staticTileSizes = builder.getI64ArrayAttr(
SmallVector<int64_t>(operandRank, ShapedType::kDynamicSize));
SmallVector<Value> tileSizes;
Value one = getIndexConstant(1);
for (int i = 0; i < operandRank; ++i) {
Value isExpanding = operandExpandingDims[i];
Value tileSize = builder.create<gml_st::SizeOp>(loc, collapsedSubset,
getIndexConstant(i));
tileSizes.push_back(
builder.create<arith::SelectOp>(loc, isExpanding, one, tileSize));
}
// Create operand tile.
auto staticTileStrides =
builder.getI64ArrayAttr(SmallVector<int64_t>(operandRank, 1));
SmallVector<Value> tileStrides = {};
auto operandTileTy = builder.getType<gml_st::TileType>(
SmallVector<int64_t>(operandRank, ShapedType::kDynamicSize));
auto operandTile = builder.create<gml_st::TileOp>(
loc, operandTileTy, operandSpace, offsets, tileSizes, tileStrides,
staticOffsets, staticTileSizes, staticTileStrides);
// Materialize operand subsets.
Value tiledInit =
builder.create<gml_st::MaterializeOp>(loc, init(), subset);
Value tiledOperand =
builder.create<gml_st::MaterializeOp>(loc, operand(), operandTile);
// Finally, materialize tiled broadcast.
auto tiledResultTy =
RankedTensorType::get(tileTy.getShape(), resultTy.getElementType());
return builder
.create<DynamicBroadcastInDimOp>(
loc, TypeRange{tiledResultTy}, tiledOperand, tiledInit,
broadcast_dimensionsAttr(), known_expanding_dimensionsAttr(),
known_nonexpanding_dimensionsAttr())
.getResult(0);
}
return {};
}
//===----------------------------------------------------------------------===//
// ScatterOp
//===----------------------------------------------------------------------===//
ParseResult ScatterOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDstStyleOp(parser, result);
}
void ScatterOp::print(OpAsmPrinter &p) {
printDstStyleOp(cast<ScatterOp>(getOperation()), p);
}
LogicalResult ScatterOp::verify() {
return verifyDestinationStyleOp(getOperation(), getNumOutputs());
}
//===----------------------------------------------------------------------===//
// GatherOp
//===----------------------------------------------------------------------===//
ParseResult GatherOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDstStyleOp(parser, result);
}
void GatherOp::print(OpAsmPrinter &p) {
printDstStyleOp(cast<GatherOp>(getOperation()), p);
}
LogicalResult GatherOp::verify() {
return verifyDestinationStyleOp(getOperation(), getNumOutputs());
}
//===----------------------------------------------------------------------===//
// TransposeOp
//===----------------------------------------------------------------------===//
ParseResult TransposeOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDstStyleOp(
parser, result, [&](OpAsmParser &parser, NamedAttrList &attributes) {
return parseDenseI64ArrayAttr(parser, attributes, "permutation");
});
}
void TransposeOp::print(OpAsmPrinter &p) {
printDstStyleOp<TransposeOp>(
cast<TransposeOp>(getOperation()), p,
[](TransposeOp op, OpAsmPrinter &p) -> SmallVector<StringRef> {
printDenseI64ArrayAttr(p, op.permutationAttrName(), op.permutation());
return {op.permutationAttrName()};
});
}
bool isValidPermutation(ArrayRef<int64_t> permutation) {
SmallVector<bool> seen(permutation.size(), false);
for (auto p : permutation) {
// Verify that each element is in [0..n-1] range and is present only once.
if (p < 0 || p >= static_cast<int64_t>(permutation.size()) || seen[p])
return false;
seen[p] = true;
}
return true;
}
LogicalResult TransposeOp::verify() {
ArrayRef<int64_t> permutationRef = permutation();
if (!isValidPermutation(permutationRef))
return emitOpError("permutation is not valid");
auto inputType = input().getType().cast<ShapedType>();
auto initType = init().getType().cast<ShapedType>();
int64_t rank = inputType.getRank();
if (rank != initType.getRank())
return emitOpError() << "input rank " << rank
<< " does not match init rank " << initType.getRank();
if (rank != static_cast<int64_t>(permutationRef.size()))
return emitOpError() << "size of permutation " << permutationRef.size()
<< " does not match the argument rank " << rank;
auto inputDims = inputType.getShape();
auto initDims = initType.getShape();
for (int64_t i = 0; i < rank; ++i) {
int64_t inputDim = inputDims[permutationRef[i]];
int64_t initDim = initDims[i];
if (!dimensionsMatch(inputDim, initDim)) {
return emitOpError() << "dim(result, " << i << ") = " << initDim
<< " doesn't match dim(input, permutation[" << i
<< "]) = " << inputDim;
}
}
return verifyDestinationStyleOp(getOperation(), getNumOutputs());
}
//===----------------------------------------------------------------------===//
// ReductionOp
//===----------------------------------------------------------------------===//
ParseResult ReductionOp::parse(OpAsmParser &parser, OperationState &result) {
if (parseDstStyleOp(
parser, result, [&](OpAsmParser &parser, NamedAttrList &attributes) {
return parseDenseI64ArrayAttr(parser, attributes, "dimensions");
}))
return failure();
SmallVector<OpAsmParser::Argument> regionArgs;
if (parser.parseArgumentList(regionArgs, OpAsmParser::Delimiter::Paren,
/*allowType=*/true, /*allowAttrs=*/true)) {
return failure();
}
Region *body = result.addRegion();
if (parser.parseRegion(*body, regionArgs)) return failure();
return success();
}
void ReductionOp::print(OpAsmPrinter &p) {
printDstStyleOp<ReductionOp>(
cast<ReductionOp>(getOperation()), p,
[](ReductionOp op, OpAsmPrinter &p) -> SmallVector<StringRef> {
printDenseI64ArrayAttr(p, op.dimensionsAttrName(), op.dimensions());
return {op.dimensionsAttrName()};
});
p << "(";
llvm::interleaveComma(combiner().getArguments(), p,
[&](auto arg) { p.printRegionArgument(arg); });
p << ") ";
p.printRegion(combiner(), /*printEntryBlockArgs=*/false);
}
LogicalResult ReductionOp::verify() {
ArrayRef<int64_t> dimensionsRef = dimensions();
for (int64_t i = 1; i < getNumInputs(); ++i) {
if (failed(mlir::verifyCompatibleShape(inputs()[i].getType(),
inputs()[0].getType()))) {
return emitOpError() << "expects all inputs to have compatible shapes. "
"Shape at input-index "
<< i
<< " is not compatible with shape at input-index 0.";
}
}
for (int64_t i = 1; i < getNumOutputs(); ++i) {
if (failed(mlir::verifyCompatibleShape(inits()[i].getType(),
inits()[0].getType()))) {
return emitOpError()
<< "expects all outputs to have compatible shapes. "
"Shape at output-index "
<< i << " is not compatible with shape at output-index 0.";
}
}
auto inputType = inputs()[0].getType().cast<ShapedType>();
auto initType = inits()[0].getType().cast<ShapedType>();
DenseSet<int64_t> dimensionsToReduce;
for (int64_t dimension : dimensionsRef) {
if (dimension < 0 || dimension >= inputType.getRank()) {
return emitOpError()
<< "dimensions for reduction should be in the range [0, "
<< inputType.getRank() - 1 << "].";
}
if (!dimensionsToReduce.insert(dimension).second) {
return emitOpError() << "duplicate reduction dimension: " << dimension;
}
}
auto inputDims = inputType.getShape();
auto initDims = initType.getShape();
// Input dimensions that will be left after the reduction.
SmallVector<int64_t> reducedInputDims;
for (const auto &en : llvm::enumerate(inputDims)) {
if (!llvm::is_contained(dimensionsRef, en.index()))
reducedInputDims.push_back(en.value());
}
if (reducedInputDims.size() != initType.getRank()) {
return emitOpError() << "number of dimensions after reduction "
<< reducedInputDims.size()
<< " doesn't match the init rank "
<< initType.getRank();
}
if (!all_of_zip(reducedInputDims, initDims, &dimensionsMatch))
return emitOpError() << "init dimensions [" << initDims
<< "] doesn't match input dimensions after reduction ["
<< reducedInputDims << "]";
Block *block = getBody();
if (static_cast<int64_t>(block->getArguments().size()) !=
getNumInputs() + getNumOutputs()) {
return emitOpError()
<< "number of block arguments " << block->getArguments().size()
<< " doesn't match the number of inputs plus the number of outputs "
<< getNumInputs() + getNumOutputs();
}
// Check that the first block arguments match the element type of the inputs.
auto inputElementTypes =
llvm::to_vector<8>(llvm::map_range(inputs().getTypes(), [](Type type) {
return type.cast<ShapedType>().getElementType();
}));
auto blockArgumentInputTypes = llvm::to_vector<8>(
llvm::map_range(block->getArguments().take_front(getNumInputs()),
[](BlockArgument arg) { return arg.getType(); }));
if (blockArgumentInputTypes != inputElementTypes) {
return emitOpError() << "input element types " << inputElementTypes
<< " do not match block argument types "
<< blockArgumentInputTypes;
}
// Check that the last block arguments match the element type of the outputs.
auto outputElementTypes =
llvm::to_vector<8>(llvm::map_range(inits().getTypes(), [](Type type) {
return type.cast<ShapedType>().getElementType();
}));
auto blockArgumentOutputTypes = llvm::to_vector<8>(
llvm::map_range(block->getArguments().take_back(getNumOutputs()),
[](BlockArgument arg) { return arg.getType(); }));
if (blockArgumentOutputTypes != outputElementTypes) {
return emitOpError() << "output element types " << outputElementTypes
<< " do not match block argument types "
<< blockArgumentOutputTypes;
}
return verifyDestinationStyleOp(getOperation(), getNumOutputs());
}
//===----------------------------------------------------------------------===//
// MapOp
//===----------------------------------------------------------------------===//
ParseResult MapOp::parse(OpAsmParser &parser, OperationState &result) {
if (parseDstStyleOp(parser, result)) return failure();
SmallVector<OpAsmParser::Argument> regionArgs;
if (parser.parseArgumentList(regionArgs, OpAsmParser::Delimiter::Paren,
/*allowType=*/true, /*allowAttrs=*/true)) {
return failure();
}
Region *body = result.addRegion();
if (parser.parseRegion(*body, regionArgs)) return failure();
return success();
}
void MapOp::print(OpAsmPrinter &p) {
printDstStyleOp<MapOp>(cast<MapOp>(getOperation()), p);
p << "(";
llvm::interleaveComma(mapper().getArguments(), p,
[&](auto arg) { p.printRegionArgument(arg); });
p << ") ";
p.printRegion(mapper(), /*printEntryBlockArgs=*/false);
}
LogicalResult MapOp::verify() {
return verifyDestinationStyleOp(getOperation(), getNumOutputs());
}
} // namespace thlo
} // namespace mlir
// Generated op classes.
#define GET_OP_CLASSES
#include "mlir-hlo/Dialect/thlo/IR/thlo_ops.cc.inc"
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
1a54fc2e1c2606c22dcef5dcdc3476b88c5fa091 | 8158d3956fdb075884326c0f81d8aaa153de4e08 | /CS 251 Project 7 Priority Queue-Dijkstra/pqueue.cpp | fde36eb7398367d02a46a012d25d35f1eaa8b4a3 | [] | no_license | michalbochnak/Priority-Queue-Dijkstra | 8e5a98f5f5600b9a7bff2f1714b718fac9eb867e | 02ba4dd44cb6e6369b865626ea67571d2831a4a0 | refs/heads/master | 2020-03-28T11:32:34.133647 | 2018-09-10T22:06:34 | 2018-09-10T22:06:34 | 148,224,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,589 | cpp | /*pqueue.cpp*/
//
// A priority queue specifically designed for Dijkstra's shortest
// weighted path algorithm. Allows for storing (vertex, distance)
// pairs, with ability for both O(logN) pop and push. Unlike
// traditional priority queues, this version deletes an existing
// (vertex, distance) pair if a new pair is pushed with the same
// vertex --- this occurs in Dijkstra's algorithm when there exists
// a path to V, but then a better path is found and V's distance
// must be updated.
//
// Internally, a min-heap is used along with a hash table to keep
// track of where vertices are currently positioned in the heap.
//
#include <iostream>
#include <iomanip>
#include <string>
#include <exception>
#include <stdexcept>
#include "pqueue.h"
using namespace std;
//
// Constructor:
//
// N is the capacity of the priority queue, i.e. the maximum # of vertices
// that can be stored. This also implies that the vertex numbers range
// from 0..N-1.
//
PQueue::PQueue(int N)
{
this->Positions = new int[N]; // array of vertex positions in queue
this->Queue = new Elem[N]; // queue itself
this->Capacity = N; // we can support N vertices at most
this->NumElements = 0; // initially empty
//
// since queue is empty, set the positions of all the vertices to
// -1, i.e. "not in queue":
//
for (int v = 0; v < N; ++v)
{
this->Positions[v] = -1;
}
}
//
// Destructor:
//
PQueue::~PQueue()
{
delete[] this->Positions;
delete[] this->Queue;
}
//
// Fill:
//
// Initializes the queue such that all N vertices are assigned
// the same distance. This is equivalent to making N calls to
// Push(V, D):
//
// foreach vertex v = 0..N-1
// push(v, distance);
//
void PQueue::Fill(double distance)
{
//
// pre-fill the queue, assigning every vertex the same distance:
//
for (int v = 0; v < this->Capacity; ++v)
{
this->Queue[v].V = v;
this->Queue[v].D = distance;
this->Positions[v] = v;
}
this->NumElements = this->Capacity;
}
//
// Push:
//
// Inserts the given pair (vertex, distance) into the priority
// queue in ascending order by distance. If two elements of the
// queue have the same distance D, which one comes first is
// undefined.
//
// NOTE: if the vertex is already in the queue with distance D,
// then the existing (vertex, D) pair is removed, and the new
// (vertex, distance) pair inserted.
//
void PQueue::Push(int vertex, double distance)
{
if (vertex < 0 || vertex >= this->Capacity)
throw logic_error("Invalid vertex passed to PQueue::Push, must be 0..N-1");
//
// Is the vertex already in the queue? If so, we need to delete the
// existing (vertex, distance) element from queue, and then re-insert
// with updated distance:
//
int position = this->Positions[vertex];
if (position >= 0) // vertex is currently stored in the queue:
{
int deletedV = this->Delete(position);
if (deletedV != vertex)
throw logic_error("**Internal error: vertex mismatch in PQueue::Push");
if (this->Positions[vertex] != -1)
throw logic_error("**Internal error: vertex position not deleted in PQueue::Push");
}
//
// At this point the vertex is not in the queue, so now we do a
// normal insert into a min heap:
//
this->Insert(vertex, distance);
// success:
return;
}
//
// PopMin:
//
// Pops (and removes) the (vertex, distance) pair at the front of
// the queue, and returns vertex. If the queue is empty, then this
// operation is an error and so a logic_error exception is thrown
// with the error message "stack empty!".
//
int PQueue::PopMin()
{
if (this->Empty())
throw logic_error("stack empty!");
int v = this->Delete(0); // min element is at front => position 0:
return v;
}
//
// Empty:
//
// Returns true if the queue is empty, false if not.
//
bool PQueue::Empty()
{
return (this->NumElements == 0);
}
//
// Dump:
//
// Dumps the contents of the queue to the console; this is for
// debugging purposes.
//
void PQueue::Dump(string title)
{
cout << ">>PQueue: " << title << endl;
cout << " # elements: " << this->NumElements << endl;
if (this->Empty()) // no output:
;
else if (this->NumElements < 100) // smallish, can print entire contents:
{
cout << std::fixed;
cout << std::setprecision(2);
cout << " ";
for (int i = 0; i < this->NumElements; ++i)
{
cout << "(" << this->Queue[i].V << "," << this->Queue[i].D << ") ";
}
cout << endl;
cout << " Positions: ";
for (int v = 0; v < this->Capacity; ++v)
{
if (this->Positions[v] != -1)
cout << "(" << v << "@" << this->Positions[v] << ") ";
}
cout << endl;
}
else // Graph contains 100+ elements, so let's print a summary:
{
cout << std::fixed;
cout << std::setprecision(2);
cout << " ";
for (int i = 0; i < 3; ++i)
{
cout << "(" << this->Queue[i].V << "," << this->Queue[i].D << ") ";
}
cout << "... ";
for (int i = this->NumElements - 3; i < this->NumElements; ++i)
{
cout << "(" << this->Queue[i].V << "," << this->Queue[i].D << ") ";
}
cout << endl;
int count = 0;
cout << " Positions: ";
for (int v = 0; v < this->Capacity; ++v)
{
if (this->Positions[v] != -1)
{
cout << "(" << v << "@" << this->Positions[v] << ") ";
count++;
if (count == 3)
break;
}
}
cout << "... ";
int v = this->Capacity - 1;
while (true)
{
if (this->Positions[v] != -1)
{
count--;
if (count == 0)
break;
}
v--;
}
for (/*empty*/; v < this->Capacity; ++v)
{
if (this->Positions[v] != -1)
{
cout << "(" << v << "@" << this->Positions[v] << ") ";
count++;
if (count == 3)
break;
}
}
cout << endl;
}
}
/*************************** PRIVATE HELPER FUNCTIONS *******************************/
//
// Insert:
//
// Inserts the given (vertex, distance) pair into the priority queue; it is
// assumed that vertex v is *not* in the queue (if it was, you must delete
// before calling Insert). Follows standard min-heap insertion algorithm
// where you insert into last position, and then swap upwards in the tree
// to it's proper position.
//
void PQueue::Insert(int v, double d)
{
if (v < 0 || v >= this->Capacity)
throw logic_error("Invalid vertex passed to PQueue::Insert");
if (this->Positions[v] != -1)
throw logic_error("**Internal error: PQueue::Insert called while vertex is still in queue");
//
// TODO:
//
Elem temp;
temp.V = v;
temp.D = d;
this->Queue[this->NumElements] = temp;
this->Positions[v] = this->NumElements;
this->NumElements++;
// check if shift is needed
if (this->Queue[this->NumElements - 1].D < this->Queue[this->getParentIndex(this->NumElements - 1)].D) {
shiftUp(this->NumElements - 1);
}
}
//
// Delete:
//
// Deletes the (vertex, distance) pair at the given position in the queue,
// where 0 <= position < # of elements. The deleted vertex v is returned.
// Use a standard min-heap deletion algorithm where deleted element is
// replaced by the last element, and then this element has to be swapped
// into position --- this can be upwards or downwards (or not at all).
//
int PQueue::Delete(int position)
{
if (this->Empty())
throw logic_error("**Internal error: call to PQueue::Delete with an empty queue");
if (position < 0 || position >= this->NumElements)
throw logic_error("**Internal error: invalid position in PQueue::Delete");
int v = -1;
//
// TODO:
//
// grab the vertex to be returned
v = this->Queue[position].V;
// last elements in the array
if (position == this->NumElements - 1) {
// clear data in the Queue array
this->Queue[position].D = -1;
this->Queue[position].V = -1;
// clear data in the Positions array
this->Positions[v] = -1;
// decrement number of elements in the Queue
this->NumElements--;
return v;
}
// root only / only one element
// decrement the size of the array and reset the values to -1
if (this->NumElements == 1) {
this->NumElements--;
this->Positions[v] = -1;
this->Queue[this->NumElements].D = -1;
this->Queue[this->NumElements].V = -1;
return v;
}
//
// more than one element in the array
//
// adjust size of the Queue
this->NumElements--;
// insert the value of the last element in the array into the element to be removed
this->Queue[position] = this->Queue[this->NumElements];
// update position array as last element was iserted into new place
this->Positions[this->Queue[position].V] = position;
// update position array for last element since it not exist anymore
this->Positions[v] = -1;
// update values in last element ( which was moved ) to -1's
this->Queue[this->NumElements].V = -1;
this->Queue[this->NumElements].D = -1;
// if in correct spot, no need to swap, return
if (this->inCorrectSpotwithRespectToParent(position)
&& this->inCorrectSpotwithRespectToChild(position)) {
return v;
}
//
// check for the swap direction: up or down the tree
//
// swaps needed
this->swap(position);
//
// done!
//
return v;
}
// function return index of smaller child
int PQueue::getSmallerChild(int position)
{
int leftIndex, rightIndex;
leftIndex = (position * 2) + 1;
rightIndex = (position * 2) + 2;
// id dostances are equal, return te index of right child
if (this->Queue[leftIndex].D == this->Queue[rightIndex].D) {
return rightIndex;
}
// return the index of the child with graater distance
else {
if (this->Queue[leftIndex].D > this->Queue[rightIndex].D) {
return leftIndex;
}
else
return rightIndex;
}
}
// checks if the node is in corrent spot with respect to parent
// specifically verifies if is <= to parent
bool PQueue::inCorrectSpotwithRespectToParent(int position) {
// check if has parent, if so verify if distance is greater than parent distance
if (position != 0) {
// check if distance is greater than parent
if (this->Queue[position].D <= this->Queue[(position - 1) / 2].D) {
return false; // less than parent, return false
}
}
return true;
}
// checks if the node is in corrent spot with respect to child
// specifically verifies if is >= to child or children
bool PQueue::inCorrectSpotwithRespectToChild(int position) {
// check if have at least one child
if ((this->Queue[(position * 2) + 1].D != -1)
|| (this->Queue[(position * 2) + 2].D != -1)) {
// check if distance is greater than smaller child,
// return false if not
if (this->Queue[position].D <= this->Queue[this->getSmallerChild(position)].D) {
return false;
}
}
return true;
}
// swaps the nodes in the tree
// assumes swaps are needed
void PQueue::swap(int position) {
// need to be swapped upward
if (!(this->inCorrectSpotwithRespectToParent(position))) {
// swap upwards
this->shiftUp(position);
}
// need to be swapped downward
if (!(this->inCorrectSpotwithRespectToChild(position))) {
// swap downwards
this->shiftDown(position);
}
}
// shifts the node down
void PQueue::shiftDown(int position) {
int leftChildIndex, rightChildIndex, minIndex;
Elem temp;
leftChildIndex = this->getLeftChildIndex(position);
rightChildIndex = this->getRightChildIndex(position);
if (rightChildIndex >= this->NumElements) {
if (leftChildIndex >= this->NumElements)
return;
else
minIndex = leftChildIndex;
}
else {
minIndex = this->getSmallerChild(position);
}
if (this->Queue[position].D > this->Queue[minIndex].D) {
// swap and update Positions array
temp = this->Queue[minIndex];
this->Queue[minIndex] = this->Queue[position];
this->Positions[position] = minIndex;
this->Queue[position] = temp;
this->Positions[minIndex] = position;
this->shiftDown(minIndex);
}
}
// shifts the node up
void PQueue::shiftUp(int position) {
int parentIndex, minIndex;
Elem temp;
parentIndex = getParentIndex(position);
if (this->Queue[position].D >= this->Queue[parentIndex].D) {
return;
}
// swap the node up
if (this->Queue[position].D < this->Queue[parentIndex].D) {
// swap and update the node position
temp = this->Queue[parentIndex];
this->Queue[parentIndex] = this->Queue[position];
this->Positions[this->Queue[parentIndex].V] = parentIndex;
this->Queue[position] = temp;
this->Positions[this->Queue[position].V] = position;
this->shiftUp(parentIndex);
}
}
// return index of left child
int PQueue::getLeftChildIndex(int position) {
return (position * 2) + 1;
}
// return index of right child
int PQueue::getRightChildIndex(int position) {
return (position * 2) + 2;
}
// return the index of of parent
int PQueue::getParentIndex(int position) {
return (position - 1) / 2;
} | [
"mbochn2@uic.edu"
] | mbochn2@uic.edu |
4b848b7136121ac5ab9585c40040b371e0d43c8e | 1a3a8991b293216d890d6ed970761685ef30ccf4 | /check/TestLpModification.cpp | dd8a722b6d1fb2884e5e9cbb386dc6212937ad04 | [
"MIT"
] | permissive | mlubin/HiGHS | 23e7530094f3f70fd2966b906798eed31a040779 | 7869054b42927f5d4a42040bcfa1a7366b70be98 | refs/heads/master | 2021-05-21T07:07:16.129077 | 2020-03-31T15:33:54 | 2020-03-31T15:33:54 | 252,594,985 | 0 | 0 | null | 2020-04-03T00:27:53 | 2020-04-03T00:27:52 | null | UTF-8 | C++ | false | false | 33,166 | cpp | #include "catch.hpp"
#include "Highs.h"
#include "lp_data/HighsLpUtils.h"
#include "Avgas.h"
void HighsStatusReport(FILE* logfile, const char* message, HighsStatus status) {
HighsLogMessage(logfile, HighsMessageType::INFO,
"%s: HighsStatus = %d - %s\n",
message, (int)status, HighsStatusToString(status).c_str());
}
bool areLpColEqual(
const int num_col0, const double* colCost0, const double* colLower0, const double* colUpper0,
const int num_nz0, const int* Astart0, const int* Aindex0, const double* Avalue0,
const int num_col1, const double* colCost1, const double* colLower1, const double* colUpper1,
const int num_nz1, const int* Astart1, const int* Aindex1, const double* Avalue1,
const double infinite_bound) {
if (num_col0 != num_col1) {
printf("areLpColEqual: %d = num_col0 != num_col1 = %d\n", num_col0, num_col1);
return false;
}
if (!num_col0) return true;
int num_col = num_col0;
for (int col = 0; col < num_col; col++) {
if (colCost0[col] != colCost1[col]) {
printf("areLpColEqual: %g = colCost0[%d] != colCost1[%d] = %g\n", colCost0[col], col, col, colCost1[col]);
return false;
}
}
for (int col = 0; col < num_col; col++) {
if (colLower0[col] <= -infinite_bound && colLower1[col] <= -infinite_bound) continue;
if (colLower0[col] != colLower1[col]) {
printf("areLpColEqual: %g = colLower0[%d] != colLower1[%d] = %g\n", colLower0[col], col, col, colLower1[col]);
return false;
}
if (colUpper0[col] >= infinite_bound && colUpper1[col] >= infinite_bound) continue;
if (colUpper0[col] != colUpper1[col]) {
printf("areLpColEqual: %g = colUpper0[%d] != colUpper1[%d] = %g\n", colUpper0[col], col, col, colUpper1[col]);
return false;
}
}
if (num_nz0 != num_nz1) {
printf("areLpColEqual: %d = num_nz0 != num_nz1 = %d\n", num_nz0, num_nz1);
return false;
}
if (!num_nz0) return true;
for (int col = 0; col < num_col; col++) {
if (Astart0[col] != Astart1[col]) {
printf("areLpColEqual: %d = Astart0[%d] != Astart1[%d] = %d\n", Astart0[col], col, col, Astart1[col]);
return false;
}
}
int num_nz = num_nz0;
for (int nz = 0; nz < num_nz; nz++) {
if (Aindex0[nz] != Aindex1[nz]) {
printf("areLpColEqual: %d = Aindex0[%d] != Aindex1[%d] = %d\n", Aindex0[nz], nz, nz, Aindex1[nz]);
return false;
}
if (Avalue0[nz] != Avalue1[nz]) {
printf("areLpColEqual: %g = Avalue0[%d] != Avalue1[%d] = %g\n", Avalue0[nz], nz, nz, Avalue1[nz]);
return false;
}
}
return true;
}
bool areLpRowEqual(const int num_row0,const double* rowLower0, const double* rowUpper0,
const int num_nz0, const int* ARstart0, const int* ARindex0, const double* ARvalue0,
const int num_row1, const double* rowLower1, const double* rowUpper1,
const int num_nz1, const int* ARstart1, const int* ARindex1, const double* ARvalue1,
const double infinite_bound) {
if (num_row0 != num_row1) {
printf("areLpRowEqual: %d = num_row0 != num_row1 = %d\n", num_row0, num_row1);
return false;
}
if (!num_row0) return true;
int num_row = num_row0;
for (int row = 0; row < num_row; row++) {
if (rowLower0[row] <= -infinite_bound && rowLower1[row] <= -infinite_bound) continue;
if (rowLower0[row] != rowLower1[row]) {
printf("areLpRowEqual: %g = rowLower0[%d] != rowLower1[%d] = %g\n", rowLower0[row], row, row, rowLower1[row]);
return false;
}
if (rowUpper0[row] >= infinite_bound && rowUpper1[row] >= infinite_bound) continue;
if (rowUpper0[row] != rowUpper1[row]) {
printf("areLpRowEqual: %g = rowUpper0[%d] != rowUpper1[%d] = %g\n", rowUpper0[row], row, row, rowUpper1[row]);
return false;
}
}
if (num_nz0 != num_nz1) {
printf("areLpRowEqual: %d = num_nz0 != num_nz1 = %d\n", num_nz0, num_nz1);
return false;
}
if (!num_nz0) return true;
for (int row = 0; row < num_row; row++) {
if (ARstart0[row] != ARstart1[row]) {
printf("areLpRowEqual: %d = ARstart0[%d] != ARstart1[%d] = %d\n", ARstart0[row], row, row, ARstart1[row]);
return false;
}
}
int num_nz = num_nz0;
for (int nz = 0; nz < num_nz; nz++) {
if (ARindex0[nz] != ARindex1[nz]) {
printf("areLpRowEqual: %d = ARindex0[%d] != ARindex1[%d] = %d\n", ARindex0[nz], nz, nz, ARindex1[nz]);
return false;
}
if (ARvalue0[nz] != ARvalue1[nz]) {
printf("areLpRowEqual: %g = ARvalue0[%d] != ARvalue1[%d] = %g\n", ARvalue0[nz], nz, nz, ARvalue1[nz]);
return false;
}
}
return true;
}
bool areLpEqual(const HighsLp lp0, const HighsLp lp1, const double infinite_bound) {
bool return_bool;
if (lp0.numCol_ > 0 && lp1.numCol_ > 0) {
int lp0_num_nz = lp0.Astart_[lp0.numCol_];
int lp1_num_nz = lp1.Astart_[lp1.numCol_];
return_bool = areLpColEqual(
lp0.numCol_, &lp0.colCost_[0], &lp0.colLower_[0], &lp0.colUpper_[0],
lp0_num_nz, &lp0.Astart_[0], &lp0.Aindex_[0], &lp0.Avalue_[0],
lp1.numCol_, &lp1.colCost_[0], &lp1.colLower_[0], &lp1.colUpper_[0],
lp1_num_nz, &lp1.Astart_[0], &lp1.Aindex_[0], &lp1.Avalue_[0],
infinite_bound);
if (!return_bool) return return_bool;
}
if (lp0.numRow_ > 0 && lp1.numRow_ > 0) {
int lp0_num_nz = 0;
int lp1_num_nz = 0;
return_bool = areLpRowEqual(
lp0.numRow_, &lp0.rowLower_[0], &lp0.rowUpper_[0],
lp0_num_nz, NULL, NULL, NULL,
lp1.numRow_, &lp1.rowLower_[0], &lp1.rowUpper_[0],
lp1_num_nz, NULL, NULL, NULL,
infinite_bound);
}
return return_bool;
}
void test_delete_keep(const int row_dim,
const bool interval, const int from_row, const int to_row,
const bool set, const int num_set_entries, const int* row_set,
const bool mask, const int* row_mask) {
int delete_from_row;
int delete_to_row;
int keep_from_row;
int keep_to_row;
int current_set_entry;
if (interval) {
printf("With index interval [%d, %d] in [%d, %d]\n", from_row, to_row, 0, row_dim-1);
} else if (set) {
printf("With index set\n");
for (int set = 0; set < num_set_entries; set++) printf(" %2d", set);
printf("\n");
for (int set = 0; set < num_set_entries; set++) printf(" %2d", row_set[set]);
printf("\n");
} else {
printf("With index mask\n");
for (int row = 0; row < row_dim; row++) printf(" %2d", row);
printf("\n");
for (int row = 0; row < row_dim; row++) printf(" %2d", row_mask[row]);
printf("\n");
}
keep_from_row = 0;
if (interval) {
keep_to_row = from_row-1;
} else if (set) {
current_set_entry = 0;
keep_to_row = row_set[0]-1;
} else {
keep_to_row = row_dim;
for (int row = 0; row < row_dim; row++) {
if (row_mask[row]) {
keep_to_row = row-1;
break;
}
}
}
printf("Keep [%2d, %2d]\n", 0, keep_to_row);
if (keep_to_row >= row_dim-1) return;
for (int k = 0; k < row_dim; k++) {
updateOutInIx(row_dim,
interval, from_row, to_row,
set, num_set_entries, row_set,
mask, row_mask,
delete_from_row, delete_to_row,
keep_from_row, keep_to_row,
current_set_entry);
printf("Delete [%2d, %2d]; keep [%2d, %2d]\n", delete_from_row, delete_to_row, keep_from_row, keep_to_row);
if (delete_to_row >= row_dim-1 || keep_to_row >= row_dim-1) break;
}
}
bool test_all_delete_keep(int num_row) {
// Test the extraction of intervals from interval, set and mask
bool interval = false;
bool set = false;
bool mask = false;
int row_dim = num_row;
int from_row = 3;
int to_row = 6;
int num_set_entries = 4;
int row_set[] = {1, 4, 5, 8};
int row_mask[] = {0,1,0,0,1,1,0,0,1,0};
int save_from_row = from_row;
int save_row_set_0 = row_set[0];
int save_row_mask_0 = row_mask[0];
int to_pass = 2;//2
for (int pass = 0; pass <= to_pass; pass++) {
printf("\nTesting delete-keep: pass %d\n", pass);
if (pass == 1) {
// Mods to test LH limit behaviour
from_row = 0;
row_set[0] = 0;
row_mask[0] = 1;
} else if (pass == 2) {
// Mods to test RH limit behaviour
from_row = save_from_row;
to_row = 9;
row_set[0] = save_row_set_0;
row_set[3] = 9;
row_mask[0] = save_row_mask_0;
row_mask[9] = 1;
}
interval = true;
test_delete_keep(row_dim,
interval, from_row, to_row,
set, num_set_entries, row_set,
mask, row_mask);
interval = false;
set = true;
test_delete_keep(row_dim,
interval, from_row, to_row,
set, num_set_entries, row_set,
mask, row_mask);
set = false;
mask = true;
test_delete_keep(row_dim,
interval, from_row, to_row,
set, num_set_entries, row_set,
mask, row_mask);
}
return true;
}
void messageReportLp(const char* message, const HighsLp &lp) {
HighsOptions options;
options.output = stdout;
options.message_level = ML_ALWAYS;
HighsPrintMessage(options.output, options.message_level, ML_VERBOSE,
"\nReporting LP: %s\n", message);
reportLp(options, lp, 2);
}
void messageReportMatrix(const char* message, const int num_col, const int num_nz,
const int* start, const int* index, const double* value) {
HighsOptions options;
options.output = stdout;
options.message_level = ML_ALWAYS;
HighsPrintMessage(options.output, options.message_level, ML_VERBOSE,
"\nReporting Matrix: %s\n", message);
reportMatrix(options, message, num_col, num_nz, start, index, value);
}
// No commas in test case name.
TEST_CASE("LP-modification", "[highs_data]") {
test_all_delete_keep(10);
HighsOptions options;
options.message_level = ML_ALWAYS;
Avgas avgas;
const int avgas_num_col = 8;
const int avgas_num_row = 10;
int num_row = 0;
int num_row_nz = 0;
vector<double> rowLower;
vector<double> rowUpper;
vector<int> ARstart;
vector<int> ARindex;
vector<double> ARvalue;
for (int row = 0; row < avgas_num_row; row++) {
avgas.row(row, num_row, num_row_nz, rowLower, rowUpper, ARstart, ARindex, ARvalue);
}
int num_col = 0;
int num_col_nz = 0;
vector<double> colCost;
vector<double> colLower;
vector<double> colUpper;
vector<int> Astart;
vector<int> Aindex;
vector<double> Avalue;
for (int col = 0; col < avgas_num_col; col++) {
avgas.col(col, num_col, num_col_nz, colCost, colLower, colUpper, Astart, Aindex, Avalue);
}
bool return_bool;
HighsStatus return_status;
HighsModelStatus model_status;
std::string message;
// Create two empty LPs: one to be initialised as AVGAS by adding
// all the columns and rows separately, the other to be built by
// adding piecemeal.
HighsLp avgas_lp;
HighsLp lp;
Highs avgas_highs(options);
return_status = avgas_highs.passModel(avgas_lp);
// printf("passModel: return_status = %s\n", HighsStatusToString(return_status).c_str());
REQUIRE(return_status == HighsStatus::OK);
return_bool = avgas_highs.addCols(num_col, &colCost[0], &colLower[0], &colUpper[0], 0, NULL, NULL, NULL);
REQUIRE(return_bool);
return_bool = avgas_highs.addRows(num_row, &rowLower[0], &rowUpper[0], num_row_nz, &ARstart[0], &ARindex[0], &ARvalue[0]);
REQUIRE(return_bool);
return_status = avgas_highs.writeModel("");
HighsStatusReport(options.logfile, "avgas_highs.writeModel(\"\")", return_status);
REQUIRE(return_status == HighsStatus::OK);
Highs highs(options);
return_status = highs.passModel(lp);
// printf("passModel: return_status = %s\n", HighsStatusToString(return_status).c_str());
REQUIRE(return_status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::NOTSET);
return_status = highs.run();
HighsStatusReport(options.logfile, "highs.run()", return_status);
REQUIRE(return_status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::MODEL_EMPTY);
// Adding column vectors and matrix to model with no rows returns an error
return_bool = highs.addCols(num_col, &colCost[0], &colLower[0], &colUpper[0], num_col_nz, &Astart[0], &Aindex[0], &Avalue[0]);
REQUIRE(!return_bool);
// Adding column vectors to model with no rows returns OK
return_bool = highs.addCols(num_col, &colCost[0], &colLower[0], &colUpper[0], 0, NULL, NULL, NULL);
REQUIRE(return_bool);
return_status = highs.writeModel("");
HighsStatusReport(options.logfile, "highs.writeModel(\"\")", return_status);
REQUIRE(return_status == HighsStatus::OK);
// Adding row vectors and matrix to model with columns returns OK
return_bool = highs.addRows(num_row, &rowLower[0], &rowUpper[0], num_row_nz, &ARstart[0], &ARindex[0], &ARvalue[0]);
REQUIRE(return_bool);
return_status = highs.writeModel("");
HighsStatusReport(options.logfile, "highs.writeModel(\"\")", return_status);
REQUIRE(return_status == HighsStatus::OK);
// const HighsLp &reference_avgas = avgas_highs.getLp();
// const HighsLp &reference_lp = highs.getLp();
return_bool = areLpEqual(highs.getLp(), avgas_highs.getLp(), options.infinite_bound);
REQUIRE(return_bool);
return_status = highs.run();
HighsStatusReport(options.logfile, "highs.run()", return_status);
REQUIRE(return_status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
double avgas_optimal_objective_value;
highs.getHighsInfoValue("objective_function_value", avgas_optimal_objective_value);
double optimal_objective_value;
#ifdef HiGHSDEV
const HighsSolution& solution = highs.getSolution();
const HighsBasis& basis = highs.getBasis();
highs.reportModelStatusSolutionBasis("After avgas solve", model_status, highs.getLp(), solution, basis);
#endif
// Getting columns from the LP is OK
int col1357_col_mask[] = {0, 1, 0, 1, 0, 1, 0, 1};
int col1357_col_set[] = {1, 3, 5, 7};
int col1357_illegal_col_set[] = {3, 7, 1, 5};
int col1357_num_ix = 4;
int col1357_num_col;
int col1357_num_nz;
double *col1357_cost = (double *)malloc(sizeof(double) * col1357_num_ix);
double *col1357_lower = (double *)malloc(sizeof(double) * col1357_num_ix);
double *col1357_upper = (double *)malloc(sizeof(double) * col1357_num_ix);
int *col1357_start = (int *)malloc(sizeof(int) * col1357_num_ix);
int *col1357_index = (int *)malloc(sizeof(int) * num_col_nz);
double *col1357_value = (double *)malloc(sizeof(double) * num_col_nz);
return_bool = highs.getCols(3, 6, col1357_num_col, col1357_cost, col1357_lower, col1357_upper,
col1357_num_nz, col1357_start, col1357_index, col1357_value);
REQUIRE(return_bool==true);
// Calling getCols using an unordered set should be OK but for now HiGHS returns an error
return_bool = highs.getCols(col1357_num_ix, col1357_illegal_col_set, col1357_num_col, col1357_cost, col1357_lower, col1357_upper,
col1357_num_nz, col1357_start, col1357_index, col1357_value);
REQUIRE(!return_bool);
return_bool = highs.getCols(col1357_num_ix, col1357_col_set, col1357_num_col, col1357_cost, col1357_lower, col1357_upper,
col1357_num_nz, col1357_start, col1357_index, col1357_value);
REQUIRE(return_bool);
return_bool = highs.getCols(col1357_col_mask, col1357_num_col, col1357_cost, col1357_lower, col1357_upper,
col1357_num_nz, col1357_start, col1357_index, col1357_value);
REQUIRE(return_bool);
// Try to delete an empty range of cols: OK
return_bool = highs.deleteCols(0, -1);
REQUIRE(return_bool);
// Try to delete more cols than there are: ERROR
return_bool = highs.deleteCols(0, num_col+1);
REQUIRE(!return_bool);
return_bool = highs.deleteCols(col1357_num_ix, col1357_col_set);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleting columns 1, 3, 5, 7";
// messageReportLp(message.c_str(), highs.getLp());
// printf("%s", message.c_str()); reportLp(highs.getLp(), 2);
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_bool = highs.addCols(col1357_num_col, col1357_cost, col1357_lower, col1357_upper,
col1357_num_nz, col1357_start, col1357_index, col1357_value);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After restoring columns 1, 3, 5, 7\n";
// printf("%s", message.c_str()); reportLp(highs.getLp(), 2);
highs.reportModelStatusSolutionBasis(message,
highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_status = highs.run();
HighsStatusReport(options.logfile, "highs.run()", return_status);
REQUIRE(return_status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
highs.getHighsInfoValue("objective_function_value", optimal_objective_value);
REQUIRE(optimal_objective_value == avgas_optimal_objective_value);
#ifdef HiGHSDEV
highs.reportModelStatusSolutionBasis("After re-solving",
highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Delete all the columns: OK
return_bool = highs.deleteCols(0, num_col-1);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleting all columns";
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Delete all the rows: OK
return_bool = highs.deleteRows(0, num_row-1);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleting all rows";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Adding column vectors to model with no rows returns OK
return_bool = highs.addCols(num_col, &colCost[0], &colLower[0], &colUpper[0], 0, NULL, NULL, NULL);
REQUIRE(return_bool);
message = "With columns but no rows";
// messageReportLp(message.c_str(), highs.getLp());
// Adding row vectors and matrix to model with columns returns OK
return_bool = highs.addRows(num_row, &rowLower[0], &rowUpper[0], num_row_nz, &ARstart[0], &ARindex[0], &ARvalue[0]);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "With columns but and rows";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Getting rows from the LP is OK
int from_row_ix = 0;
int to_row_ix = 3;
int row0135789_row_set[] = {0, 1, 3, 5, 7, 8, 9};
int row0135789_row_mask[] = {1, 1, 0, 1, 0, 1, 0, 1, 1, 1};
int row0135789_num_ix = 7;
int row0135789_num_row;
int row0135789_num_nz;
double *row0135789_lower = (double *)malloc(sizeof(double) * row0135789_num_ix);
double *row0135789_upper = (double *)malloc(sizeof(double) * row0135789_num_ix);
int *row0135789_start = (int *)malloc(sizeof(int) * row0135789_num_ix);
int *row0135789_index = (int *)malloc(sizeof(int) * num_row_nz);
double *row0135789_value = (double *)malloc(sizeof(double) * num_row_nz);
return_bool = highs.getRows(from_row_ix, to_row_ix, row0135789_num_row, row0135789_lower, row0135789_upper,
row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
REQUIRE(return_bool);
// messageReportMatrix("Get by interval\nRow ", row0135789_num_row, row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
return_bool = highs.getRows(row0135789_num_ix, row0135789_row_set, row0135789_num_row, row0135789_lower, row0135789_upper,
row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
REQUIRE(return_bool);
// messageReportMatrix("Get by set\nRow ", row0135789_num_row, row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
return_bool = highs.getRows(row0135789_row_mask, row0135789_num_row, row0135789_lower, row0135789_upper,
row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
REQUIRE(return_bool);
// messageReportMatrix("Get by mask\nRow ", row0135789_num_row, row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
return_bool = highs.getRows(row0135789_num_ix, row0135789_row_set, row0135789_num_row, row0135789_lower, row0135789_upper,
row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
REQUIRE(return_bool);
return_bool = highs.deleteRows(row0135789_num_ix, row0135789_row_set);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleting rows 0-1, 3, 5, 7-9";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
int row012_row_set[] = {0, 1, 2};
int row012_row_mask[] = {1, 1, 1};
int row012_num_ix = 3;
int row012_num_row;
int row012_num_nz;
double *row012_lower = (double *)malloc(sizeof(double) * row012_num_ix);
double *row012_upper = (double *)malloc(sizeof(double) * row012_num_ix);
int *row012_start = (int *)malloc(sizeof(int) * row012_num_ix);
int *row012_index = (int *)malloc(sizeof(int) * num_row_nz);
double *row012_value = (double *)malloc(sizeof(double) * num_row_nz);
return_bool = highs.getRows(row012_num_ix, row012_row_set, row012_num_row, row012_lower, row012_upper,
row012_num_nz, row012_start, row012_index, row012_value);
REQUIRE(return_bool);
return_bool = highs.deleteRows(row012_row_mask);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleting rows 0-2";
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Delete all the columns: OK
return_bool = highs.deleteCols(0, num_col-1);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleting all columns";
messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Can't add rows with no columns
return_bool = highs.addRows(row0135789_num_row, row0135789_lower, row0135789_upper,
row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
REQUIRE(!return_bool);
// Adding column vectors to model with no rows returns OK
return_bool = highs.addCols(num_col, &colCost[0], &colLower[0], &colUpper[0], 0, NULL, NULL, NULL);
REQUIRE(return_bool);
return_bool = highs.addRows(row0135789_num_row, row0135789_lower, row0135789_upper,
row0135789_num_nz, row0135789_start, row0135789_index, row0135789_value);
REQUIRE(return_bool);
return_bool = highs.addRows(row012_num_row, row012_lower, row012_upper,
row012_num_nz, row012_start, row012_index, row012_value);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After restoring all rows";
messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_status = highs.run();
HighsStatusReport(options.logfile, "highs.run()", return_status);
REQUIRE(return_status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
highs.getHighsInfoValue("objective_function_value", optimal_objective_value);
REQUIRE(optimal_objective_value == avgas_optimal_objective_value);
#ifdef HiGHSDEV
message = "After resolve";
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Try to delete an empty range of rows: OK
return_bool = highs.deleteRows(0, -1);
REQUIRE(return_bool);
// Try to delete more rows than there are: ERROR
return_bool = highs.deleteRows(0, num_row);
REQUIRE(!return_bool);
return_bool = highs.getCols(col1357_col_mask, col1357_num_col, col1357_cost, col1357_lower, col1357_upper,
col1357_num_nz, col1357_start, col1357_index, col1357_value);
REQUIRE(return_bool);
return_bool = highs.deleteCols(col1357_num_ix, col1357_col_set);
REQUIRE(return_bool);
int col0123_col_mask[] = {1, 1, 1, 1};
// int col0123_col_set[] = {0, 1, 2, 3};
int col0123_num_ix = 4;
int col0123_num_col;
int col0123_num_nz;
double *col0123_cost = (double *)malloc(sizeof(double) * col0123_num_ix);
double *col0123_lower = (double *)malloc(sizeof(double) * col0123_num_ix);
double *col0123_upper = (double *)malloc(sizeof(double) * col0123_num_ix);
int *col0123_start = (int *)malloc(sizeof(int) * col0123_num_ix);
int *col0123_index = (int *)malloc(sizeof(int) * num_col_nz);
double *col0123_value = (double *)malloc(sizeof(double) * num_col_nz);
return_bool = highs.getCols(col0123_col_mask, col0123_num_col, col0123_cost, col0123_lower, col0123_upper,
col0123_num_nz, col0123_start, col0123_index, col0123_value);
REQUIRE(return_bool);
// messageReportMatrix("Get col1357 by mask\nRow ", col1357_num_col, col1357_num_nz, col1357_start, col1357_index, col1357_value);
// messageReportMatrix("Get col0123 by mask\nRow ", col0123_num_col, col0123_num_nz, col0123_start, col0123_index, col0123_value);
return_bool = highs.deleteRows(0, num_row-1);
REQUIRE(return_bool);
return_bool = highs.deleteCols(col0123_col_mask);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleting all rows and columns";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Adding row vectors to model with no columns returns OK
return_bool = highs.addRows(row0135789_num_row, row0135789_lower, row0135789_upper,
0, NULL, NULL, NULL);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After restoring 7 rows";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_bool = highs.addRows(row012_num_row, row012_lower, row012_upper,
0, row012_start, row012_index, row012_value);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After restoring all rows";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_bool = highs.addCols(col1357_num_col, col1357_cost, col1357_lower, col1357_upper,
col1357_num_nz, col1357_start, col1357_index, col1357_value);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After restoring columns 1, 3, 5, 7";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_status = highs.run();
HighsStatusReport(options.logfile, "highs.run()", return_status);
REQUIRE(return_status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
#ifdef HiGHSDEV
message = "After solving after restoring all rows and columns 1, 3, 5, 7";
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_bool = highs.addCols(col0123_num_col, col0123_cost, col0123_lower, col0123_upper,
col0123_num_nz, col0123_start, col0123_index, col0123_value);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After restoring columns 0-3";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
return_status = highs.run();
HighsStatusReport(options.logfile, "highs.run()", return_status);
REQUIRE(return_status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
highs.getHighsInfoValue("objective_function_value", optimal_objective_value);
REQUIRE(optimal_objective_value == avgas_optimal_objective_value);
return_bool = highs.deleteRows(0, num_row-1);
REQUIRE(return_bool);
return_bool = highs.deleteCols(0, num_col-1);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "After deleteing all rows and columns";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Adding column vectors to model with no rows returns OK
return_bool = highs.addCols(num_col, &colCost[0], &colLower[0], &colUpper[0], 0, NULL, NULL, NULL);
REQUIRE(return_bool);
#ifdef HiGHSDEV
message = "With columns but no rows";
// messageReportLp(message.c_str(), highs.getLp());
highs.reportModelStatusSolutionBasis(message, highs.getModelStatus(), highs.getLp(), solution, basis);
#endif
// Adding row vectors and matrix to model with columns returns OK
return_bool = highs.addRows(num_row, &rowLower[0], &rowUpper[0], num_row_nz, &ARstart[0], &ARindex[0], &ARvalue[0]);
REQUIRE(return_bool);
col1357_cost[0] = 2.01;
col1357_cost[1] = 2.31;
col1357_cost[2] = 2.51;
col1357_cost[3] = 2.71;
col1357_lower[0] = 0.01;
col1357_lower[1] = 0.31;
col1357_lower[2] = 0.51;
col1357_lower[3] = 0.71;
col1357_upper[0] = 1.01;
col1357_upper[1] = 1.31;
col1357_upper[2] = 1.51;
col1357_upper[3] = 1.71;
row0135789_lower[0] = -0.01;
row0135789_lower[1] = -0.11;
row0135789_lower[2] = -0.31;
row0135789_lower[3] = -0.51;
row0135789_lower[4] = -0.71;
row0135789_lower[5] = -0.81;
row0135789_lower[6] = -0.91;
row0135789_upper[0] = 3.01;
row0135789_upper[1] = 3.11;
row0135789_upper[2] = 3.31;
row0135789_upper[3] = 3.51;
row0135789_upper[4] = 3.71;
row0135789_upper[5] = 3.81;
row0135789_upper[6] = 3.91;
// Attempting to set a cost to infinity returns error
return_bool = highs.changeColCost(7, HIGHS_CONST_INF);
REQUIRE(!return_bool);
// Attempting to set a cost to a finite value returns OK
return_bool = highs.changeColCost(7, 77);
REQUIRE(return_bool);
return_bool = highs.changeColsCost(col1357_num_ix, col1357_col_set, col1357_cost);
REQUIRE(return_bool);
// Attempting to set row bounds with infinite lower bound returns error
return_bool = highs.changeRowBounds(2, HIGHS_CONST_INF, 3.21);
REQUIRE(!return_bool);
return_bool = highs.changeRowBounds(2, -HIGHS_CONST_INF, 3.21);
REQUIRE(return_bool);
// Attempting to set col bounds with -infinite upper bound returns error
return_bool = highs.changeColBounds(2, 0.21, -HIGHS_CONST_INF);
REQUIRE(!return_bool);
return_bool = highs.changeColBounds(2, 0.21, HIGHS_CONST_INF);
REQUIRE(return_bool);
return_bool = highs.changeRowsBounds(row0135789_num_ix, row0135789_row_set, row0135789_lower, row0135789_upper);
REQUIRE(return_bool);
return_bool = highs.changeColsBounds(col1357_num_ix, col1357_col_set, col1357_lower, col1357_upper);
REQUIRE(return_bool);
// messageReportLp("After changing costs and bounds", highs.getLp());
// Return the LP to its original state with a mask
return_bool = highs.changeColsCost(col1357_col_mask, &colCost[0]);
REQUIRE(return_bool);
return_bool = highs.changeColBounds(2, colLower[2], colUpper[2]);
REQUIRE(return_bool);
return_bool = highs.changeColsBounds(col1357_col_mask, &colLower[0], &colUpper[0]);
REQUIRE(return_bool);
return_bool = highs.changeRowsBounds(row0135789_row_mask, &rowLower[0], &rowUpper[0]);
REQUIRE(return_bool);
return_bool = highs.changeRowBounds(2, rowLower[2], rowUpper[2]);
REQUIRE(return_bool);
return_bool = areLpEqual(avgas_highs.getLp(), highs.getLp(), options.infinite_bound);
REQUIRE(return_bool);
int before_num_col;
int after_num_col;
int rm_col;
int before_num_row;
int after_num_row;
int rm_row;
before_num_col = highs.getNumCols();
rm_col = 0;
return_bool = highs.deleteCols(rm_col, rm_col);
REQUIRE(return_bool);
after_num_col = highs.getNumCols();
printf("After removing col %d / %d have %d cols\n", rm_col, before_num_col, after_num_col);
REQUIRE(after_num_col == before_num_col-1);
before_num_row = highs.getNumRows();
rm_row = 0;
return_bool = highs.deleteRows(rm_row, rm_row);
REQUIRE(return_bool);
after_num_row = highs.getNumRows();
printf("After removing row %d / %d have %d rows\n", rm_row, before_num_row, after_num_row);
REQUIRE(after_num_row == before_num_row-1);
before_num_col = highs.getNumCols();
rm_col = before_num_col-1;
return_bool = highs.deleteCols(rm_col, rm_col);
REQUIRE(return_bool);
after_num_col = highs.getNumCols();
printf("After removing col %d / %d have %d cols\n", rm_col, before_num_col, after_num_col);
REQUIRE(after_num_col == before_num_col-1);
before_num_row = highs.getNumRows();
rm_row = before_num_row-1;
return_bool = highs.deleteRows(rm_row, rm_row);
REQUIRE(return_bool);
after_num_row = highs.getNumRows();
printf("After removing row %d / %d have %d rows\n", rm_row, before_num_row, after_num_row);
REQUIRE(after_num_row == before_num_row-1);
// messageReportLp("After deleting all rows and columns", highs.getLp());
// messageReportLp("After restoring costs and bounds", highs.getLp());
printf("Finished successfully\n"); fflush(stdout);
}
| [
"jajhall@ed.ac.uk"
] | jajhall@ed.ac.uk |
176929a899d037681791a660ecde10b9d4022e64 | 5fe1a2ee18212252aab3efdbd105ea27b71250c9 | /Documentos/Seguimiento1/CC1037639645/segui3.cpp | fe2444d52f3b3169fed48014e8531522917e0de6 | [] | no_license | tritio1995/CursoFCII_UdeA_2021_1 | aa7ee5aec00fd16d24b6c30bdab1848996f3d5e6 | 1a31d3e9c1adfd176766a08e8869402563722fae | refs/heads/main | 2023-08-11T20:06:37.025214 | 2021-09-30T02:44:27 | 2021-09-30T02:44:27 | 343,785,653 | 0 | 0 | null | 2021-03-02T13:34:17 | 2021-03-02T13:34:17 | null | UTF-8 | C++ | false | false | 1,439 | cpp | #include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int N; //número
int A; //número que ingresa el usuario
char p; //Quiere jugar o no
N=1+rand()%1001;
cout << "El día de hoy jugaremos a adivinar un número del 1 al 100" << endl;
cout << "Este número será generado aleatoriamente por la computadora" << endl;
cout << "Ingrese un número de 1 a 1000" << endl;
cin >> A;
if(A>1000 || A<0)
{
cout << "Ingreso un valor erroneo.Intentelo de nuevo" << endl;
cin>>A;
}
while(A!=N)
{
if(A<N)
{
cout << "Su número es menor que el número correcto" << endl; cout << "Intentelo de nuevo" << endl;
cin>>A;
}
if(A>N)
{
cout << "Su número es mayor que el número correcto" << endl;
cout << "Intentelo de nuevo" << endl;
cin>>A;
}
if(A==N)
{
cout << "Usted ha adivinado el número" << endl;
cout << "Desea jugar de nuevo (Y) o (N)" << endl;
cin>>p;
switch(p)
{
case 'y':
case 'Y':
N=1+rand()%1001;
cout << "Ingrese un número de 1 a 1000" << endl;
cin >> A;
if(A>1000 || A<0)
{
cout << "Ingreso un valor erroneo.Intentelo de nuevo" << endl;
cin>>A;
}
break;
case 'n':
case 'N':
exit(-1);
break;
}
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
a3aa672bd2688f91f71b3fa5e6daca39b08193e4 | 9530eb5b4fc5acc39d71c6d8e6637e49093f58b8 | /10701 - Pre, in and post.cpp | cf4901c5354f04307e128610a441a4a3d619e9db | [] | no_license | Mahbub20/UVA-Solutions | 9ea6ae47a22730b30168118edee0fa77eee1a1f6 | 3ed44a00130bfc9b6ce4cfe2d17c57940ffdc3c6 | refs/heads/master | 2021-01-13T08:18:12.680369 | 2018-10-03T16:15:08 | 2018-10-03T16:15:08 | 68,840,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | cpp | #include<bits/stdc++.h>
using namespace std;
int search(char ar[],char c,int n)
{
int i;
for(i = 0;i<n;i++)
{
if(ar[i]==c)return i;
}
return -1;
}
void printPostorder(char preor[],char inor[],int n)
{
int root = search(inor,preor[0],n);
if(root!=0)
{
printPostorder(preor+1,inor,root);
}
if(root!=n-1)
{
printPostorder(preor+root+1,inor+root+1,n-root-1);
}
cout << preor[0];
}
int main()
{
int t,n,l,m;
char inor[100],preor[100];
cin >> t;
getchar();
while(t--)
{
cin >> n >> preor >> inor;
printPostorder(preor,inor,n);
cout << endl;
}
}
| [
"mmahbub569@gmail.com"
] | mmahbub569@gmail.com |
c4ccaf1fdb66fd3ef4b999b505a55f0454837441 | 2cc62ba1e940e03c9dc9bbed60189c6e3bc186f5 | /AR21_rpt09/AR21_cds_project/AR21_cds_project.ino | 10e246eb0edd1f3e180e3e72dd9a73f31afbe48a | [] | no_license | HINEET/AR21 | d8a5fab69f90880dfc0327482a621ca0c088a347 | 0bc6532e17e59d50bc30f443156d1223de176e85 | refs/heads/main | 2023-05-31T17:22:44.678433 | 2021-06-16T04:46:15 | 2021-06-16T04:46:15 | 344,036,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | ino | /*
예제 6.2
빛 입력
*/
// I2C 통신 라이브러리 설정
#include <Wire.h>
// I2C LCD 라리브러리 설정
#include <LiquidCrystal_I2C.h>
// LCD I2C address 설정: 0x3F or 0x27
LiquidCrystal_I2C lcd(0x27,16,2);
// 0번 아날로그핀을 CdS 셀 입력으로 설정한다.
const int CdSPin = 0;
int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
// 16X2 LCD 모듈 설정하고 백라이트를 켠다.
lcd.init(); // LCD 설정
lcd.backlight();
// 메세지를 표시한다.
lcd.print("ex 6.2");
lcd.setCursor(0,1);
lcd.print("CdS Cell Test");
// 3초동안 메세지를 표시한다.
delay(3000);
// 모든 메세지를 삭체한 뒤
// 숫자를 제외한 부분들을 미리 출력시킨다.
lcd.clear();
lcd.setCursor(0,0);
lcd.print("ADC : ");
lcd.setCursor(0,1);
lcd.print("Illuminance:");
lcd.setCursor(15,1);
lcd.print("%");
}
void loop(){
int adcValue; // 실제 센서로부터 읽은 값 (0~1023)
int illuminance; // 현재의 밝기. 0~100%
int ledOutput = digitalRead(ledPin);
// CdS cell을 통하여 입력되는 전압을 읽는다.
adcValue = analogRead(CdSPin);
// 아날로그 입력 값을 0~100의 범위로 변경한다.
illuminance = map(adcValue,0,1023,100,0);
// 전에 표시했던 내용을 지우고
// LCD에 ADC 값과 밝기를 출력한다.
// 지우지 않으면 이전에 표시했던 값이 남게 된다.
// 전에 표시했던 내용을 지운다.
if(illuminance<=50){
lcd.noBacklight();
digitalWrite(ledPin, HIGH);// LED 점등
}
else{
lcd.backlight();
digitalWrite(ledPin, LOW);// LED 소등
}
lcd.setCursor(9,0);
lcd.print(" ");
// ADC 값을 표시한다
lcd.setCursor(9,0);
lcd.print(adcValue);
// 전에 표시했던 내용을 지운다.
lcd.setCursor(13,1);
lcd.print(" ");
// 밝기를 표시한다
lcd.setCursor(12,1);
lcd.print(illuminance);
delay(1000);
}
| [
"noreply@github.com"
] | noreply@github.com |
4156c77e87049365967c1bb57e5b908a008f7e0f | 2e265d9b96fea640177144a3b8fbb17ac1e453c8 | /Core/BlopCore/Core/Sys/projectex.h | 4b2748c774da59b1697260b9a711e8b1bc598766 | [] | no_license | theKashey/4D | 516c5b22e7a1dc138f6d8680bb536596d7e53306 | cba569a6a5572b2e9038b7cb4e5e1db59dea090c | refs/heads/master | 2021-01-15T19:04:51.721305 | 2017-08-09T13:13:38 | 2017-08-09T13:13:38 | 99,805,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,021 | h | //---------------------------------------------------------------------------
//#pragma once
//#ifndef unuse_PEX
#ifndef ProjectExH
#define ProjectExH
//---------------------------------------------------------------------------
#pragma pack(push,1)
struct blopTimeStamp
{
BYTE YEAR;
BYTE Month;
BYTE Day;
BYTE Hour;
BYTE Minute;
BYTE Second;
void SetNOW();
};
#pragma pack(pop)
//#include "Memory\SmartPtr.h"
#include "BlopMessages.h"
#include "MessageCommands.h"
#include "Math\LtlMath.h"
#include "Vectors\VectorBase.h"
#include "SmartVector.h"
#include "ProjectMemory.h"
#include "strings\bStrings.h"
#include "Threads\blopThreads.h"
#include "SectionLocker.h"
#include "ServerUtils.h"
#include "..\blopBaseObject.h"
#include "..\System\DLLManager.h"
#include "..\Loaders\bFiles.h" //FileSys.h"
#include "..\Sound\SoundMe.h"
#include "Profiler.h"
#include "..\Plugins\Pluginloader.h"
#include "ProjectDividors.h"
#include "Counters\counters.h"
/**/
//#include "Forms\BaseForms.h"
#define AssertIfGREATER(Condition,Message,OnOk,OnFall,RetFall)\
if((Condition)>0){ ConsoleOut->Printf(Message,OnOk);RetFall;}\
else ConsoleOut->Printf(Message,OnFall);
namespace Time
{
double DLLTYPE Get();
DWORD DLLTYPE GetD();
double DLLTYPE Time();
void SetThisTime();
};
//int DLLTYPE RegisterNewConsoleClass(LPCSTR Name,int Class);
#define RegisterNewConsoleClass(a,b,c)inRegisterNewConsoleClass(a,#a,b,c)
void DLLTYPE inRegisterNewConsoleClass(DWORD &SYS,LPCSTR VName,LPCSTR Name,int Class);
void DLLTYPE Print2Console (DWORD System,LPCSTR TextMessage);
void DLLTYPE Error2Console (DWORD System,LPCSTR TextMessage);
void DLLTYPE Warning2Console(DWORD System,LPCSTR TextMessage);
template<class A>void DLLTYPE Print2Console (DWORD System,LPCSTR Format,A B,...){DOFORMAT(a,Format);Print2Console(System,a) ;return;}
template<class A>void DLLTYPE Error2Console (DWORD System,LPCSTR Format,A B,...){DOFORMAT(a,Format);Error2Console(System,a) ;return;}
template<class A>void DLLTYPE Warning2Console(DWORD System,LPCSTR Format,A B,...){DOFORMAT(a,Format);Warning2Console(System,a);return;}
namespace inTHREAD
{
void DLLTYPE Print2Console (DWORD System,LPCSTR Format,...);
void DLLTYPE Error2Console (DWORD System,LPCSTR Format,...);
void DLLTYPE Warning2Console(DWORD System,LPCSTR Format,...);
};
#ifdef isTHREAD
#define Print2Console inTHREAD::Print2Console
#define Error2Console inTHREAD::Error2Console
#define Warning2Console inTHREAD::Warning2Console
#endif
void DLLTYPE SetDefaultConsole(ConsoleUtil* Console);
namespace ConsoleSystems
{
DWORD DLLTYPE Plugin();
DWORD DLLTYPE Util();
};
namespace VARS
{
struct DLLTYPE TFVAR
{
private:
double Val;
public:
typedef const double cdouble;
typedef const DWORD cdword;
typedef double * pdouble;
operator cdouble();
operator pdouble();
// operator cdword ();
double operator =(double src);
};
struct DLLTYPE TSVAR
{
private:
GString Val;
public:
//operator LPCSTR()const;
typedef GString & GStringRef;
operator GStringRef();
LPCSTR operator =(LPCSTR src);
};
typedef TFVAR &TFVARref;
typedef TSVAR &TSVARref;
TFVARref DLLTYPE fvars(DWORD &V,LPCSTR Name=NULL);
TSVARref DLLTYPE svars(DWORD &V,LPCSTR Name=NULL);
struct CVarNameRefOut
{
char Name[256];
BYTE Type;
DWORD ID;
};
typedef const CVarNameRefOut& CVarNameRefOutRef;
CVarNameRefOutRef DLLTYPE GetVarByName(LPCSTR Name);
/*
TDVAR &dvars(DWORD &V,LPCSTR Name=NULL);
TAVAR &avars(DWORD &V,LPCSTR Name=NULL);
*/
extern DWORD fv_FPS;
extern DWORD fv_FTIME_d_20;
extern DWORD fv_FRAMETIME;
extern DWORD fv_GAMETIME;
extern DWORD fv_TIMEFACTOR;
extern DWORD fv_FSPAN_d_20;
//float DLLTYPE FrameTime
#define REGFVAR(a,b) VARS::fvars(a,b);
void Init();
};
#endif
//#endif
| [
"akorzunov@atlassian.com"
] | akorzunov@atlassian.com |
2355b3564398487841833e0f75f60a8e25b5cee3 | 9cd2729d327c75aeddefd3b9e054967899762567 | /eje 6.3.cpp | 2ced4d790f8d01a612df68773747f96686f47943 | [] | no_license | MayraMacedo/set2 | 021c121289c8a450cf9e11da46c988d5488a8c9e | ee768bf09a83fdbf7dceafe5464b20dee9d704ea | refs/heads/master | 2020-03-11T16:18:43.659011 | 2018-04-18T20:30:27 | 2018-04-18T20:30:27 | 130,113,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | cpp | #include<iostream>
#include <string>
using namespace std;
int largo;
void transpose ( const int input [][largo],int output [][anchura]) {
for(int i = 0; i < anchura ; ++ i ) {
for (int j = 0; j < largo ; ++ j ) {
output [ j ][ i ] = input [ i ][ j ];
}
}
}
int main()
{
int largo,anchura;
int A[2][2]={{1,2},{3,4}}
int C[2][2]={{0,0},{0,0}}
transpose(A[2][2],C[2][2])
}
| [
"noreply@github.com"
] | noreply@github.com |
e8e3d7d48dc1733b5e469bd53ecc5b5c83db0818 | f05b1163db8ae8c6d9f38a0121cbb0444d188142 | /src/5_szemely/megoldas/hallgato.cpp | 607a3babb5cac02b6739341904ab2fec78273600 | [] | no_license | pekmil/CppTutorial | 05a21ca9722cb890e365e09b32afdbc4f59c835a | e8797f2aeda3248329f182f2d998d90f08f30fc2 | refs/heads/master | 2021-06-23T08:48:47.006677 | 2019-04-17T10:46:29 | 2019-04-17T10:49:19 | 125,821,578 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | #include "hallgato.h"
#include <iostream>
Hallgato::Hallgato(const string &v, const string &k, unsigned int kor, const string &neptun, unsigned int felevek):
Szemely(v, k, kor),
neptun(neptun),
felevek(felevek)
{
}
const string &Hallgato::getNeptun() const
{
return neptun;
}
unsigned int Hallgato::getFelevek() const
{
return felevek;
}
void Hallgato::setFelevek(unsigned int value)
{
felevek = value;
}
bool Hallgato::furcsa() const
{
return (eletkor-felevek/2)<18;
}
void Hallgato::kiir() const
{
Szemely::kiir();
cout << " " << neptun << ", befejezett felevek: " << felevek << endl;
}
| [
"pekmil88@gmail.com"
] | pekmil88@gmail.com |
131e70b418b93e29fefc8949f224423ee4061ace | bf7eae0400ab87441d2ced3e952afc7163e111ac | /Project 6 - Assembler/API/BinaryCodeFile.h | 5641c2ad7ff18733780c4260d5a8aad03d6054cb | [] | no_license | asapbuddy/nand2tetris | 64afff7fd6119dd5db1ab4209ba58f84e997a4a6 | 3911283d202cdc97adcbab4f6ae9c8f59ba97860 | refs/heads/master | 2021-04-04T13:42:51.416234 | 2020-07-21T07:21:45 | 2020-07-21T07:21:45 | 248,458,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | h | #pragma once
#include <iosfwd>
#include <string>
#include <vector>
#include "TextFile.h"
class BinaryCodeFile : public TextFile
{
const char* filename_;
public:
explicit BinaryCodeFile(const char* filename)
: filename_(filename)
{
}
BinaryCodeFile(const BinaryCodeFile& sourceCode)
: BinaryCodeFile(sourceCode.filename_)
{
}
std::ifstream GetFileInputStream() const override;
std::ofstream GetFileOutputStream() const override;
std::vector<std::string> ReadAllLines() override;
void WriteAllLines(std::vector<std::string> lines) override;
~BinaryCodeFile() override = default;
};
| [
"asap.buddy@protonmail.com"
] | asap.buddy@protonmail.com |
92de3e4a6bb1c6e4ed6038250980dc2c6caaa8c7 | 949eb290baa025da4bf5966a7c7445cc6a7c3982 | /include/FalconEngine/Core/Memory.h | fa38a2acd89708da0d1f83786af6bbfbea68f291 | [
"MIT"
] | permissive | study-game-engines/falcon | 980f0edba5b4f2f5c89c8c7e1033781315c57920 | c4d1fed789218d1994908b8dbbcd6c01961f9ef2 | refs/heads/master | 2023-08-14T17:45:50.070647 | 2021-05-25T07:38:57 | 2021-05-25T07:38:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,301 | h | #pragma once
#include <cstdint>
#include <FalconEngine/Core/Macro.h>
namespace FalconEngine
{
/************************************************************************/
/* Memory Allocation */
/************************************************************************/
inline int64_t
Kilobytes(int i)
{
return i * 1024LL;
}
inline int64_t
Megabytes(int i)
{
return Kilobytes(i) * 1024LL;
}
inline int64_t
Gigabytes(int i)
{
return Megabytes(i) * 1024LL;
}
inline int64_t
Terabytes(int i)
{
return Gigabytes(i) * 1024LL;
}
void
PushMemoryRecord(void *pointer, const char *file, size_t line);
void
PopMemoryRecord(void *pointer);
extern const char *__file__;
extern size_t __line__;
}
#if defined(FALCON_ENGINE_DEBUG_MEMORY)
// http://stackoverflow.com/questions/619467/macro-to-replace-c-operator-new
#define FALCON_ENGINE_NEW(memoryPool) (FalconEngine::__file__=__FILE__, FalconEngine::__line__=__LINE__) && 0 ? NULL : new(memoryPool)
#define FALCON_ENGINE_DELETE(memoryPointer) (FalconEngine::__file__=__FILE__, FalconEngine::__line__=__LINE__) && 0 ? NULL : delete memoryPointer
#else
#define FALCON_ENGINE_NEW(memoryPool) new(memoryPool)
#define FALCON_ENGINE_DELETE(memoryPool) delete(memoryPool)
#endif
#define FALCON_ENGINE_DELETER_DECLARE(PlatformClass, PlatformDeleterClass) \
class PlatformDeleterClass \
{ \
public: \
void operator()(PlatformClass *platformClass); \
}; \
#define FALCON_ENGINE_DELETER_IMPLEMENT(PlatformClass, PlatformDeleterClass) \
void \
PlatformDeleterClass::operator()(PlatformClass *platformClass) \
{ \
delete platformClass; \
}
// NOTE(Wuxiang): On concern about static method copy in different translation unit, read:
// http://stackoverflow.com/questions/5372091/are-static-member-functions-in-c-copied-in-multiple-translation-units
// http://stackoverflow.com/questions/12248747/singleton-with-multithreads
#define FALCON_ENGINE_SINGLETON_LEAK_DECLARE(SingletonClass) \
public: \
static SingletonClass * \
GetInstance() \
{ \
static SingletonClass sInstance; \
return &sInstance; \
} \
#define FALCON_ENGINE_SINGLETON_SAFE_DECLARE(SingletonClass) \
FALCON_ENGINE_SINGLETON_LEAK_DECLARE(SingletonClass) \
public: \
void \
Destroy();
| [
"linwx_xin@hotmail.com"
] | linwx_xin@hotmail.com |
69358490a3c9cac368c255d7a2d267bd5c707544 | a753c6522f7f7c00539750cd3bb1ce13e178015d | /Server/cmd_pm.h | 1d8c36844e5387b23f1878634e6210f0001ba848 | [] | no_license | b-reynolds/Chatterbox | 046203718bf121344e891dbbee9fb35009e1f261 | 235aa2c07e999e1379a09c8d3233598f7d2c1432 | refs/heads/master | 2021-05-09T00:38:26.058451 | 2017-04-27T12:26:36 | 2017-04-27T12:26:36 | 119,749,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | h | #pragma once
#include "command.h"
/*
* \brief Send a private message (E.g PM John Hello World).
* Message is sent to the specified recipient.
* Messages must be between 1 and 128 characters long.
*/
class CmdPm : public Command
{
public:
CmdPm() : Command(Type::kPm) {};
bool execute(User& user, std::vector<User>& users, std::vector<Room>& rooms, std::vector<std::string>& parameters) override;
private:
// Accepted message length range
const unsigned int kMsgLengthMin = 1;
const unsigned int kMsgLengthMax = 128;
};
| [
"benr420@gmail.com"
] | benr420@gmail.com |
97c537366928229c545b1decae5dcbbd5b8a9a56 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13746/function13746_schedule_8/function13746_schedule_8_wrapper.cpp | e56fa0291154ced0cd2dd0991a7897808bd6bd51 | [] | 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 | 930 | cpp | #include "Halide.h"
#include "function13746_schedule_8_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(256, 2048, 64);
Halide::Buffer<int32_t> buf0(256, 2048, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13746_schedule_8(buf00.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/function13746/function13746_schedule_8/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 |
12c0500d878e7ccb243b5834c5fdf3b1f2da59be | ff2d6327ab9bf7584ce59530c1f496663aa7454e | /hdu1828.cpp | 1ab8eb5e43b482f460f1e145cd7b22447c9174bb | [] | no_license | hsyi/hestudyalg | b364ce4c431f6d67eb425808dddbfbf41729dfdd | eea0fabdb86f5d8be138c8a6a7819b59879186bd | refs/heads/master | 2021-01-13T07:19:33.026592 | 2017-04-09T09:18:17 | 2017-04-09T09:18:17 | 71,562,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,606 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAXL=2e4+11;
const int MAXN=5e3+11;
struct Seg{
int y1,y2,x;
bool in;
Seg(){}
Seg(int y1,int y2,int x,bool in):y1(y1),y2(y2),x(x),in(in){}
bool operator < (const Seg &a) const{ return x<a.x;}
} seg[MAXN<<1];
int len[MAXL<<2],cnt[MAXL<<2],cover[MAXL<<2];
bool lbd[MAXL<<2],rbd[MAXL<<2];
void PushUp(int l,int r,int rt){
if(cover[rt]) {len[rt]=r-l+1;cnt[rt]=2;lbd[rt]=rbd[rt]=1;}
else if(l==r) {len[rt]=0;cnt[rt]=0;lbd[rt]=rbd[rt]=0;}
else{
len[rt]=len[rt<<1]+len[rt<<1|1];
cnt[rt]+=cnt[rt<<1]+cnt[rt<<1|1];
lbd[rt]=lbd[rt<<1];
rbd[rt]=rbd[rt<<1|1];
if(rbd[rt<<1] && lbd[rt<<1|1]) cnt[rt]-=2;
}
}
void update(int l,int r,int add,int L,int R,int rt){
if(l<=L&&r>=R) {
cover[rt]+=add;
PushUp(L,R,rt);
return;
}
int mid=(L+R)/2;
if(l<=mid) update(l,r,add,L,mid,rt<<1);
if(r>mid) update(l,r,add,mid+1,R,rt<<1|1);
PushUp(L,R,rt);
}
int n,sz;
int main(){
ios_base::sync_with_stdio(false);
cin>>n;
for(int i=0;i<n;i++){
int x1,x2,y1,y2;
cin>>x1>>y1>>x2>>y2;
seg[sz++]=Seg(y1,y2,x1,true);
seg[sz++]=Seg(y1,y2,x2,false);
}
sort(seg,seg+sz);
int ans=0;
int lastx=seg[0].x;
for(int i=0;i<sz;i++){
int tmp=len[1];
ans+=(seg[i].x-lastx)*cnt[1];
update(seg[i].y1,seg[i].y2-1,seg[i].in?1:-1,-10000,10000,1);
ans+=abs(tmp-len[1]);
lastx=seg[i].x;
}
cout<<ans<<endl;
return 0;
}
| [
"heshengyi@heshengyideMacBook-Pro.local"
] | heshengyi@heshengyideMacBook-Pro.local |
776ea6d4cdd3815518bce60cca531ad03d906a27 | 740a6ca8ef931889d45bf3acc3680c0a02caf5da | /src/rock.cpp | dfc7156b79316a7e801fcd0b0faf9b61117e5d4b | [] | no_license | ravsodhi/opengl-3d-game | 023d0d080be4dd0c25f43998efde8d1d86fc0436 | a24ca12bb0299f7be5a6133cb70b90657c8c4d02 | refs/heads/master | 2022-08-16T17:32:30.372355 | 2018-05-05T07:27:55 | 2018-05-05T07:27:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,859 | cpp | #include "rock.h"
#include "main.h"
Rock::Rock(float x, float y, float z, float rot, float rad)
{
this->position = glm::vec3(x, y, z);
this->rotation = rot;
static GLfloat base_vertex_buffer_data[30000];
int i = 0;
bool alt = 0;
float change = 50;
this->radius = rad;
for (float alpha = 0; alpha < 181.0; alpha += 1)
{
for (float theta = 0; theta < 361.0;i+=9)
{
base_vertex_buffer_data[i] = this->radius * sin(alpha * M_PI / 180.0) * cos(theta * M_PI / 180.0);
base_vertex_buffer_data[i+1] = this->radius * sin(alpha * M_PI / 180.0);
base_vertex_buffer_data[i+2] = this->radius * sin(alpha * M_PI / 180.0) * sin(theta * M_PI / 180.0);
base_vertex_buffer_data[i+3] = this->radius * sin((alpha + 1) * M_PI / 180.0) * cos(theta * M_PI / 180.0);
base_vertex_buffer_data[i+4] = this->radius * cos((alpha + 1) * M_PI / 180.0);
base_vertex_buffer_data[i+5] = this->radius * sin((alpha + 1) * M_PI / 180.0) * sin(theta * M_PI / 180.0);
if (!alt)
{
base_vertex_buffer_data[i+6] = this->radius * sin((alpha + 1) * M_PI / 180.0) * cos((theta + change) * M_PI / 180.0);
base_vertex_buffer_data[i+7] = this->radius * cos((alpha + 1) * M_PI / 180.0);
base_vertex_buffer_data[i+8] = this->radius * sin((alpha + 1) * M_PI / 180.0) * sin((theta + change) * M_PI / 180.0);
theta += change;
}
else
{
base_vertex_buffer_data[i+6] = this->radius * sin(alpha * M_PI / 180.0) * cos((theta - change) * M_PI / 180.0);
base_vertex_buffer_data[i+7] = this->radius * cos(alpha * M_PI / 180.0);
base_vertex_buffer_data[i+8] = this->radius * sin(alpha * M_PI / 180.0) * sin((theta - change) * M_PI / 180.0);
}
alt = !alt;
}
}
this->object = create3DObject(GL_TRIANGLES, i / 3, base_vertex_buffer_data, COLOR_GRAY);
}
void Rock::draw(glm::mat4 VP)
{
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
// glm::mat4 translate = glmq::translate (glm::vec3(0,0,0)); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 1, 1));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->object);
}
void Rock::set_position(float x, float y, float z)
{
this->position = glm::vec3(x, y, z);
}
void Rock::tick()
{
}
bounding_box_t Rock::bounding_box()
{
bounding_box_t bbox = {this->position.x, this->position.y, this->position.z, 2*this->radius, 2*this->radius, 2*this->radius};
return bbox;
} | [
"ravsimar.sodhi@research.iiit.ac.in"
] | ravsimar.sodhi@research.iiit.ac.in |
2288c427d6b8501c7f50a8dfd585f71f012e7b41 | ecb2595d223f2100752cdcb7a31a459ffbe5b3d6 | /CardLineage/GameData.h | 6ab153a5cfb2538ca036ac4898ee53f3e2385f9f | [] | no_license | DeviSerene/CardLineage | 5d1e2b6a63f4babc2d24f43e440494b5938636d1 | 9646f701c8ca17f344f12078272099be8ac66d2d | refs/heads/master | 2020-03-30T21:41:20.307074 | 2018-10-09T15:53:25 | 2018-10-09T15:53:25 | 151,638,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | h | #pragma once
#include <SDL.h>
#include <iostream>
#include <SDL_mixer.h>
#include <SDL_ttf.h> //text
#include <SDL_image.h> //images
#include "SpriteFactory.h"
#include "AudioManager.h"
#include <memory>
class GamestateManager;
class GameData
{
public:
GameData();
~GameData();
int Init(int _windowX, int _windowY);
std::shared_ptr<GamestateManager> m_stateManager;
unsigned int GetLastTime() { return m_lastTime; }
void SetLastTime(unsigned int _f) { m_lastTime = _f; }
SDL_Window* GetWindow() { return m_window; }
SDL_Renderer* GetRenderer() { return m_renderer; }
private:
SDL_Window* m_window;
SDL_Renderer* m_renderer;
unsigned int m_lastTime;
};
| [
"deviserene@gmail.com"
] | deviserene@gmail.com |
30e6042fc89ddce4ee89858dec6363a95d7c2b8d | 5f2832d1e9e410676520040fac63246c84c8600d | /Old_4_Switch_1_Fan.ino | ee449c02af4610b442ad6a0fcec6862236546db0 | [] | no_license | saikrishnachoppa/Switch-code | 9f54f4286d3a94b28db4099ead9ecac4d49443e8 | bbdd651015b8a0b52909c83a5c605983a80879be | refs/heads/master | 2022-04-27T16:43:45.080906 | 2020-04-30T01:30:56 | 2020-04-30T01:30:56 | 255,867,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,163 | ino | #include<EEPROM.h>
int in1 = PA4;
int in2 = PB0;
int in3 = PB9;
int in4 = PB5;
int in5 = PB11;
int in6 = PA15;
int in7 = PA11;
int in8 = PA8;
int in9 = PB12;
String incomingByte;
char *strings[10];
char *ptr = NULL;
String u0,u1,u2,u3,u4,u5,u6,u7,u8;
int state1 = HIGH;
int state2 = HIGH;
int state3 = HIGH;
int state4 = HIGH;
int state5 = HIGH;
int state6 = HIGH;
int state7 = HIGH;
int state8 = HIGH;
int state9 = HIGH;
int r1;
int r2;
int r3;
int r4;
int r5;
int r6;
int r7;
int r8;
int r9;
int p1 = LOW;
int p2 = LOW;
int p3 = LOW;
int p4 = LOW;
int p5 = LOW;
int p6 = LOW;
int p7 = LOW;
int p8 = LOW;
int p9 = LOW;
int ledState1 = HIGH;
int ledState2 = HIGH;
int ledState3 = HIGH;
int ledState4 = HIGH;
int ledState5 = HIGH;
int ledState6 = HIGH;
int ledState7 = HIGH;
int ledState8 = HIGH;
int ledState9 = HIGH;
void setup()
{
Serial.begin(9600);
pinMode(in1, INPUT);
pinMode(in2, INPUT);
pinMode(in3, INPUT);
pinMode(in4, INPUT);
pinMode(in5, INPUT);
pinMode(in6, INPUT);
pinMode(in7, INPUT);
pinMode(in8, INPUT);
pinMode(in9, INPUT);
pinMode(PB1, OUTPUT);
pinMode(PB10, OUTPUT);
pinMode(PC15, OUTPUT);
pinMode(PC14, OUTPUT);
pinMode(PC13, OUTPUT);
pinMode(PB8, OUTPUT);
pinMode(PA12, OUTPUT);
pinMode(PB15, OUTPUT);
pinMode(PB14, OUTPUT);
pinMode(PB13, OUTPUT);
pinMode(PA0, OUTPUT);
pinMode(PA1, OUTPUT);
pinMode(PB7, OUTPUT);
pinMode(PA5, OUTPUT);
pinMode(PA6, OUTPUT);
pinMode(PA7, OUTPUT);
pinMode(PB6, OUTPUT);
ledState1 = EEPROM.read(0); //reading the first sensor data from eeprom
delay(10);
ledState2 = EEPROM.read(1); //reading the second sensor data from eeprom
delay(10);
ledState3 = EEPROM.read(2); //reading the third sensor data from eeprom
delay(10);
ledState4 = EEPROM.read(3);
delay(10);
ledState5 = EEPROM.read(4);
delay(10);
ledState6 = EEPROM.read(5); //reading the first sensor data from eeprom
delay(10);
ledState7 = EEPROM.read(6); //reading the second sensor data from eeprom
delay(10);
ledState8 = EEPROM.read(7); //reading the third sensor data from eeprom
delay(10);
ledState9 = EEPROM.read(8);
delay(10);
LS(ledState1, ledState2, ledState3, ledState4, ledState5, ledState6, ledState7, ledState8, ledState9);
}
void loop()
{
if(Serial.available() > 0)
{
incomingByte = Serial.readStringUntil('\n');
Serial.println(incomingByte);
int str_len = incomingByte.length() + 1;
char char_array[str_len];
incomingByte.toCharArray(char_array, str_len);
byte index = 0;
ptr = strtok(char_array, ",");
while (ptr != NULL)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, ",");
}
u0 = strings[0];
u1 = strings[1];
u2 = strings[2];
u3 = strings[3];
u4 = strings[4];
u5 = strings[5];
u6 = strings[6];
u7 = strings[7];
u8 = strings[8];
LS(u0.toInt(), u1.toInt(), u2.toInt(), u3.toInt(), u4.toInt(), u5.toInt(), u6.toInt(), u7.toInt(), u8.toInt());
}
r1 = digitalRead(in1); //first sensor input data
r2 = digitalRead(in2); //second sensor input data
r3 = digitalRead(in3); //third sensor input data
r4 = digitalRead(in4); //third sensor input data
r5 = digitalRead(in5); //third sensor input data
r6 = digitalRead(in6); //third sensor input data
r7 = digitalRead(in7); //third sensor input data
r8 = digitalRead(in8); //third sensor input data
r9 = digitalRead(in9); //third sensor input data
LS(r1,r2,r3,r4,r5,r6,r7,r8,r9);
}
void LS(int r11, int r21, int r31, int r41, int r51, int r61, int r71, int r81, int r91){
if (r11 == HIGH && p1 == LOW) { //if first sensor data is HIGH and p1 is LOW then Enter IF condition
if (state1 == HIGH){ //if state1 is high then relay and led will turn on
state1 = LOW;
digitalWrite(PB1, HIGH);
digitalWrite(PA0, HIGH);
EEPROM.write(0, 1);
delay(10);
}
else{ //if state1 is low then relay and led will turn off
state1 = HIGH;
digitalWrite(PB1, LOW);
digitalWrite(PA0, LOW);
EEPROM.write(0, 0);
delay(10);
}
}
p1 = r11; // first loop p1 value will change LOW to HIGH
if (r21 == HIGH && p2 == LOW) { //if second sensor data is HIGH and p2 is LOW then relay will turn on and also led will turn on
if (state2 == HIGH){ //if state2 is high then relay and led will turn on
state2 = LOW;
digitalWrite(PB10, HIGH);
digitalWrite(PA1, HIGH);
EEPROM.write(1, 1);
delay(10);
}
else{ //if state2 is low then relay and led will turn off
state2 = HIGH;
digitalWrite(PB10, LOW);
digitalWrite(PA1, LOW);
EEPROM.write(1, 0);
delay(10);
}
}
p2 = r21; // first loop p2 value will change LOW to HIGH
if (r31 == HIGH && p3 == LOW) { //if third sensor data is HIGH and p3 is low then relay will turn on and also led will turn on
if (state3 == HIGH){ //if state3 is high then relay and led will turn on
state3 = LOW;
digitalWrite(PC15, HIGH);
digitalWrite(PB7, HIGH);
EEPROM.write(2, 1);
delay(10);
}
else{ //if state3 is low then relay and led will turn off
state3 = HIGH;
digitalWrite(PC15, LOW);
digitalWrite(PB7, LOW);
EEPROM.write(2, 0);
delay(10);
}
}
p3 = r31; // first loop p3 value will change LOW to HIGH
if (r41 == HIGH && p4 == LOW) { //if third sensor data is HIGH and p3 is low then relay will turn on and also led will turn on
if (state4 == HIGH){ //if state3 is high then relay and led will turn on
state4 = LOW;
digitalWrite(PC14, HIGH);
digitalWrite(PA5, HIGH);
EEPROM.write(3, 1);
delay(10);
}
else{ //if state3 is low then relay and led will turn off
state4 = HIGH;
digitalWrite(PC14, LOW);
digitalWrite(PA5, LOW);
EEPROM.write(3, 0);
delay(10);
}
}
p4 = r41;
if (r51 == HIGH && p5 == LOW) { //if third sensor data is HIGH and p3 is low then relay will turn on and also led will turn on
if (state5 == HIGH){ //if state3 is high then relay and led will turn on
state5 = LOW;
digitalWrite(PC13, HIGH);
digitalWrite(PB8, HIGH);
EEPROM.write(4, 1);
delay(10);
}
else{ //if state3 is low then relay and led will turn off
state5 = HIGH;
digitalWrite(PB13, LOW);
digitalWrite(PB14, LOW);
digitalWrite(PB15, LOW);
digitalWrite(PA12, LOW);
digitalWrite(PB8, LOW);
digitalWrite(PC13, LOW);
digitalWrite(PA6, LOW);
digitalWrite(PA7, LOW);
digitalWrite(PB6, LOW);
EEPROM.write(4, 0);
delay(10);
}
}
p5 = r51;
if (r61 == HIGH && p6 == LOW) { //if third sensor data is HIGH and p3 is low then relay will turn on and also led will turn on
if (state6 == HIGH && state5 == LOW){ //if state3 is high then relay and led will turn on
state6 = LOW;
digitalWrite(PC13, HIGH);
digitalWrite(PB8, HIGH);
digitalWrite(PA12, HIGH);
digitalWrite(PA6, HIGH);
digitalWrite(PA7, LOW);
digitalWrite(PB6, LOW);
EEPROM.write(5, 1);
delay(10);
}
else{ //if state3 is low then relay and led will turn off
state6 = HIGH;
digitalWrite(PB13, LOW);
digitalWrite(PB14, LOW);
digitalWrite(PB15, LOW);
digitalWrite(PA12, LOW);
digitalWrite(PA6, LOW);
digitalWrite(PA7, LOW);
digitalWrite(PB6, LOW);
EEPROM.write(5, 0);
delay(10);
}
}
p6 = r61;
if (r71 == HIGH && p7 == LOW) { //if third sensor data is HIGH and p3 is low then relay will turn on and also led will turn on
if (state7 == HIGH && state5 == LOW){ //if state3 is high then relay and led will turn on
state7 = LOW;
digitalWrite(PC13, HIGH);
digitalWrite(PB8, HIGH);
digitalWrite(PA12, HIGH);
digitalWrite(PB15, HIGH);
digitalWrite(PA6, LOW);
digitalWrite(PA7, HIGH);
digitalWrite(PB6, LOW);
EEPROM.write(6, 1);
delay(10);
}
else{ //if state3 is low then relay and led will turn off
state7 = HIGH;
digitalWrite(PB13, LOW);
digitalWrite(PB14, LOW);
digitalWrite(PB15, LOW);
digitalWrite(PA6, HIGH);
digitalWrite(PA7, LOW);
digitalWrite(PB6, LOW);
EEPROM.write(6, 0);
delay(10);
}
}
p7 = r71;
if (r81 == HIGH && p8 == LOW) { //if third sensor data is HIGH and p3 is low then relay will turn on and also led will turn on
if (state8 == HIGH && state5 == LOW){ //if state3 is high then relay and led will turn on
state8 = LOW;
digitalWrite(PC13, HIGH);
digitalWrite(PB8, HIGH);
digitalWrite(PA12, HIGH);
digitalWrite(PB15, HIGH);
digitalWrite(PB14, HIGH);
digitalWrite(PA6, HIGH);
digitalWrite(PA7, HIGH);
digitalWrite(PB6, LOW);
EEPROM.write(7, 1);
delay(10);
}
else{ //if state3 is low then relay and led will turn off
state8 = HIGH;
digitalWrite(PB13, LOW);
digitalWrite(PB14, LOW);
digitalWrite(PA6, LOW);
digitalWrite(PA7, HIGH);
digitalWrite(PB6, LOW);
EEPROM.write(7, 0);
delay(10);
}
}
p8 = r81;
if (r91 == HIGH && p9 == LOW) { //if third sensor data is HIGH and p3 is low then relay will turn on and also led will turn on
if (state9 == HIGH && state5 == LOW){ //if state3 is high then relay and led will turn on
state9 = LOW;
digitalWrite(PC13, HIGH);
digitalWrite(PB8, HIGH);
digitalWrite(PA12, HIGH);
digitalWrite(PB15, HIGH);
digitalWrite(PB14, HIGH);
digitalWrite(PB13, HIGH);
digitalWrite(PA6, LOW);
digitalWrite(PA7, LOW);
digitalWrite(PB6, HIGH);
EEPROM.write(8, 1);
delay(10);
}
else{ //if state3 is low then relay and led will turn off
state9 = HIGH;
digitalWrite(PB13, LOW);
digitalWrite(PA6, HIGH);
digitalWrite(PA7, HIGH);
digitalWrite(PB6, LOW);
EEPROM.write(8, 0);
delay(10);
}
}
p9 = r91;
}
| [
"noreply@github.com"
] | noreply@github.com |
e5d3113ac4c0c69920467f0a71c7da8279bc2c5e | abc7f2c829f199c6f922df24fec6dd78a02b7dbe | /rpc/HBGeneralize.cpp | e334eaf68401ed627ce3e41162ed75a76a2b1ea4 | [] | no_license | madhavsuresh/KloakDB | b84d6d86f4b6e3b6f883ea0c33d1f1df2d706f71 | 18280d811484d650f06c4df9e1500bcdd2c7bb56 | refs/heads/master | 2023-07-20T12:48:41.699555 | 2019-07-16T01:45:06 | 2019-07-16T01:45:06 | 136,368,160 | 3 | 0 | null | 2023-07-05T20:51:28 | 2018-06-06T18:11:47 | C++ | UTF-8 | C++ | false | false | 1,454 | cpp | //
// Created by madhav on 9/24/18.
//
#include "HBGeneralize.h"
#include "../TableStatistics.h"
#include "DOClient.h"
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
void HBGeneralize::Generalize(std::vector<TableStatistics> allStats) {
int num_hosts = allStats.size();
for (int i = 0; i < num_hosts; i++) {
for (int j = 0; j < num_hosts; j++) {
std::map<int, int> newMap;
if (j == i) {
continue;
}
std::map<int, int> currMap = allStats.at(j).GetMap();
for (std::map<int, int>::iterator it = currMap.begin();
it != currMap.end(); ++it) {
if (newMap.count(it->first) == 1) {
newMap[it->first] += it->second;
} else {
newMap[it->first] = it->second;
}
}
}
}
}
void HBGeneralize::generalize() {
std::vector<TableStatistics> allStats;
VaultDBClient client(
grpc::CreateChannel("0.0.0.0:50051", grpc::InsecureChannelCredentials()));
std::string db1 = "dbname=test";
std::string q1 = "SELECT floor, COUNT(*) from rpc_test group by floor;";
std::string q2 = "SELECT floor, COUNT(*) from rpc_test1 group by floor;";
table_t *t1 = client.GetTable(db1, q1);
table_t *t2 = client.GetTable(db1, q2);
TableStatistics ts;
ts.IngestAllocatedTable(t1);
TableStatistics ts2;
ts2.IngestAllocatedTable(t2);
allStats.push_back(ts);
allStats.push_back(ts2);
HBGeneralize::Generalize(allStats);
}
| [
"madhav@thoughtbison.net"
] | madhav@thoughtbison.net |
460f008382f2d587ba86f5130854f48cc7e982b4 | 0d188ac348c99f5f83bcfde9c83033c696e74c52 | /archive/to-2006/phd-neuralsim/brainlib/ErrorInterface.cpp | fc615fd015fe343cdbf2e0d6e28411616bb73af6 | [] | no_license | pliniker/attic | ebb3085fbc7465017144f0fced1243c28e4eb82c | 35b009f6bac41564e3396f272a2bc0ff1b1ec21e | refs/heads/master | 2021-01-10T06:18:40.788507 | 2015-11-23T18:42:57 | 2015-11-23T18:42:57 | 46,632,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,418 | cpp |
#include <iostream>
#include "ErrorInterface.h"
static nnet::ErrorInterfaceBase* error_interface;
nnet::ErrorInterfaceBase::~ErrorInterfaceBase() {}
void nnet::ErrorInterface::alert( std::string a ) {
std::cerr << a << std::endl;
}
void nnet::ErrorInterface::log( std::string l ) {
std::cerr << l << std::endl;
}
bool nnet::ErrorInterface::ask( std::string q ) {
std::cerr << q << "... no" << std::endl;
return false;
}
void nnet::ErrorInterface::clear() {}
void nnet::error::set_error_interface( nnet::ErrorInterfaceBase* iface ) {
if( ::error_interface ) delete error_interface;
::error_interface = iface;
}
void nnet::error::alert( std::string a ) {
::error_interface->alert( a );
}
void nnet::error::log( std::string e ) {
::error_interface->log( e );
}
bool nnet::error::ask( std::string q ) {
return ::error_interface->ask( q );
}
void nnet::error::clear() {
::error_interface->clear();
}
void nnet::error::std_exception( std::string in, const char* what ) {
std::string msg = in + ": " + what;
log( msg );
alert( msg );
}
std::string const nnet::error::NewObjectFailed = "Exception thrown in creating a new object.\nIf this persists with the same object type there is probably a bug in the respective plugin code.";
std::string const nnet::error::DeleteObjectFailed = "Exception thrown in deleting an object.\nThere is probably an error in a destructor somewhere down the line.\n";
std::string const nnet::error::CheckObjectFailed = "Exception thrown in verifying a layer.\nIf this persists there is probably a bug in the respective plugin code.\nYou may want to delete the layer.";
std::string const nnet::error::RecallObjectFailed = "Exception thrown in recalling a layer.\nIf this persists there is probably a bug in the respective plugin code.\nYou may want to delete the layer.";
std::string const nnet::error::LearnObjectFailed = "Exception thrown in training a layer.\nIf this persists there is probably a bug in the respective plugin code.\nYou may want to delete the layer.";
std::string const nnet::error::ResetObjectFailed = "Exception thrown in resetting a layer.\nIf this persists there is probably a bug in the respective plugin code.\nYou may want to delete the layer.";
std::string const nnet::error::UnserializeFailed = "Exception thrown in loading from disk.\nThis may leave the application in an unpredictable state: the application will quit.";
| [
"peter.liniker+github@gmail.com"
] | peter.liniker+github@gmail.com |
1034d21573019999f4157c4f7c2d63b0b11f0e33 | 30501193c536aae05feaa8b69974795b0d2df45e | /Tree/Tree construction.cpp | 0005a51df70f6f0ce31a705af6744d930d246867 | [] | no_license | misuki7435/Tree-practice | 71d1fdea5b9f62212e7a4100cea7144ddf2b0045 | 82a4dec607fb6fa52cd6ac21a124ecae1beec350 | refs/heads/master | 2020-12-03T15:44:21.059591 | 2020-01-03T14:56:38 | 2020-01-03T14:56:38 | 231,377,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | cpp | #include<iostream>
#include<vector>
#include<string>
#include "node.h"
//example input (A(B(E(K,L),F),C(G),D(H(M),I,J)))
using namespace std;
void createTree(node *&root, string str)
{
root->data = str[1];
int cranketL = 1, cranketR = 0;
int index = 2;
while(cranketL != cranketR) {
if(str[index] == '(')
cranketL++;
else if(str[index] == ')')
cranketR++;
if(cranketL == cranketR + 2 && str[index] == '(') {
root->leftChild = new node;
string temp = str;
temp.erase(temp.begin(), temp.begin() + index);
createTree(root->leftChild, temp);
}
if(cranketL == cranketR+1 && str[index] >= 'A' && str[index] <= 'Z') {
root->rightChild = new node;
root = root->rightChild;
root->data = str[index];
}
index++;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
50633b9502ec6c4eee9450b57efd40b7602ed0a9 | 7cc5183d0b36133330b6cd428435e6b64a46e051 | /tensorflow/compiler/xla/service/gpu/conditional_thunk.cc | ccaa279e9f349b6c172c7ef358ee0a1c68c90a4f | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | shizukanaskytree/tensorflow | cfd0f3c583d362c62111a56eec9da6f9e3e0ddf9 | 7356ce170e2b12961309f0bf163d4f0fcf230b74 | refs/heads/master | 2022-11-19T04:46:43.708649 | 2022-11-12T09:03:54 | 2022-11-12T09:10:12 | 177,024,714 | 2 | 1 | Apache-2.0 | 2021-11-10T19:53:04 | 2019-03-21T21:13:38 | C++ | UTF-8 | C++ | false | false | 2,946 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/conditional_thunk.h"
#include <memory>
#include "tensorflow/compiler/xla/hlo/ir/hlo_instruction.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/tsl/platform/errors.h"
namespace xla {
namespace gpu {
ConditionalThunk::ConditionalThunk(
ThunkInfo thunk_info, ConditionalThunkConfig config,
const BufferAllocation::Slice& branch_index_buffer_index)
: Thunk(Kind::kConditional, thunk_info),
config_(std::move(config)),
branch_index_buffer_index_(branch_index_buffer_index) {}
Status ConditionalThunk::Initialize(const GpuExecutable& executable,
se::StreamExecutor* executor) {
if (config_.branch_index_is_bool) {
TF_RET_CHECK(config_.branch_thunks.size() == 2);
} else {
TF_RET_CHECK(!config_.branch_thunks.empty());
}
for (auto& branch_thunk : config_.branch_thunks) {
TF_RETURN_IF_ERROR(branch_thunk->Initialize(executable, executor));
}
return OkStatus();
}
Status ConditionalThunk::ExecuteOnStream(const ExecuteParams& params) {
auto& stream = *params.stream;
// Copy the predicate value from device.
int32_t branch_index = -1;
bool pred = false;
se::DeviceMemoryBase branch_index_address =
params.buffer_allocations->GetDeviceAddress(branch_index_buffer_index_);
if (config_.branch_index_is_bool) {
stream.ThenMemcpy(&pred, branch_index_address, sizeof(bool));
} else {
stream.ThenMemcpy(&branch_index, branch_index_address, sizeof(int32_t));
}
Status block_status = stream.BlockHostUntilDone();
if (!block_status.ok()) {
return InternalError(
"Failed to retrieve branch_index value on stream %p: %s.", &stream,
block_status.error_message());
}
if (config_.branch_index_is_bool) {
branch_index = pred ? 0 : 1;
} else {
// Handle default scenario for branch_index not in [0, num_branches).
if (branch_index < 0 || branch_index >= config_.branch_count) {
branch_index = config_.branch_count - 1;
}
}
// Execute the branch computation corresponding to the value of branch_index.
TF_RETURN_IF_ERROR(
config_.branch_thunks[branch_index]->ExecuteOnStream(params));
return OkStatus();
}
} // namespace gpu
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
fcb7987f767d2c6730f06b9bd702a0663b32cbcc | 70abdf4e8e2e18318b1c451f1ecb8808c3af1153 | /KGCA_Game/KG_GameProjects/KG_Engine/UI_Ammo_font.h | 3835381bcd402cbc279bb7a1832c72e575655a19 | [] | no_license | Byeng-Yong-Choi/Byeng_Yong-Game | 0815e0944cd8c7d8d0093fc1d58662f5bd75845f | 0ac592e66f6d895b277ceb2c829338b13b94f14f | refs/heads/master | 2023-03-11T07:12:34.809028 | 2021-02-22T19:10:29 | 2021-02-22T19:10:29 | 276,743,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | h | #pragma once
#include "UI_font.h"
namespace KYS
{
#define AMMOFONT_MIN 0
#define AMMOFONT_MAX 9
class UI_Ammo_font : public UI_font
{
public:
UI_Ammo_font();
virtual ~UI_Ammo_font();
public:
virtual void SetValue(UI_VALUE type, int paramCount, ...);
virtual void UpdateUv() override;
public:
virtual bool Init() override;
public:
void SetAmmo(int ammo);
int GetAmmo() { return _ammoCount; }
void AddAmmo(int ammo);
private:
int _ammoCount;
MyUV _uv;
};
}
| [
"58583903+Byeng-Yong-Choi@users.noreply.github.com"
] | 58583903+Byeng-Yong-Choi@users.noreply.github.com |
9d0a6fb057d21e41db6e3e2150c1963aae09d08c | 271135be815b2dde5f3cfeecb5d428a0350b70b5 | /Arduino/livingSensor.ino | 4dadb8d7d3f15862ec0fedf237ab797177671ed0 | [] | no_license | garry0325/GarryHomeKitHub | 4e6707befab5aa654a3b858d3466a65563ef9fd1 | 500ca7a1c25199dbd67fdc7830280989958d663c | refs/heads/master | 2021-07-06T14:38:48.736923 | 2020-10-22T07:07:03 | 2020-10-22T07:07:03 | 196,574,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | ino | #include <Adafruit_Sensor.h>
#include<Wire.h>
#include<BH1750.h>
#include <DHT_U.h>
#include <SoftwareSerial.h>
#include <JeeLib.h>
#define pinDHT 8
#define typeDHT 11
#define bluetoothPinTXD 5
#define bluetoothPinRXD 6
#define airPin 0
#define refreshFrequency 240000
DHT dhtSensor(pinDHT,typeDHT);
BH1750 lightMeter;
SoftwareSerial bt(bluetoothPinTXD,bluetoothPinRXD);
float temperature;
float humidity;
float battery;
ISR(WDT_vect)
{
Sleepy::watchdogEvent();
}
void setup() {
// put your setup code here, to run once:
pinMode(airPin,INPUT);
Wire.begin();
lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
bt.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
temperature=dhtSensor.readTemperature();
humidity=dhtSensor.readHumidity();
uint16_t lux=lightMeter.readLightLevel();
bt.print((String)temperature+","+(String)humidity+","+(String)lux);
//delay(refreshFrequency);
Sleepy::loseSomeTime(refreshFrequency);
}
| [
"garry0325@Garrys-MacBook-Pro-Retina.local"
] | garry0325@Garrys-MacBook-Pro-Retina.local |
07026f9031945336f3848c98b37ecfee5361b442 | eedd904304046caceb3e982dec1d829c529da653 | /clanlib/ClanLib-2.2.8/Examples/Display/Particle/Sources/Demos/simple.cpp | 6c69d98f8b7fe428bd15a1a5089df26f3e4a0169 | [] | no_license | PaulFSherwood/cplusplus | b550a9a573e9bca5b828b10849663e40fd614ff0 | 999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938 | refs/heads/master | 2023-06-07T09:00:20.421362 | 2023-05-21T03:36:50 | 2023-05-21T03:36:50 | 12,607,904 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,899 | cpp | /*
////////////////////////////////////////////////////////////////////////////
// LinearParticle Example - Simple
////////////////////////////////////////////////////////////////////////////
Example of using LinearParticle to make simple trail.
Note : For simplicity, the motion of object in this exampls is frame based
hence the object moves faster in higher FPS. Motions of particles and effects
in other examples are calculated in hybrid of time based and frame based
system which is much more flexible and robust but more complicated.
- 31/10/2006
////////////////////////////////////////////////////////////////////////////
*/
#include "precomp.h"
#include "simple.h"
#include "../LinearParticle/L_ParticleSystem.h"
#include "framerate_counter.h"
int DemoSimple::run(CL_DisplayWindow &window)
{
quit = false;
// Set the window
window.set_title("LinearParticle Example - Simple ");
// Connect the Window close event
CL_Slot slot_quit = window.sig_window_close().connect(this, &DemoSimple::on_window_close);
// Connect a keyboard handler to on_key_up()
CL_Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &DemoSimple::on_input_up);
// Get the graphic context
CL_GraphicContext gc = window.get_gc();
// initialize LinearParticle
L_ParticleSystem::init();
// create surface to be used for particle and set the alignment
CL_Sprite surface(gc,"Resources/light16p.png");
surface.set_alignment(origin_center);
// create a sample of particle with life of 5000
L_Particle particle(&surface,5000);
// create dropping effect with period of 16
L_DroppingEffect dropper(0,0,16);
// add the particle to dropper effect
dropper.add(&particle);
// initialize particle effect
dropper.initialize();
float x_pos = 320;
float y_pos = 240;
float x_vel = 3.0f;
float y_vel = 3.0f;
CL_Font font(gc, "tahoma", 16 );
FramerateCounter frameratecounter;
// Run until someone presses escape
while (!quit)
{
gc.clear();
x_pos += x_vel;
y_pos += y_vel;
if( x_pos > 640 || x_pos < 0 )
x_vel = -x_vel;
if( y_pos > 480 || y_pos < 0 )
y_vel = -y_vel;
dropper.set_position(x_pos, y_pos);
dropper.trigger();
/* pass frame time to L_ParticleEffect::run(int) for time based system,
a constant number would be a reference time unit for frame based system. */
dropper.run(16);
// draw dropping effect
L_DrawParticle(gc,dropper);
frameratecounter.show_fps(gc, font);
window.flip(0); // Set to "1" to lock to screen refresh rate
frameratecounter.frame_shown();
CL_KeepAlive::process(0);
}
// deinitialize LinearParticle
L_ParticleSystem::deinit();
return 0;
}
// A key was pressed
void DemoSimple::on_input_up(const CL_InputEvent &key, const CL_InputState &state)
{
if(key.id == CL_KEY_ESCAPE)
{
quit = true;
}
}
// The window was closed
void DemoSimple::on_window_close()
{
quit = true;
}
| [
"paulfsherwood@gmail.com"
] | paulfsherwood@gmail.com |
273aca7a520cb54ea7d3923f4c28bca9d9b2e8fa | 8f66f32dd2e53ed1bcaed905d18294b643b7019c | /uftgrid/cpp/Stdafx.cpp | d76df37edb7eb005ed0d46c3060c244496b636bf | [] | no_license | fredleefarr/UTFGrid-Renderer | a094ac8eaa4627ac2f842e5b94900758839497b9 | 03e892ae3720618f7c8dea949987d5908ece408c | refs/heads/master | 2020-05-19T17:02:10.330034 | 2012-02-16T12:27:33 | 2012-02-16T12:27:33 | 3,459,629 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | cpp | // stdafx.cpp : source file that includes just the standard includes
// cpp.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"fred.leefarr@airpost.net"
] | fred.leefarr@airpost.net |
8055478df0282747ef3a3437693a9040bbd49110 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /components/app_modal/javascript_dialog_manager.cc | 14427e30891ed57e8e586aa8945a0a774600aa1f | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 13,219 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/app_modal/javascript_dialog_manager.h"
#include <algorithm>
#include <utility>
#include "base/bind.h"
#include "base/i18n/rtl.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "components/app_modal/app_modal_dialog_queue.h"
#include "components/app_modal/javascript_dialog_extensions_client.h"
#include "components/app_modal/javascript_native_dialog_factory.h"
#include "components/app_modal/native_app_modal_dialog.h"
#include "components/strings/grit/components_strings.h"
#include "components/url_formatter/elide_url.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/javascript_dialog_type.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/font_list.h"
namespace app_modal {
namespace {
#if !defined(OS_ANDROID)
// Keep in sync with kDefaultMessageWidth, but allow some space for the rest of
// the text.
const int kUrlElideWidth = 350;
#endif
class DefaultExtensionsClient : public JavaScriptDialogExtensionsClient {
public:
DefaultExtensionsClient() {}
~DefaultExtensionsClient() override {}
private:
// JavaScriptDialogExtensionsClient:
void OnDialogOpened(content::WebContents* web_contents) override {}
void OnDialogClosed(content::WebContents* web_contents) override {}
bool GetExtensionName(content::WebContents* web_contents,
const GURL& alerting_frame_url,
std::string* name_out) override {
return false;
}
DISALLOW_COPY_AND_ASSIGN(DefaultExtensionsClient);
};
bool ShouldDisplaySuppressCheckbox(
ChromeJavaScriptDialogExtraData* extra_data) {
return extra_data->has_already_shown_a_dialog_;
}
} // namespace
// static
JavaScriptDialogManager* JavaScriptDialogManager::GetInstance() {
return base::Singleton<JavaScriptDialogManager>::get();
}
void JavaScriptDialogManager::SetNativeDialogFactory(
std::unique_ptr<JavaScriptNativeDialogFactory> factory) {
native_dialog_factory_ = std::move(factory);
}
void JavaScriptDialogManager::SetExtensionsClient(
std::unique_ptr<JavaScriptDialogExtensionsClient> extensions_client) {
extensions_client_ = std::move(extensions_client);
}
JavaScriptDialogManager::JavaScriptDialogManager()
: extensions_client_(new DefaultExtensionsClient) {
}
JavaScriptDialogManager::~JavaScriptDialogManager() {
}
base::string16 JavaScriptDialogManager::GetTitle(
content::WebContents* web_contents,
const GURL& alerting_frame_url) {
// For extensions, show the extension name, but only if the origin of
// the alert matches the top-level WebContents.
std::string name;
if (extensions_client_->GetExtensionName(web_contents, alerting_frame_url,
&name))
return base::UTF8ToUTF16(name);
// Otherwise, return the formatted URL.
return GetTitleImpl(web_contents->GetURL(), alerting_frame_url);
}
namespace {
// Unwraps an URL to get to an embedded URL.
GURL UnwrapURL(const GURL& url) {
// GURL will unwrap filesystem:// URLs so ask it to do so.
const GURL* unwrapped_url = url.inner_url();
if (unwrapped_url)
return *unwrapped_url;
// GURL::inner_url() should unwrap blob: URLs but doesn't do so
// (https://crbug.com/690091). Therefore, do it manually.
//
// https://url.spec.whatwg.org/#origin defines the origin of a blob:// URL as
// the origin of the URL which results from parsing the "path", which boils
// down to everything after the scheme. GURL's 'GetContent()' gives us exactly
// that. See url::Origin()'s constructor.
if (url.SchemeIsBlob())
return GURL(url.GetContent());
return url;
}
} // namespace
// static
base::string16 JavaScriptDialogManager::GetTitleImpl(
const GURL& parent_frame_url,
const GURL& alerting_frame_url) {
GURL unwrapped_parent_frame_url = UnwrapURL(parent_frame_url);
GURL unwrapped_alerting_frame_url = UnwrapURL(alerting_frame_url);
bool is_same_origin_as_main_frame =
(unwrapped_parent_frame_url.GetOrigin() ==
unwrapped_alerting_frame_url.GetOrigin());
if (unwrapped_alerting_frame_url.IsStandard() &&
!unwrapped_alerting_frame_url.SchemeIsFile()) {
#if defined(OS_ANDROID)
base::string16 url_string = url_formatter::FormatUrlForSecurityDisplay(
unwrapped_alerting_frame_url,
url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
#else
base::string16 url_string = url_formatter::ElideHost(
unwrapped_alerting_frame_url, gfx::FontList(), kUrlElideWidth);
#endif
return l10n_util::GetStringFUTF16(
is_same_origin_as_main_frame ? IDS_JAVASCRIPT_MESSAGEBOX_TITLE
: IDS_JAVASCRIPT_MESSAGEBOX_TITLE_IFRAME,
base::i18n::GetDisplayStringInLTRDirectionality(url_string));
}
return l10n_util::GetStringUTF16(
is_same_origin_as_main_frame
? IDS_JAVASCRIPT_MESSAGEBOX_TITLE_NONSTANDARD_URL
: IDS_JAVASCRIPT_MESSAGEBOX_TITLE_NONSTANDARD_URL_IFRAME);
}
void JavaScriptDialogManager::RunJavaScriptDialog(
content::WebContents* web_contents,
content::RenderFrameHost* render_frame_host,
content::JavaScriptDialogType dialog_type,
const base::string16& message_text,
const base::string16& default_prompt_text,
DialogClosedCallback callback,
bool* did_suppress_message) {
*did_suppress_message = false;
ChromeJavaScriptDialogExtraData* extra_data =
&javascript_dialog_extra_data_[web_contents];
if (extra_data->suppress_javascript_messages_) {
// If a page tries to open dialogs in a tight loop, the number of
// suppressions logged can grow out of control. Arbitrarily cap the number
// logged at 100. That many suppressed dialogs is enough to indicate the
// page is doing something very hinky.
if (extra_data->suppressed_dialog_count_ < 100) {
// Log a suppressed dialog as one that opens and then closes immediately.
UMA_HISTOGRAM_MEDIUM_TIMES(
"JSDialogs.FineTiming.TimeBetweenDialogCreatedAndSameDialogClosed",
base::TimeDelta());
// Only increment the count if it's not already at the limit, to prevent
// overflow.
extra_data->suppressed_dialog_count_++;
}
*did_suppress_message = true;
return;
}
base::TimeTicks now = base::TimeTicks::Now();
if (!last_creation_time_.is_null()) {
// A new dialog has been created: log the time since the last one was
// created.
UMA_HISTOGRAM_MEDIUM_TIMES(
"JSDialogs.FineTiming.TimeBetweenDialogCreatedAndNextDialogCreated",
now - last_creation_time_);
}
last_creation_time_ = now;
// Also log the time since a dialog was closed, but only if this is the first
// dialog that was opened since the closing.
if (!last_close_time_.is_null()) {
UMA_HISTOGRAM_MEDIUM_TIMES(
"JSDialogs.FineTiming.TimeBetweenDialogClosedAndNextDialogCreated",
now - last_close_time_);
last_close_time_ = base::TimeTicks();
}
base::string16 dialog_title =
GetTitle(web_contents, render_frame_host->GetLastCommittedURL());
extensions_client_->OnDialogOpened(web_contents);
AppModalDialogQueue::GetInstance()->AddDialog(new JavaScriptAppModalDialog(
web_contents, &javascript_dialog_extra_data_, dialog_title, dialog_type,
message_text, default_prompt_text,
ShouldDisplaySuppressCheckbox(extra_data),
false, // is_before_unload_dialog
false, // is_reload
base::BindOnce(&JavaScriptDialogManager::OnDialogClosed,
base::Unretained(this), web_contents,
std::move(callback))));
}
void JavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents,
content::RenderFrameHost* render_frame_host,
bool is_reload,
DialogClosedCallback callback) {
RunBeforeUnloadDialogWithOptions(web_contents, render_frame_host, is_reload,
false, std::move(callback));
}
void JavaScriptDialogManager::RunBeforeUnloadDialogWithOptions(
content::WebContents* web_contents,
content::RenderFrameHost* render_frame_host,
bool is_reload,
bool is_app,
DialogClosedCallback callback) {
ChromeJavaScriptDialogExtraData* extra_data =
&javascript_dialog_extra_data_[web_contents];
if (extra_data->suppress_javascript_messages_) {
// If a site harassed the user enough for them to put it on mute, then it
// lost its privilege to deny unloading.
std::move(callback).Run(true, base::string16());
return;
}
// Build the dialog message. We explicitly do _not_ allow the webpage to
// specify the contents of this dialog, as per the current spec
//
// https://html.spec.whatwg.org/#unloading-documents, step 8:
//
// "The message shown to the user is not customizable, but instead
// determined by the user agent. In particular, the actual value of the
// returnValue attribute is ignored."
//
// This message used to be customizable, but it was frequently abused by
// scam websites so the specification was changed.
base::string16 title;
if (is_app) {
title = l10n_util::GetStringUTF16(
is_reload ? IDS_BEFORERELOAD_APP_MESSAGEBOX_TITLE
: IDS_BEFOREUNLOAD_APP_MESSAGEBOX_TITLE);
} else {
title = l10n_util::GetStringUTF16(is_reload
? IDS_BEFORERELOAD_MESSAGEBOX_TITLE
: IDS_BEFOREUNLOAD_MESSAGEBOX_TITLE);
}
const base::string16 message =
l10n_util::GetStringUTF16(IDS_BEFOREUNLOAD_MESSAGEBOX_MESSAGE);
extensions_client_->OnDialogOpened(web_contents);
AppModalDialogQueue::GetInstance()->AddDialog(new JavaScriptAppModalDialog(
web_contents, &javascript_dialog_extra_data_, title,
content::JAVASCRIPT_DIALOG_TYPE_CONFIRM, message,
base::string16(), // default_prompt_text
ShouldDisplaySuppressCheckbox(extra_data),
true, // is_before_unload_dialog
is_reload,
base::BindOnce(&JavaScriptDialogManager::OnBeforeUnloadDialogClosed,
base::Unretained(this), web_contents,
std::move(callback))));
}
bool JavaScriptDialogManager::HandleJavaScriptDialog(
content::WebContents* web_contents,
bool accept,
const base::string16* prompt_override) {
AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
if (!dialog_queue->HasActiveDialog() ||
dialog_queue->active_dialog()->web_contents() != web_contents) {
return false;
}
JavaScriptAppModalDialog* dialog = static_cast<JavaScriptAppModalDialog*>(
dialog_queue->active_dialog());
if (dialog->javascript_dialog_type() ==
content::JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_ALERT) {
// Alert dialogs only have one button: OK. Any "handling" of this dialog has
// to be a click on the OK button.
accept = true;
}
if (accept) {
if (prompt_override)
dialog->SetOverridePromptText(*prompt_override);
dialog->native_dialog()->AcceptAppModalDialog();
} else {
dialog->native_dialog()->CancelAppModalDialog();
}
return true;
}
void JavaScriptDialogManager::CancelDialogs(content::WebContents* web_contents,
bool reset_state) {
AppModalDialogQueue* queue = AppModalDialogQueue::GetInstance();
JavaScriptAppModalDialog* active_dialog = queue->active_dialog();
for (auto* dialog : *queue) {
// Invalidating the active dialog might trigger showing a not-yet
// invalidated dialog, so invalidate the active dialog last.
if (dialog == active_dialog)
continue;
if (dialog->web_contents() == web_contents)
dialog->Invalidate();
}
if (active_dialog && active_dialog->web_contents() == web_contents)
active_dialog->Invalidate();
if (reset_state)
javascript_dialog_extra_data_.erase(web_contents);
}
void JavaScriptDialogManager::OnBeforeUnloadDialogClosed(
content::WebContents* web_contents,
DialogClosedCallback callback,
bool success,
const base::string16& user_input) {
enum class StayVsLeave {
STAY = 0,
LEAVE = 1,
MAX,
};
UMA_HISTOGRAM_ENUMERATION(
"JSDialogs.OnBeforeUnloadStayVsLeave",
static_cast<int>(success ? StayVsLeave::LEAVE : StayVsLeave::STAY),
static_cast<int>(StayVsLeave::MAX));
OnDialogClosed(web_contents, std::move(callback), success, user_input);
}
void JavaScriptDialogManager::OnDialogClosed(
content::WebContents* web_contents,
DialogClosedCallback callback,
bool success,
const base::string16& user_input) {
// If an extension opened this dialog then the extension may shut down its
// lazy background page after the dialog closes. (Dialogs are closed before
// their WebContents is destroyed so |web_contents| is still valid here.)
extensions_client_->OnDialogClosed(web_contents);
last_close_time_ = base::TimeTicks::Now();
std::move(callback).Run(success, user_input);
}
} // namespace app_modal
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
2b5f701eeb67c6b1d8454727bdbed0b4bf38e4f1 | 321e07f9d187c6d19d767dad821e7aa926ceb9cb | /first_time/leetcode/c++/295. Find Median from Data Stream.cpp | d66a8e48224720d06940142cc09291f34ae50cef | [] | no_license | Pipi24/OJ | f98dd24d2b743ba73519fb51c73e62981561ef0e | e4ff506c7a9aca4117519b35297469d0b139f81b | refs/heads/master | 2023-06-02T18:05:03.928215 | 2021-06-10T10:03:36 | 2021-06-10T10:03:36 | 119,809,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 782 | cpp | class MedianFinder {
priority_queue<int> max_heap;
priority_queue<int, vector<int>, greater<int>> min_heap;
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
max_heap.push(num);
min_heap.push(max_heap.top());
max_heap.pop();
if(max_heap.size()<min_heap.size()){
max_heap.push(min_heap.top());
min_heap.pop();
}
}
double findMedian() {
return max_heap.size()>min_heap.size()?(double)max_heap.top():(max_heap.top()+min_heap.top())/2.0;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/ | [
"347127951@qq.com"
] | 347127951@qq.com |
f295533291c2ebf75ef16fb52519d3d414c40d47 | f92710bd5204f729666072e2a1e5e5c8c256e004 | /Diglett/Diglett/DeadGameState.h | fa53658da64cb56f18ad3979c7f1f55bde5adf58 | [] | no_license | CiaranDeasy/diglett_cave | 96cf364967488dcc78366cb5eb994a47c923c962 | 751e4ee73b351f73456d5332af6f6066325752d0 | refs/heads/master | 2021-01-01T06:50:19.724812 | 2014-06-18T16:32:05 | 2014-06-18T16:32:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,634 | h | #pragma once
#ifndef DEAD_GAME_STATE_H
#define DEAD_GAME_STATE_H
#include "GameState.h"
#include <SFML/Graphics.hpp>
#include "GameWindow.h"
#include "TextPopUp.h"
#include "Player.h"
/* This abstract class represents a state that the game can be in, such as the
main game, or a particular menu. */
class DeadGameState : public GameState {
public:
DeadGameState( GameWindow *gameWindow, Player& player );
~DeadGameState();
// Represents the behaviour that should be performed each game tick when
// the game is in this state.
virtual void gameTick( float deltaTime );
// Draws all elements of the game state.
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
// Indicates whether the game state below this one should be drawn behind
// it, eg: if this is a menu overlaying the main game.
virtual bool drawUnderlyingState();
private:
class DeadInputHandler : public InputHandler {
public:
DeadInputHandler( DeadGameState& gameState );
~DeadInputHandler();
void processInputs();
private:
DeadGameState& gameState;
};
friend class DeadInputHandler;
// The message displayed, telling the player they are dead.
static const std::string DEATH_MESSAGE;
DeadInputHandler inputHandler;
GameWindow *gameWindow;
TextPopUp deadNotification;
Player& player;
// Polls the GameWindow for window events and responds to them accordingly.
void handleWindowEvents();
// Respawns the player, then marks the DeadGameState as dead.
void respawn();
};
#endif // DEAD_GAME_STATE_H
| [
"cfd27@cam.ac.uk"
] | cfd27@cam.ac.uk |
6b315d9869d7ebd1c17350fbe9bdc5ea77cff25a | 0ee21652c5d4b41be13c8db871261ab48e5f6878 | /src/rpc/request.cpp | 8e2ab137938f733e88e15994ef8162d5f779c171 | [
"MIT"
] | permissive | The-Bitcoin-Phantom/The-bitcoin-Phantom | 60f4a8f85e1a5235dc40b84b7c04bcd0e846c52d | c914b51924932f07026eb6ba057c6e375e4dcdac | refs/heads/master | 2020-08-25T06:46:47.745015 | 2019-10-23T05:59:27 | 2019-10-23T05:59:27 | 216,977,357 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,843 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The bitphantom Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <rpc/request.h>
#include <fs.h>
#include <random.h>
#include <rpc/protocol.h>
#include <util/system.h>
#include <util/strencodings.h>
/**
* JSON-RPC protocol. bitphantom speaks version 1.0 for maximum compatibility,
* but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
* unspecified (HTTP errors and contents of 'error').
*
* 1.0 spec: http://json-rpc.org/wiki/specification
* 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html
*/
UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id)
{
UniValue request(UniValue::VOBJ);
request.pushKV("method", strMethod);
request.pushKV("params", params);
request.pushKV("id", id);
return request;
}
UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const UniValue& id)
{
UniValue reply(UniValue::VOBJ);
if (!error.isNull())
reply.pushKV("result", NullUniValue);
else
reply.pushKV("result", result);
reply.pushKV("error", error);
reply.pushKV("id", id);
return reply;
}
std::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id)
{
UniValue reply = JSONRPCReplyObj(result, error, id);
return reply.write() + "\n";
}
UniValue JSONRPCError(int code, const std::string& message)
{
UniValue error(UniValue::VOBJ);
error.pushKV("code", code);
error.pushKV("message", message);
return error;
}
/** Username used when cookie authentication is in use (arbitrary, only for
* recognizability in debugging/logging purposes)
*/
static const std::string COOKIEAUTH_USER = "__cookie__";
/** Default name for auth cookie file */
static const std::string COOKIEAUTH_FILE = ".cookie";
/** Get name of RPC authentication cookie file */
static fs::path GetAuthCookieFile(bool temp=false)
{
std::string arg = gArgs.GetArg("-rpccookiefile", COOKIEAUTH_FILE);
if (temp) {
arg += ".tmp";
}
return AbsPathForConfigVal(fs::path(arg));
}
bool GenerateAuthCookie(std::string *cookie_out)
{
const size_t COOKIE_SIZE = 32;
unsigned char rand_pwd[COOKIE_SIZE];
GetRandBytes(rand_pwd, COOKIE_SIZE);
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd, rand_pwd+COOKIE_SIZE);
/** the umask determines what permissions are used to create this file -
* these are set to 077 in init.cpp unless overridden with -sysperms.
*/
fsbridge::ofstream file;
fs::path filepath_tmp = GetAuthCookieFile(true);
file.open(filepath_tmp);
if (!file.is_open()) {
LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath_tmp.string());
return false;
}
file << cookie;
file.close();
fs::path filepath = GetAuthCookieFile(false);
if (!RenameOver(filepath_tmp, filepath)) {
LogPrintf("Unable to rename cookie authentication file %s to %s\n", filepath_tmp.string(), filepath.string());
return false;
}
LogPrintf("Generated RPC authentication cookie %s\n", filepath.string());
if (cookie_out)
*cookie_out = cookie;
return true;
}
bool GetAuthCookie(std::string *cookie_out)
{
fsbridge::ifstream file;
std::string cookie;
fs::path filepath = GetAuthCookieFile();
file.open(filepath);
if (!file.is_open())
return false;
std::getline(file, cookie);
file.close();
if (cookie_out)
*cookie_out = cookie;
return true;
}
void DeleteAuthCookie()
{
try {
fs::remove(GetAuthCookieFile());
} catch (const fs::filesystem_error& e) {
LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
}
}
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue &in, size_t num)
{
if (!in.isArray()) {
throw std::runtime_error("Batch must be an array");
}
std::vector<UniValue> batch(num);
for (size_t i=0; i<in.size(); ++i) {
const UniValue &rec = in[i];
if (!rec.isObject()) {
throw std::runtime_error("Batch member must be object");
}
size_t id = rec["id"].get_int();
if (id >= num) {
throw std::runtime_error("Batch member id larger than size");
}
batch[id] = rec;
}
return batch;
}
void JSONRPCRequest::parse(const UniValue& valRequest)
{
// Parse request
if (!valRequest.isObject())
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const UniValue& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
UniValue valMethod = find_value(request, "method");
if (valMethod.isNull())
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (!valMethod.isStr())
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (fLogIPs)
LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s\n", SanitizeString(strMethod),
this->authUser, this->peerAddr);
else
LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s\n", SanitizeString(strMethod), this->authUser);
// Parse params
UniValue valParams = find_value(request, "params");
if (valParams.isArray() || valParams.isObject())
params = valParams;
else if (valParams.isNull())
params = UniValue(UniValue::VARR);
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
}
| [
"dinesh@xiornis.com"
] | dinesh@xiornis.com |
bf881cc62b0481a881078d9c780a88585e59e5d4 | 924049378ea1e986b5b2f09c7c99ee5577b4675e | /src/merkleblock.cpp | c901bf05c1c1e6f045b5e66e38b3f5242e0d6cb6 | [
"MIT"
] | permissive | wincash/WincashGold | 06bc94246b23d1931076067b2b8ef509d2fb6541 | ff5935c021acde8b78d10cff7dce2fcfadc3518a | refs/heads/master | 2022-11-22T00:45:47.164233 | 2020-07-20T22:20:57 | 2020-07-20T22:20:57 | 271,636,521 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,796 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2017 The WINCASHGOLD developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "merkleblock.h"
#include "hash.h"
#include "primitives/block.h" // for MAX_BLOCK_SIZE
#include "utilstrencodings.h"
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
{
header = block.GetBlockHeader();
std::vector<bool> vMatch;
std::vector<uint256> vHashes;
vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size());
for (unsigned int i = 0; i < block.vtx.size(); i++) {
const uint256& hash = block.vtx[i].GetHash();
if (filter.IsRelevantAndUpdate(block.vtx[i])) {
vMatch.push_back(true);
vMatchedTxn.push_back(std::make_pair(i, hash));
} else
vMatch.push_back(false);
vHashes.push_back(hash);
}
txn = CPartialMerkleTree(vHashes, vMatch);
}
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256>& vTxid)
{
if (height == 0) {
// hash at height 0 is the txids themself
return vTxid[pos];
} else {
// calculate left hash
uint256 left = CalcHash(height - 1, pos * 2, vTxid), right;
// calculate right hash if not beyond the end of the array - copy left hash otherwise1
if (pos * 2 + 1 < CalcTreeWidth(height - 1))
right = CalcHash(height - 1, pos * 2 + 1, vTxid);
else
right = left;
// combine subhashes
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch)
{
// determine whether this node is the parent of at least one matched txid
bool fParentOfMatch = false;
for (unsigned int p = pos << height; p < (pos + 1) << height && p < nTransactions; p++)
fParentOfMatch |= vMatch[p];
// store as flag bit
vBits.push_back(fParentOfMatch);
if (height == 0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, store hash and stop
vHash.push_back(CalcHash(height, pos, vTxid));
} else {
// otherwise, don't store any hash, but descend into the subtrees
TraverseAndBuild(height - 1, pos * 2, vTxid, vMatch);
if (pos * 2 + 1 < CalcTreeWidth(height - 1))
TraverseAndBuild(height - 1, pos * 2 + 1, vTxid, vMatch);
}
}
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int& nBitsUsed, unsigned int& nHashUsed, std::vector<uint256>& vMatch)
{
if (nBitsUsed >= vBits.size()) {
// overflowed the bits array - failure
fBad = true;
return 0;
}
bool fParentOfMatch = vBits[nBitsUsed++];
if (height == 0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (nHashUsed >= vHash.size()) {
// overflowed the hash array - failure
fBad = true;
return 0;
}
const uint256& hash = vHash[nHashUsed++];
if (height == 0 && fParentOfMatch) // in case of height 0, we have a matched txid
vMatch.push_back(hash);
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
uint256 left = TraverseAndExtract(height - 1, pos * 2, nBitsUsed, nHashUsed, vMatch), right;
if (pos * 2 + 1 < CalcTreeWidth(height - 1))
right = TraverseAndExtract(height - 1, pos * 2 + 1, nBitsUsed, nHashUsed, vMatch);
else
right = left;
// and combine them before returning
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch) : nTransactions(vTxid.size()), fBad(false)
{
// reset state
vBits.clear();
vHash.clear();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
TraverseAndBuild(nHeight, 0, vTxid, vMatch);
}
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256>& vMatch)
{
vMatch.clear();
// An empty set will not work
if (nTransactions == 0)
return 0;
// check for excessively high numbers of transactions
if (nTransactions > MAX_BLOCK_SIZE_CURRENT / 60) // 60 is the lower bound for the size of a serialized CTransaction
return 0;
// there can never be more hashes provided than one for every txid
if (vHash.size() > nTransactions)
return 0;
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (vBits.size() < vHash.size())
return 0;
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
unsigned int nBitsUsed = 0, nHashUsed = 0;
uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
// verify that no problems occured during the tree traversal
if (fBad)
return 0;
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((nBitsUsed + 7) / 8 != (vBits.size() + 7) / 8)
return 0;
// verify that all hashes were consumed
if (nHashUsed != vHash.size())
return 0;
return hashMerkleRoot;
}
| [
"52337058+wincash@users.noreply.github.com"
] | 52337058+wincash@users.noreply.github.com |
c53483ab7da6b43341549bdd4e8b73c5622b0ab2 | 039d23c0602dc087e4476e2071220e1e8fcd3529 | /intersection-of-two-linked-lists.cc | 5912b6626f8d42fb6abb0f75a81eb87c71ea0e33 | [] | no_license | evilyingyun/LeetCode | a8f6b3f196e53a00c48cd1727fcdc0a590611db9 | bd58a3943a44cc56e8b002f1c50fa8c4b4c3ccd3 | refs/heads/master | 2021-01-24T01:34:33.589286 | 2015-01-13T15:59:27 | 2015-01-13T15:59:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | cc | class Solution {
public:
ListNode *getIntersectionNode(ListNode *a, ListNode *b) {
int d = 0;
for (ListNode *p = a; p; p = p->next) d++;
for (ListNode *p = b; p; p = p->next) d--;
while (d > 0) a = a->next, d--;
while (d < 0) b = b->next, d++;
while (a != b) a = a->next, b = b->next;
return a;
}
};
| [
"i@maskray.me"
] | i@maskray.me |
373e563c0f69ddefd27723ad68c4f75e82247cb8 | 5ccc0793853d0d66844f9097edc089411a4ee0ea | /mc/old/tx1/tx1.ino | 7f6dc2c53dcd70303387435cd51fe76d25820624 | [] | no_license | serge-v/sensors | d82621052eb5d9a82df0eb004911d23035266733 | 2eae9cbdce18f333582a3074a82f6f4a464425a1 | refs/heads/master | 2020-12-25T17:34:49.103157 | 2015-11-18T12:33:19 | 2015-11-18T12:33:19 | 17,455,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | ino | //Simple RFM12B wireless demo - transimtter - no ack
//Glyn Hudson openenergymonitor.org GNU GPL V3 7/7/11
//Credit to JCW from Jeelabs.org for RFM12
#include <JeeLib.h> //from jeelabs.org
#define myNodeID 10 //node ID of tx (range 0-30)
#define network 212 //network group (can be in the range 1-250).
#define freq RF12_433MHZ //Freq of RF12B can be RF12_433MHZ, RF12_868MHZ or RF12_915MHZ. Match freq to module
char emontx = 'A';
void setup() {
pinMode(7, OUTPUT);
rf12_initialize(myNodeID,freq,network); //Initialize RFM12 with settings defined above
Serial.begin(115200);
Serial.println("RFM12B Transmitter - Simple demo");
Serial.print("Node: ");
Serial.print(myNodeID);
Serial.print(" Freq: ");
if (freq == RF12_433MHZ) Serial.print("433Mhz");
if (freq == RF12_868MHZ) Serial.print("868Mhz");
if (freq == RF12_915MHZ) Serial.print("915Mhz");
Serial.print(" Network: ");
Serial.println(network);
}
void loop()
{
if (emontx++ > 'Z')
emontx = 'A';
int i = 0;
while (!rf12_canSend() && i<10)
{
rf12_recvDone();
i++;
}
rf12_sendStart(0, &emontx, sizeof emontx);
Serial.println(emontx);
digitalWrite(7, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100); // wait for a second
digitalWrite(7, LOW); // turn the LED off by making the voltage LOW
delay(1000);
delay(2000);
}
| [
"noro@vois8.home"
] | noro@vois8.home |
942e4aa36d70107ea7487e144a7b9fb9fadc3f5f | c1960d70ef66dcfb5dc9d030000e96c26e3c5832 | /include/nucleus/files/file_path.h | 925435359c55334e5955f62871f17395d8530cf7 | [
"ISC"
] | permissive | ShaheedLegion/nucleus | b6ba0cf41eee053a9c6952531dc0c81d1b7ab175 | f9c9a8ca47d221a520542a54ec8c3e8ed6674d1c | refs/heads/master | 2020-12-26T03:32:59.059663 | 2015-06-24T12:27:44 | 2015-06-24T12:27:44 | 38,127,191 | 0 | 0 | null | 2015-06-26T18:31:05 | 2015-06-26T18:31:05 | null | UTF-8 | C++ | false | false | 3,942 | h | // Copyright (c) 2015, Tiaan Louw
//
// 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.
#ifndef NUCLEUS_FILES_FILE_PATH_H_
#define NUCLEUS_FILES_FILE_PATH_H_
#include <functional>
#include <string>
#include "nucleus/config.h"
namespace nu {
class FilePath {
public:
#if OS(POSIX)
// On most posix platforms, native pathnames are char arrays, and the encoding
// may or may not be specified. On Mac OS X, native pathnames are encoded in
// UTF-8.
using StringType = std::string;
#else
// On Windows, native pathnames are wchar_t arrays encoded in UTF-16.
using StringType = std::wstring;
#endif
using CharType = StringType::value_type;
// Null-terminated array of separators used to separate components in
// hierarchical paths. Each character in this array is a valid separator, but
// kSeparators[0] is treated as the canonical separator and will be used when
// composing pathnames.
static const CharType kSeparators[];
// A special path component meaning "this directory."
static const CharType kCurrentDirectory[];
// A special path component meaning "the parent directory."
static const CharType kParentDirectory[];
// The character used to identify a file extension.
static const CharType kExtensionSeparator;
// Returns true if ch is a FilePath separator.
static bool isSeparator(CharType ch);
FilePath();
FilePath(const StringType& path);
FilePath(const FilePath& other);
~FilePath();
// Make a copy of the path.
FilePath& operator=(const FilePath& other);
// Operators.
bool operator==(const FilePath& other) const;
bool operator!=(const FilePath& other) const;
bool operator<(const FilePath& other) const;
// Return the path as a string.
const StringType& getPath() const { return m_path; }
// Return true if the path is empty.
bool isEmpty() const { return m_path.empty(); }
// Clear our the path.
void clear();
// Returns a FilePath corresponding to the directory containing ht epath named
// by this object, stripping away the file component.
FilePath dirName() const;
// Returns a FilePath corresponding to the last path component of this object,
// either a file or a directory.
FilePath baseName() const;
// Returns a FilePath by appending a separator and the supplied path component
// to this object's path. Append takes care to avoid adding excessive
// separators if this object's path already ends with a separator.
FilePath append(const StringType& component) const;
FilePath append(const FilePath& component) const;
private:
// Remove trailing separators from this object.
void stripTrailingSeparatorsInternal();
// A string representation of the path in this object.
StringType m_path;
};
// Macro for string literal initialization of FilePath::CharType[].
#if OS(POSIX)
#define FILE_PATH_LITERAL(Str) Str
#elif OS(WIN)
#define FILE_PATH_LITERAL(Str) L##Str
#endif
} // namespace nu
// Provide a std::hash for a FilePath.
namespace std {
template <>
struct hash<nu::FilePath> {
std::size_t operator()(const nu::FilePath& path) const {
using std::hash;
hash<nu::FilePath::StringType> hashFunc;
return hashFunc(path.getPath());
}
};
} // namespace std
#endif // NUCLEUS_FILES_FILE_PATH_H_
| [
"tiaanl@gmail.com"
] | tiaanl@gmail.com |
b454cd095d13947ecd2f29f421294cc7a6d00a15 | 993dc3ab9132772a40b50eec1cd1fa09b5487e1b | /imageeditorengine/inc/MJpegSave.h | 127537c7ea632489a3806f38acce88ef9d1a4d10 | [] | no_license | SymbianSource/oss.FCL.sf.app.imgeditor | c421f8e73b20bdafcead4996aa1b5876f3e081b8 | 77320f0d084576e49b70e92c70921959e1809d35 | refs/heads/master | 2021-01-16T23:03:41.398394 | 2010-11-15T12:21:35 | 2010-11-15T12:21:35 | 68,768,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,259 | h | /*
* Copyright (c) 2010 Ixonos Plc.
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the "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:
* Ixonos Plc
*
* Description:
*
*/
#ifndef __MJPEGSAVE_H__
#define __MJPEGSAVE_H__
#include <e32std.h>
class MJpegSave
{
public:
virtual ~MJpegSave() {}
/// Starts jpeg save
/// @param aSize size of jpeg file
/// @param aExif descriptor containing exif data
/// @param aSaveBufferSize save buffer size in bytes
/// @param aQuality quality factor 0..100
virtual void StartSaveL( const TSize& aSize, TPtr8 aExif, TInt aSaveBufferSize, TInt aQuality ) = 0;
/// Saves one macroblock
/// at the moment macroblocks are 8x8 pixels
/// @param aBitmap 8x8 pixels RGB bitmap 32bits per pixel ( 0RGB )
virtual void SaveBlock( const TBitmapHandle& aBitmap ) = 0;
/// Finalizes the save to file
virtual void FinalizeSave() = 0;
/// Finalizes the save to buffer
/// @return TPtrC8 save buffer descriptor
virtual TPtrC8 Finalize() = 0;
};
#endif
| [
"mikael.laine@ixonos.com"
] | mikael.laine@ixonos.com |
08a1c0175ffecae11b5cff47fa6fc19d9bc58640 | 5abfdfe1b17a1f42009693d57b8354274dcbbfbe | /View/carsview.h | d31079d91f651ca16c2d70bc54918fa0391be8e1 | [] | no_license | gomitolof/CarsCrew | b310a3d6468d1678af32ca130b65105a73906cdc | 49673dbdb995eea03b0c572244f5a8bad34d5c67 | refs/heads/master | 2021-03-27T22:56:45.727229 | 2020-03-16T21:29:55 | 2020-03-16T21:29:55 | 247,815,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,676 | h | #ifndef CARSVIEW_H
#define CARSVIEW_H
#include <QWidget>
class QComboBox;
class QLineEdit;
class insertCar;
class ResearchingCars;
class CarDetail;
class Controller;
class QCloseEvent;
class QListWidget;
class CarsView : public QWidget{
Q_OBJECT
private:
Controller *controller;
QString filename;
QComboBox* attribute;
QLineEdit* searchBar;
QListWidget* list;
insertCar* form;
CarDetail* dialog;
ResearchingCars* results;
protected:
virtual void closeEvent(QCloseEvent *) override;
private slots:
void setResearchValidator(const QString&);
public:
explicit CarsView(bool =false, QWidget* = nullptr);
~CarsView() override;
void add() const;
QString selectedItem() const;
int itemRow() const;
void remove() const;
void remove(int) const;
void removeAll() const;
insertCar* getForm() const;
CarDetail* getCarDetail() const;
ResearchingCars* getResults() const;
QString getFilename() const;
QString getResearchAttribute() const;
QString getResearchKey() const;
QListWidget* getList() const;
void openDialog() const;
void openSportCar(QString, QString, int, double, QString);
void openOffRoadCar(QString, QString, int, double);
void openVintageCar(QString, QString, int, int);
void openRallyCar(QString, QString, int, double, QString, bool);
void setCarName(QString);
void openResearchWindow(QListWidget*);
QString saveAsFilename();
QString saveFilename();
void loadData();
void loadPage(bool =false);
void showEnvironment(QString) const;
void errorMessage(const QString&, const QString&) const;
};
#endif // CarsView_H
| [
"fifreda@hotmail.it"
] | fifreda@hotmail.it |
0b97cece20e56147acf4c13a6627c2a93bf3375c | 03c71398ebae1405492d7e141c1fc6199d37d56f | /Labs/Lab10/Fibonacci.cpp | 0cb90855932500607b5af3290350918469ed2efc | [] | no_license | AStockinger/Cpp-Projects | f40bea19ddd84fb07cc10c1c1e761a82f6bd07b9 | f53d22a1067ddbdb8cacb2e5bbc91f4360916d1c | refs/heads/master | 2020-04-11T20:14:14.455812 | 2018-12-18T04:48:03 | 2018-12-18T04:48:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | cpp | /******************************************************************************
** Program name: Lab 10
** Author: Amy Stockinger
** Date: 11/24/18
** Description: Fibonacci functions
** source: https://www.codeproject.com/tips/109443/fibonacci-recursive-and-non-recursive-c
******************************************************************************/
#include <iostream>
#include "Fibonacci.hpp"
int FibonacciIterative(int N){
int first = 0; // define first 2 fibonacci nums because thats how the rest are calculated
int second = 1;
int counter = 2; // counter is 2 since we already defined the first 2 fibonacci nums
while(counter < N){
int temp = second; // hold one number in a temp since one is used to calculate two
second = first + second; // change the second num
first = temp; // now change the first
counter++;
}
if(N == 0){ // if N = 0, then return 0 as nothing
return 0;
}
else{ // else return the preceding two fibonacci nums added to make the Nth num
return first + second;
}
}
int FibonacciRecursive(int N){
if(N == 0 || N == 1){ // the base cases
return N;
}
else{
return FibonacciRecursive(N - 1) + FibonacciRecursive(N - 2);
}
} | [
"noreply@github.com"
] | noreply@github.com |
7fbaf110c467c24cc5dc8dc5b88e1d80e941f4b5 | a2f9618474d27a9898eaa424da4ce06abcc192e9 | /day 16.cpp | 6f577143becef5ec328c13f874f52aeb32d3dcc9 | [] | no_license | kunal121/C-And-Cpp-Questions | 4299b1ec33b753c381aafd53c94d645b127c68af | af331cec311a5de8835177c16f000b63b5a162f2 | refs/heads/master | 2020-04-05T09:35:57.270507 | 2019-10-19T16:21:41 | 2019-10-19T16:21:41 | 81,636,991 | 12 | 18 | null | 2019-10-19T16:21:42 | 2017-02-11T07:05:20 | C++ | UTF-8 | C++ | false | false | 721 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string.h>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
string S;
cin >> S;
int l;
try
{
//if(l==1)
// cout<<S;
//else
// throw(S);
l=stoi(S);
cout << l;
}
catch(...)
{
cout<<"Bad String";
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
0e50690ae4caf9236ecc83f75351c930dc08b26e | 8eb38bc45be0cfb66baa1a64a97083898176caa0 | /42_Trapping_Rain_Water.cpp | a1bd04cc76383d98a1deb1a8138a7f6b803845b2 | [] | no_license | LeoJY/Leetcode | 9dcb208d77c8adb549329904b74212c9841da51a | 680c4a3f6dd18517f928c6878280844fc9b69219 | refs/heads/master | 2020-05-29T09:16:48.013833 | 2017-01-23T16:28:05 | 2017-01-23T16:28:05 | 69,497,745 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | //42. Trapping Rain Water
//Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
class Solution {
public:
int trap(vector<int>& height) {
int l = 0, r = height.size() - 1, maxleft = 0, maxright = 0, water = 0;
while (l <= r){
if (height[l] < height[r]){
if (height[l] > maxleft) maxleft = height[l++];
else water += maxleft - height[l++];
}
else{
if (height[r] > maxright) maxright = height[r--];
else water += maxright - height[r--];
}
}
return water;
}
};
| [
"leojy1993@gmail.com"
] | leojy1993@gmail.com |
35960bc1560590d74535fbeaa72392475ef7e9c3 | 8c794e65878bd48969f9f20873b8ba249664c948 | /CameraManager.h | 5d9ab86905951015d3e96844cbf94f5db1035994 | [] | no_license | ziggysmalls/LotusEngine | adb343d7b7057ab794543ba3f22e4a74cd0ed7e6 | 5fb5aaaf3c5a2b00fa78d4e5fb0fb6386b6a88f8 | refs/heads/main | 2023-06-05T11:23:11.215918 | 2021-06-15T21:58:26 | 2021-06-15T21:58:26 | 377,301,913 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,231 | h | #ifndef _CameraManager
#define _CameraManager
#include "AzulCore.h"
class CameraManager
{
private:
// private camera references
Camera* currentCamera;
Camera* defaultCamera;
Camera* default2DCamera;
Camera* current2DCamera;
void Delete();
public:
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Gets current camera. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <returns> Null if it fails, else the current camera. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
Camera* GetCurrentCamera();
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Gets current 2D camera. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <returns> Null if it fails, else the current 2D camera. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
Camera* GetCurrent2DCamera();
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Sets a new camera. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <param name="newcam"> [in,out] If non-null, the newcam. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void SetCurrentCamera(Camera* newcam);
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Sets current 2D camera. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <param name="newcam"> [in,out] If non-null, the newcam. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void SetCurrent2DCamera(Camera* newcam);
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Updates Current Camera. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
////////////////////////////////////////////////////////////////////////////////////////////////////
void Update();
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Sets a perspective. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <param name="FieldOfView_Degs"> The field of view in degrees. </param>
/// <param name="AspectRatio"> The aspect ratio. </param>
/// <param name="NearDist"> The near distance. </param>
/// <param name="FarDist"> The far distance. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void setPerspective(const float FieldOfView_Degs, const float AspectRatio, const float NearDist, const float FarDist);
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Sets an orthographic. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <param name="xMin"> The minimum. </param>
/// <param name="xMax"> The maximum. </param>
/// <param name="yMin"> The minimum. </param>
/// <param name="yMax"> The maximum. </param>
/// <param name="zMin"> The minimum. </param>
/// <param name="zMax"> The maximum. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void setOrthographic(const float xMin, const float xMax, const float yMin, const float yMax, const float zMin, const float zMax);
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Sets a viewport. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <param name="inX"> The in x coordinate. </param>
/// <param name="inY"> The in y coordinate. </param>
/// <param name="width"> The width. </param>
/// <param name="height"> The height. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void setViewport(const int inX, const int inY, const int width, const int height);
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Sets orient and position. </summary>
///
/// <remarks> Ezequiel Arrieta, 3/3/2021. </remarks>
///
/// <param name="Up_vect"> The up vect. </param>
/// <param name="inLookAt_pt"> The in look at point. </param>
/// <param name="pos_pt"> The position point. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void setOrientAndPosition(const Vect& Up_vect, const Vect& inLookAt_pt, const Vect& pos_pt);
CameraManager();
CameraManager(const CameraManager&) = delete;
CameraManager& operator=(const CameraManager&) = delete;
~CameraManager();
};
#endif _CameraManager | [
"noreply@github.com"
] | noreply@github.com |
9d4a8f7b3893868c4438ea868b21013b8651e53d | 61bd1270ec9722a9519f0311cf1ecc01f401b2fe | /Codechef/JAN20B/BRKBKS.cpp | 668c4f3f0d482c7b41a1574800756e75c16e7f81 | [] | no_license | GonzaloPereira/CompetitiveProgramming | 495aef87835d13b9f5491b8ac56ef0face9be428 | ffc06d855ca021490cc071b92dd3aa84a978dd5b | refs/heads/main | 2021-11-19T03:34:46.578008 | 2021-08-10T00:46:29 | 2021-08-10T00:46:29 | 190,089,378 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
while(t--){
int a,b,c,s; cin >> s >> a >> b >> c;
if(a+b+c <= s){
cout << 1 << endl;
continue;
}
if(a<c){
if(a+b <= s) cout << 2 <<endl;
else cout << 3 << endl;
}else{
if(b+c <= s) cout << 2 << endl;
else cout << 3 << endl;
}
}
return 0;
} | [
"gonzaloapr45@gmail.com"
] | gonzaloapr45@gmail.com |
2694fa834679f7c9475e17053b5fd16763a74da9 | b677894966f2ae2d0585a31f163a362e41a3eae0 | /ns3/ns-3.26/src/lte/model/lte-ffr-soft-algorithm.cc | 30173f1dcddc4a41051868b1fc8f4eddf8a7bf77 | [
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | cyliustack/clusim | 667a9eef2e1ea8dad1511fd405f3191d150a04a8 | cbedcf671ba19fded26e4776c0e068f81f068dfd | refs/heads/master | 2022-10-06T20:14:43.052930 | 2022-10-01T19:42:19 | 2022-10-01T19:42:19 | 99,692,344 | 7 | 3 | Apache-2.0 | 2018-07-04T10:09:24 | 2017-08-08T12:51:33 | Python | UTF-8 | C++ | false | false | 22,245 | cc | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2014 Piotr Gawlowicz
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Piotr Gawlowicz <gawlowicz.p@gmail.com>
*
*/
#include "lte-ffr-soft-algorithm.h"
#include <ns3/log.h>
#include "ns3/boolean.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("LteFfrSoftAlgorithm");
NS_OBJECT_ENSURE_REGISTERED (LteFfrSoftAlgorithm);
static const struct FfrSoftDownlinkDefaultConfiguration
{
uint8_t cellId;
uint8_t dlBandwidth;
uint8_t dlCommonSubBandwidth;
uint8_t dlEgdeSubBandOffset;
uint8_t dlEdgeSubBandwidth;
} g_ffrSoftDownlinkDefaultConfiguration[] = {
{ 1, 15, 2, 0, 4},
{ 2, 15, 2, 4, 4},
{ 3, 15, 2, 8, 4},
{ 1, 25, 6, 0, 6},
{ 2, 25, 6, 6, 6},
{ 3, 25, 6, 12, 6},
{ 1, 50, 21, 0, 9},
{ 2, 50, 21, 9, 9},
{ 3, 50, 21, 18, 11},
{ 1, 75, 36, 0, 12},
{ 2, 75, 36, 12, 12},
{ 3, 75, 36, 24, 15},
{ 1, 100, 28, 0, 24},
{ 2, 100, 28, 24, 24},
{ 3, 100, 28, 48, 24}
};
static const struct FfrSoftUplinkDefaultConfiguration
{
uint8_t cellId;
uint8_t ulBandwidth;
uint8_t ulCommonSubBandwidth;
uint8_t ulEgdeSubBandOffset;
uint8_t ulEdgeSubBandwidth;
} g_ffrSoftUplinkDefaultConfiguration[] = {
{ 1, 15, 3, 0, 4},
{ 2, 15, 3, 4, 4},
{ 3, 15, 3, 8, 4},
{ 1, 25, 6, 0, 6},
{ 2, 25, 6, 6, 6},
{ 3, 25, 6, 12, 6},
{ 1, 50, 21, 0, 9},
{ 2, 50, 21, 9, 9},
{ 3, 50, 21, 18, 11},
{ 1, 75, 36, 0, 12},
{ 2, 75, 36, 12, 12},
{ 3, 75, 36, 24, 15},
{ 1, 100, 28, 0, 24},
{ 2, 100, 28, 24, 24},
{ 3, 100, 28, 48, 24}
};
const uint16_t NUM_DOWNLINK_CONFS (sizeof (g_ffrSoftDownlinkDefaultConfiguration) / sizeof (FfrSoftDownlinkDefaultConfiguration));
const uint16_t NUM_UPLINK_CONFS (sizeof (g_ffrSoftUplinkDefaultConfiguration) / sizeof (FfrSoftUplinkDefaultConfiguration));
LteFfrSoftAlgorithm::LteFfrSoftAlgorithm ()
: m_ffrSapUser (0),
m_ffrRrcSapUser (0),
m_dlEgdeSubBandOffset (0),
m_dlEdgeSubBandwidth (0),
m_ulEgdeSubBandOffset (0),
m_ulEdgeSubBandwidth (0),
m_measId (0)
{
NS_LOG_FUNCTION (this);
m_ffrSapProvider = new MemberLteFfrSapProvider<LteFfrSoftAlgorithm> (this);
m_ffrRrcSapProvider = new MemberLteFfrRrcSapProvider<LteFfrSoftAlgorithm> (this);
}
LteFfrSoftAlgorithm::~LteFfrSoftAlgorithm ()
{
NS_LOG_FUNCTION (this);
}
void
LteFfrSoftAlgorithm::DoDispose ()
{
NS_LOG_FUNCTION (this);
delete m_ffrSapProvider;
delete m_ffrRrcSapProvider;
}
TypeId
LteFfrSoftAlgorithm::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::LteFfrSoftAlgorithm")
.SetParent<LteFfrAlgorithm> ()
.SetGroupName("Lte")
.AddConstructor<LteFfrSoftAlgorithm> ()
.AddAttribute ("UlCommonSubBandwidth",
"Uplink Medium (Common) SubBandwidth Configuration in number of Resource Block Groups",
UintegerValue (6),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_ulCommonSubBandwidth),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("UlEdgeSubBandOffset",
"Uplink Edge SubBand Offset in number of Resource Block Groups",
UintegerValue (0),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_ulEgdeSubBandOffset),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("UlEdgeSubBandwidth",
"Uplink Edge SubBandwidth Configuration in number of Resource Block Groups",
UintegerValue (6),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_ulEdgeSubBandwidth),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("DlCommonSubBandwidth",
"Downlink Medium (Common) SubBandwidth Configuration in number of Resource Block Groups",
UintegerValue (6),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_dlCommonSubBandwidth),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("DlEdgeSubBandOffset",
"Downlink Edge SubBand Offset in number of Resource Block Groups",
UintegerValue (0),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_dlEgdeSubBandOffset),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("DlEdgeSubBandwidth",
"Downlink Edge SubBandwidth Configuration in number of Resource Block Groups",
UintegerValue (0),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_dlEdgeSubBandwidth),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("CenterRsrqThreshold",
"If the RSRQ of is worse than this threshold, UE should be served in Medium sub-band",
UintegerValue (30),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_centerSubBandThreshold),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("EdgeRsrqThreshold",
"If the RSRQ of is worse than this threshold, UE should be served in Edge sub-band",
UintegerValue (20),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_egdeSubBandThreshold),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("CenterAreaPowerOffset",
"PdschConfigDedicated::Pa value for Center Sub-band, default value dB0",
UintegerValue (5),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_centerAreaPowerOffset),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("MediumAreaPowerOffset",
"PdschConfigDedicated::Pa value for Medium Sub-band, default value dB0",
UintegerValue (5),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_mediumAreaPowerOffset),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("EdgeAreaPowerOffset",
"PdschConfigDedicated::Pa value for Edge Sub-band, default value dB0",
UintegerValue (5),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_edgeAreaPowerOffset),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("CenterAreaTpc",
"TPC value which will be set in DL-DCI for UEs in center area"
"Absolute mode is used, default value 1 is mapped to -1 according to"
"TS36.213 Table 5.1.1.1-2",
UintegerValue (1),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_centerAreaTpc),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("MediumAreaTpc",
"TPC value which will be set in DL-DCI for UEs in medium area"
"Absolute mode is used, default value 1 is mapped to -1 according to"
"TS36.213 Table 5.1.1.1-2",
UintegerValue (1),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_mediumAreaTpc),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("EdgeAreaTpc",
"TPC value which will be set in DL-DCI for UEs in edge area"
"Absolute mode is used, default value 1 is mapped to -1 according to"
"TS36.213 Table 5.1.1.1-2",
UintegerValue (1),
MakeUintegerAccessor (&LteFfrSoftAlgorithm::m_edgeAreaTpc),
MakeUintegerChecker<uint8_t> ())
;
return tid;
}
void
LteFfrSoftAlgorithm::SetLteFfrSapUser (LteFfrSapUser* s)
{
NS_LOG_FUNCTION (this << s);
m_ffrSapUser = s;
}
LteFfrSapProvider*
LteFfrSoftAlgorithm::GetLteFfrSapProvider ()
{
NS_LOG_FUNCTION (this);
return m_ffrSapProvider;
}
void
LteFfrSoftAlgorithm::SetLteFfrRrcSapUser (LteFfrRrcSapUser* s)
{
NS_LOG_FUNCTION (this << s);
m_ffrRrcSapUser = s;
}
LteFfrRrcSapProvider*
LteFfrSoftAlgorithm::GetLteFfrRrcSapProvider ()
{
NS_LOG_FUNCTION (this);
return m_ffrRrcSapProvider;
}
void
LteFfrSoftAlgorithm::DoInitialize ()
{
NS_LOG_FUNCTION (this);
LteFfrAlgorithm::DoInitialize ();
NS_ASSERT_MSG (m_dlBandwidth > 14,"DlBandwidth must be at least 15 to use FFR algorithms");
NS_ASSERT_MSG (m_ulBandwidth > 14,"UlBandwidth must be at least 15 to use FFR algorithms");
if (m_frCellTypeId != 0)
{
SetDownlinkConfiguration (m_frCellTypeId, m_dlBandwidth);
SetUplinkConfiguration (m_frCellTypeId, m_ulBandwidth);
}
NS_LOG_LOGIC (this << " requesting Event A1 measurements"
<< " (threshold = 0" << ")");
LteRrcSap::ReportConfigEutra reportConfig;
reportConfig.eventId = LteRrcSap::ReportConfigEutra::EVENT_A1;
reportConfig.threshold1.choice = LteRrcSap::ThresholdEutra::THRESHOLD_RSRQ;
reportConfig.threshold1.range = 0;
reportConfig.triggerQuantity = LteRrcSap::ReportConfigEutra::RSRQ;
reportConfig.reportInterval = LteRrcSap::ReportConfigEutra::MS120;
m_measId = m_ffrRrcSapUser->AddUeMeasReportConfigForFfr (reportConfig);
}
void
LteFfrSoftAlgorithm::Reconfigure ()
{
NS_LOG_FUNCTION (this);
if (m_frCellTypeId != 0)
{
SetDownlinkConfiguration (m_frCellTypeId, m_dlBandwidth);
SetUplinkConfiguration (m_frCellTypeId, m_ulBandwidth);
}
InitializeDownlinkRbgMaps ();
InitializeUplinkRbgMaps ();
m_needReconfiguration = false;
}
void
LteFfrSoftAlgorithm::SetDownlinkConfiguration (uint16_t cellId, uint8_t bandwidth)
{
NS_LOG_FUNCTION (this);
for (uint16_t i = 0; i < NUM_DOWNLINK_CONFS; ++i)
{
if ((g_ffrSoftDownlinkDefaultConfiguration[i].cellId == cellId)
&& g_ffrSoftDownlinkDefaultConfiguration[i].dlBandwidth == m_dlBandwidth)
{
m_dlCommonSubBandwidth = g_ffrSoftDownlinkDefaultConfiguration[i].dlCommonSubBandwidth;
m_dlEgdeSubBandOffset = g_ffrSoftDownlinkDefaultConfiguration[i].dlEgdeSubBandOffset;
m_dlEdgeSubBandwidth = g_ffrSoftDownlinkDefaultConfiguration[i].dlEdgeSubBandwidth;
}
}
}
void
LteFfrSoftAlgorithm::SetUplinkConfiguration (uint16_t cellId, uint8_t bandwidth)
{
NS_LOG_FUNCTION (this);
for (uint16_t i = 0; i < NUM_UPLINK_CONFS; ++i)
{
if ((g_ffrSoftUplinkDefaultConfiguration[i].cellId == cellId)
&& g_ffrSoftUplinkDefaultConfiguration[i].ulBandwidth == m_ulBandwidth)
{
m_ulCommonSubBandwidth = g_ffrSoftUplinkDefaultConfiguration[i].ulCommonSubBandwidth;
m_ulEgdeSubBandOffset = g_ffrSoftUplinkDefaultConfiguration[i].ulEgdeSubBandOffset;
m_ulEdgeSubBandwidth = g_ffrSoftUplinkDefaultConfiguration[i].ulEdgeSubBandwidth;
}
}
}
void
LteFfrSoftAlgorithm::InitializeDownlinkRbgMaps ()
{
m_dlRbgMap.clear ();
m_dlCenterRbgMap.clear ();
m_dlMediumRbgMap.clear ();
m_dlEdgeRbgMap.clear ();
int rbgSize = GetRbgSize (m_dlBandwidth);
m_dlRbgMap.resize (m_dlBandwidth / rbgSize, false);
m_dlCenterRbgMap.resize (m_dlBandwidth / rbgSize, true);
m_dlMediumRbgMap.resize (m_dlBandwidth / rbgSize, false);
m_dlEdgeRbgMap.resize (m_dlBandwidth / rbgSize, false);
NS_ASSERT_MSG (m_dlCommonSubBandwidth <= m_dlBandwidth,"DlCommonSubBandwidth higher than DlBandwidth");
NS_ASSERT_MSG (m_dlCommonSubBandwidth + m_dlEgdeSubBandOffset <= m_dlBandwidth,
"DlCommonSubBandwidth + DlEgdeSubBandOffset higher than DlBandwidth");
NS_ASSERT_MSG (m_dlEgdeSubBandOffset <= m_dlBandwidth,"DlEgdeSubBandOffset higher than DlBandwidth");
NS_ASSERT_MSG (m_dlEdgeSubBandwidth <= m_dlBandwidth,"DlEdgeSubBandwidth higher than DlBandwidth");
NS_ASSERT_MSG ((m_dlCommonSubBandwidth + m_dlEgdeSubBandOffset + m_dlEdgeSubBandwidth) <= m_dlBandwidth,
"(DlCommonSubBandwidth + DlEgdeSubBandOffset+DlEdgeSubBandwidth) higher than DlBandwidth");
for (uint8_t i = 0;
i < m_dlCommonSubBandwidth / rbgSize; i++)
{
m_dlMediumRbgMap[i] = true;
m_dlCenterRbgMap[i] = false;
}
for (uint8_t i = (m_dlCommonSubBandwidth + m_dlEgdeSubBandOffset) / rbgSize;
i < (m_dlCommonSubBandwidth + m_dlEgdeSubBandOffset + m_dlEdgeSubBandwidth) / rbgSize; i++)
{
m_dlEdgeRbgMap[i] = true;
m_dlCenterRbgMap[i] = false;
}
}
void
LteFfrSoftAlgorithm::InitializeUplinkRbgMaps ()
{
m_ulRbgMap.clear ();
m_ulCenterRbgMap.clear ();
m_ulMediumRbgMap.clear ();
m_ulEdgeRbgMap.clear ();
m_ulRbgMap.resize (m_ulBandwidth, false);
m_ulCenterRbgMap.resize (m_ulBandwidth, true);
m_ulMediumRbgMap.resize (m_ulBandwidth, false);
m_ulEdgeRbgMap.resize (m_ulBandwidth, false);
NS_ASSERT_MSG (m_ulCommonSubBandwidth <= m_ulBandwidth,"UlCommonSubBandwidth higher than UlBandwidth");
NS_ASSERT_MSG (m_ulCommonSubBandwidth + m_ulEgdeSubBandOffset <= m_ulBandwidth,
"UlCommonSubBandwidth + UlEgdeSubBandOffset higher than UlBandwidth");
NS_ASSERT_MSG (m_ulEgdeSubBandOffset <= m_ulBandwidth,"UlEgdeSubBandOffset higher than UlBandwidth");
NS_ASSERT_MSG (m_ulEdgeSubBandwidth <= m_ulBandwidth,"UlEdgeSubBandwidth higher than UlBandwidth");
NS_ASSERT_MSG ((m_ulCommonSubBandwidth + m_ulEgdeSubBandOffset + m_ulEdgeSubBandwidth) <= m_ulBandwidth,
"(UlCommonSubBandwidth + UlEgdeSubBandOffset+UlEdgeSubBandwidth) higher than UlBandwidth");
for (uint8_t i = 0;
i < m_ulCommonSubBandwidth; i++)
{
m_ulMediumRbgMap[i] = true;
m_ulCenterRbgMap[i] = false;
}
for (uint8_t i = (m_ulCommonSubBandwidth + m_ulEgdeSubBandOffset);
i < (m_ulCommonSubBandwidth + m_ulEgdeSubBandOffset + m_ulEdgeSubBandwidth); i++)
{
m_ulEdgeRbgMap[i] = true;
m_ulCenterRbgMap[i] = false;
}
}
std::vector <bool>
LteFfrSoftAlgorithm::DoGetAvailableDlRbg ()
{
NS_LOG_FUNCTION (this);
if (m_needReconfiguration)
{
Reconfigure ();
}
if (m_dlRbgMap.empty ())
{
InitializeDownlinkRbgMaps ();
}
return m_dlRbgMap;
}
bool
LteFfrSoftAlgorithm::DoIsDlRbgAvailableForUe (int rbgId, uint16_t rnti)
{
NS_LOG_FUNCTION (this);
bool isCenterRbg = m_dlCenterRbgMap[rbgId];
bool isMediumRbg = m_dlMediumRbgMap[rbgId];
bool isEdgeRbg = m_dlEdgeRbgMap[rbgId];
std::map< uint16_t, uint8_t >::iterator it = m_ues.find (rnti);
if (it == m_ues.end ())
{
m_ues.insert (std::pair< uint16_t, uint8_t > (rnti, AreaUnset));
}
it = m_ues.find (rnti);
//if UE area is unknown, serve UE in medium (common) RBGs
if (it->second == AreaUnset)
{
return isMediumRbg;
}
bool isCenterUe = false;
bool isMediumUe = false;
bool isEdgeUe = false;
if (it->second == CenterArea )
{
isCenterUe = true;
}
else if (it->second == MediumArea)
{
isMediumUe = true;
}
else if (it->second == EdgeArea)
{
isEdgeUe = true;
}
return (isCenterRbg && isCenterUe) || (isMediumRbg && isMediumUe) || (isEdgeRbg && isEdgeUe);
}
std::vector <bool>
LteFfrSoftAlgorithm::DoGetAvailableUlRbg ()
{
NS_LOG_FUNCTION (this);
if (m_ulRbgMap.empty ())
{
InitializeUplinkRbgMaps ();
}
return m_ulRbgMap;
}
bool
LteFfrSoftAlgorithm::DoIsUlRbgAvailableForUe (int rbgId, uint16_t rnti)
{
NS_LOG_FUNCTION (this);
if (!m_enabledInUplink)
{
return true;
}
bool isCenterRbg = m_ulCenterRbgMap[rbgId];
bool isMediumRbg = m_ulMediumRbgMap[rbgId];
bool isEdgeRbg = m_ulEdgeRbgMap[rbgId];
std::map< uint16_t, uint8_t >::iterator it = m_ues.find (rnti);
if (it == m_ues.end ())
{
m_ues.insert (std::pair< uint16_t, uint8_t > (rnti, AreaUnset));
}
it = m_ues.find (rnti);
//if UE area is unknown, serve UE in medium (common) RBGs
if (it->second == AreaUnset)
{
return isMediumRbg;
}
bool isCenterUe = false;
bool isMediumUe = false;
bool isEdgeUe = false;
if (it->second == CenterArea )
{
isCenterUe = true;
}
else if (it->second == MediumArea)
{
isMediumUe = true;
}
else if (it->second == EdgeArea)
{
isEdgeUe = true;
}
return (isCenterRbg && isCenterUe) || (isMediumRbg && isMediumUe) || (isEdgeRbg && isEdgeUe);
}
void
LteFfrSoftAlgorithm::DoReportDlCqiInfo (const struct FfMacSchedSapProvider::SchedDlCqiInfoReqParameters& params)
{
NS_LOG_FUNCTION (this);
NS_LOG_WARN ("Method should not be called, because it is empty");
}
void
LteFfrSoftAlgorithm::DoReportUlCqiInfo (const struct FfMacSchedSapProvider::SchedUlCqiInfoReqParameters& params)
{
NS_LOG_FUNCTION (this);
NS_LOG_WARN ("Method should not be called, because it is empty");
}
void
LteFfrSoftAlgorithm::DoReportUlCqiInfo (std::map <uint16_t, std::vector <double> > ulCqiMap)
{
NS_LOG_FUNCTION (this);
NS_LOG_WARN ("Method should not be called, because it is empty");
}
uint8_t
LteFfrSoftAlgorithm::DoGetTpc (uint16_t rnti)
{
NS_LOG_FUNCTION (this);
if (!m_enabledInUplink)
{
return 1; // 1 is mapped to 0 for Accumulated mode, and to -1 in Absolute mode TS36.213 Table 5.1.1.1-2
}
//TS36.213 Table 5.1.1.1-2
// TPC | Accumulated Mode | Absolute Mode
//------------------------------------------------
// 0 | -1 | -4
// 1 | 0 | -1
// 2 | 1 | 1
// 3 | 3 | 4
//------------------------------------------------
// here Absolute mode is used
std::map< uint16_t, uint8_t >::iterator it = m_ues.find (rnti);
if (it == m_ues.end ())
{
return 1;
}
if (it->second == CenterArea )
{
return m_centerAreaTpc;
}
else if (it->second == MediumArea)
{
return m_mediumAreaTpc;
}
else if (it->second == EdgeArea)
{
return m_edgeAreaTpc;
}
return 1;
}
uint8_t
LteFfrSoftAlgorithm::DoGetMinContinuousUlBandwidth ()
{
NS_LOG_FUNCTION (this);
if (!m_enabledInUplink)
{
return m_ulBandwidth;
}
uint8_t centerSubBandwidth = 0;
uint8_t mediumSubBandwidth = 0;
uint8_t edgeSubBandwidth = 0;
for (uint8_t i = 0; i < m_ulCenterRbgMap.size (); i++)
{
if ( m_ulCenterRbgMap[i] == true)
{
centerSubBandwidth++;
}
}
for (uint8_t i = 0; i < m_ulMediumRbgMap.size (); i++)
{
if ( m_ulMediumRbgMap[i] == true)
{
mediumSubBandwidth++;
}
}
for (uint8_t i = 0; i < m_ulEdgeRbgMap.size (); i++)
{
if ( m_ulEdgeRbgMap[i] == true)
{
edgeSubBandwidth++;
}
}
uint8_t minContinuousUlBandwidth = m_ulBandwidth;
minContinuousUlBandwidth =
((centerSubBandwidth > 0 ) && (centerSubBandwidth < minContinuousUlBandwidth)) ? centerSubBandwidth : minContinuousUlBandwidth;
minContinuousUlBandwidth =
((mediumSubBandwidth > 0 ) && (mediumSubBandwidth < minContinuousUlBandwidth)) ? mediumSubBandwidth : minContinuousUlBandwidth;
minContinuousUlBandwidth =
((edgeSubBandwidth > 0 ) && (edgeSubBandwidth < minContinuousUlBandwidth)) ? edgeSubBandwidth : minContinuousUlBandwidth;
NS_LOG_INFO ("minContinuousUlBandwidth: " << (int)minContinuousUlBandwidth);
return minContinuousUlBandwidth;
}
void
LteFfrSoftAlgorithm::DoReportUeMeas (uint16_t rnti,
LteRrcSap::MeasResults measResults)
{
NS_LOG_FUNCTION (this << rnti << (uint16_t) measResults.measId);
NS_LOG_INFO ("RNTI :" << rnti << " MeasId: " << (uint16_t) measResults.measId
<< " RSRP: " << (uint16_t)measResults.rsrpResult
<< " RSRQ: " << (uint16_t)measResults.rsrqResult);
NS_ASSERT_MSG (m_centerSubBandThreshold >= m_egdeSubBandThreshold,
"CenterSubBandThreshold must be higher than EgdeSubBandThreshold");
if (measResults.measId != m_measId)
{
NS_LOG_WARN ("Ignoring measId " << (uint16_t) measResults.measId);
}
else
{
std::map< uint16_t, uint8_t >::iterator it = m_ues.find (rnti);
if (it == m_ues.end ())
{
m_ues.insert (std::pair< uint16_t, uint8_t > (rnti, AreaUnset));
}
it = m_ues.find (rnti);
if (measResults.rsrqResult >= m_centerSubBandThreshold)
{
if (it->second != CenterArea)
{
NS_LOG_INFO ("UE RNTI: " << rnti << " will be served in Center sub-band");
it->second = CenterArea;
LteRrcSap::PdschConfigDedicated pdschConfigDedicated;
pdschConfigDedicated.pa = m_centerAreaPowerOffset;
m_ffrRrcSapUser->SetPdschConfigDedicated (rnti, pdschConfigDedicated);
}
}
else if (measResults.rsrqResult < m_egdeSubBandThreshold)
{
if (it->second != EdgeArea )
{
NS_LOG_INFO ("UE RNTI: " << rnti << " will be served in Edge sub-band");
it->second = EdgeArea;
LteRrcSap::PdschConfigDedicated pdschConfigDedicated;
pdschConfigDedicated.pa = m_edgeAreaPowerOffset;
m_ffrRrcSapUser->SetPdschConfigDedicated (rnti, pdschConfigDedicated);
}
}
else
{
if (it->second != MediumArea)
{
NS_LOG_INFO ("UE RNTI: " << rnti << " will be served in Medium sub-band");
it->second = MediumArea;
LteRrcSap::PdschConfigDedicated pdschConfigDedicated;
pdschConfigDedicated.pa = m_mediumAreaPowerOffset;
m_ffrRrcSapUser->SetPdschConfigDedicated (rnti, pdschConfigDedicated);
}
}
}
}
void
LteFfrSoftAlgorithm::DoRecvLoadInformation (EpcX2Sap::LoadInformationParams params)
{
NS_LOG_FUNCTION (this);
NS_LOG_WARN ("Method should not be called, because it is empty");
}
} // end of namespace ns3
| [
"you@example.com"
] | you@example.com |
de82c0bba13232b1629c5adfdb4f8ea673c359e1 | a8b16548143b33b3760dbffa98314b0ae12b4367 | /Milestones/Milestone4/NonPerishable.h | 1e09ef075c143f2162f9923c7c73f2d9c336a8ec | [] | no_license | rdella84/Workshops | bd388188e0a059abc7715b5af2f5204bbc05087a | 601a2a5cb3d027fecb95c27dffc913a427acea11 | refs/heads/master | 2021-01-22T06:44:17.954223 | 2017-04-12T03:40:09 | 2017-04-12T03:40:09 | 81,781,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | h | #ifndef ICT_NONPERISHABLE_H__
#define ICT_NONPERISHABLE_H__
#include <iostream>
#include "Item.h"
#include "Error.h"
using namespace std;
namespace ict {
class NonPerishable : public Item {
Error m_err;
protected:
bool ok()const;
void error(const char* message);
virtual char signature()const;
public:
fstream& save(std::fstream& file)const;
fstream& load(std::fstream& file);
ostream& write(ostream& ostr, bool linear)const;
istream& read(std::istream& is);
// Tax cal
const double ttlCost()const;
};
}
#endif | [
"regio.della84@gmail.com"
] | regio.della84@gmail.com |
5185f151eab5bc5a25914baee9d2da0aee75caf2 | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /components/arc/net/arc_net_host_impl.cc | 09caeb9c66c59b912175ddb08bfb8731a2972c43 | [
"BSD-3-Clause"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 23,234 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/arc/net/arc_net_host_impl.h"
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "chromeos/login/login_state.h"
#include "chromeos/network/managed_network_configuration_handler.h"
#include "chromeos/network/network_connection_handler.h"
#include "chromeos/network/network_handler.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/network_type_pattern.h"
#include "chromeos/network/network_util.h"
#include "chromeos/network/onc/onc_utils.h"
#include "components/arc/arc_bridge_service.h"
namespace {
const int kGetNetworksListLimit = 100;
chromeos::NetworkStateHandler* GetStateHandler() {
return chromeos::NetworkHandler::Get()->network_state_handler();
}
chromeos::ManagedNetworkConfigurationHandler* GetManagedConfigurationHandler() {
return chromeos::NetworkHandler::Get()
->managed_network_configuration_handler();
}
chromeos::NetworkConnectionHandler* GetNetworkConnectionHandler() {
return chromeos::NetworkHandler::Get()->network_connection_handler();
}
bool IsDeviceOwner() {
// Check whether the logged-in Chrome OS user is allowed to add or
// remove WiFi networks.
return chromeos::LoginState::Get()->GetLoggedInUserType() ==
chromeos::LoginState::LOGGED_IN_USER_OWNER;
}
std::string GetStringFromOncDictionary(const base::DictionaryValue* dict,
const char* key,
bool required) {
std::string value;
dict->GetString(key, &value);
if (required && value.empty())
NOTREACHED();
return value;
}
arc::mojom::SecurityType TranslateONCWifiSecurityType(
const base::DictionaryValue* dict) {
std::string type = GetStringFromOncDictionary(dict, onc::wifi::kSecurity,
true /* required */);
if (type == onc::wifi::kWEP_PSK)
return arc::mojom::SecurityType::WEP_PSK;
else if (type == onc::wifi::kWEP_8021X)
return arc::mojom::SecurityType::WEP_8021X;
else if (type == onc::wifi::kWPA_PSK)
return arc::mojom::SecurityType::WPA_PSK;
else if (type == onc::wifi::kWPA_EAP)
return arc::mojom::SecurityType::WPA_EAP;
else
return arc::mojom::SecurityType::NONE;
}
arc::mojom::WiFiPtr TranslateONCWifi(const base::DictionaryValue* dict) {
arc::mojom::WiFiPtr wifi = arc::mojom::WiFi::New();
// Optional; defaults to 0.
dict->GetInteger(onc::wifi::kFrequency, &wifi->frequency);
wifi->bssid =
GetStringFromOncDictionary(dict, onc::wifi::kBSSID, false /* required */);
wifi->hex_ssid = GetStringFromOncDictionary(dict, onc::wifi::kHexSSID,
true /* required */);
// Optional; defaults to false.
dict->GetBoolean(onc::wifi::kHiddenSSID, &wifi->hidden_ssid);
wifi->security = TranslateONCWifiSecurityType(dict);
// Optional; defaults to 0.
dict->GetInteger(onc::wifi::kSignalStrength, &wifi->signal_strength);
return wifi;
}
mojo::Array<mojo::String> TranslateStringArray(const base::ListValue* list) {
mojo::Array<mojo::String> strings = mojo::Array<mojo::String>::New(0);
for (size_t i = 0; i < list->GetSize(); i++) {
std::string value;
list->GetString(i, &value);
DCHECK(!value.empty());
strings.push_back(static_cast<mojo::String>(value));
}
return strings;
}
mojo::Array<arc::mojom::IPConfigurationPtr> TranslateONCIPConfigs(
const base::ListValue* list) {
mojo::Array<arc::mojom::IPConfigurationPtr> configs =
mojo::Array<arc::mojom::IPConfigurationPtr>::New(0);
for (size_t i = 0; i < list->GetSize(); i++) {
const base::DictionaryValue* ip_dict = nullptr;
arc::mojom::IPConfigurationPtr configuration =
arc::mojom::IPConfiguration::New();
list->GetDictionary(i, &ip_dict);
DCHECK(ip_dict);
// crbug.com/625229 - Gateway is not always present (but it should be).
configuration->gateway = GetStringFromOncDictionary(
ip_dict, onc::ipconfig::kGateway, false /* required */);
configuration->ip_address = GetStringFromOncDictionary(
ip_dict, onc::ipconfig::kIPAddress, true /* required */);
const base::ListValue* dns_list;
if (!ip_dict->GetList(onc::ipconfig::kNameServers, &dns_list))
NOTREACHED();
configuration->name_servers = TranslateStringArray(dns_list);
if (!ip_dict->GetInteger(onc::ipconfig::kRoutingPrefix,
&configuration->routing_prefix)) {
NOTREACHED();
}
std::string type = GetStringFromOncDictionary(ip_dict, onc::ipconfig::kType,
true /* required */);
configuration->type = type == onc::ipconfig::kIPv6
? arc::mojom::IPAddressType::IPV6
: arc::mojom::IPAddressType::IPV4;
configuration->web_proxy_auto_discovery_url = GetStringFromOncDictionary(
ip_dict, onc::ipconfig::kWebProxyAutoDiscoveryUrl,
false /* required */);
configs.push_back(std::move(configuration));
}
return configs;
}
arc::mojom::ConnectionStateType TranslateONCConnectionState(
const base::DictionaryValue* dict) {
std::string connection_state = GetStringFromOncDictionary(
dict, onc::network_config::kConnectionState, true /* required */);
if (connection_state == onc::connection_state::kConnected)
return arc::mojom::ConnectionStateType::CONNECTED;
else if (connection_state == onc::connection_state::kConnecting)
return arc::mojom::ConnectionStateType::CONNECTING;
else if (connection_state == onc::connection_state::kNotConnected)
return arc::mojom::ConnectionStateType::NOT_CONNECTED;
NOTREACHED();
return arc::mojom::ConnectionStateType::NOT_CONNECTED;
}
void TranslateONCNetworkTypeDetails(const base::DictionaryValue* dict,
arc::mojom::NetworkConfiguration* mojo) {
std::string type = GetStringFromOncDictionary(
dict, onc::network_config::kType, true /* required */);
if (type == onc::network_type::kCellular) {
mojo->type = arc::mojom::NetworkType::CELLULAR;
} else if (type == onc::network_type::kEthernet) {
mojo->type = arc::mojom::NetworkType::ETHERNET;
} else if (type == onc::network_type::kVPN) {
mojo->type = arc::mojom::NetworkType::VPN;
} else if (type == onc::network_type::kWiFi) {
mojo->type = arc::mojom::NetworkType::WIFI;
const base::DictionaryValue* wifi_dict = nullptr;
dict->GetDictionary(onc::network_config::kWiFi, &wifi_dict);
DCHECK(wifi_dict);
mojo->wifi = TranslateONCWifi(wifi_dict);
} else if (type == onc::network_type::kWimax) {
mojo->type = arc::mojom::NetworkType::WIMAX;
} else {
NOTREACHED();
}
}
arc::mojom::NetworkConfigurationPtr TranslateONCConfiguration(
const base::DictionaryValue* dict) {
arc::mojom::NetworkConfigurationPtr mojo =
arc::mojom::NetworkConfiguration::New();
mojo->connection_state = TranslateONCConnectionState(dict);
mojo->guid = GetStringFromOncDictionary(dict, onc::network_config::kGUID,
true /* required */);
const base::ListValue* ip_config_list = nullptr;
if (dict->GetList(onc::network_config::kIPConfigs, &ip_config_list)) {
DCHECK(ip_config_list);
mojo->ip_configs = TranslateONCIPConfigs(ip_config_list);
}
mojo->guid = GetStringFromOncDictionary(dict, onc::network_config::kGUID,
true /* required */);
mojo->mac_address = GetStringFromOncDictionary(
dict, onc::network_config::kMacAddress, true /* required */);
TranslateONCNetworkTypeDetails(dict, mojo.get());
return mojo;
}
void ForgetNetworkSuccessCallback(
const arc::mojom::NetHost::ForgetNetworkCallback& mojo_callback) {
mojo_callback.Run(arc::mojom::NetworkResult::SUCCESS);
}
void ForgetNetworkFailureCallback(
const arc::mojom::NetHost::ForgetNetworkCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "ForgetNetworkFailureCallback: " << error_name;
mojo_callback.Run(arc::mojom::NetworkResult::FAILURE);
}
void StartConnectSuccessCallback(
const arc::mojom::NetHost::StartConnectCallback& mojo_callback) {
mojo_callback.Run(arc::mojom::NetworkResult::SUCCESS);
}
void StartConnectFailureCallback(
const arc::mojom::NetHost::StartConnectCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "StartConnectFailureCallback: " << error_name;
mojo_callback.Run(arc::mojom::NetworkResult::FAILURE);
}
void StartDisconnectSuccessCallback(
const arc::mojom::NetHost::StartDisconnectCallback& mojo_callback) {
mojo_callback.Run(arc::mojom::NetworkResult::SUCCESS);
}
void StartDisconnectFailureCallback(
const arc::mojom::NetHost::StartDisconnectCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "StartDisconnectFailureCallback: " << error_name;
mojo_callback.Run(arc::mojom::NetworkResult::FAILURE);
}
void GetDefaultNetworkSuccessCallback(
const arc::ArcNetHostImpl::GetDefaultNetworkCallback& callback,
const std::string& service_path,
const base::DictionaryValue& dictionary) {
// TODO(cernekee): Figure out how to query Chrome for the default physical
// service if a VPN is connected, rather than just reporting the
// default logical service in both fields.
callback.Run(TranslateONCConfiguration(&dictionary),
TranslateONCConfiguration(&dictionary));
}
void GetDefaultNetworkFailureCallback(
const arc::ArcNetHostImpl::GetDefaultNetworkCallback& callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
LOG(ERROR) << "Failed to query default logical network";
callback.Run(nullptr, nullptr);
}
void DefaultNetworkFailureCallback(
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
LOG(ERROR) << "Failed to query default logical network";
}
} // namespace
namespace arc {
ArcNetHostImpl::ArcNetHostImpl(ArcBridgeService* bridge_service)
: ArcService(bridge_service), binding_(this), weak_factory_(this) {
arc_bridge_service()->net()->AddObserver(this);
GetStateHandler()->AddObserver(this, FROM_HERE);
}
ArcNetHostImpl::~ArcNetHostImpl() {
DCHECK(thread_checker_.CalledOnValidThread());
arc_bridge_service()->net()->RemoveObserver(this);
if (chromeos::NetworkHandler::IsInitialized()) {
GetStateHandler()->RemoveObserver(this, FROM_HERE);
}
}
void ArcNetHostImpl::OnInstanceReady() {
DCHECK(thread_checker_.CalledOnValidThread());
mojom::NetHostPtr host;
binding_.Bind(GetProxy(&host));
arc_bridge_service()->net()->instance()->Init(std::move(host));
}
void ArcNetHostImpl::GetNetworksDeprecated(
bool configured_only,
bool visible_only,
const GetNetworksDeprecatedCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
if (configured_only && visible_only) {
VLOG(1) << "Illegal arguments - both configured and visible networks "
"requested.";
return;
}
mojom::GetNetworksRequestType type =
mojom::GetNetworksRequestType::CONFIGURED_ONLY;
if (visible_only) {
type = mojom::GetNetworksRequestType::VISIBLE_ONLY;
}
GetNetworks(type, callback);
}
void ArcNetHostImpl::GetNetworks(mojom::GetNetworksRequestType type,
const GetNetworksCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
mojom::NetworkDataPtr data = mojom::NetworkData::New();
bool configured_only = true;
bool visible_only = false;
if (type == mojom::GetNetworksRequestType::VISIBLE_ONLY) {
configured_only = false;
visible_only = true;
}
// Retrieve list of nearby wifi networks
chromeos::NetworkTypePattern network_pattern =
chromeos::onc::NetworkTypePatternFromOncType(onc::network_type::kWiFi);
std::unique_ptr<base::ListValue> network_properties_list =
chromeos::network_util::TranslateNetworkListToONC(
network_pattern, configured_only, visible_only,
kGetNetworksListLimit);
// Extract info for each network and add it to the list.
// Even if there's no WiFi, an empty (size=0) list must be returned and not a
// null one. The explicitly sized New() constructor ensures the non-null
// property.
mojo::Array<mojom::WifiConfigurationPtr> networks =
mojo::Array<mojom::WifiConfigurationPtr>::New(0);
for (const auto& value : *network_properties_list) {
mojom::WifiConfigurationPtr wc = mojom::WifiConfiguration::New();
base::DictionaryValue* network_dict = nullptr;
value->GetAsDictionary(&network_dict);
DCHECK(network_dict);
// kName is a post-processed version of kHexSSID.
std::string tmp;
network_dict->GetString(onc::network_config::kName, &tmp);
DCHECK(!tmp.empty());
wc->ssid = tmp;
tmp.clear();
network_dict->GetString(onc::network_config::kGUID, &tmp);
DCHECK(!tmp.empty());
wc->guid = tmp;
base::DictionaryValue* wifi_dict = nullptr;
network_dict->GetDictionary(onc::network_config::kWiFi, &wifi_dict);
DCHECK(wifi_dict);
if (!wifi_dict->GetInteger(onc::wifi::kFrequency, &wc->frequency))
wc->frequency = 0;
if (!wifi_dict->GetInteger(onc::wifi::kSignalStrength,
&wc->signal_strength))
wc->signal_strength = 0;
if (!wifi_dict->GetString(onc::wifi::kSecurity, &tmp))
NOTREACHED();
DCHECK(!tmp.empty());
wc->security = tmp;
if (!wifi_dict->GetString(onc::wifi::kBSSID, &tmp))
NOTREACHED();
DCHECK(!tmp.empty());
wc->bssid = tmp;
mojom::VisibleNetworkDetailsPtr details =
mojom::VisibleNetworkDetails::New();
details->frequency = wc->frequency;
details->signal_strength = wc->signal_strength;
details->bssid = wc->bssid;
wc->details = mojom::NetworkDetails::New();
wc->details->set_visible(std::move(details));
networks.push_back(std::move(wc));
}
data->networks = std::move(networks);
callback.Run(std::move(data));
}
void ArcNetHostImpl::CreateNetworkSuccessCallback(
const arc::mojom::NetHost::CreateNetworkCallback& mojo_callback,
const std::string& service_path,
const std::string& guid) {
VLOG(1) << "CreateNetworkSuccessCallback";
cached_guid_ = guid;
cached_service_path_ = service_path;
mojo_callback.Run(guid);
}
void ArcNetHostImpl::CreateNetworkFailureCallback(
const arc::mojom::NetHost::CreateNetworkCallback& mojo_callback,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> error_data) {
VLOG(1) << "CreateNetworkFailureCallback: " << error_name;
mojo_callback.Run("");
}
void ArcNetHostImpl::CreateNetwork(mojom::WifiConfigurationPtr cfg,
const CreateNetworkCallback& callback) {
if (!IsDeviceOwner()) {
callback.Run("");
return;
}
std::unique_ptr<base::DictionaryValue> properties(new base::DictionaryValue);
std::unique_ptr<base::DictionaryValue> wifi_dict(new base::DictionaryValue);
if (cfg->hexssid.is_null() || !cfg->details) {
callback.Run("");
return;
}
mojom::ConfiguredNetworkDetailsPtr details =
std::move(cfg->details->get_configured());
if (!details) {
callback.Run("");
return;
}
properties->SetStringWithoutPathExpansion(onc::network_config::kType,
onc::network_config::kWiFi);
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kHexSSID,
cfg->hexssid.get());
wifi_dict->SetBooleanWithoutPathExpansion(onc::wifi::kAutoConnect,
details->autoconnect);
if (cfg->security.get().empty()) {
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kSecurity,
onc::wifi::kSecurityNone);
} else {
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kSecurity,
cfg->security.get());
if (!details->passphrase.is_null()) {
wifi_dict->SetStringWithoutPathExpansion(onc::wifi::kPassphrase,
details->passphrase.get());
}
}
properties->SetWithoutPathExpansion(onc::network_config::kWiFi,
std::move(wifi_dict));
std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
GetManagedConfigurationHandler()->CreateConfiguration(
user_id_hash, *properties,
base::Bind(&ArcNetHostImpl::CreateNetworkSuccessCallback,
weak_factory_.GetWeakPtr(), callback),
base::Bind(&ArcNetHostImpl::CreateNetworkFailureCallback,
weak_factory_.GetWeakPtr(), callback));
}
bool ArcNetHostImpl::GetNetworkPathFromGuid(const std::string& guid,
std::string* path) {
const chromeos::NetworkState* network =
GetStateHandler()->GetNetworkStateFromGuid(guid);
if (network) {
*path = network->path();
return true;
}
if (cached_guid_ == guid) {
*path = cached_service_path_;
return true;
} else {
return false;
}
}
void ArcNetHostImpl::ForgetNetwork(const mojo::String& guid,
const ForgetNetworkCallback& callback) {
if (!IsDeviceOwner()) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
std::string path;
if (!GetNetworkPathFromGuid(guid, &path)) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
cached_guid_.clear();
GetManagedConfigurationHandler()->RemoveConfiguration(
path, base::Bind(&ForgetNetworkSuccessCallback, callback),
base::Bind(&ForgetNetworkFailureCallback, callback));
}
void ArcNetHostImpl::StartConnect(const mojo::String& guid,
const StartConnectCallback& callback) {
std::string path;
if (!GetNetworkPathFromGuid(guid, &path)) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
GetNetworkConnectionHandler()->ConnectToNetwork(
path, base::Bind(&StartConnectSuccessCallback, callback),
base::Bind(&StartConnectFailureCallback, callback), false);
}
void ArcNetHostImpl::StartDisconnect(const mojo::String& guid,
const StartDisconnectCallback& callback) {
std::string path;
if (!GetNetworkPathFromGuid(guid, &path)) {
callback.Run(mojom::NetworkResult::FAILURE);
return;
}
GetNetworkConnectionHandler()->DisconnectNetwork(
path, base::Bind(&StartDisconnectSuccessCallback, callback),
base::Bind(&StartDisconnectFailureCallback, callback));
}
void ArcNetHostImpl::GetWifiEnabledState(
const GetWifiEnabledStateCallback& callback) {
bool is_enabled = GetStateHandler()->IsTechnologyEnabled(
chromeos::NetworkTypePattern::WiFi());
callback.Run(is_enabled);
}
void ArcNetHostImpl::SetWifiEnabledState(
bool is_enabled,
const SetWifiEnabledStateCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
chromeos::NetworkStateHandler::TechnologyState state =
GetStateHandler()->GetTechnologyState(
chromeos::NetworkTypePattern::WiFi());
// WiFi can't be enabled or disabled in these states.
if ((state == chromeos::NetworkStateHandler::TECHNOLOGY_PROHIBITED) ||
(state == chromeos::NetworkStateHandler::TECHNOLOGY_UNINITIALIZED) ||
(state == chromeos::NetworkStateHandler::TECHNOLOGY_UNAVAILABLE)) {
VLOG(1) << "SetWifiEnabledState failed due to WiFi state: " << state;
callback.Run(false);
} else {
GetStateHandler()->SetTechnologyEnabled(
chromeos::NetworkTypePattern::WiFi(), is_enabled,
chromeos::network_handler::ErrorCallback());
callback.Run(true);
}
}
void ArcNetHostImpl::StartScan() {
GetStateHandler()->RequestScan();
}
void ArcNetHostImpl::ScanCompleted(const chromeos::DeviceState* /*unused*/) {
if (!arc_bridge_service()->net()->instance()) {
VLOG(2) << "NetInstance not ready yet";
return;
}
if (arc_bridge_service()->net()->version() < 1) {
VLOG(1) << "NetInstance does not support ScanCompleted.";
return;
}
arc_bridge_service()->net()->instance()->ScanCompleted();
}
void ArcNetHostImpl::GetDefaultNetwork(
const GetDefaultNetworkCallback& callback) {
const chromeos::NetworkState* default_network =
GetStateHandler()->DefaultNetwork();
if (!default_network) {
VLOG(1) << "GetDefaultNetwork: no default network";
callback.Run(nullptr, nullptr);
return;
}
VLOG(1) << "GetDefaultNetwork: default network is "
<< default_network->path();
std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
GetManagedConfigurationHandler()->GetProperties(
user_id_hash, default_network->path(),
base::Bind(&GetDefaultNetworkSuccessCallback, callback),
base::Bind(&GetDefaultNetworkFailureCallback, callback));
}
void ArcNetHostImpl::DefaultNetworkSuccessCallback(
const std::string& service_path,
const base::DictionaryValue& dictionary) {
if (!arc_bridge_service()->net()->instance()) {
VLOG(2) << "NetInstance is null.";
return;
}
arc_bridge_service()->net()->instance()->DefaultNetworkChanged(
TranslateONCConfiguration(&dictionary),
TranslateONCConfiguration(&dictionary));
}
void ArcNetHostImpl::DefaultNetworkChanged(
const chromeos::NetworkState* network) {
if (arc_bridge_service()->net()->version() < 2) {
VLOG(1) << "ArcBridgeService does not support DefaultNetworkChanged.";
return;
}
if (!network) {
VLOG(1) << "No default network";
arc_bridge_service()->net()->instance()->DefaultNetworkChanged(nullptr,
nullptr);
return;
}
VLOG(1) << "New default network: " << network->path();
std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
GetManagedConfigurationHandler()->GetProperties(
user_id_hash, network->path(),
base::Bind(&arc::ArcNetHostImpl::DefaultNetworkSuccessCallback,
weak_factory_.GetWeakPtr()),
base::Bind(&DefaultNetworkFailureCallback));
}
void ArcNetHostImpl::DeviceListChanged() {
if (arc_bridge_service()->net()->version() < 3) {
VLOG(1) << "ArcBridgeService does not support DeviceListChanged.";
return;
}
bool is_enabled = GetStateHandler()->IsTechnologyEnabled(
chromeos::NetworkTypePattern::WiFi());
arc_bridge_service()->net()->instance()->WifiEnabledStateChanged(is_enabled);
}
void ArcNetHostImpl::OnShuttingDown() {
GetStateHandler()->RemoveObserver(this, FROM_HERE);
}
} // namespace arc
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
f5c1429250d46c1594c821aab95d4286d02cd290 | 7524106d9776f24311be4e6050cedd2a10e31282 | /problems/uva/pid/x725/xmain_725.cpp | 099bf9b5ac8fdc235485b904b25f7fb128d08e39 | [] | no_license | Exr0nProjects/learn_cpp | f0d0ab1fd26adaea18d711c3cce16d63e0b2a7dc | c0fcb9783fa4ce76701fe234599bc13876cc4083 | refs/heads/master | 2023-04-11T08:19:42.923015 | 2021-01-27T02:41:35 | 2021-01-27T02:41:35 | 180,021,931 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,533 | cpp | /*
ID: spoytie2
TASK: 725
LANG: C++14
*/
/*
* Problem 725 (onlinejudge/pid/725)
* Create time: Sun 26 Jan 2020 @ 13:26 (PST)
* Accept time: Sun 26 Jan 2020 @ 14:22 (PST)
*
*/
#include <iostream>
#include <cstdio>
#include <tuple>
#include <vector>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <random>
#include <chrono>
#include <utility>
#include <exception>
#include <algorithm>
#include <functional>
#define cn const int
#define ll long long
#define cl const long long
#define ca const auto &
#define vi vector<int>
#define pii pair<int, int>
#define vii vector<pii>
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define INF 0x7FFFFFFF
// for macro overloading, see https://stackoverflow.com/questions/11761703/overloading-macro-on-number-of-arguments
// this set is designed for one indexed collections
#define FOR_(i, b, e) for (int i = (b); i < (e); ++i)
#define FOR(i, e) FOR_(i, 0, (e))
#define FORR_(i, b, e) for (int i = (e)-1; i >= (b); --i)
#define FORR(i, e) FORR_(i, 0, e)
#define SORT(a, n) std::sort((a), (a) + (n))
#define TRAV(a, x) for (auto &a : x)
#define SORTV(v) std::sort((v).begin(), (v).end())
void setIO(const std::string &name = "725");
typedef struct
{
int f, t, w, n;
} Edge;
#define TRAVE(s, e) for (int e = head[s]; e; e = edges[e].n)
const int MX = -1;
//#define __USING_EDGELIST
//void addEdge(cn a, cn b, cn w=1);
//Edge edges[MX*MX];
//int ect=1, head[MX];
using namespace std;
int N;
int calc()
{
double a = 0, b = 0;
return a == b * N;
}
int main()
{
setIO();
scanf("%d", &N);
int first = true;
while (N > 0)
{
if (first)
first = false;
else
printf("\n");
bool flag = 0;
FOR_(fli, 1234, 99999)
{
int used[10] = {};
FOR(i, 5)
{
used[(fli / (int)pow(10, i)) % 10] = true;
}
int top = N * fli;
if (top / 100000)
continue; // too big
FOR(i, 5)
{
used[top / (int)pow(10, i) % 10] = true;
}
int sz = 0;
FOR(i, 10)
sz += used[i];
if (sz == 10 && N * fli == top)
{
flag = true;
printf("%05d / %05d = %d\n", top, fli, N);
}
}
if (!flag)
{
printf("There are no solutions for %d.\n", N);
}
scanf("%d", &N);
}
return 0;
}
// boilerplate functions
void setIO(const string &name)
{
ios_base::sync_with_stdio(0);
cin.tie(0); // fast cin/cout
if (fopen((name + ".in").c_str(), "r") != nullptr)
{
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w+", stdout);
}
}
/*
Benjamin Qi
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)
#define pb push_back
*/
/*
thecodingwizard
#define FOR(i, a, b) for (int i=a; i<(b); i++)
#define F0R(i, a) for (int i=0; i<(a); i++)
#define FORd(i,a,b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)
#define SORT(vec) sort(vec.begin(), vec.end())
#define INF 1000000000
#define LL_INF 4500000000000000000
#define LSOne(S) (S & (-S))
#define EPS 1e-9
#define A first
#define B second
#define mp make_pair
#define pb push_back
#define PI acos(-1.0)
#define ll long long
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
*/
| [
"spotyie@gmail.com"
] | spotyie@gmail.com |
2b8d1139cdc264f4eb1000bf05b8eb4967c78c18 | 7ee32ddb0cdfdf1993aa4967e1045790690d7089 | /Topcoder/PowerPlants.cpp | 9d69413e7b904a2b117f7aa724e671a6caff7086 | [] | no_license | ajimenezh/Programing-Contests | b9b91c31814875fd5544d63d7365b3fc20abd354 | ad47d1f38b780de46997f16fbaa3338c9aca0e1a | refs/heads/master | 2020-12-24T14:56:14.154367 | 2017-10-16T21:05:01 | 2017-10-16T21:05:01 | 11,746,917 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,065 | cpp | #include <iostream>
#include <sstream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <utility>
#include <set>
#include <map>
#include <deque>
#include <queue>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <stdio.h>
using namespace std;
#define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
class PowerPlants {
public:
int minCost(vector <string> connectionCost, string plantList, int numPlants) ;
};
int cost[20][20];
int n;
int dp[1<<16];
int m;
int solve(int mask) {
if (__builtin_popcount(mask)>=m) return 0;
if (dp[mask]>=0) return dp[mask];
int tmp = 100000000;
for (int i=0; i<n; i++) if ((1<<i)&mask) {
for (int j=0; j<n; j++) if (((1<<j)&mask)==0) {
tmp = min(tmp, cost[i][j] + solve(mask | (1<<j)));
}
}
tmp = min(tmp, 100000000);
dp[mask] = tmp;
return tmp;
}
int PowerPlants::minCost(vector <string> connectionCost, string plantList, int numPlants) {
m = numPlants;
n = plantList.length();
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
if (connectionCost[i][j]>='0' && connectionCost[i][j]<='9') {
cost[i][j] = connectionCost[i][j] - '0';
}
else cost[i][j] = connectionCost[i][j] - 'A' + 10;
}
}
for (int i=0; i<(1<<n); i++) dp[i] = -1;
int mask = 0;
for (int i=0; i<n; i++) if (plantList[i]=='Y') mask |= (1<<i);
int res = solve(mask);
if (res==100000000) return -1;
return res;
};
//BEGIN CUT HERE
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 1)
{
cout << "Testing PowerPlants (500.0 points)" << endl << endl;
for (int i = 0; i < 20; i++)
{
ostringstream s; s << argv[0] << " " << i;
int exitCode = system(s.str().c_str());
if (exitCode)
cout << "#" << i << ": Runtime Error" << endl;
}
int T = time(NULL)-1394025096;
double PT = T/60.0, TT = 75.0;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
cout << endl;
cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl;
cout << "Score : " << 500.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl;
}
else
{
int _tc; istringstream(argv[1]) >> _tc;
PowerPlants _obj;
int _expected, _received;
time_t _start = clock();
switch (_tc)
{
case 0:
{
string connectionCost[] = {"024",
"203",
"430"};
string plantList = "YNN";
int numPlants = 3;
_expected = 5;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}
case 1:
{
string connectionCost[] = {"0AB",
"A0C",
"CD0"};
string plantList = "YNN";
int numPlants = 3;
_expected = 21;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}
case 2:
{
string connectionCost[] = {"1ABCD",
"35HF8",
"FDM31",
"AME93",
"01390"};
string plantList = "NYNNN";
int numPlants = 5;
_expected = 14;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}
case 3:
{
string connectionCost[] = {"012",
"123",
"234"};
string plantList = "NNY";
int numPlants = 2;
_expected = 2;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}
case 4:
{
string connectionCost[] = {"1309328",
"DS2389U",
"92EJFAN",
"928FJNS",
"FJS0DJF",
"9FWJW0E",
"23JFNFS"};
string plantList = "YYNYYNY";
int numPlants = 4;
_expected = 0;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}
case 5:
{
string connectionCost[] = {"01","20"};
string plantList = "YN";
int numPlants = 2;
_expected = 1;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}
/*case 6:
{
string connectionCost[] = ;
string plantList = ;
int numPlants = ;
_expected = ;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}*/
/*case 7:
{
string connectionCost[] = ;
string plantList = ;
int numPlants = ;
_expected = ;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}*/
/*case 8:
{
string connectionCost[] = ;
string plantList = ;
int numPlants = ;
_expected = ;
_received = _obj.minCost(vector <string>(connectionCost, connectionCost+sizeof(connectionCost)/sizeof(string)), plantList, numPlants); break;
}*/
default: return 0;
}
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC;
if (_received == _expected)
cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl;
else
{
cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl;
cout << " Expected: " << _expected << endl;
cout << " Received: " << _received << endl;
}
}
}
//END CUT HERE
| [
"alejandrojh90@gmail.com"
] | alejandrojh90@gmail.com |
22a41692686eafaef628f0c315ab89192beba3a0 | 4622598e3ed7bb693b95d59663bdf69dbf678b9c | /Source (2).cpp | 040f473ac9b3c3f56847219f00bc02f44b4198ab | [] | no_license | roman-blyschak/LB3 | c19117bd8a369107944aa65bcc662c3d74814a56 | febf56e673ff8091061f0a97b946eb5b8215a76a | refs/heads/master | 2022-09-08T05:45:07.080108 | 2020-05-18T19:19:52 | 2020-05-18T19:19:52 | 265,038,512 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 937 | cpp | #include <iostream>
#include <stdio.h>
#include <iomanip>
using namespace std;
void func(int** arr, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
arr[i][j] = 1;
}
for (int j = i + 1; j < n - i - 1; j++) {
arr[i][j] = 0;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << setw(4) << arr[i][j];
cout << endl;
}
}
int main()
{
setlocale(LC_ALL, "Ukr");
int** arr, n;
cout << "Âåäiòü ðîçìið ìàòðèöi: ";
cin >> n;
cout << "-----------------------------------------------------" << endl;
arr = new int* [n];
for (int i = 0; i < n; i++)
{
arr[i] = new int[n];
}
func(arr, n);
for (int i = 0; i < n; i++)
{
delete[] arr[i];
}
delete[] arr;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
cfe384fbf54c4795d433a38d62571b361dc395ef | 664b5e8e92b44eecc14e60390152bdaee864b70a | /framework/src/gui/kernel/dwevent.h | aaf3b05a5bd3c55066997d4581efd36b6cf4cb7e | [] | no_license | JerryZhou/Raccoon | a44f178ec47e3eb8181d05e6ca870d02c75477e8 | f8da3ddf82f0e5d2918d890eafbff77a61025d1e | refs/heads/master | 2016-09-05T20:24:23.866920 | 2013-10-25T08:14:53 | 2013-10-25T08:14:53 | 8,606,064 | 8 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,971 | h | #pragma once
#include "dweventid.h"
#include "dwgui/dwrttiobject.h"
//------------------------------------------------------------------------------
class DwGraphicsView;
class DwGraphicsItem;
// NB! DWEVENT AND SUBCLASS MUST SUPPORT THE COPY AND ASSIGN CONSTUCTOR
//------------------------------------------------------------------------------
class DW_GUI_EXPORT DwEvent : public DwRttiObject
{
DW_DECLARE_EVENTID(DwEvent);
public:
DwEvent();
virtual ~DwEvent();
inline void setAccepted(bool accepted);
inline bool isAccepted() const;
inline void accept();
inline void ignore();
inline void setUp(bool up);
inline bool isUp() const;
inline void setBacktrace(bool need);
inline bool isBacktrace() const;
inline void setTraced(bool traced);
inline bool isTraced() const;
inline void setMarked(bool mark);
inline bool isMarked() const;
bool isA(const DwEventId *) const;
protected:
uint16_t m_accept : 1;
uint16_t m_dir : 1;
uint16_t m_backtrace : 1;
uint16_t m_traced : 1;
uint16_t m_reserved : 12;
private:
};// end of DwEvent
//------------------------------------------------------------------------------
/**
*/
inline void DwEvent::setAccepted(bool accepted)
{
m_accept = accepted;
}
//------------------------------------------------------------------------------
/**
*/
inline bool DwEvent::isAccepted() const
{
return m_accept;
}
//------------------------------------------------------------------------------
/**
*/
inline void DwEvent::accept()
{
m_accept = true;
}
//------------------------------------------------------------------------------
/**
*/
inline void DwEvent::ignore()
{
m_accept = false;
}
//------------------------------------------------------------------------------
/**
*/
inline void DwEvent::setUp(bool up)
{
m_dir = !up;
}
//------------------------------------------------------------------------------
/**
*/
inline bool DwEvent::isUp() const
{
return !m_dir;
}
//------------------------------------------------------------------------------
/**
*/
inline void DwEvent::setBacktrace(bool need)
{
m_backtrace = need;
}
//------------------------------------------------------------------------------
/**
*/
inline bool DwEvent::isBacktrace() const
{
return m_backtrace;
}
//------------------------------------------------------------------------------
/**
*/
inline void DwEvent::setTraced(bool traced)
{
m_traced = traced;
}
//------------------------------------------------------------------------------
/**
*/
inline bool DwEvent::isTraced() const
{
return m_traced;
}
//------------------------------------------------------------------------------
/**
*/
inline void DwEvent::setMarked(bool mark)
{
m_reserved = mark;
}
//------------------------------------------------------------------------------
/**
*/
inline bool DwEvent::isMarked() const
{
return !!(m_reserved);
} | [
"jerryzhou@outlook.com"
] | jerryzhou@outlook.com |
98be774abf23d03bea2a9cdef3220ab706d7196c | 46d0d46130689a1593cfb50d0420841dc21b1bdd | /MakeAndBreak/Math.cpp | 034ff9ebb4a78d70c0b9b179139829e7fadc3e58 | [] | no_license | aida147/MakeAndBreak | 4161d5137b270c2cd01f48d11d47c99d59fdbd1b | 9c27f246f3e86ccf3c4500f070d79b9c79f0d9d9 | refs/heads/master | 2016-08-12T07:22:44.230753 | 2015-11-01T21:00:10 | 2015-11-01T21:00:10 | 45,356,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | cpp | /*
* Math.cpp
*
* Created on: Jul 11, 2013
* Author: aida
*/
#include "Math.h"
namespace FM {
float EPS = 1e-6;
float abs(float a) { return a > 0 ? a : -a; }
bool equ(float a, float b) { return abs(a-b) < EPS; }
bool less(float a, float b) { return a + EPS < b; }
bool greater(float a, float b) { return less(b, a); }
bool lequ(float a, float b) { return a < b + EPS; }
bool gequ(float a, float b) { return lequ(b, a); }
bool min(float a, float b) { return a < b ? a : b; }
bool max(float a, float b) { return a > b ? a : b; }
}
| [
"aida.khosroshahi@gmail.com"
] | aida.khosroshahi@gmail.com |
5db1b37534931641ea58c5fbf8b018744c1a0088 | 96e4a63fa13c9de227961e17d030fa83ba0ccc72 | /binaryTreePaths.cpp | f8082425f8e0aea15939c62c4fb1e5035615d439 | [] | no_license | githubwlh2014/leetcode | ba9c4d1b7e418a67a2591f483a115b410dda2045 | e7373971695382fc0fe7c328611299c7009eb52f | refs/heads/master | 2021-01-10T10:47:04.019674 | 2016-04-26T12:48:19 | 2016-04-26T12:48:19 | 43,340,390 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,668 | cpp | #include<iostream>
#include<string>
#include<vector>
using namespace std;
string itoa(int m)
{
if(m==0)
return "0";
if(m==-2147483648)
return "-2147483648";
string tag="";
string str="";
if(m<0)
{
tag+='-';
m=-m;
}
while(m)
{
str=char(m%10+'0')+str;
m/=10;
}
str=tag+str;
return str;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void searchPaths(TreeNode* root,vector<string>& contains,vector<int>& stackOfNode)
{
if(root==NULL)
return ;
stackOfNode.push_back(root->val);
if(root->left==NULL&&root->right==NULL)
{
string str=itoa(stackOfNode[0]); //转换
for(int i=1;i<stackOfNode.size();i++)
{
str+="->"+itoa(stackOfNode[i]); //转换
}
contains.push_back(str);
}else
{
searchPaths(root->left,contains,stackOfNode);
searchPaths(root->right,contains,stackOfNode);
}
stackOfNode.erase(stackOfNode.end()-1);//如果此处用的不是引用,即可省去这一步
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> contains;
vector<int> stackOfNode;
if(!root)
contains;
searchPaths(root,contains,stackOfNode);
return contains;
}
int main()
{
TreeNode t1(1);
TreeNode t2(2);
TreeNode t3(3);
TreeNode t4(4);
t4.left=&t2;
t2.left=&t1;
t2.right=&t3;
vector<string> contains=binaryTreePaths(&t4);
for(int i=0;i<contains.size();i++)
cout<<contains[i]<<endl;
}
| [
"812799024@qq.com"
] | 812799024@qq.com |
2509b84804282f7596432696063fd3371a1e468a | 215a0b63ec1cd97d37e9f4d0ffca5dd90e6bcd1e | /BattleTank/Source/BattleTank/Public/TankPlayerController.h | 6e85ad6f112c8ffb3d1a63cf5c2e6c7c2b87e4e8 | [] | no_license | eah3699/04_Battle-Tank | ab05e15d61a73a94eb19315fa2a5e5e8b026cc4b | 9a7643134464ca2df9aabcccc68811ed65df2052 | refs/heads/master | 2021-01-18T20:46:50.902975 | 2016-10-16T18:47:40 | 2016-10-16T18:47:40 | 69,809,983 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Tank.h"
#include "GameFramework/PlayerController.h"
#include "TankPlayerController.generated.h" // Must be the last include
/**
*
*/
UCLASS()
class BATTLETANK_API ATankPlayerController : public APlayerController
{
GENERATED_BODY()
private:
ATank* GetControlledTank() const;
virtual void BeginPlay() override;
virtual void Tick(float DeltaTime) override;
// Start the tank moving the barrel so that a shot would hit where
// the crosshair intersects the world
void AimTowardsCrosshair();
// Return an OUT parameter, true if hit landscape
bool GetSightRayHitLocation(FVector& HitLocation) const;
UPROPERTY(EditAnywhere)
float CrosshairXLocation = 0.5;
UPROPERTY(EditAnywhere)
float CrosshairYLocation = 0.3333;
bool GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const;
bool GetLookVectorHitLocation(FVector LookDirection, FVector& HitLocation) const;
UPROPERTY(EditAnywhere)
float LineTraceRange = 1000000;
};
| [
"eah3699@gmail.com"
] | eah3699@gmail.com |
dee2845f5046030676cc7c28e7f8cd80363da5aa | 7e6a80713d00a973e11e89bde411c46534a6e40f | /win9x/scrnmng.cpp | 689ec8aca1b2e20268eaede20bf1501a25e8ca87 | [] | no_license | takamichih/np2_t | a55a2c0c2ee4896bf7d8e8773e89e4404b556816 | 45f3d8191df49b1881eb8ff0b88fdfeb8d0e406d | refs/heads/master | 2021-01-10T02:47:14.971114 | 2016-02-16T15:40:19 | 2016-02-16T15:40:19 | 52,145,261 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 24,079 | cpp | /**
* @file scrnmng.cpp
* @brief Screen Manager (DirectDraw2)
*
* @author $Author: yui $
* @date $Date: 2011/03/07 09:54:11 $
*/
#include "compiler.h"
#include <ddraw.h>
#ifndef __GNUC__
#include <winnls32.h>
#endif
#include "resource.h"
#include "np2.h"
#include "winloc.h"
#include "mousemng.h"
#include "scrnmng.h"
// #include "sysmng.h"
#include "np2class.h"
#include "pccore.h"
#include "scrndraw.h"
#include "palettes.h"
#if defined(SUPPORT_DCLOCK)
#include "subwnd\dclock.h"
#endif
#include "recvideo.h"
#if !defined(__GNUC__)
#pragma comment(lib, "ddraw.lib")
#pragma comment(lib, "dxguid.lib")
#endif // !defined(__GNUC__)
//! 8BPP パレット数
#define PALLETES_8BPP NP2PAL_TEXT3
extern WINLOCEX np2_winlocexallwin(HWND base);
typedef struct {
LPDIRECTDRAW ddraw1;
LPDIRECTDRAW2 ddraw2;
LPDIRECTDRAWSURFACE primsurf;
LPDIRECTDRAWSURFACE backsurf;
#if defined(SUPPORT_DCLOCK)
LPDIRECTDRAWSURFACE clocksurf;
#endif
LPDIRECTDRAWCLIPPER clipper;
LPDIRECTDRAWPALETTE palette;
UINT scrnmode;
int width;
int height;
int extend;
int cliping;
RGB32 pal16mask;
UINT8 r16b;
UINT8 l16r;
UINT8 l16g;
UINT8 menudisp;
int menusize;
RECT scrn;
RECT rect;
RECT scrnclip;
RECT rectclip;
PALETTEENTRY pal[256];
} DDRAW;
typedef struct {
int width;
int height;
int extend;
int multiple;
} SCRNSTAT;
static DDRAW ddraw;
SCRNMNG scrnmng;
static SCRNSTAT scrnstat;
static SCRNSURF scrnsurf;
static void setwindowsize(HWND hWnd, int width, int height)
{
RECT workrc;
SystemParametersInfo(SPI_GETWORKAREA, 0, &workrc, 0);
const int scx = GetSystemMetrics(SM_CXSCREEN);
const int scy = GetSystemMetrics(SM_CYSCREEN);
UINT cnt = 2;
do
{
RECT rectwindow;
GetWindowRect(hWnd, &rectwindow);
RECT rectclient;
GetClientRect(hWnd, &rectclient);
int winx = (np2oscfg.winx != CW_USEDEFAULT) ? np2oscfg.winx : rectwindow.left;
int winy = (np2oscfg.winy != CW_USEDEFAULT) ? np2oscfg.winy : rectwindow.top;
int cx = width;
cx += np2oscfg.paddingx * 2;
cx += rectwindow.right - rectwindow.left;
cx -= rectclient.right - rectclient.left;
int cy = height;
cy += np2oscfg.paddingy * 2;
cy += rectwindow.bottom - rectwindow.top;
cy -= rectclient.bottom - rectclient.top;
if (scx < cx)
{
winx = (scx - cx) / 2;
}
else
{
if ((winx + cx) > workrc.right)
{
winx = workrc.right - cx;
}
if (winx < workrc.left)
{
winx = workrc.left;
}
}
if (scy < cy)
{
winy = (scy - cy) / 2;
}
else
{
if ((winy + cy) > workrc.bottom)
{
winy = workrc.bottom - cy;
}
if (winy < workrc.top)
{
winy = workrc.top;
}
}
MoveWindow(hWnd, winx, winy, cx, cy, TRUE);
} while (--cnt);
}
static void renewalclientsize(BOOL winloc) {
int width;
int height;
int extend;
UINT fscrnmod;
int multiple;
int scrnwidth;
int scrnheight;
int tmpcy;
WINLOCEX wlex;
width = min(scrnstat.width, ddraw.width);
height = min(scrnstat.height, ddraw.height);
extend = 0;
// 描画範囲〜
if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) {
ddraw.rect.right = width;
ddraw.rect.bottom = height;
scrnwidth = width;
scrnheight = height;
fscrnmod = np2oscfg.fscrnmod & FSCRNMOD_ASPECTMASK;
switch(fscrnmod) {
default:
case FSCRNMOD_NORESIZE:
break;
case FSCRNMOD_ASPECTFIX8:
scrnwidth = (ddraw.width << 3) / width;
scrnheight = (ddraw.height << 3) / height;
multiple = min(scrnwidth, scrnheight);
scrnwidth = (width * multiple) >> 3;
scrnheight = (height * multiple) >> 3;
break;
case FSCRNMOD_ASPECTFIX:
scrnwidth = ddraw.width;
scrnheight = (scrnwidth * height) / width;
if (scrnheight >= ddraw.height) {
scrnheight = ddraw.height;
scrnwidth = (scrnheight * width) / height;
}
break;
case FSCRNMOD_LARGE:
scrnwidth = ddraw.width;
scrnheight = ddraw.height;
break;
}
ddraw.scrn.left = (ddraw.width - scrnwidth) / 2;
ddraw.scrn.top = (ddraw.height - scrnheight) / 2;
ddraw.scrn.right = ddraw.scrn.left + scrnwidth;
ddraw.scrn.bottom = ddraw.scrn.top + scrnheight;
// メニュー表示時の描画領域
ddraw.rectclip = ddraw.rect;
ddraw.scrnclip = ddraw.scrn;
if (ddraw.scrnclip.top < ddraw.menusize) {
ddraw.scrnclip.top = ddraw.menusize;
tmpcy = ddraw.height - ddraw.menusize;
if (scrnheight > tmpcy) {
switch(fscrnmod) {
default:
case FSCRNMOD_NORESIZE:
tmpcy = min(tmpcy, height);
ddraw.rectclip.bottom = tmpcy;
break;
case FSCRNMOD_ASPECTFIX8:
case FSCRNMOD_ASPECTFIX:
ddraw.rectclip.bottom = (tmpcy * height) / scrnheight;
break;
case FSCRNMOD_LARGE:
break;
}
}
ddraw.scrnclip.bottom = ddraw.menusize + tmpcy;
}
}
else {
multiple = scrnstat.multiple;
if (!(ddraw.scrnmode & SCRNMODE_ROTATE)) {
if ((np2oscfg.paddingx) && (multiple == 8)) {
extend = min(scrnstat.extend, ddraw.extend);
}
scrnwidth = (width * multiple) >> 3;
scrnheight = (height * multiple) >> 3;
ddraw.rect.right = width + extend;
ddraw.rect.bottom = height;
ddraw.scrn.left = np2oscfg.paddingx - extend;
ddraw.scrn.top = np2oscfg.paddingy;
}
else {
if ((np2oscfg.paddingy) && (multiple == 8)) {
extend = min(scrnstat.extend, ddraw.extend);
}
scrnwidth = (height * multiple) >> 3;
scrnheight = (width * multiple) >> 3;
ddraw.rect.right = height;
ddraw.rect.bottom = width + extend;
ddraw.scrn.left = np2oscfg.paddingx;
ddraw.scrn.top = np2oscfg.paddingy - extend;
}
ddraw.scrn.right = np2oscfg.paddingx + scrnwidth;
ddraw.scrn.bottom = np2oscfg.paddingy + scrnheight;
wlex = NULL;
if (winloc) {
wlex = np2_winlocexallwin(g_hWndMain);
}
winlocex_setholdwnd(wlex, g_hWndMain);
setwindowsize(g_hWndMain, scrnwidth, scrnheight);
winlocex_move(wlex);
winlocex_destroy(wlex);
}
scrnsurf.width = width;
scrnsurf.height = height;
scrnsurf.extend = extend;
}
static void clearoutofrect(const RECT *target, const RECT *base) {
LPDIRECTDRAWSURFACE primsurf;
DDBLTFX ddbf;
RECT rect;
primsurf = ddraw.primsurf;
if (primsurf == NULL) {
return;
}
ZeroMemory(&ddbf, sizeof(ddbf));
ddbf.dwSize = sizeof(ddbf);
ddbf.dwFillColor = 0;
rect.left = base->left;
rect.right = base->right;
rect.top = base->top;
rect.bottom = target->top;
if (rect.top < rect.bottom) {
primsurf->Blt(&rect, NULL, NULL, DDBLT_COLORFILL, &ddbf);
}
rect.top = target->bottom;
rect.bottom = base->bottom;
if (rect.top < rect.bottom) {
primsurf->Blt(&rect, NULL, NULL, DDBLT_COLORFILL, &ddbf);
}
rect.top = max(base->top, target->top);
rect.bottom = min(base->bottom, target->bottom);
if (rect.top < rect.bottom) {
rect.left = base->left;
rect.right = target->left;
if (rect.left < rect.right) {
primsurf->Blt(&rect, NULL, NULL, DDBLT_COLORFILL, &ddbf);
}
rect.left = target->right;
rect.right = base->right;
if (rect.left < rect.right) {
primsurf->Blt(&rect, NULL, NULL, DDBLT_COLORFILL, &ddbf);
}
}
}
static void clearoutscreen(void) {
RECT base;
POINT clipt;
RECT target;
GetClientRect(g_hWndMain, &base);
clipt.x = 0;
clipt.y = 0;
ClientToScreen(g_hWndMain, &clipt);
base.left += clipt.x;
base.top += clipt.y;
base.right += clipt.x;
base.bottom += clipt.y;
target.left = base.left + ddraw.scrn.left;
target.top = base.top + ddraw.scrn.top;
target.right = base.left + ddraw.scrn.right;
target.bottom = base.top + ddraw.scrn.bottom;
clearoutofrect(&target, &base);
}
static void clearoutfullscreen(void) {
RECT base;
const RECT *scrn;
base.left = 0;
base.top = 0;
base.right = ddraw.width;
base.bottom = ddraw.height;
if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU)) {
scrn = &ddraw.scrn;
base.top = 0;
}
else {
scrn = &ddraw.scrnclip;
base.top = ddraw.menusize;
}
clearoutofrect(scrn, &base);
#if defined(SUPPORT_DCLOCK)
DispClock::GetInstance()->Redraw();
#endif
}
static void paletteinit()
{
HDC hdc = GetDC(g_hWndMain);
GetSystemPaletteEntries(hdc, 0, 256, ddraw.pal);
ReleaseDC(g_hWndMain, hdc);
#if defined(SUPPORT_DCLOCK)
const RGB32* pal32 = DispClock::GetInstance()->GetPalettes();
for (UINT i = 0; i < 4; i++)
{
ddraw.pal[i + START_PALORG].peBlue = pal32[i].p.b;
ddraw.pal[i + START_PALORG].peRed = pal32[i].p.r;
ddraw.pal[i + START_PALORG].peGreen = pal32[i].p.g;
ddraw.pal[i + START_PALORG].peFlags = PC_RESERVED | PC_NOCOLLAPSE;
}
#endif
for (UINT i = 0; i < PALLETES_8BPP; i++)
{
ddraw.pal[i + START_PAL].peFlags = PC_RESERVED | PC_NOCOLLAPSE;
}
ddraw.ddraw2->CreatePalette(DDPCAPS_8BIT, ddraw.pal, &ddraw.palette, 0);
ddraw.primsurf->SetPalette(ddraw.palette);
}
static void paletteset()
{
if (ddraw.palette != NULL)
{
for (UINT i = 0; i < PALLETES_8BPP; i++)
{
ddraw.pal[i + START_PAL].peRed = np2_pal32[i].p.r;
ddraw.pal[i + START_PAL].peBlue = np2_pal32[i].p.b;
ddraw.pal[i + START_PAL].peGreen = np2_pal32[i].p.g;
}
ddraw.palette->SetEntries(0, START_PAL, PALLETES_8BPP, &ddraw.pal[START_PAL]);
}
}
static void make16mask(DWORD bmask, DWORD rmask, DWORD gmask) {
UINT8 sft;
sft = 0;
while((!(bmask & 0x80)) && (sft < 32)) {
bmask <<= 1;
sft++;
}
ddraw.pal16mask.p.b = (UINT8)bmask;
ddraw.r16b = sft;
sft = 0;
while((rmask & 0xffffff00) && (sft < 32)) {
rmask >>= 1;
sft++;
}
ddraw.pal16mask.p.r = (UINT8)rmask;
ddraw.l16r = sft;
sft = 0;
while((gmask & 0xffffff00) && (sft < 32)) {
gmask >>= 1;
sft++;
}
ddraw.pal16mask.p.g = (UINT8)gmask;
ddraw.l16g = sft;
}
// ----
void scrnmng_initialize(void) {
scrnstat.width = 640;
scrnstat.height = 400;
scrnstat.extend = 1;
scrnstat.multiple = 8;
setwindowsize(g_hWndMain, 640, 400);
}
BRESULT scrnmng_create(UINT8 scrnmode) {
DWORD winstyle;
DWORD winstyleex;
LPDIRECTDRAW2 ddraw2;
DDSURFACEDESC ddsd;
DDPIXELFORMAT ddpf;
int width;
int height;
UINT bitcolor;
UINT fscrnmod;
DEVMODE devmode;
ZeroMemory(&scrnmng, sizeof(scrnmng));
winstyle = GetWindowLong(g_hWndMain, GWL_STYLE);
winstyleex = GetWindowLong(g_hWndMain, GWL_EXSTYLE);
if (scrnmode & SCRNMODE_FULLSCREEN) {
scrnmode &= ~SCRNMODE_ROTATEMASK;
scrnmng.flag = SCRNFLAG_FULLSCREEN;
winstyle &= ~(WS_CAPTION | WS_SYSMENU | WS_THICKFRAME);
winstyle |= WS_POPUP;
winstyleex |= WS_EX_TOPMOST;
ddraw.menudisp = 0;
ddraw.menusize = GetSystemMetrics(SM_CYMENU);
np2class_enablemenu(g_hWndMain, FALSE);
}
else {
scrnmng.flag = SCRNFLAG_HAVEEXTEND;
winstyle |= WS_SYSMENU;
if (np2oscfg.thickframe) {
winstyle |= WS_THICKFRAME;
}
if (np2oscfg.wintype < 2) {
winstyle |= WS_CAPTION;
}
winstyle &= ~WS_POPUP;
winstyleex &= ~WS_EX_TOPMOST;
}
SetWindowLong(g_hWndMain, GWL_STYLE, winstyle);
SetWindowLong(g_hWndMain, GWL_EXSTYLE, winstyleex);
if (DirectDrawCreate(NULL, &ddraw.ddraw1, NULL) != DD_OK) {
goto scre_err;
}
ddraw.ddraw1->QueryInterface(IID_IDirectDraw2, (void **)&ddraw2);
ddraw.ddraw2 = ddraw2;
if (scrnmode & SCRNMODE_FULLSCREEN) {
#if defined(SUPPORT_DCLOCK)
DispClock::GetInstance()->Initialize();
#endif
ddraw2->SetCooperativeLevel(g_hWndMain,
DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
width = np2oscfg.fscrn_cx;
height = np2oscfg.fscrn_cy;
bitcolor = np2oscfg.fscrnbpp;
fscrnmod = np2oscfg.fscrnmod;
if ((fscrnmod & (FSCRNMOD_SAMERES | FSCRNMOD_SAMEBPP)) &&
(EnumDisplaySettings(NULL, ENUM_REGISTRY_SETTINGS, &devmode))) {
if (fscrnmod & FSCRNMOD_SAMERES) {
width = devmode.dmPelsWidth;
height = devmode.dmPelsHeight;
}
if (fscrnmod & FSCRNMOD_SAMEBPP) {
bitcolor = devmode.dmBitsPerPel;
}
}
if ((width == 0) || (height == 0)) {
width = 640;
height = (np2oscfg.force400)?400:480;
}
if (bitcolor == 0) {
#if !defined(SUPPORT_PC9821)
bitcolor = (scrnmode & SCRNMODE_HIGHCOLOR)?16:8;
#else
bitcolor = 16;
#endif
}
if (ddraw2->SetDisplayMode(width, height, bitcolor, 0, 0) != DD_OK) {
goto scre_err;
}
ddraw2->CreateClipper(0, &ddraw.clipper, NULL);
ddraw.clipper->SetHWnd(0, g_hWndMain);
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
if (ddraw2->CreateSurface(&ddsd, &ddraw.primsurf, NULL) != DD_OK) {
goto scre_err;
}
// fullscrn_clearblank();
ZeroMemory(&ddpf, sizeof(ddpf));
ddpf.dwSize = sizeof(DDPIXELFORMAT);
if (ddraw.primsurf->GetPixelFormat(&ddpf) != DD_OK) {
goto scre_err;
}
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwWidth = 640;
ddsd.dwHeight = 480;
if (ddraw2->CreateSurface(&ddsd, &ddraw.backsurf, NULL) != DD_OK) {
goto scre_err;
}
if (bitcolor == 8) {
paletteinit();
}
else if (bitcolor == 16) {
make16mask(ddpf.dwBBitMask, ddpf.dwRBitMask, ddpf.dwGBitMask);
}
else if (bitcolor == 24) {
}
else if (bitcolor == 32) {
}
else {
goto scre_err;
}
#if defined(SUPPORT_DCLOCK)
DispClock::GetInstance()->SetPalettes(bitcolor);
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwWidth = DCLOCK_WIDTH;
ddsd.dwHeight = DCLOCK_HEIGHT;
ddraw2->CreateSurface(&ddsd, &ddraw.clocksurf, NULL);
DispClock::GetInstance()->Reset();
#endif
}
else {
ddraw2->SetCooperativeLevel(g_hWndMain, DDSCL_NORMAL);
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
if (ddraw2->CreateSurface(&ddsd, &ddraw.primsurf, NULL) != DD_OK) {
goto scre_err;
}
ddraw2->CreateClipper(0, &ddraw.clipper, NULL);
ddraw.clipper->SetHWnd(0, g_hWndMain);
ddraw.primsurf->SetClipper(ddraw.clipper);
ZeroMemory(&ddpf, sizeof(ddpf));
ddpf.dwSize = sizeof(DDPIXELFORMAT);
if (ddraw.primsurf->GetPixelFormat(&ddpf) != DD_OK) {
goto scre_err;
}
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
if (!(scrnmode & SCRNMODE_ROTATE)) {
ddsd.dwWidth = 640 + 1;
ddsd.dwHeight = 480;
}
else {
ddsd.dwWidth = 480;
ddsd.dwHeight = 640 + 1;
}
width = 640;
height = 480;
if (ddraw2->CreateSurface(&ddsd, &ddraw.backsurf, NULL) != DD_OK) {
goto scre_err;
}
bitcolor = ddpf.dwRGBBitCount;
if (bitcolor == 8) {
paletteinit();
}
else if (bitcolor == 16) {
make16mask(ddpf.dwBBitMask, ddpf.dwRBitMask, ddpf.dwGBitMask);
}
else if (bitcolor == 24) {
}
else if (bitcolor == 32) {
}
else {
goto scre_err;
}
ddraw.extend = 1;
}
scrnmng.bpp = (UINT8)bitcolor;
scrnsurf.bpp = bitcolor;
ddraw.scrnmode = scrnmode;
ddraw.width = width;
ddraw.height = height;
ddraw.cliping = 0;
renewalclientsize(FALSE);
// screenupdate = 3; // update!
return(SUCCESS);
scre_err:
scrnmng_destroy();
return(FAILURE);
}
void scrnmng_destroy(void) {
if (scrnmng.flag & SCRNFLAG_FULLSCREEN) {
np2class_enablemenu(g_hWndMain, (!np2oscfg.wintype));
}
#if defined(SUPPORT_DCLOCK)
if (ddraw.clocksurf) {
ddraw.clocksurf->Release();
ddraw.clocksurf = NULL;
}
#endif
if (ddraw.backsurf) {
ddraw.backsurf->Release();
ddraw.backsurf = NULL;
}
if (ddraw.palette) {
ddraw.palette->Release();
ddraw.palette = NULL;
}
if (ddraw.clipper) {
ddraw.clipper->Release();
ddraw.clipper = NULL;
}
if (ddraw.primsurf) {
ddraw.primsurf->Release();
ddraw.primsurf = NULL;
}
if (ddraw.ddraw2) {
if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) {
ddraw.ddraw2->SetCooperativeLevel(g_hWndMain, DDSCL_NORMAL);
}
ddraw.ddraw2->Release();
ddraw.ddraw2 = NULL;
}
if (ddraw.ddraw1) {
ddraw.ddraw1->Release();
ddraw.ddraw1 = NULL;
}
ZeroMemory(&ddraw, sizeof(ddraw));
}
void scrnmng_querypalette(void) {
if (ddraw.palette) {
ddraw.primsurf->SetPalette(ddraw.palette);
}
}
RGB16 scrnmng_makepal16(RGB32 pal32) {
RGB32 pal;
pal.d = pal32.d & ddraw.pal16mask.d;
return((RGB16)((pal.p.g << ddraw.l16g) +
(pal.p.r << ddraw.l16r) + (pal.p.b >> ddraw.r16b)));
}
void scrnmng_fullscrnmenu(int y) {
UINT8 menudisp;
if (scrnmng.flag & SCRNFLAG_FULLSCREEN) {
menudisp = ((y >= 0) && (y < ddraw.menusize))?1:0;
if (ddraw.menudisp != menudisp) {
ddraw.menudisp = menudisp;
if (menudisp == 1) {
np2class_enablemenu(g_hWndMain, TRUE);
}
else {
np2class_enablemenu(g_hWndMain, FALSE);
clearoutfullscreen();
}
}
}
}
void scrnmng_topwinui(void) {
mousemng_disable(MOUSEPROC_WINUI);
if (!ddraw.cliping++) { // ver0.28
if (scrnmng.flag & SCRNFLAG_FULLSCREEN) {
ddraw.primsurf->SetClipper(ddraw.clipper);
}
#ifndef __GNUC__
WINNLSEnableIME(g_hWndMain, TRUE);
#endif
}
}
void scrnmng_clearwinui(void) {
if ((ddraw.cliping > 0) && (!(--ddraw.cliping))) {
#ifndef __GNUC__
WINNLSEnableIME(g_hWndMain, FALSE);
#endif
if (scrnmng.flag & SCRNFLAG_FULLSCREEN) {
ddraw.primsurf->SetClipper(0);
}
}
if (scrnmng.flag & SCRNFLAG_FULLSCREEN) {
np2class_enablemenu(g_hWndMain, FALSE);
clearoutfullscreen();
ddraw.menudisp = 0;
}
else {
if (np2oscfg.wintype) {
np2class_enablemenu(g_hWndMain, FALSE);
InvalidateRect(g_hWndMain, NULL, TRUE);
}
}
mousemng_enable(MOUSEPROC_WINUI);
}
void scrnmng_setwidth(int posx, int width) {
scrnstat.width = width;
renewalclientsize(TRUE);
}
void scrnmng_setextend(int extend) {
scrnstat.extend = extend;
scrnmng.allflash = TRUE;
renewalclientsize(TRUE);
}
void scrnmng_setheight(int posy, int height) {
scrnstat.height = height;
renewalclientsize(TRUE);
}
const SCRNSURF *scrnmng_surflock(void) {
DDSURFACEDESC destscrn;
HRESULT r;
ZeroMemory(&destscrn, sizeof(destscrn));
destscrn.dwSize = sizeof(destscrn);
if (ddraw.backsurf == NULL) {
return(NULL);
}
r = ddraw.backsurf->Lock(NULL, &destscrn, DDLOCK_WAIT, NULL);
if (r == DDERR_SURFACELOST) {
ddraw.backsurf->Restore();
r = ddraw.backsurf->Lock(NULL, &destscrn, DDLOCK_WAIT, NULL);
}
if (r != DD_OK) {
// TRACEOUT(("backsurf lock error: %d (%d)", r));
return(NULL);
}
if (!(ddraw.scrnmode & SCRNMODE_ROTATE)) {
scrnsurf.ptr = (UINT8 *)destscrn.lpSurface;
scrnsurf.xalign = scrnsurf.bpp >> 3;
scrnsurf.yalign = destscrn.lPitch;
}
else if (!(ddraw.scrnmode & SCRNMODE_ROTATEDIR)) {
scrnsurf.ptr = (UINT8 *)destscrn.lpSurface;
scrnsurf.ptr += (scrnsurf.width - 1) * destscrn.lPitch;
scrnsurf.xalign = 0 - destscrn.lPitch;
scrnsurf.yalign = scrnsurf.bpp >> 3;
}
else {
scrnsurf.ptr = (UINT8 *)destscrn.lpSurface;
scrnsurf.ptr += (scrnsurf.height - 1) * (scrnsurf.bpp >> 3);
scrnsurf.xalign = destscrn.lPitch;
scrnsurf.yalign = 0 - (scrnsurf.bpp >> 3);
}
return(&scrnsurf);
}
void scrnmng_surfunlock(const SCRNSURF *surf) {
ddraw.backsurf->Unlock(NULL);
scrnmng_update();
recvideo_update();
}
void scrnmng_update(void) {
POINT clip;
RECT dst;
RECT *rect;
RECT *scrn;
HRESULT r;
if (scrnmng.palchanged) {
scrnmng.palchanged = FALSE;
paletteset();
}
if (ddraw.backsurf != NULL) {
if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) {
if (scrnmng.allflash) {
scrnmng.allflash = 0;
clearoutfullscreen();
}
if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU)) {
rect = &ddraw.rect;
scrn = &ddraw.scrn;
}
else {
rect = &ddraw.rectclip;
scrn = &ddraw.scrnclip;
}
r = ddraw.primsurf->Blt(scrn, ddraw.backsurf, rect,
DDBLT_WAIT, NULL);
if (r == DDERR_SURFACELOST) {
ddraw.backsurf->Restore();
ddraw.primsurf->Restore();
ddraw.primsurf->Blt(scrn, ddraw.backsurf, rect,
DDBLT_WAIT, NULL);
}
}
else {
if (scrnmng.allflash) {
scrnmng.allflash = 0;
clearoutscreen();
}
clip.x = 0;
clip.y = 0;
ClientToScreen(g_hWndMain, &clip);
dst.left = clip.x + ddraw.scrn.left;
dst.top = clip.y + ddraw.scrn.top;
dst.right = clip.x + ddraw.scrn.right;
dst.bottom = clip.y + ddraw.scrn.bottom;
r = ddraw.primsurf->Blt(&dst, ddraw.backsurf, &ddraw.rect,
DDBLT_WAIT, NULL);
if (r == DDERR_SURFACELOST) {
ddraw.backsurf->Restore();
ddraw.primsurf->Restore();
ddraw.primsurf->Blt(&dst, ddraw.backsurf, &ddraw.rect,
DDBLT_WAIT, NULL);
}
}
}
}
// ----
void scrnmng_setmultiple(int multiple)
{
if (scrnstat.multiple != multiple)
{
scrnstat.multiple = multiple;
renewalclientsize(TRUE);
}
}
int scrnmng_getmultiple(void)
{
return scrnstat.multiple;
}
// ----
#if defined(SUPPORT_DCLOCK)
static const RECT rectclk = {0, 0, DCLOCK_WIDTH, DCLOCK_HEIGHT};
BOOL scrnmng_isdispclockclick(const POINT *pt) {
if (pt->y >= (ddraw.height - DCLOCK_HEIGHT)) {
return(TRUE);
}
else {
return(FALSE);
}
}
void scrnmng_dispclock(void)
{
if (!ddraw.clocksurf)
{
return;
}
if (!DispClock::GetInstance()->IsDisplayed())
{
return;
}
const RECT* scrn;
if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU))
{
scrn = &ddraw.scrn;
}
else
{
scrn = &ddraw.scrnclip;
}
if ((scrn->bottom + DCLOCK_HEIGHT) > ddraw.height)
{
return;
}
DispClock::GetInstance()->Make();
DDSURFACEDESC dest;
ZeroMemory(&dest, sizeof(dest));
dest.dwSize = sizeof(dest);
if (ddraw.clocksurf->Lock(NULL, &dest, DDLOCK_WAIT, NULL) == DD_OK)
{
DispClock::GetInstance()->Draw(scrnmng.bpp, dest.lpSurface, dest.lPitch);
ddraw.clocksurf->Unlock(NULL);
}
if (ddraw.primsurf->BltFast(ddraw.width - DCLOCK_WIDTH - 4,
ddraw.height - DCLOCK_HEIGHT,
ddraw.clocksurf, (RECT *)&rectclk,
DDBLTFAST_WAIT) == DDERR_SURFACELOST)
{
ddraw.primsurf->Restore();
ddraw.clocksurf->Restore();
}
DispClock::GetInstance()->CountDown(np2oscfg.DRAW_SKIP);
}
#endif
// ----
typedef struct {
int bx;
int by;
int cx;
int cy;
int mul;
} SCRNSIZING;
static SCRNSIZING scrnsizing;
enum {
SIZING_ADJUST = 12
};
void scrnmng_entersizing(void) {
RECT rectwindow;
RECT rectclient;
int cx;
int cy;
GetWindowRect(g_hWndMain, &rectwindow);
GetClientRect(g_hWndMain, &rectclient);
scrnsizing.bx = (np2oscfg.paddingx * 2) +
(rectwindow.right - rectwindow.left) -
(rectclient.right - rectclient.left);
scrnsizing.by = (np2oscfg.paddingy * 2) +
(rectwindow.bottom - rectwindow.top) -
(rectclient.bottom - rectclient.top);
cx = min(scrnstat.width, ddraw.width);
cx = (cx + 7) >> 3;
cy = min(scrnstat.height, ddraw.height);
cy = (cy + 7) >> 3;
if (!(ddraw.scrnmode & SCRNMODE_ROTATE)) {
scrnsizing.cx = cx;
scrnsizing.cy = cy;
}
else {
scrnsizing.cx = cy;
scrnsizing.cy = cx;
}
scrnsizing.mul = scrnstat.multiple;
}
void scrnmng_sizing(UINT side, RECT *rect) {
int width;
int height;
int mul;
if ((side != WMSZ_TOP) && (side != WMSZ_BOTTOM)) {
width = rect->right - rect->left - scrnsizing.bx + SIZING_ADJUST;
width /= scrnsizing.cx;
}
else {
width = 16;
}
if ((side != WMSZ_LEFT) && (side != WMSZ_RIGHT)) {
height = rect->bottom - rect->top - scrnsizing.by + SIZING_ADJUST;
height /= scrnsizing.cy;
}
else {
height = 16;
}
mul = min(width, height);
if (mul <= 0) {
mul = 1;
}
else if (mul > 16) {
mul = 16;
}
width = scrnsizing.bx + (scrnsizing.cx * mul);
height = scrnsizing.by + (scrnsizing.cy * mul);
switch(side) {
case WMSZ_LEFT:
case WMSZ_TOPLEFT:
case WMSZ_BOTTOMLEFT:
rect->left = rect->right - width;
break;
case WMSZ_RIGHT:
case WMSZ_TOP:
case WMSZ_TOPRIGHT:
case WMSZ_BOTTOM:
case WMSZ_BOTTOMRIGHT:
default:
rect->right = rect->left + width;
break;
}
switch(side) {
case WMSZ_TOP:
case WMSZ_TOPLEFT:
case WMSZ_TOPRIGHT:
rect->top = rect->bottom - height;
break;
case WMSZ_LEFT:
case WMSZ_RIGHT:
case WMSZ_BOTTOM:
case WMSZ_BOTTOMLEFT:
case WMSZ_BOTTOMRIGHT:
default:
rect->bottom = rect->top + height;
break;
}
scrnsizing.mul = mul;
}
void scrnmng_exitsizing(void)
{
scrnmng_setmultiple(scrnsizing.mul);
InvalidateRect(g_hWndMain, NULL, TRUE); // ugh
}
| [
"yui@7c2116fe-53d0-4aec-ab59-80607f05abc0"
] | yui@7c2116fe-53d0-4aec-ab59-80607f05abc0 |
dd82cb8290b05637646e4e6a7eedd3adfe5d58fe | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/BLSM/src/blsm_aux.cpp | d30e6ff65d867acac45f30b24a160d6d90868fbe | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,066 | cpp | #include <RcppEigen.h>
#include <numeric>
//[[Rcpp::depends(RcppEigen)]]
//' @title Geodesic distance
//' @description Evaluate geodesic distance (shortest path) between all pairs of nodes in the network.
//'
//' @param M Input adjacency matrix
//'
//' @return Matrix containing all the pairwise geodesic distances
//' @examples dst(example_adjacency_matrix)
//' @export
// [[Rcpp::export]]
Eigen::MatrixXd dst(const Eigen::Map<Eigen::MatrixXd> M){
int g=M.rows();
Eigen::MatrixXd Yr=M;
Eigen::MatrixXd Dst=M;
for (int i(0); i<g;i++){
for (int j(0); j<g;j++){
if (M(i,j)==1){
Dst(i,j)=1;
}
else {
Dst(i,j)=g;
}
}
}
for (int r(2);r<g;r++){
Yr=Yr*M;
for (int i(0); i<g;i++){
for (int j(0); j<g;j++){
if (Yr(i,j)>0 && Dst(i,j)==g){
Dst(i,j)=r;
}
}
}
}
return Dst;
}
//' @title Distance between latent positions
//' @description Compute the square root of the Euclidean distances between latent positions and
//' return them with a negative sign.
//'
//' @param Z Latent positions matrix. The matrix size must be \code{(n,k)}, where \code{n} and \code{k} denote respectively
//' the number of nodes in the network and the latent space dimensionality.
//' @return Matrix containing the negative square root of the Euclidean distances between latent positions
//' @examples pos = matrix(rnorm(20), ncol=2)
//' lpz_dist(pos)
//' @export
// [[Rcpp::export]]
Eigen::MatrixXd lpz_dist(Eigen::MatrixXd Z){
Eigen::MatrixXd ZtZ=Z*(Z.adjoint());
int k=Z.rows();
Eigen::MatrixXd temp;
temp.setOnes(1,k);
Eigen::MatrixXd temp2=ZtZ.diagonal()*temp;
Eigen::MatrixXd mg=temp2;
mg=mg+temp2.adjoint()-ZtZ*2;
for (int i(0);i<k;i++){
for (int j(0);j<k;j++){
mg(i,j)=-sqrt(mg(i,j));
}
}
return mg;
}
//' @title Network log-likelihood
//' @description Compute the log-likelihood of the whole observed network based on the
//' latent positions estimates and the model assumptions. See \link[BLSM]{BLSM} for more information.
//'
//' @param Y Adjacency matrix of the observed network
//' @param lpz Matrix containing the negative square root of the Euclidean distances between latent positions
//' (output of \link[BLSM]{lpz_dist})
//' @param alpha Model variable \eqn{\alpha}
//' @param W BLSM Weights matrix of the observed network
//'
//' @return Log-likelihood of the observed network
// [[Rcpp::export]]
double lpY (Eigen::MatrixXd Y, Eigen::MatrixXd lpz, double alpha, Eigen::MatrixXd W){
double val(0);
double lpg;
int k=lpz.rows();
for (int i(0);i<k;i++){
for (int j(0);j<k;j++){
if (i!=j){
lpg=W(i,j)*lpz(i,j)+alpha;
val=val+Y(i,j)*lpg-log(1+exp(lpg));
}
}
}
return val;
}
//' @title Network (positive) log-likelihood
//' @description Compute the (positive) log-likelihood of the whole observed network based on the
//' latent positions estimates and the model assumptions. The inputs are slightly different from those of \link[BLSM]{lpY},
//' so the function basically applies some preprocessing before calling \link[BLSM]{lpY} and returning its value with the opposite sign.
//'
//' @param avZ Vector containing the \eqn{\alpha} value and the latent positions
//' @param Y Adjacency matrix of the observed network
//' @param W BLSM Weights matrix of the observed network
//'
//' @return Log-likelihood of the observed network
// [[Rcpp::export]]
double mlpY (Eigen::VectorXd avZ, Eigen::MatrixXd Y, Eigen::MatrixXd W){
int k=Y.rows();
double val(0);
double alpha=avZ(0);
Eigen::MatrixXd Z=avZ.tail(avZ.size()-1);
Z.resize(k,2);
Eigen::MatrixXd lpz=lpz_dist(Z);
val = lpY (Y, lpz, alpha, W);
return -val;
}
//' @title lpz_dist optimized for individual updates
//' @description Compute the square root of the Euclidean distances between a specific coordinate in the latent space
//' and all the others. The function follows almost the same approach as \link[BLSM]{lpz_dist}, but it is
//' more suitable for the individual updates occurring during the simulation.
//'
//' @param Z Latent positions matrix
//' @param node Specific node in the network corresponding to the latent coordinate which will be used as reference
//' @param diag Diagonal from \code{t(Z)\%*\%Z} matrix, passed to speed up the process.
//' @return Vector containing the negative square root of the Euclidean distances between latent positions
// [[Rcpp::export]]
Eigen::VectorXd lpz_distNODE(Eigen::MatrixXd Z, int node, Eigen::VectorXd diag){
int k=Z.rows();
Eigen::VectorXd ZtZ=Z.row(node)*(Z.adjoint());
Eigen::VectorXd temp(k);
temp.fill(diag(node));
Eigen::VectorXd mg;
mg=temp+diag-ZtZ*2;
for (int i(0);i<k;i++){
mg(i)=-sqrt(mg(i));
}
return mg;
}
//' @title Network log-likelihood for individual updates
//' @description Compute the log-likelihood of the whole observed network based on the
//' latent positions estimates and the model assumptions. The function follows almost the same approach as \link[BLSM]{lpY}, but it is
//' more suitable for the individual updates occurring during the simulation.
//' @param Y Adjacency matrix of the observed network
//' @param Z Latent positions matrix
//' @param alpha Model variable \eqn{\alpha}
//' @param node Specific node in the network corresponding to the latent coordinate which will be used as reference
//' @param diag Diagonal from \code{t(Z)\%*\%Z} matrix, passed to speed up the process.
//' @param W BLSM Weights matrix of the observed network
//'
//' @return Log-likelihood of the observed network
// [[Rcpp::export]]
double lpYNODE (Eigen::MatrixXd Y, Eigen::MatrixXd Z, double alpha, int node, Eigen::VectorXd diag, Eigen::MatrixXd W){
int k=Z.rows();
double val(0);
Eigen::VectorXd lpz=lpz_distNODE(Z, node, diag);
double lpg;
for (int i(0);i<k;i++){
if (i!=node){
lpg=W(i,node)*lpz(i)+alpha;
val+=Y(i,node)*lpg-log(1+exp(lpg));
}
}
return val;
}
//' @title Update step for the latent positions
//' @description Accept/reject the proposals for the latent positions
//'
//' @param Y Adjacency matrix of the observed network
//' @param Z Latent positions matrix
//' @param W BLSM Weights matrix of the observed network
//' @param alpha Model variable \eqn{\alpha}
//' @param zdelta Standard deviation of the Gaussian proposal for latent positions
//' @param mu_z Mean of the Gaussian prior distribution for latent positions
//' @param sd_z Standard deviation of the Gaussian prior distribution for latent positions
//'
//' @return Updated latent positions matrix
// [[Rcpp::export]]
Eigen::MatrixXd Z_up (Eigen::MatrixXd Y, Eigen::MatrixXd Z, Eigen::MatrixXd W, double alpha, double zdelta, double mu_z, double sd_z){
Rcpp::RNGScope scope;
int k=Z.rows();
int h=Z.cols();
Eigen::MatrixXd Znew = Z;
double lnew, lold, hr ;
Rcpp::NumericVector UP(h), D1(h), D2(h), OLD(h);
Eigen::VectorXd ZtZ=(Z*(Z.adjoint())).diagonal();
for (int i(0);i<k;i++){
for (int j(0);j<h;j++){
OLD[j] = Z(i,j);
UP[j] = Rcpp::rnorm(1,OLD[j],zdelta)[0];
Znew(i,j) = UP[j];
}
D1 = Rcpp::dnorm(UP, mu_z, sd_z, TRUE);
D2 = Rcpp::dnorm(OLD, mu_z, sd_z, TRUE);
lold=lpYNODE(Y,Z,alpha,i, ZtZ, W);
ZtZ(i) = Znew.row(i)*Znew.row(i).adjoint();
lnew=lpYNODE(Y,Znew,alpha, i, ZtZ, W);
hr = 2*(lnew-lold) + std::accumulate(D1.begin(),D1.end(),0) - std::accumulate(D2.begin(),D2.end(),0);
if (Rcpp::runif(1).at(0)>exp(hr)) {
Znew.row(i)=Z.row(i);
ZtZ(i) = Znew.row(i)*Znew.row(i).adjoint();
}
else {
Z.row(i)=Znew.row(i);
}
}
return Znew;
}
//' @title Update step for the \eqn{\alpha} variable
//' @description Accept/reject the proposal for the \eqn{\alpha} model variable
//'
//' @param Y Adjacency matrix of the observed network
//' @param lpz Matrix containing the negative square root of the Euclidean distances between latent positions
//' @param W BLSM Weights matrix of the observed network
//' @param alpha Model variable \eqn{\alpha}
//' @param adelta The uniform proposal for \eqn{\alpha} is defined on the \eqn{[-adelta,+adelta]} interval
//' @param a_a Shape parameter of the Gamma prior distribution for \eqn{\alpha}. The value is usually set to 1, so the prior is actually an exponential distribution.
//' @param a_b Rate parameter of the Gamma prior distribution for \eqn{\alpha}.
//'
//' @return Updated value of the \eqn{\alpha} variable
// [[Rcpp::export]]
double alpha_up (Eigen::MatrixXd Y, Eigen::MatrixXd lpz, Eigen::MatrixXd W, double alpha, double adelta, double a_a, double a_b){
Rcpp::RNGScope scope;
double lnew, lold, hr;
Rcpp::NumericVector alphanew(1),alphaV(1);
alphanew[0] = std::abs(alpha+Rcpp::runif(1,-adelta,adelta)[0]);
alphaV[0] = alpha;
lnew=lpY(Y,lpz,alphanew[0], W);
lold=lpY(Y,lpz,alpha, W);
hr=lnew-lold + Rcpp::dgamma(alphanew,a_a,a_b,TRUE)[0] - Rcpp::dgamma(alphaV,a_a,a_b,TRUE)[0];
if(Rcpp::runif(1).at(0)>exp(hr)){
alphanew[0]=alpha;
}
return alphanew[0];
}
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
7e5531945c47ff1193f2eea2a2c5964ea3408fb6 | 158b631998f70d64a4bdc9017ebeb136e91b6e10 | /src/midi/io/vli.h | ff2d003b2698a77556dce8a5ad0903c784d3201e | [] | no_license | JonasDeBoeck/MIDI-visualizer | 536d7f1ca7b82726e5e43ce09dc3aca5096dcd84 | 0dd0b4962f66c05fb270bc2d164b07efbe5dddab | refs/heads/master | 2022-11-17T23:33:35.388286 | 2020-07-14T14:02:14 | 2020-07-14T14:02:14 | 279,589,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | h | #ifndef VLI_H
#define VLI_H
#include <istream>
#include <iostream>
namespace io {
uint64_t read_variable_length_integer(std::istream& in);
}
#endif | [
"Jonas.deboeck@student.ucll.be"
] | Jonas.deboeck@student.ucll.be |
100093a5041266c29358d28f3153ab305cc4a9d1 | cc7ea7d3af5afdfab52c4ade486f2b733147415b | /folly/fibers/async/test/AsyncTest.cpp | 88343e713eb7500e8901e14b085623c668ccc8f2 | [
"MIT",
"Apache-2.0"
] | permissive | couchbasedeps/folly | f2d70e1b2c629761e40e15248ea17335e651fc40 | 99a218de8a87c48f8164afb614401717c58cce8a | refs/heads/master | 2022-09-09T08:32:46.196956 | 2021-02-26T21:43:46 | 2021-02-26T21:45:23 | 152,815,030 | 1 | 3 | Apache-2.0 | 2022-08-22T12:19:33 | 2018-10-12T22:48:10 | C++ | UTF-8 | C++ | false | false | 11,298 | cpp | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/fibers/async/Async.h>
#include <folly/fibers/FiberManager.h>
#include <folly/fibers/FiberManagerMap.h>
#include <folly/fibers/async/Baton.h>
#include <folly/fibers/async/Collect.h>
#include <folly/fibers/async/FiberManager.h>
#include <folly/fibers/async/Future.h>
#include <folly/fibers/async/Promise.h>
#include <folly/fibers/async/WaitUtils.h>
#include <folly/io/async/EventBase.h>
#include <folly/portability/GMock.h>
#include <folly/portability/GTest.h>
#include <folly/experimental/coro/Sleep.h>
#include <folly/fibers/async/Task.h>
using namespace ::testing;
using namespace folly::fibers;
namespace {
std::string getString() {
return "foo";
}
async::Async<void> getAsyncNothing() {
return {};
}
async::Async<std::string> getAsyncString() {
return getString();
}
async::Async<folly::Optional<std::string>> getOptionalAsyncString() {
// use move constructor to convert Async<std::string> to
// Async<folly::Optional<std::string>>
return getAsyncString();
}
async::Async<std::tuple<int, float, std::string>> getTuple() {
return {0, 0.0, "0"};
}
struct NonCopyableNonMoveable {
NonCopyableNonMoveable(const NonCopyableNonMoveable&) = delete;
NonCopyableNonMoveable(NonCopyableNonMoveable&&) = delete;
NonCopyableNonMoveable& operator=(NonCopyableNonMoveable const&) = delete;
NonCopyableNonMoveable& operator=(NonCopyableNonMoveable&&) = delete;
};
async::Async<NonCopyableNonMoveable const&> getReference() {
thread_local NonCopyableNonMoveable const value{};
return value;
}
} // namespace
TEST(AsyncTest, asyncAwait) {
folly::EventBase evb;
auto& fm = getFiberManager(evb);
EXPECT_NO_THROW(
fm.addTaskFuture([&]() {
async::init_await(getAsyncNothing());
EXPECT_EQ(getString(), async::init_await(getAsyncString()));
EXPECT_EQ(getString(), *async::init_await(getOptionalAsyncString()));
async::init_await(getTuple());
decltype(auto) ref = async::init_await(getReference());
static_assert(
std::is_same<decltype(ref), NonCopyableNonMoveable const&>::value,
"");
}).getVia(&evb));
}
TEST(AsyncTest, asyncBaton) {
folly::EventBase evb;
auto& fm = getFiberManager(evb);
std::chrono::steady_clock::time_point start;
EXPECT_NO_THROW(
fm.addTaskFuture([&]() {
constexpr auto kTimeout = std::chrono::milliseconds(230);
{
Baton baton;
baton.post();
EXPECT_NO_THROW(async::await(async::baton_wait(baton)));
}
{
Baton baton;
start = std::chrono::steady_clock::now();
auto res = async::await(async::baton_try_wait_for(baton, kTimeout));
EXPECT_FALSE(res);
EXPECT_LE(start + kTimeout, std::chrono::steady_clock::now());
}
{
Baton baton;
start = std::chrono::steady_clock::now();
auto res = async::await(
async::baton_try_wait_until(baton, start + kTimeout));
EXPECT_FALSE(res);
EXPECT_LE(start + kTimeout, std::chrono::steady_clock::now());
}
}).getVia(&evb));
}
TEST(AsyncTest, asyncPromise) {
folly::EventBase evb;
auto& fm = getFiberManager(evb);
fm.addTaskFuture([&]() {
auto res = async::await(
async::promiseWait([](Promise<int> p) { p.setValue(42); }));
EXPECT_EQ(res, 42);
}).getVia(&evb);
}
TEST(AsyncTest, asyncFuture) {
folly::EventBase evb;
auto& fm = getFiberManager(evb);
// Return format: Info about where continuation runs (thread_id,
// in_fiber_loop, on_active_fiber)
auto getSemiFuture = []() {
return folly::futures::sleep(std::chrono::milliseconds(1))
.defer([](auto&&) {
return std::make_tuple(
std::this_thread::get_id(),
FiberManager::getFiberManagerUnsafe() != nullptr,
onFiber());
});
};
fm.addTaskFuture([&]() {
auto this_thread_id = std::this_thread::get_id();
{
// Unspecified executor: Deferred work will be executed inline on
// producer thread
auto res = async::init_await(
async::futureWait(getSemiFuture().toUnsafeFuture()));
EXPECT_NE(this_thread_id, std::get<0>(res));
EXPECT_FALSE(std::get<1>(res));
EXPECT_FALSE(std::get<2>(res));
}
{
// Specified executor: Deferred work will be executed on evb
auto res =
async::init_await(async::futureWait(getSemiFuture().via(&evb)));
EXPECT_EQ(this_thread_id, std::get<0>(res));
EXPECT_FALSE(std::get<1>(res));
EXPECT_FALSE(std::get<2>(res));
}
{
// Unspecified executor: Deferred work will be executed inline on
// consumer thread main-context
auto res = async::init_await(async::futureWait(getSemiFuture()));
EXPECT_EQ(this_thread_id, std::get<0>(res));
EXPECT_TRUE(std::get<1>(res));
EXPECT_FALSE(std::get<2>(res));
}
}).getVia(&evb);
}
#if FOLLY_HAS_COROUTINES
TEST(AsyncTest, asyncTask) {
auto coroFn =
[]() -> folly::coro::Task<std::tuple<std::thread::id, bool, bool>> {
co_await folly::coro::sleep(std::chrono::milliseconds(1));
co_return std::make_tuple(
std::this_thread::get_id(),
FiberManager::getFiberManagerUnsafe() != nullptr,
onFiber());
};
auto voidCoroFn = []() -> folly::coro::Task<void> {
co_await folly::coro::sleep(std::chrono::milliseconds(1));
};
folly::EventBase evb;
auto& fm = getFiberManager(evb);
fm.addTaskFuture([&]() {
// Coroutine should run to completion on fiber main context
EXPECT_EQ(
std::make_tuple(std::this_thread::get_id(), true, false),
async::init_await(async::taskWait(coroFn())));
async::init_await(async::taskWait(voidCoroFn()));
}).getVia(&evb);
}
#endif
TEST(AsyncTest, asyncTraits) {
static_assert(!async::is_async_v<int>);
static_assert(async::is_async_v<async::Async<int>>);
static_assert(
std::is_same<int, async::async_inner_type_t<async::Async<int>>>::value);
static_assert(
std::is_same<int&, async::async_inner_type_t<async::Async<int&>>>::value);
}
#if __cpp_deduction_guides >= 201703
TEST(AsyncTest, asyncConstructorGuides) {
auto getLiteral = []() { return async::Async(1); };
// int&& -> int
static_assert(
std::is_same<int, async::async_inner_type_t<decltype(getLiteral())>>::
value);
int i = 0;
auto tryGetRef = [&]() { return async::Async(static_cast<int&>(i)); };
// int& -> int
static_assert(
std::is_same<int, async::async_inner_type_t<decltype(tryGetRef())>>::
value);
auto tryGetConstRef = [&]() {
return async::Async(static_cast<const int&>(i));
};
// const int& -> int
static_assert(
std::is_same<int, async::async_inner_type_t<decltype(tryGetConstRef())>>::
value);
// int& explicitly constructed
auto getRef = [&]() { return async::Async<int&>(i); };
static_assert(
std::is_same<int&, async::async_inner_type_t<decltype(getRef())>>::value);
}
#endif
TEST(FiberManager, asyncFiberManager) {
{
folly::EventBase evb;
bool completed = false;
async::addFiberFuture(
[&]() -> async::Async<void> {
completed = true;
return {};
},
getFiberManager(evb))
.getVia(&evb);
EXPECT_TRUE(completed);
size_t count = 0;
EXPECT_EQ(
1,
async::addFiberFuture(
[count]() mutable -> async::Async<int> { return ++count; },
getFiberManager(evb))
.getVia(&evb));
}
{
bool outerCompleted = false;
async::executeOnFiberAndWait([&]() -> async::Async<void> {
bool innerCompleted = false;
async::await(async::executeOnNewFiber([&]() -> async::Async<void> {
innerCompleted = true;
return {};
}));
EXPECT_TRUE(innerCompleted);
outerCompleted = true;
return {};
});
EXPECT_TRUE(outerCompleted);
}
{
bool outerCompleted = false;
bool innerCompleted = false;
async::executeOnFiberAndWait([&]() -> async::Async<void> {
outerCompleted = true;
async::addFiber(
[&]() -> async::Async<void> {
innerCompleted = true;
return {};
},
FiberManager::getFiberManager());
return {};
});
EXPECT_TRUE(outerCompleted);
EXPECT_TRUE(innerCompleted);
}
}
TEST(AsyncTest, collect) {
auto makeVoidTask = [](bool& ref) {
return [&]() -> async::Async<void> {
ref = true;
return {};
};
};
auto makeRetTask = [](int val) {
return [=]() -> async::Async<int> { return val; };
};
async::executeOnFiberAndWait([&]() -> async::Async<void> {
{
std::array<bool, 3> cs{false, false, false};
std::vector<folly::Function<async::Async<void>()>> tasks;
tasks.emplace_back(makeVoidTask(cs[0]));
tasks.emplace_back(makeVoidTask(cs[1]));
tasks.emplace_back(makeVoidTask(cs[2]));
async::await(async::collectAll(tasks));
EXPECT_THAT(cs, ElementsAre(true, true, true));
}
{
std::vector<folly::Function<async::Async<int>()>> tasks;
tasks.emplace_back(makeRetTask(1));
tasks.emplace_back(makeRetTask(2));
tasks.emplace_back(makeRetTask(3));
EXPECT_THAT(async::await(async::collectAll(tasks)), ElementsAre(1, 2, 3));
}
{
std::array<bool, 3> cs{false, false, false};
async::await(async::collectAll(
makeVoidTask(cs[0]), makeVoidTask(cs[1]), makeVoidTask(cs[2])));
EXPECT_THAT(cs, ElementsAre(true, true, true));
}
{
EXPECT_EQ(
std::make_tuple(1, 2, 3),
async::await(async::collectAll(
makeRetTask(1), makeRetTask(2), makeRetTask(3))));
}
return {};
});
}
TEST(FiberManager, remoteFiberManager) {
folly::EventBase evb;
auto& fm = getFiberManager(evb);
bool test1Finished = false;
bool test2Finished = false;
std::atomic<bool> remoteFinished = false;
std::thread remote([&]() {
async::executeOnRemoteFiberAndWait(
[&]() -> async::Async<void> {
test1Finished = true;
return {};
},
fm);
async::executeOnFiberAndWait([&] {
return async::executeOnRemoteFiber(
[&]() -> async::Async<void> {
test2Finished = true;
return {};
},
fm);
});
remoteFinished = true;
});
while (!remoteFinished) {
evb.loopOnce();
}
remote.join();
EXPECT_TRUE(test1Finished);
EXPECT_TRUE(test2Finished);
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
2a16c692122982dae100d9debea19cde51a578b0 | 445da2f263a72d102536d04dceb7dbb45c5e8353 | /practice/mathisreal.cpp | c7b15e45bd0243f17238036c4bfee7de6f90ed0f | [] | no_license | AsminBudha/Competitive-Programming | 4f05a11270541c66c7e1f7ef060f886140e43be9 | b8994caa29ae4976d36f1e2512f299b45815810d | refs/heads/master | 2020-05-15T21:12:46.639324 | 2019-07-18T15:38:46 | 2019-07-18T15:38:46 | 182,493,853 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,656 | cpp | #include <bits/stdc++.h>
#define MAX 100000
using namespace std;
//typedefs
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<pii> vpii;
typedef map<int, int> mii;
//Constants
const ll MOD = 10e9 + 7;
const long double PI = acos((long double)(-1.0));
const long double EPS = 1e-9;
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
map<long, long> cycle;
vector<long> vect(10001);
int main()
{
map<string,int> mp;
mp["byte"]=0;
mp["kb"]=1;
mp["mb"]=2;
mp["gb"]=3;
mp["pb"]=4;
freopen("../input.txt","r",stdin);
int t;
cin>>t;
for(int cs=1;cs<=t;cs++){
cout<<"Case "<<cs<<": ";
int n;
cin>>n;
string s1,s2;
cin>>s1>>s2;
for(int i=0;i<s1.size();i++)
s1[i]=tolower(s1[i]);
for(int i=0;i<s1.size();i++)
s2[i]=tolower(s2[i]);
// s2=tolower(s2);
double ans=0;
if(s1!="bit" & s2!="bit"){
int times=abs(mp[s1]-mp[s2]);
ll div=pow(1024,times);
if(mp[s2]<mp[s1]){
ans=(double)n*div;
}
else{
ans=(double)n/div;
}
}
else if(s1=="bit" && s2=="bit"){
ans=(double)n;
}
else if(s1==s2){
ans=(double)n;
}
else if(s1=="bit"){
int times=abs(mp["byte"]-mp[s2]);
ll div=pow(1024,times);
if(mp[s2]<mp["byte"]){
ans=(double)n*div*8;
}
else{
ans=(double)n/(div*8);
}
}
else if(s2=="bit"){
int times=abs(mp["byte"]-mp[s1]);
ll div=pow(1024,times);
if(mp[s1]<mp["byte"]){
ans=(double)n/(div*8);
}
else{
ans=(double)n*(div*8);
}
}
printf("%.15lf\n",ans);
}
return 0;
} | [
"sminmgr@gmail.com"
] | sminmgr@gmail.com |
5d16607def3be8b97e58c09bcd3da36213909236 | f55fedabd92ac86dbf7bc591d37b2d3dbff5bd59 | /C++experence_2/company.h | b0a7a0861f73c770718c2e01adab35d82f483015 | [] | no_license | kepengxu/C-data_struct | 0752f5ac001fc5d7164dcae71aa38af6c9b4ae90 | 615659f5ad7b1b0bf204a6a4a7278697bd1006d6 | refs/heads/master | 2021-09-10T19:58:48.853704 | 2018-04-01T03:47:30 | 2018-04-01T03:47:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | h | //
// Created by cooper on 18-4-1.
//
#ifndef C_EXPERENCE_2_COMPANY_H
#define C_EXPERENCE_2_COMPANY_H
#include<string>
#include<algorithm>
#include<vector>
#include <fstream>
#include"staff.h"
using namespace std;
class company {
public:
string companyname;
string company_registration_time;
vector<staff> staff_data;
float stock_money;
string legal_person;
company(string companyname,string company_registration_time,float stock_money,string legal_person);
bool add_staff(staff &s);//往vector中加入信息
bool modify_staff(int age,int number,string address,string position);
bool delete_staff(int number);
bool seek(int number);
bool sort_salary();
// void print_all();
bool output_tofile();
bool readfromfile();
};
#endif //C_EXPERENCE_2_COMPANY_H
| [
"noreply@github.com"
] | noreply@github.com |
580ecfd411e4af259188ca5cc1fc3fc2d78443a8 | d0280f46cd5cafcb6be5ebb6d842847efd959dda | /VFLogServer/HandlerSquid.cpp | 8ec1c4f7da7515f6463747af200e86ed82851a6f | [] | no_license | lkn2007/VFLog | e274213c95de94ae26795d89fefa228228493627 | c37c3508c7de13779a0d6dc3573428b4e6da2621 | refs/heads/master | 2023-03-21T13:35:08.363024 | 2021-03-22T00:23:07 | 2021-03-22T00:23:07 | 336,636,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | cpp | #include "HandlerSquid.h"
bool HandlerSquid::write(const std::string& vflogclient_id, const std::string& client_handler, const std::string& log_string)const
{
MYSQL* conn;
//MYSQL_RES* res;
//MYSQL_ROW row;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "localhost", "root", "lbvtlhjk", "vflog_db", 3306, NULL, 0);
int qstate;
if (conn)
{
std::stringstream ss(log_string);
std::string data;
std::string tmp2;
while (std::getline(ss, data, '\n'))
{
std::stringstream ss2(data);
std::string tmp;
tmp = "('" + vflogclient_id + "',";
int counter = 0;
while (std::getline(ss2, data, ' '))
{
if (data.size() == 0)
{
continue;
}
tmp += "'" + data + "'" + ",";
counter++;
}
tmp.erase(tmp.size() - 1);
tmp += ")";
tmp2 += tmp + ",";
}
tmp2.erase(tmp2.size() - 1);
std::string query = "INSERT INTO squids(`clients_id`,`linux_time`, `time_response`, `request_source`, `request_status/http_status_code`, `size_request`, `metod_request`, `url_reques`, `user_name`, `hierarchy_status/requesting_server`, `mime_type`) VALUES" + tmp2;
const char* q = query.c_str();
qstate = mysql_query(conn, q);
if (qstate != 0)
{
std::cout << "Insert Error\n" << mysql_error(conn) << "\n";
return false;
}
mysql_close(conn);
}
else
{
std::cout << "Connection to database has failed!\n";
return false;
}
return true;
} | [
"61288324+lkn2007@users.noreply.github.com"
] | 61288324+lkn2007@users.noreply.github.com |
b67d31712e2b6b30d4c04a63c4f5a4b03b0e4b06 | 26439e03389b81ef8e7c44b06ba66687862fc060 | /src/server/Server.cpp | ca07abc6893efcc9747883265a2350b1930c789d | [
"MIT"
] | permissive | officialabd/HTCPCP-SERVER | 5aa7d2391f3c714b387482fb53effc9eda8504fc | 592611836f327beee10d55a839b5ef1d6c832789 | refs/heads/main | 2023-05-10T02:53:46.036797 | 2021-05-18T21:31:30 | 2021-05-18T21:31:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,597 | cpp | #include "../../headers/server/Server.h"
int count = 0;
void *clientThread(void *arg);
void runServer(int port) {
int re = 0;
int server_sck = socket(AF_INET, SOCK_STREAM, 0);
errorHandler(server_sck, (char *)"Initialize server socket failed");
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
memset(addr.sin_zero, '\0', sizeof(addr.sin_zero));
re = bind(server_sck, (sockaddr *)&addr, sizeof(addr));
errorHandler(re, (char *)"Binding failed");
re = listen(server_sck, QUEUE);
errorHandler(re, (char *)"Listening failed");
std::vector<pthread_t> tids;
int pots_temp_b[5] = {0, 0, 0, 0, 0};
int *pot_pb = (int *)calloc(sizeof(int), 5);
pot_pb = pots_temp_b;
int pots_temp_p[5] = {0, 0, 0, 0, 0};
int *pot_pp = (int *)calloc(sizeof(int), 5);
pot_pp = pots_temp_p;
while (true) {
ClientData *client = (ClientData *)calloc(sizeof(ClientData), 1);
socklen_t clientSize = sizeof(client->addr);
client->potsAreBrewing = pot_pb;
client->potsArePooring = pot_pp;
client->sck = accept(server_sck, (sockaddr *)&client->addr, &clientSize);
while (count >= 5) {
}
pthread_t tid;
re = pthread_create(&tid, NULL, clientThread, client);
errorHandler(re, (char *)"Create thread failed");
tids.push_back(tid);
}
}
void *clientThread(void *arg) {
count++;
ClientData *client = (ClientData *)arg;
clientHandler(client);
count--;
pthread_exit(0);
}
| [
"officialabd@gmail.com"
] | officialabd@gmail.com |
e521d712da18af15c37f3857bb4185c5746af39f | cec33e87371444500a068711afdfbe6dc1ea050e | /src/walletdb.cpp | 32fb999ce409ba77d738b55b678c40421f35ee7f | [
"MIT"
] | permissive | troybeags/bingocoin | 2a0bb874fa9a0a086c032582763ff8b082403261 | c5d13a61ea2ff102ab98bfa2265d70c6bbb23f53 | refs/heads/master | 2021-01-21T10:25:46.957893 | 2017-05-20T06:56:14 | 2017-05-20T06:56:14 | 90,503,347 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,351 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletdb.h"
#include "base58.h"
#include "protocol.h"
#include "serialize.h"
#include "sync.h"
#include "wallet.h"
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
using namespace std;
using namespace boost;
static uint64_t nAccountingEntryNumber = 0;
extern bool fWalletUnlockStakingOnly;
//
// CWalletDB
//
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("tx"), hash), wtx);
}
bool CWalletDB::EraseTx(uint256 hash)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("tx"), hash));
}
bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta, false))
return false;
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata &keyMeta)
{
const bool fEraseUnencryptedKey = true;
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta))
return false;
if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false))
return false;
if (fEraseUnencryptedKey)
{
Erase(std::make_pair(std::string("key"), vchPubKey));
Erase(std::make_pair(std::string("wkey"), vchPubKey));
}
return true;
}
bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
}
bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false);
}
bool CWalletDB::WriteBestBlock(const CBlockLocator& locator)
{
nWalletDBUpdated++;
return Write(std::string("bestblock"), locator);
}
bool CWalletDB::ReadBestBlock(CBlockLocator& locator)
{
return Read(std::string("bestblock"), locator);
}
bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext)
{
nWalletDBUpdated++;
return Write(std::string("orderposnext"), nOrderPosNext);
}
bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey)
{
nWalletDBUpdated++;
return Write(std::string("defaultkey"), vchPubKey);
}
bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool)
{
return Read(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::ErasePool(int64_t nPool)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("pool"), nPool));
}
bool CWalletDB::WriteMinVersion(int nVersion)
{
return Write(std::string("minversion"), nVersion);
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
account.SetNull();
return Read(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
{
return Write(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
}
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
{
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
}
int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount)
{
list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
int64_t nCreditDebit = 0;
BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
ssKey >> acentry.nEntryNo;
entries.push_back(acentry);
}
pcursor->close();
}
DBErrors
CWalletDB::ReorderTransactions(CWallet* pwallet)
{
LOCK(pwallet->cs_wallet);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
ListAccountCreditDebit("", acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
int64_t& nOrderPosNext = pwallet->nOrderPosNext;
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
class CWalletScanState {
public:
unsigned int nKeys;
unsigned int nCKeys;
unsigned int nKeyMeta;
bool fIsEncrypted;
bool fAnyUnordered;
int nFileVersion;
vector<uint256> vWalletUpgrade;
CWalletScanState() {
nKeys = nCKeys = nKeyMeta = 0;
fIsEncrypted = false;
fAnyUnordered = false;
nFileVersion = 0;
}
};
bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
CWalletScanState &wss, string& strType, string& strErr)
{
try {
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
ssKey >> strType;
if (strType == "name")
{
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx& wtx = pwallet->mapWallet[hash];
ssValue >> wtx;
if (wtx.CheckTransaction() && (wtx.GetHash() == hash))
wtx.BindWallet(pwallet);
else
{
pwallet->mapWallet.erase(hash);
return false;
}
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
{
if (!ssValue.empty())
{
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
}
if (wtx.nOrderPos == -1)
wss.fAnyUnordered = true;
//// debug print
//LogPrintf("LoadWallet %s\n", wtx.GetHash().ToString());
//LogPrintf(" %12d %s %s %s\n",
// wtx.vout[0].nValue,
// DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()),
// wtx.hashBlock.ToString(),
// wtx.mapValue["message"]);
}
else if (strType == "acentry")
{
string strAccount;
ssKey >> strAccount;
uint64_t nNumber;
ssKey >> nNumber;
if (nNumber > nAccountingEntryNumber)
nAccountingEntryNumber = nNumber;
if (!wss.fAnyUnordered)
{
CAccountingEntry acentry;
ssValue >> acentry;
if (acentry.nOrderPos == -1)
wss.fAnyUnordered = true;
}
}
else if (strType == "key" || strType == "wkey")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid())
{
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
CKey key;
CPrivKey pkey;
uint256 hash = 0;
if (strType == "key")
{
wss.nKeys++;
ssValue >> pkey;
} else {
CWalletKey wkey;
ssValue >> wkey;
pkey = wkey.vchPrivKey;
}
// Old wallets store keys as "key" [pubkey] => [privkey]
// ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
// using EC operations as a checksum.
// Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
// remaining backwards-compatible.
try
{
ssValue >> hash;
}
catch(...){}
bool fSkipCheck = false;
if (hash != 0)
{
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + pkey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
if (Hash(vchKey.begin(), vchKey.end()) != hash)
{
strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
return false;
}
fSkipCheck = true;
}
if (!key.Load(pkey, vchPubKey, fSkipCheck))
{
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (!pwallet->LoadKey(key, vchPubKey))
{
strErr = "Error reading wallet database: LoadKey failed";
return false;
}
}
else if (strType == "mkey")
{
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if(pwallet->mapMasterKeys.count(nID) != 0)
{
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
return false;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
}
else if (strType == "ckey")
{
wss.nCKeys++;
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
strErr = "Error reading wallet database: LoadCryptedKey failed";
return false;
}
wss.fIsEncrypted = true;
}
else if (strType == "keymeta")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
// find earliest key creation time, as wallet birthday
if (!pwallet->nTimeFirstKey ||
(keyMeta.nCreateTime < pwallet->nTimeFirstKey))
pwallet->nTimeFirstKey = keyMeta.nCreateTime;
}
else if (strType == "defaultkey")
{
ssValue >> pwallet->vchDefaultKey;
}
else if (strType == "pool")
{
int64_t nIndex;
ssKey >> nIndex;
CKeyPool keypool;
ssValue >> keypool;
pwallet->setKeyPool.insert(nIndex);
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (pwallet->mapKeyMetadata.count(keyid) == 0)
pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
else if (strType == "version")
{
ssValue >> wss.nFileVersion;
if (wss.nFileVersion == 10300)
wss.nFileVersion = 300;
}
else if (strType == "cscript")
{
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> script;
if (!pwallet->LoadCScript(script))
{
strErr = "Error reading wallet database: LoadCScript failed";
return false;
}
}
else if (strType == "orderposnext")
{
ssValue >> pwallet->nOrderPosNext;
}
} catch (...)
{
return false;
}
return true;
}
static bool IsKeyType(string strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey = CPubKey();
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
// Try to be tolerant of single corrupt records:
string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
{
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType))
result = DB_CORRUPT;
else
{
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
LogPrintf("%s\n", strErr);
}
pcursor->close();
}
catch (boost::thread_interrupted) {
throw;
}
catch (...) {
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
if (result != DB_LOAD_OK)
return result;
LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
WriteTx(hash, pwallet->mapWallet[hash]);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
return DB_NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
if (wss.fAnyUnordered)
result = ReorderTransactions(pwallet);
return result;
}
void ThreadFlushWalletDB(const string& strFile)
{
// Make this thread recognisable as the wallet flushing thread
RenameThread("bingocoin-wallet");
static bool fOneThread;
if (fOneThread)
return;
fOneThread = true;
if (!GetBoolArg("-flushwallet", true))
return;
unsigned int nLastSeen = nWalletDBUpdated;
unsigned int nLastFlushed = nWalletDBUpdated;
int64_t nLastWalletUpdate = GetTime();
while (true)
{
MilliSleep(500);
if (nLastSeen != nWalletDBUpdated)
{
nLastSeen = nWalletDBUpdated;
nLastWalletUpdate = GetTime();
}
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
{
TRY_LOCK(bitdb.cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
while (mi != bitdb.mapFileUseCount.end())
{
nRefCount += (*mi).second;
mi++;
}
if (nRefCount == 0)
{
boost::this_thread::interruption_point();
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end())
{
LogPrint("db", "Flushing wallet.dat\n");
nLastFlushed = nWalletDBUpdated;
int64_t nStart = GetTimeMillis();
// Flush wallet.dat so it's self contained
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart);
}
}
}
}
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (true)
{
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
{
// Flush log data to the dat file
bitdb.CloseDb(wallet.strWalletFile);
bitdb.CheckpointLSN(wallet.strWalletFile);
bitdb.mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
filesystem::path pathDest(strDest);
if (filesystem::is_directory(pathDest))
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 104000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
filesystem::copy_file(pathSrc, pathDest);
#endif
LogPrintf("copied wallet.dat to %s\n", pathDest.string());
return true;
} catch(const filesystem::filesystem_error &e) {
LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
return false;
}
//
// Try to (very carefully!) recover wallet.dat if there is a problem.
//
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
{
// Recovery procedure:
// move wallet.dat to wallet.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to wallet.dat
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
std::string newFilename = strprintf("wallet.%d.bak", now);
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
bool fSuccess = allOK;
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0)
{
LogPrintf("Cannot create database file %s\n", filename);
return false;
}
CWallet dummyWallet;
CWalletScanState wss;
DbTxn* ptxn = dbenv.TxnBegin();
BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
{
if (fOnlyKeys)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
string strType, strErr;
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
wss, strType, strErr);
if (!IsKeyType(strType))
continue;
if (!fReadOK)
{
LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr);
continue;
}
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
delete pdbCopy;
return fSuccess;
}
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
{
return CWalletDB::Recover(dbenv, filename, false);
}
| [
"troy.beagley@outlook.com"
] | troy.beagley@outlook.com |
2b33ee4187f2a3f3db4c5c2921161200b83c92de | 86f22c67e65438948b982663f8b72a29090504a2 | /fem-sim/reduced_sim_gauss/src/reduced_sim_example.cpp | fecd0d54d4d9c85d27a12f9965ae05071e30563b | [] | no_license | itsvismay/research-experiments | 2738270859db259d917e2baf8a6af4115c195d8f | 4e49063f9fa53eda156e5cd5ded9c1caf45170ca | refs/heads/master | 2021-09-03T23:01:40.704813 | 2018-01-11T22:37:54 | 2018-01-11T22:37:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,114 | cpp | #include <vector>
//#include <Qt3DIncludes.h>
#include <GaussIncludes.h>
#include <ForceSpring.h>
#include <FEMIncludes.h>
#include <PhysicalSystemParticles.h>
//Any extra things I need such as constraints
#include <ConstraintFixedPoint.h>
#include <TimeStepperEulerImplicitLinear.h>
#include <igl/writeDMAT.h>
#include <igl/readDMAT.h>
#include <igl/viewer/Viewer.h>
#include <igl/readMESH.h>
#include <igl/unproject_onto_mesh.h>
#include <igl/get_seconds.h>
#include <igl/jet.h>
#include <igl/slice.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <sstream>
#include <boost/filesystem.hpp>
// Optimization
#include <LBFGS.h>
// JSON
#include <json.hpp>
// Tensorflow
#include <tensorflow/core/platform/env.h>
#include <tensorflow/core/public/session.h>
using json = nlohmann::json;
namespace fs = boost::filesystem;
using Eigen::VectorXd;
using Eigen::Vector3d;
using Eigen::VectorXi;
using Eigen::MatrixXd;
using Eigen::MatrixXi;
using Eigen::SparseMatrix;
using namespace LBFGSpp;
using namespace Gauss;
using namespace FEM;
using namespace ParticleSystem; //For Force Spring
/* Tetrahedral finite elements */
//typedef physical entities I need
typedef PhysicalSystemFEM<double, NeohookeanTet> NeohookeanTets;
typedef World<double,
std::tuple<PhysicalSystemParticleSingle<double> *, NeohookeanTets *>,
std::tuple<ForceSpringFEMParticle<double> *>,
std::tuple<ConstraintFixedPoint<double> *> > MyWorld;
typedef TimeStepperEulerImplictLinear<double, AssemblerEigenSparseMatrix<double>,
AssemblerEigenVector<double> > MyTimeStepper;
// Mesh
Eigen::MatrixXd V; // Verts
Eigen::MatrixXi T; // Tet indices
Eigen::MatrixXi F; // Face indices
int n_dof;
// Mouse/Viewer state
Eigen::RowVector3f last_mouse;
Eigen::RowVector3d dragged_pos;
bool is_dragging = false;
int dragged_vert = 0;
int current_frame = 0;
// Parameters
bool saving_training_data = false;
std::string output_dir = "output_data/";
void save_displacements_DMAT(const std::string path, MyWorld &world, NeohookeanTets *tets) { // TODO: Add mouse position data to ouput
auto q = mapDOFEigen(tets->getQ(), world);
Eigen::Map<Eigen::MatrixXd> dV(q.data(), V.cols(), V.rows()); // Get displacements only
Eigen::MatrixXd displacements = dV.transpose();
igl::writeDMAT(path, displacements, false); // Don't use ascii
}
void save_base_configurations_DMAT(Eigen::MatrixXd &V, Eigen::MatrixXi &F) {
std::stringstream verts_filename, faces_filename;
verts_filename << output_dir << "base_verts.dmat";
faces_filename << output_dir << "base_faces.dmat";
igl::writeDMAT(verts_filename.str(), V, false); // Don't use ascii
igl::writeDMAT(faces_filename.str(), F, false); // Don't use ascii
}
// Todo put this in utilities
Eigen::MatrixXd getCurrentVertPositions(MyWorld &world, NeohookeanTets *tets) {
// Eigen::Map<Eigen::MatrixXd> q(mapStateEigen<0>(world).data(), V.cols(), V.rows()); // Get displacements only
auto q = mapDOFEigen(tets->getQ(), world);
Eigen::Map<Eigen::MatrixXd> dV(q.data(), V.cols(), V.rows()); // Get displacements only
return V + dV.transpose();
}
void reset_world (MyWorld &world) {
auto q = mapStateEigen(world); // TODO is this necessary?
q.setZero();
}
// -- My integrator
template <typename ReducedSpaceImpl>
class ReducedSpace
{
public:
template<typename ...Params> // TODO necessary?
ReducedSpace(Params ...params) : m_impl(params...) {}
ReducedSpace() : m_impl() {}
inline VectorXd encode(const VectorXd &q) {
return m_impl.encode(q);
}
inline VectorXd decode(const VectorXd &z) {
return m_impl.decode(z);
}
inline VectorXd jacobian_transpose_vector_product(const VectorXd &z, const VectorXd &q) {
// d decode / d z * q
return m_impl.jacobian_transpose_vector_product(z, q);
}
inline double get_energy(const VectorXd &z) {
return m_impl.get_energy(z);
}
inline double get_energy_discrete(const VectorXd &z, MyWorld *world, NeohookeanTets *tets) {
return m_impl.get_energy_discrete(z, world, tets);
}
private:
ReducedSpaceImpl m_impl;
};
class IdentitySpaceImpl
{
public:
IdentitySpaceImpl(int n) {
m_I.resize(n,n);
m_I.setIdentity();
}
inline VectorXd encode(const VectorXd &q) {return q;}
inline VectorXd decode(const VectorXd &z) {return z;}
inline VectorXd jacobian_transpose_vector_product(const VectorXd &z, const VectorXd &q) {return q;}
inline double get_energy(const VectorXd &z) {std::cout << "Reduced energy not implemented!" << std::endl;}
inline double get_energy_discrete(const VectorXd &z, MyWorld *world, NeohookeanTets *tets) {std::cout << "Reduced energy not implemented!" << std::endl;}
private:
SparseMatrix<double> m_I;
};
class ConstraintSpaceImpl
{
public:
ConstraintSpaceImpl(const SparseMatrix<double> &P) {
m_P = P;
}
inline VectorXd encode(const VectorXd &q) {return m_P * q;}
inline VectorXd decode(const VectorXd &z) {return m_P.transpose() * z;}
inline VectorXd jacobian_transpose_vector_product(const VectorXd &z, const VectorXd &q) {return m_P * q;}
inline double get_energy(const VectorXd &z) {std::cout << "Reduced energy not implemented!" << std::endl;}
inline double get_energy_discrete(const VectorXd &z, MyWorld *world, NeohookeanTets *tets) {std::cout << "Reduced energy not implemented!" << std::endl;}
private:
SparseMatrix<double> m_P;
};
class LinearSpaceImpl
{
public:
LinearSpaceImpl(const MatrixXd &U) : m_U(U) {
std::cout<<"U rows: " << U.rows() << std::endl;
std::cout<<"U cols: " << U.cols() << std::endl;
}
inline VectorXd encode(const VectorXd &q) {
return m_U * q;
}
inline VectorXd decode(const VectorXd &z) {
return m_U.transpose() * z;
}
inline VectorXd jacobian_transpose_vector_product(const VectorXd &z, const VectorXd &q) { // TODO: do this without copy?
return m_U * q;
}
inline double get_energy(const VectorXd &z) {std::cout << "Reduced energy not implemented!" << std::endl;}
inline double get_energy_discrete(const VectorXd &z, MyWorld *world, NeohookeanTets *tets) {std::cout << "Reduced energy not implemented!" << std::endl;}
private:
MatrixXd m_U;
};
namespace tf = tensorflow;
auto tf_dtype = tf::DT_DOUBLE;
typedef double tf_dtype_type;
class AutoEncoderSpaceImpl
{
public:
AutoEncoderSpaceImpl(fs::path tf_models_root, json integrator_config) {
m_enc_dim = integrator_config["ae_encoded_dim"];
fs::path decoder_path = tf_models_root / "decoder.pb";
fs::path decoder_jac_path = tf_models_root / "decoder_jac.pb";
fs::path encoder_path = tf_models_root / "encoder.pb";
// Decoder
tf::Status status = tf::NewSession(tf::SessionOptions(), &m_decoder_session);
checkStatus(status);
tf::GraphDef decoder_graph_def;
status = ReadBinaryProto(tf::Env::Default(), decoder_path.string(), &decoder_graph_def);
checkStatus(status);
status = m_decoder_session->Create(decoder_graph_def);
checkStatus(status);
// Decoder Jacobian
status = tf::NewSession(tf::SessionOptions(), &m_decoder_jac_session);
checkStatus(status);
tf::GraphDef decoder_jac_graph_def;
status = ReadBinaryProto(tf::Env::Default(), decoder_jac_path.string(), &decoder_jac_graph_def);
checkStatus(status);
status = m_decoder_jac_session->Create(decoder_jac_graph_def);
checkStatus(status);
// Encoder
status = tf::NewSession(tf::SessionOptions(), &m_encoder_session);
checkStatus(status);
tf::GraphDef encoder_graph_def;
status = ReadBinaryProto(tf::Env::Default(), encoder_path.string(), &encoder_graph_def);
checkStatus(status);
status = m_encoder_session->Create(encoder_graph_def);
checkStatus(status);
if(integrator_config["use_reduced_energy"]) {
fs::path energy_model_path = tf_models_root / "energy_model.pb";
status = tf::NewSession(tf::SessionOptions(), &m_energy_model_session);
checkStatus(status);
tf::GraphDef energy_model_graph_def;
status = ReadBinaryProto(tf::Env::Default(), energy_model_path.string(), &energy_model_graph_def);
checkStatus(status);
status = m_energy_model_session->Create(energy_model_graph_def);
checkStatus(status);
}
if(integrator_config["use_discrete_reduced_energy"]) {
fs::path discrete_energy_model_path = tf_models_root / "discrete_energy_model.pb";
status = tf::NewSession(tf::SessionOptions(), &m_discrete_energy_model_session);
checkStatus(status);
tf::GraphDef discrete_energy_model_graph_def;
status = ReadBinaryProto(tf::Env::Default(), discrete_energy_model_path.string(), &discrete_energy_model_graph_def);
checkStatus(status);
status = m_discrete_energy_model_session->Create(discrete_energy_model_graph_def);
checkStatus(status);
}
// -- Testing
// tf::Tensor z_tensor(tf::DT_FLOAT, tf::TensorShape({1, 3}));
// auto z_tensor_mapped = z_tensor.tensor<tf_dtype_type, 2>();
// z_tensor_mapped(0, 0) = 0.0;
// z_tensor_mapped(0, 1) = 0.0;
// z_tensor_mapped(0, 2) = 0.0;
// tf::Tensor q_tensor(tf::DT_FLOAT, tf::TensorShape({1, 1908}));
// auto q_tensor_mapped = q_tensor.tensor<tf_dtype_type, 2>();
// for(int i =0; i < 1908; i++) {
// q_tensor_mapped(0, i) = 0.0;
// }
// // std::vector<std::pair<tf::string, tf::Tensor>>integrator_config["energy_model_config"]["enabled"] input_tensors = {{"x", x}, {"y", y}};
// std::vector<tf::Tensor> q_outputs;
// status = m_decoder_session->Run({{"decoder_input:0", z_tensor}},
// {"output_node0:0"}, {}, &q_outputs);
// checkStatus(status);
// std::vector<tf::Tensor> z_outputs;
// status = m_encoder_session->Run({{"encoder_input:0", q_tensor}},
// {"output_node0:0"}, {}, &z_outputs);
// checkStatus(status);
// tf::Tensor q_output = q_outputs[0];
// std::cout << "Success: " << q_output.flat<tf_dtype_type>() << "!" << std::endl;
// tf::Tensor z_output = z_outputs[0];
// std::cout << "Success: " << z_output.flat<tf_dtype_type>() << "!" << std::endl;
// std::cout << "Jac: " << jacobian(Vector3d(0.0,0.0,0.0)) << std::endl;
}
inline VectorXd encode(const VectorXd &q) {
tf::Tensor q_tensor(tf_dtype, tf::TensorShape({1, n_dof}));
auto q_tensor_mapped = q_tensor.tensor<tf_dtype_type, 2>();
for(int i =0; i < q.size(); i++) {
q_tensor_mapped(0, i) = q[i];
} // TODO map with proper function
std::vector<tf::Tensor> z_outputs;
tf::Status status = m_encoder_session->Run({{"encoder_input:0", q_tensor}},
{"output_node0:0"}, {}, &z_outputs);
auto z_tensor_mapped = z_outputs[0].tensor<tf_dtype_type, 2>();
VectorXd res(m_enc_dim); // TODO generalize and below in decode
for(int i = 0; i < res.size(); i++) {
res[i] = z_tensor_mapped(0,i);
}
return res;
}
inline VectorXd decode(const VectorXd &z) {
tf::Tensor z_tensor(tf_dtype, tf::TensorShape({1, m_enc_dim})); // TODO generalize
auto z_tensor_mapped = z_tensor.tensor<tf_dtype_type, 2>();
for(int i =0; i < z.size(); i++) {
z_tensor_mapped(0, i) = (float)z[i];
} // TODO map with proper function
std::vector<tf::Tensor> q_outputs;
tf::Status status = m_decoder_session->Run({{"decoder_input:0", z_tensor}},
{"output_node0:0"}, {}, &q_outputs);
auto q_tensor_mapped = q_outputs[0].tensor<tf_dtype_type, 2>();
VectorXd res(n_dof);
for(int i = 0; i < res.size(); i++) {
res[i] = q_tensor_mapped(0,i);
}
return res;
}
// Using finite differences
// TODO I should be able to do this as a single pass right? put all the inputs into one tensor
inline VectorXd jacobian_transpose_vector_product(const VectorXd &z, const VectorXd &q) { // TODO: do this without copy?
VectorXd res(z.size());
//Finite differences gradient
double t = 0.0005;
for(int i = 0; i < z.size(); i++) {
VectorXd dz_pos(z);
VectorXd dz_neg(z);
dz_pos[i] += t;
dz_neg[i] -= t;
res[i] = q.dot((decode(dz_pos) - decode(dz_neg)) / (2.0 * t));
}
return res;
}
// Analytical
// inline VectorXd jacobian_transpose_vector_product(const VectorXd &z) { // TODO: do this without copy?
// tf::Tensor z_tensor(tf_dtype, tf::TensorShape({1, m_enc_dim})); // TODO generalize
// auto z_tensor_mapped = z_tensor.tensor<tf_dtype_type, 2>();
// for(int i =0; i < z.size(); i++) {
// z_tensor_mapped(0, i) = (float)z[i];
// } // TODO map with proper function
// std::vector<tf::Tensor> jac_outputs;
// tf::Status status = m_decoder_jac_session->Run({{"decoder_input:0", z_tensor}},
// {"TensorArrayStack/TensorArrayGatherV3:0"}, {}, &jac_outputs); // TODO get better names
// auto jac_tensor_mapped = jac_outputs[0].tensor<tf_dtype_type, m_enc_dim>();
// MatrixXd res(n_dof, m_enc_dim); // TODO generalize
// for(int i = 0; i < res.rows(); i++) {
// for(int j = 0; j < res.cols(); j++) {
// res(i,j) = jac_tensor_mapped(0,i,j);
// }
// }
// return res;
// }
inline double get_energy(const VectorXd &z) {
tf::Tensor z_tensor(tf_dtype, tf::TensorShape({1, m_enc_dim})); // TODO generalize
auto z_tensor_mapped = z_tensor.tensor<tf_dtype_type, 2>();
for(int i =0; i < z.size(); i++) {
z_tensor_mapped(0, i) = (float)z[i];
} // TODO map with proper function
std::vector<tf::Tensor> q_outputs;
tf::Status status = m_energy_model_session->Run({{"energy_model_input:0", z_tensor}},
{"output_node0:0"}, {}, &q_outputs);
auto energy_tensor_mapped = q_outputs[0].tensor<tf_dtype_type, 2>();
return energy_tensor_mapped(0,0) * 1000.0; // TODO keep track of this normalizaiton factor
}
inline double get_energy_discrete(const VectorXd &z, MyWorld *world, NeohookeanTets *tets) {
tf::Tensor z_tensor(tf_dtype, tf::TensorShape({1, m_enc_dim})); // TODO generalize
auto z_tensor_mapped = z_tensor.tensor<tf_dtype_type, 2>();
for(int i =0; i < z.size(); i++) {
z_tensor_mapped(0, i) = (float)z[i];
} // TODO map with proper function
std::vector<tf::Tensor> energy_weight_outputs;
tf::Status status = m_discrete_energy_model_session->Run({{"energy_model_input:0", z_tensor}},
{"output_node0:0"}, {}, &energy_weight_outputs);
auto energy_weight_tensor_mapped = energy_weight_outputs[0].tensor<tf_dtype_type, 2>();
int n_tets = tets->getImpl().getNumElements();
double eps = 0.01;
double scale = 1000.0; // TODO link this to training data
double summed_energy = 0.0;
int n_tets_used = 0;
for(int i = 0; i < n_tets; i++) {
double energy_weight_i = energy_weight_tensor_mapped(0, i);
// std::cout << energy_weight_i << ", ";
if(energy_weight_i > eps) {
auto element = tets->getImpl().getElement(i);
summed_energy = energy_weight_i * element->getStrainEnergy(world->getState()); //TODO is the scale right? Is getting the state slow?
n_tets_used++;
}
}
// std::cout << std::endl;
// std::cout << "n_tets_used: " << n_tets_used << std::endl;
return summed_energy;
}
void checkStatus(const tf::Status& status) {
if (!status.ok()) {
std::cout << status.ToString() << std::endl;
exit(1);
}
}
private:
int m_enc_dim;
tf::Session* m_decoder_session;
tf::Session* m_decoder_jac_session;
tf::Session* m_encoder_session;
tf::Session* m_energy_model_session;
tf::Session* m_discrete_energy_model_session;
};
template <typename ReducedSpaceType>
class GPLCObjective
{
public:
GPLCObjective(
fs::path model_root,
json integrator_config,
VectorXd cur_z,
VectorXd prev_z,
MyWorld *world,
NeohookeanTets *tets,
ReducedSpaceType *reduced_space ) :
m_cur_z(cur_z),
m_prev_z(prev_z),
m_world(world),
m_tets(tets),
m_reduced_space(reduced_space)
{
m_use_reduced_energy = integrator_config["use_reduced_energy"];
m_h = integrator_config["timestep"];
// Construct mass matrix and external forces
AssemblerEigenSparseMatrix<double> M_asm;
getMassMatrix(M_asm, *m_world);
m_M = *M_asm;
VectorXd g(m_M.cols());
for(int i=0; i < g.size(); i += 3) {
g[i] = 0.0;
g[i+1] = integrator_config["gravity"];
g[i+2] = 0.0;
}
m_F_ext = m_M * g;
m_interaction_force = VectorXd::Zero(m_F_ext.size());
if(integrator_config["use_energy_completion"]) {
fs::path pca_components_path("pca_results/energy_pca_components.dmat");
fs::path sample_tets_path("pca_results/energy_indices.dmat");
MatrixXd U;
igl::readDMAT((model_root / pca_components_path).string(), U);
MatrixXi tet_indices_mat;
igl::readDMAT((model_root / sample_tets_path).string(), tet_indices_mat);\
m_energy_sample_tets = tet_indices_mat;
m_energy_basis = U.transpose();
std::cout << m_energy_basis.rows() << " " << m_energy_basis.cols() <<std::endl;
std::cout << tet_indices_mat.maxCoeff() <<std::endl;
m_energy_sampled_basis = igl::slice(m_energy_basis, tet_indices_mat, 1);
m_summed_energy_basis = m_energy_basis.colwise().sum();
std::cout << m_summed_energy_basis.size()<<std::endl;
}
}
void set_prev_zs(const VectorXd &cur_z, const VectorXd &prev_z) {
m_cur_z = cur_z;
m_prev_z = prev_z;
}
void set_interaction_force(const VectorXd &interaction_force) {
m_interaction_force = interaction_force;
}
// Just short helpers
inline VectorXd dec(const VectorXd &z) { return m_reduced_space->decode(z); }
inline VectorXd enc(const VectorXd &q) { return m_reduced_space->encode(q); }
inline VectorXd jtvp(const VectorXd &z, const VectorXd &q) { return m_reduced_space->jacobian_transpose_vector_product(z, q); }
double current_energy_using_completion() {
int n_sample_tets = m_energy_sample_tets.rows();
VectorXd sampled_energy(n_sample_tets);
for(int i = 0; i < n_sample_tets; i++) { // TODO parallel
sampled_energy[i] = m_tets->getImpl().getElement(i)->getStrainEnergy(m_world->getState());
}
// VectorXd alpha = m_energy_sampled_basis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(sampled_energy);
VectorXd alpha = (m_energy_sampled_basis.transpose() * m_energy_sampled_basis).ldlt().solve(m_energy_sampled_basis.transpose() * sampled_energy);
// std::cout << alpha.size() << std::endl;
// std::cout << m_energy_sampled_basis.rows() << " " << m_energy_sampled_basis.cols() << std::endl;
// std::cout << sampled_energy.size() << std::endl;
return m_summed_energy_basis.dot(alpha); // TODO is this right?
}
double objective(const VectorXd &new_z) { // TODO delete when done with finite differnece
// -- Compute GPLCObjective objective
double energy, reduced_energy;
// if(m_use_reduced_energy) {
// reduced_energy = m_reduced_space->get_energy(new_z);
Eigen::Map<Eigen::VectorXd> q = mapDOFEigen(m_tets->getQ(), *m_world);
VectorXd new_q = dec(new_z);
for(int i=0; i < q.size(); i++) {
q[i] = new_q[i]; // TODO is this the fastest way to do this?
}
//m_reduced_space->get_energy_discrete(new_z, m_world, m_tets);
// }
// else {
// energy = m_tets->getStrainEnergy(m_world->getState());
// }
// std::cout << "Energy: " << energy << ", Reduced Energy: " << reduced_energy << std::endl;
// std::cout << m_use_reduced_energy << std::endl;
if(m_use_reduced_energy) {
energy = current_energy_using_completion();;
}
else {
energy = m_tets->getStrainEnergy(m_world->getState());
}
VectorXd A = new_q - 2.0 * dec(m_cur_z) + dec(m_prev_z);
return 0.5 * A.transpose() * m_M * A + m_h * m_h * energy - m_h * m_h * A.transpose() * (m_F_ext + m_interaction_force);
}
double operator()(const VectorXd& new_z, VectorXd& grad)
{
// Update the tets with candidate configuration
// Eigen::Map<Eigen::VectorXd> q = mapDOFEigen(m_tets->getQ(), *m_world);
// VectorXd new_q = dec(new_z);
// for(int i=0; i < q.size(); i++) {
// q[i] = new_q[i]; // TODO is this the fastest way to do this?
// }
// -- Compute GPLCObjective objective
double obj_val = 0.0;
// VectorXd A = new_q - 2.0 * dec(m_cur_z) + dec(m_prev_z); // TODO: avoid decodes here by saving the qs aswell
obj_val = objective(new_z);
// double energy;
// if(m_use_reduced_energy) {
// energy = m_reduced_space->get_energy(z);
// }
// else {
// energy = m_tets->getStrainEnergy(m_world->getState());
// }
// obj_val = 0.5 * A.transpose() * m_M * A + m_h * m_h * energy - m_h * m_h * A.transpose() * (m_F_ext + m_interaction_force);
if(m_use_reduced_energy) {
// Finite differences gradient
double t = 0.0005;
for(int i = 0; i < new_z.size(); i++) {
VectorXd dq_pos(new_z);
VectorXd dq_neg(new_z);
dq_pos[i] += t;
dq_neg[i] -= t;
grad[i] = (objective(dq_pos) - obj_val) / (1.0 * t);
}
} else {
VectorXd new_q = dec(new_z);
VectorXd A = new_q - 2.0 * dec(m_cur_z) + dec(m_prev_z);
// -- Compute gradient
AssemblerEigenVector<double> internal_force; //maybe?
ASSEMBLEVECINIT(internal_force, new_q.size());
m_tets->getInternalForce(internal_force, m_world->getState());
ASSEMBLEEND(internal_force);
grad = jtvp(new_z, m_M * A - m_h * m_h * (*internal_force) - m_h * m_h * (m_F_ext + m_interaction_force));
}
// std::cout << "Objective: " << obj_val << std::endl;
// std::cout << "grad: " << grad << std::endl;
// std::cout << "z: " << new_z << std::endl;
return obj_val;
}
private:
VectorXd m_cur_z;
VectorXd m_prev_z;
VectorXd m_F_ext;
VectorXd m_interaction_force;
SparseMatrix<double> m_M; // mass matrix
double m_h;
MyWorld *m_world;
NeohookeanTets *m_tets;
bool m_use_reduced_energy;
ReducedSpaceType *m_reduced_space;
MatrixXi m_energy_sample_tets;
MatrixXd m_energy_basis;
MatrixXd m_energy_sampled_basis;
VectorXd m_summed_energy_basis;
};
template <typename ReducedSpaceType>
class GPLCTimeStepper {
public:
GPLCTimeStepper(fs::path model_root, json integrator_config, MyWorld *world, NeohookeanTets *tets, ReducedSpaceType *reduced_space) :
m_world(world), m_tets(tets), m_reduced_space(reduced_space) {
// Set up lbfgs params
json lbfgs_config = integrator_config["lbfgs_config"];
m_lbfgs_param.epsilon = lbfgs_config["lbfgs_epsilon"]; //1e-8// TODO replace convergence test with abs difference
//m_lbfgs_param.delta = 1e-3;
m_lbfgs_param.max_iterations = lbfgs_config["lbfgs_max_iterations"];//500;//300;
m_solver = new LBFGSSolver<double>(m_lbfgs_param);
reset_zs_to_current_world();
m_gplc_objective = new GPLCObjective<ReducedSpaceType>(model_root, integrator_config, m_cur_z, m_prev_z, world, tets, reduced_space);
}
~GPLCTimeStepper() {
delete m_solver;
delete m_gplc_objective;
}
void step(const VectorXd &interaction_force) {
double start_time = igl::get_seconds();
VectorXd z_param = m_cur_z; // Stores both the first guess and the final result
double min_val_res;
m_gplc_objective->set_interaction_force(interaction_force);
m_gplc_objective->set_prev_zs(m_cur_z, m_prev_z);
int niter = m_solver->minimize(*m_gplc_objective, z_param, min_val_res);
std::cout << niter << " iterations" << std::endl;
std::cout << "objective val = " << min_val_res << std::endl;
m_prev_z = m_cur_z;
m_cur_z = z_param; // TODO: Use pointers to avoid copies
update_world_with_current_configuration();
std::cout << "Timestep took: " << igl::get_seconds() - start_time << "s" << std::endl;
return;
}
void update_world_with_current_configuration() {
// TODO: is this the fastest way to do this?
Eigen::Map<Eigen::VectorXd> gauss_map_q = mapDOFEigen(m_tets->getQ(), *m_world);
VectorXd cur_q = m_reduced_space->decode(m_cur_z);
for(int i=0; i < cur_q.size(); i++) {
gauss_map_q[i] = cur_q[i];
}
}
void reset_zs_to_current_world() {
Eigen::Map<Eigen::VectorXd> gauss_map_q = mapDOFEigen(m_tets->getQ(), *m_world);
m_prev_z = m_reduced_space->encode(gauss_map_q);
m_cur_z = m_reduced_space->encode(gauss_map_q);
update_world_with_current_configuration();
}
// void test_gradient() {
// auto q_map = mapDOFEigen(m_tets->getQ(), *m_world);
// VectorXd q(m_reduced_space->encode(q_map));
// GPLCObjective<ReducedSpaceType> fun(q, q, 0.001, m_world, m_tets);
// VectorXd fun_grad(q.size());
// double fun_val = fun(q, fun_grad);
// VectorXd finite_diff_grad(q.size());
// VectorXd empty(q.size());
// double t = 0.000001;
// for(int i = 0; i < q.size(); i++) {
// VectorXd dq_pos(q);
// VectorXd dq_neg(q);
// dq_pos[i] += t;
// dq_neg[i] -= t;
// finite_diff_grad[i] = (fun(dq_pos, empty) - fun(dq_neg, empty)) / (2.0 * t);
// }
// VectorXd diff = fun_grad - finite_diff_grad;
// std::cout << "q size: " << q.size() << std::endl;
// std::cout << "Function val: " << fun_val << std::endl;
// std::cout << "Gradient diff: " << diff.norm() << std::endl;
// assert(diff.norm() < 1e-4);
// }
private:
LBFGSParam<double> m_lbfgs_param;
LBFGSSolver<double> *m_solver;
GPLCObjective<ReducedSpaceType> *m_gplc_objective;
VectorXd m_prev_z;
VectorXd m_cur_z;
MyWorld *m_world;
NeohookeanTets *m_tets;
ReducedSpaceType *m_reduced_space;
};
SparseMatrix<double> construct_constraints_P(NeohookeanTets *tets) {
// Construct constraint projection matrix
// Fixes all vertices with minimum x coordinate to 0
int dim = 0; // x
auto min_x_val = tets->getImpl().getV()(0,dim);
std::vector<unsigned int> min_verts;
for(unsigned int ii=0; ii<tets->getImpl().getV().rows(); ++ii) {
if(tets->getImpl().getV()(ii,dim) < min_x_val) {
min_x_val = tets->getImpl().getV()(ii,dim);
min_verts.clear();
min_verts.push_back(ii);
} else if(fabs(tets->getImpl().getV()(ii,dim) - min_x_val) < 1e-5) {
min_verts.push_back(ii);
}
}
std::sort(min_verts.begin(), min_verts.end());
int n = tets->getImpl().getV().rows() * 3;
int m = n - min_verts.size()*3;
SparseMatrix<double> P(m, n);
P.reserve(VectorXi::Constant(n, 1)); // Reserve enough space for 1 non-zero per column
int min_vert_i = 0;
int cur_col = 0;
for(int i = 0; i < m; i+=3){
while(min_verts[min_vert_i] * 3 == cur_col) { // Note * is for vert index -> flattened index
cur_col += 3;
min_vert_i++;
}
P.insert(i, cur_col) = 1.0;
P.insert(i+1, cur_col+1) = 1.0;
P.insert(i+2, cur_col+2) = 1.0;
cur_col += 3;
}
P.makeCompressed();
// std::cout << P << std::endl;
// -- Done constructing P
return P;
}
VectorXd compute_interaction_force(const Vector3d &dragged_pos, int dragged_vert, bool is_dragging, double spring_stiffness, NeohookeanTets *tets, const MyWorld &world) {
VectorXd force = VectorXd::Zero(n_dof); // TODO make this a sparse vector?
if(is_dragging) {
Vector3d fem_attached_pos = PosFEM<double>(&tets->getQ()[dragged_vert], dragged_vert, &tets->getImpl().getV())(world.getState());
Vector3d local_force = spring_stiffness * (dragged_pos - fem_attached_pos);
for(int i=0; i < 3; i++) {
force[dragged_vert * 3 + i] = local_force[i];
}
}
return force;
}
VectorXd get_von_mises_stresses(NeohookeanTets *tets, MyWorld &world) {
// Compute cauchy stress
int n_ele = tets->getImpl().getF().rows();
Eigen::Matrix<double, 3,3> stress = MatrixXd::Zero(3,3);
VectorXd vm_stresses(n_ele);
for(unsigned int i=0; i < n_ele; ++i) {
tets->getImpl().getElement(i)->getCauchyStress(stress, Vec3d(0,0,0), world.getState());
double s11 = stress(0, 0);
double s22 = stress(1, 1);
double s33 = stress(2, 2);
double s23 = stress(1, 2);
double s31 = stress(2, 0);
double s12 = stress(0, 1);
vm_stresses[i] = sqrt(0.5 * (s11-s22)*(s11-s22) + (s33-s11)*(s33-s11) + 6.0 * (s23*s23 + s31*s31 + s12*s12));
}
return vm_stresses;
}
typedef ReducedSpace<IdentitySpaceImpl> IdentitySpace;
typedef ReducedSpace<ConstraintSpaceImpl> ConstraintSpace;
typedef ReducedSpace<LinearSpaceImpl> LinearSpace;
typedef ReducedSpace<AutoEncoderSpaceImpl> AutoencoderSpace;
template <typename ReducedSpaceType>
void run_sim(ReducedSpaceType *reduced_space, const json &config, const fs::path &model_root) {
// -- Setting up GAUSS
MyWorld world;
igl::readMESH((model_root / "tets.mesh").string(), V, T, F);
auto material_config = config["material_config"];
auto integrator_config = config["integrator_config"];
auto visualization_config = config["visualization_config"];
NeohookeanTets *tets = new NeohookeanTets(V,T);
n_dof = tets->getImpl().getV().rows() * 3;
for(auto element: tets->getImpl().getElements()) {
element->setDensity(material_config["density"]);
element->setParameters(material_config["youngs_modulus"], material_config["poissons_ratio"]);
}
world.addSystem(tets);
fixDisplacementMin(world, tets);
world.finalize(); //After this all we're ready to go (clean up the interface a bit later)
reset_world(world);
// --- Finished GAUSS set up
// --- My integrator set up
double spring_stiffness = visualization_config["interaction_spring_stiffness"];
VectorXd interaction_force = VectorXd::Zero(n_dof);
GPLCTimeStepper<ReducedSpaceType> gplc_stepper(model_root, integrator_config, &world, tets, reduced_space);
bool show_stress = visualization_config["show_stress"];
/** libigl display stuff **/
igl::viewer::Viewer viewer;
viewer.callback_pre_draw = [&](igl::viewer::Viewer & viewer)
{
// predefined colors
const Eigen::RowVector3d orange(1.0,0.7,0.2);
const Eigen::RowVector3d yellow(1.0,0.9,0.2);
const Eigen::RowVector3d blue(0.2,0.3,0.8);
const Eigen::RowVector3d green(0.2,0.6,0.3);
if(is_dragging) {
Eigen::MatrixXd part_pos(1, 3);
part_pos(0,0) = dragged_pos[0]; // TODO why is eigen so confusing.. I just want to make a matrix from vec
part_pos(0,1) = dragged_pos[1];
part_pos(0,2) = dragged_pos[2];
viewer.data.set_points(part_pos, orange);
} else {
Eigen::MatrixXd part_pos = MatrixXd::Zero(1,3);
part_pos(0,0)=100000.0;
viewer.data.set_points(part_pos, orange);
}
if(viewer.core.is_animating)
{
// Save Current configuration
std::stringstream filename;
filename << output_dir << "displacements_" << current_frame << ".dmat";
if(saving_training_data) {
save_displacements_DMAT(filename.str(), world, tets);
}
// stepper.step(world);
auto q = mapDOFEigen(tets->getQ(), world);
// std::cout << "Potential = " << tets->getStrainEnergy(world.getState()) << std::endl;
Eigen::MatrixXd newV = getCurrentVertPositions(world, tets);
// std::cout<< newV.block(0,0,10,3) << std::endl;
viewer.data.set_vertices(newV);
viewer.data.compute_normals();
current_frame++;
interaction_force = compute_interaction_force(dragged_pos, dragged_vert, is_dragging, spring_stiffness, tets, world);
gplc_stepper.step(interaction_force);
// test_gradient(world, tets);
}
if(show_stress) {
// Do stress field viz
VectorXd vm_stresses = get_von_mises_stresses(tets, world);
// vm_stresses is per element... Need to compute avg value per vertex
VectorXd vm_per_vert = VectorXd::Zero(V.rows());
VectorXi neighbors_per_vert = VectorXi::Zero(V.rows());
int t = 0;
for(int i=0; i < T.rows(); i++) {
for(int j=0; j < 4; j++) {
t++;
int vert_index = T(i,j);
vm_per_vert[vert_index] += vm_stresses[i];
neighbors_per_vert[vert_index]++;
}
}
for(int i=0; i < vm_per_vert.size(); i++) {
vm_per_vert[i] /= neighbors_per_vert[i];
}
VectorXd vm_per_face = VectorXd::Zero(F.rows());
for(int i=0; i < vm_per_face.size(); i++) {
vm_per_face[i] = (vm_per_vert[F(i,0)] + vm_per_vert[F(i,1)] + vm_per_vert[F(i,2)])/3.0;
}
std::cout << vm_per_face.maxCoeff() << " " << vm_per_face.minCoeff() << std::endl;
MatrixXd C;
//VectorXd((vm_per_face.array() - vm_per_face.minCoeff()) / vm_per_face.maxCoeff())
igl::jet(vm_per_face / 60.0, false, C);
viewer.data.set_colors(C);
}
return false;
};
viewer.callback_key_pressed = [&](igl::viewer::Viewer &, unsigned int key, int mod)
{
switch(key)
{
case 'P':
case 'p':
{
viewer.core.is_animating = !viewer.core.is_animating;
break;
}
case 'r':
case 'R':
{
reset_world(world);
gplc_stepper.reset_zs_to_current_world();
break;
}
default:
return false;
}
return true;
};
viewer.callback_mouse_down = [&](igl::viewer::Viewer&, int, int)->bool
{
Eigen::MatrixXd curV = getCurrentVertPositions(world, tets);
last_mouse = Eigen::RowVector3f(viewer.current_mouse_x,viewer.core.viewport(3)-viewer.current_mouse_y,0);
// Find closest point on mesh to mouse position
int fid;
Eigen::Vector3f bary;
if(igl::unproject_onto_mesh(
last_mouse.head(2),
viewer.core.view * viewer.core.model,
viewer.core.proj,
viewer.core.viewport,
curV, F,
fid, bary))
{
long c;
bary.maxCoeff(&c);
dragged_pos = curV.row(F(fid,c)) + Eigen::RowVector3d(0.001,0.0,0.0); //Epsilon offset so we don't div by 0
dragged_vert = F(fid,c);
is_dragging = true;
// forceSpring->getImpl().setStiffness(spring_stiffness);
// auto pinned_q = mapDOFEigen(pinned_point->getQ(), world);
// pinned_q = dragged_pos;//(dragged_pos).cast<double>(); // necessary?
// fem_attached_pos = PosFEM<double>(&tets->getQ()[dragged_vert],dragged_vert, &tets->getImpl().getV());
// forceSpring->getImpl().setPosition0(fem_attached_pos);
return true;
}
return false; // TODO false vs true??
};
viewer.callback_mouse_up = [&](igl::viewer::Viewer&, int, int)->bool
{
is_dragging = false;
return false;
};
viewer.callback_mouse_move = [&](igl::viewer::Viewer &, int,int)->bool
{
if(is_dragging) {
Eigen::RowVector3f drag_mouse(
viewer.current_mouse_x,
viewer.core.viewport(3) - viewer.current_mouse_y,
last_mouse(2));
Eigen::RowVector3f drag_scene,last_scene;
igl::unproject(
drag_mouse,
viewer.core.view*viewer.core.model,
viewer.core.proj,
viewer.core.viewport,
drag_scene);
igl::unproject(
last_mouse,
viewer.core.view*viewer.core.model,
viewer.core.proj,
viewer.core.viewport,
last_scene);
dragged_pos += ((drag_scene-last_scene)*4.5).cast<double>(); //TODO why do I need to fine tune this
last_mouse = drag_mouse;
}
return false;
};
viewer.data.set_mesh(V,F);
viewer.core.show_lines = true;
viewer.core.invert_normals = true;
viewer.core.is_animating = false;
viewer.data.face_based = true;
viewer.launch();
}
int main(int argc, char **argv) {
// Load the configuration file
fs::path model_root(argv[1]);
fs::path sim_config("sim_config.json");
std::ifstream fin((model_root / sim_config).string());
json config;
fin >> config;
auto integrator_config = config["integrator_config"];
std::string reduced_space_string = integrator_config["reduced_space_type"];
if(reduced_space_string == "linear") {
std::string pca_dim(std::to_string((int)integrator_config["pca_dim"]));
fs::path pca_components_path("pca_results/pca_components_" + pca_dim + ".dmat");
MatrixXd U;
igl::readDMAT((model_root / pca_components_path).string(), U);
LinearSpace reduced_space(U);
run_sim<LinearSpace>(&reduced_space, config, model_root);
}
else if(reduced_space_string == "autoencoder") {
fs::path tf_models_root(model_root / "tf_models/");
AutoencoderSpace reduced_space(tf_models_root, integrator_config);
run_sim<AutoencoderSpace>(&reduced_space, config, model_root);
}
else if(reduced_space_string == "full") {
std::cout << "Not yet implemented." << std::endl;
// ConstraintSpace reduced_space(construct_constraints_P(tets));
// run_sim<ConstraintSpace>(&reduced_space, config, model_root);
}
else {
std::cout << "Not yet implemented." << std::endl;
return 1;
}
return EXIT_SUCCESS;
}
| [
"lawsonfulton@gmail.com"
] | lawsonfulton@gmail.com |
6e50f3ea795d906eda6efafc538a357dbb7d3fe0 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE124_Buffer_Underwrite/s03/CWE124_Buffer_Underwrite__new_char_memmove_11.cpp | 18d41c3d97f9f3ff6f0ef49244e465e6a976c84c | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 4,784 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__new_char_memmove_11.cpp
Label Definition File: CWE124_Buffer_Underwrite__new.label.xml
Template File: sources-sink-11.tmpl.cpp
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sink: memmove
* BadSink : Copy string to data using memmove
* Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse())
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE124_Buffer_Underwrite__new_char_memmove_11
{
#ifndef OMITBAD
void bad()
{
char * data;
data = NULL;
if(globalReturnsTrue())
{
{
char * dataBuffer = new char[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
}
}
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
memmove(data, source, 100*sizeof(char));
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by new [] so can't safely call delete [] on it */
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */
static void goodG2B1()
{
char * data;
data = NULL;
if(globalReturnsFalse())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
char * dataBuffer = new char[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
}
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
memmove(data, source, 100*sizeof(char));
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by new [] so can't safely call delete [] on it */
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
char * data;
data = NULL;
if(globalReturnsTrue())
{
{
char * dataBuffer = new char[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
}
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
memmove(data, source, 100*sizeof(char));
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by new [] so can't safely call delete [] on it */
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE124_Buffer_Underwrite__new_char_memmove_11; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
a144fbe22672598d51a7f77a48b435835a588724 | 714d4d2796e9b5771a1850a62c9ef818239f5e77 | /chrome/browser/extensions/api/content_settings/content_settings_api.cc | 0030797ab026950e9cab4f087aa0ec9dcef5816f | [
"BSD-3-Clause"
] | permissive | CapOM/ChromiumGStreamerBackend | 6c772341f815d62d4b3c4802df3920ffa815d52a | 1dde005bd5d807839b5d45271e9f2699df5c54c9 | refs/heads/master | 2020-12-28T19:34:06.165451 | 2015-10-21T15:42:34 | 2015-10-23T11:00:45 | 45,056,006 | 2 | 0 | null | 2015-10-27T16:58:16 | 2015-10-27T16:58:16 | null | UTF-8 | C++ | false | false | 12,318 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/content_settings/content_settings_api.h"
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/extensions/api/content_settings/content_settings_api_constants.h"
#include "chrome/browser/extensions/api/content_settings/content_settings_helpers.h"
#include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
#include "chrome/browser/extensions/api/content_settings/content_settings_store.h"
#include "chrome/browser/extensions/api/preference/preference_api_constants.h"
#include "chrome/browser/extensions/api/preference/preference_helpers.h"
#include "chrome/browser/plugins/plugin_finder.h"
#include "chrome/browser/plugins/plugin_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/content_settings.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "content/public/browser/plugin_service.h"
#include "extensions/browser/extension_prefs_scope.h"
#include "extensions/common/error_utils.h"
using content::BrowserThread;
using content::PluginService;
namespace Clear = extensions::api::content_settings::ContentSetting::Clear;
namespace Get = extensions::api::content_settings::ContentSetting::Get;
namespace Set = extensions::api::content_settings::ContentSetting::Set;
namespace pref_helpers = extensions::preference_helpers;
namespace pref_keys = extensions::preference_api_constants;
namespace {
bool RemoveContentType(base::ListValue* args,
ContentSettingsType* content_type) {
std::string content_type_str;
if (!args->GetString(0, &content_type_str))
return false;
// We remove the ContentSettingsType parameter since this is added by the
// renderer, and is not part of the JSON schema.
args->Remove(0, NULL);
*content_type =
extensions::content_settings_helpers::StringToContentSettingsType(
content_type_str);
return *content_type != CONTENT_SETTINGS_TYPE_DEFAULT;
}
} // namespace
namespace extensions {
namespace helpers = content_settings_helpers;
namespace keys = content_settings_api_constants;
bool ContentSettingsContentSettingClearFunction::RunSync() {
ContentSettingsType content_type;
EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type));
scoped_ptr<Clear::Params> params(Clear::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
ExtensionPrefsScope scope = kExtensionPrefsScopeRegular;
bool incognito = false;
if (params->details.scope ==
api::content_settings::SCOPE_INCOGNITO_SESSION_ONLY) {
scope = kExtensionPrefsScopeIncognitoSessionOnly;
incognito = true;
}
if (incognito) {
// We don't check incognito permissions here, as an extension should be
// always allowed to clear its own settings.
} else {
// Incognito profiles can't access regular mode ever, they only exist in
// split mode.
if (GetProfile()->IsOffTheRecord()) {
error_ = keys::kIncognitoContextError;
return false;
}
}
scoped_refptr<ContentSettingsStore> store =
ContentSettingsService::Get(GetProfile())->content_settings_store();
store->ClearContentSettingsForExtension(extension_id(), scope);
return true;
}
bool ContentSettingsContentSettingGetFunction::RunSync() {
ContentSettingsType content_type;
EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type));
scoped_ptr<Get::Params> params(Get::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
GURL primary_url(params->details.primary_url);
if (!primary_url.is_valid()) {
error_ = ErrorUtils::FormatErrorMessage(keys::kInvalidUrlError,
params->details.primary_url);
return false;
}
GURL secondary_url(primary_url);
if (params->details.secondary_url.get()) {
secondary_url = GURL(*params->details.secondary_url);
if (!secondary_url.is_valid()) {
error_ = ErrorUtils::FormatErrorMessage(keys::kInvalidUrlError,
*params->details.secondary_url);
return false;
}
}
std::string resource_identifier;
if (params->details.resource_identifier.get())
resource_identifier = params->details.resource_identifier->id;
bool incognito = false;
if (params->details.incognito.get())
incognito = *params->details.incognito;
if (incognito && !include_incognito()) {
error_ = pref_keys::kIncognitoErrorMessage;
return false;
}
HostContentSettingsMap* map;
content_settings::CookieSettings* cookie_settings;
if (incognito) {
if (!GetProfile()->HasOffTheRecordProfile()) {
// TODO(bauerb): Allow reading incognito content settings
// outside of an incognito session.
error_ = keys::kIncognitoSessionOnlyError;
return false;
}
map = HostContentSettingsMapFactory::GetForProfile(
GetProfile()->GetOffTheRecordProfile());
cookie_settings = CookieSettingsFactory::GetForProfile(
GetProfile()->GetOffTheRecordProfile()).get();
} else {
map = HostContentSettingsMapFactory::GetForProfile(GetProfile());
cookie_settings = CookieSettingsFactory::GetForProfile(GetProfile()).get();
}
ContentSetting setting;
if (content_type == CONTENT_SETTINGS_TYPE_COOKIES) {
// TODO(jochen): Do we return the value for setting or for reading cookies?
bool setting_cookie = false;
setting = cookie_settings->GetCookieSetting(primary_url, secondary_url,
setting_cookie, NULL);
} else {
setting = map->GetContentSetting(primary_url, secondary_url, content_type,
resource_identifier);
}
base::DictionaryValue* result = new base::DictionaryValue();
result->SetString(keys::kContentSettingKey,
helpers::ContentSettingToString(setting));
SetResult(result);
return true;
}
bool ContentSettingsContentSettingSetFunction::RunSync() {
ContentSettingsType content_type;
EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type));
scoped_ptr<Set::Params> params(Set::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
std::string primary_error;
ContentSettingsPattern primary_pattern =
helpers::ParseExtensionPattern(params->details.primary_pattern,
&primary_error);
if (!primary_pattern.IsValid()) {
error_ = primary_error;
return false;
}
ContentSettingsPattern secondary_pattern = ContentSettingsPattern::Wildcard();
if (params->details.secondary_pattern.get()) {
std::string secondary_error;
secondary_pattern =
helpers::ParseExtensionPattern(*params->details.secondary_pattern,
&secondary_error);
if (!secondary_pattern.IsValid()) {
error_ = secondary_error;
return false;
}
}
std::string resource_identifier;
if (params->details.resource_identifier.get())
resource_identifier = params->details.resource_identifier->id;
std::string setting_str;
EXTENSION_FUNCTION_VALIDATE(
params->details.setting->GetAsString(&setting_str));
ContentSetting setting;
EXTENSION_FUNCTION_VALIDATE(
helpers::StringToContentSetting(setting_str, &setting));
EXTENSION_FUNCTION_VALIDATE(HostContentSettingsMap::IsSettingAllowedForType(
GetProfile()->GetPrefs(), setting, content_type));
// Some content setting types support the full set of values listed in
// content_settings.json only for exceptions. For the default setting,
// some values might not be supported.
// For example, camera supports [allow, ask, block] for exceptions, but only
// [ask, block] for the default setting.
if (primary_pattern == ContentSettingsPattern::Wildcard() &&
secondary_pattern == ContentSettingsPattern::Wildcard() &&
!HostContentSettingsMap::IsDefaultSettingAllowedForType(
GetProfile()->GetPrefs(), setting, content_type)) {
static const char kUnsupportedDefaultSettingError[] =
"'%s' is not supported as the default setting of %s.";
// TODO(msramek): Get the same human readable name as is presented
// externally in the API, i.e. chrome.contentSettings.<name>.set().
std::string readable_type_name;
switch (content_type) {
case CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC:
readable_type_name = "microphone";
break;
case CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA:
readable_type_name = "camera";
break;
default:
DCHECK(false) << "No human-readable type name defined for this type.";
}
error_ = base::StringPrintf(
kUnsupportedDefaultSettingError,
content_settings_helpers::ContentSettingToString(setting),
readable_type_name.c_str());
return false;
}
ExtensionPrefsScope scope = kExtensionPrefsScopeRegular;
bool incognito = false;
if (params->details.scope ==
api::content_settings::SCOPE_INCOGNITO_SESSION_ONLY) {
scope = kExtensionPrefsScopeIncognitoSessionOnly;
incognito = true;
}
if (incognito) {
// Regular profiles can't access incognito unless include_incognito is true.
if (!GetProfile()->IsOffTheRecord() && !include_incognito()) {
error_ = pref_keys::kIncognitoErrorMessage;
return false;
}
} else {
// Incognito profiles can't access regular mode ever, they only exist in
// split mode.
if (GetProfile()->IsOffTheRecord()) {
error_ = keys::kIncognitoContextError;
return false;
}
}
if (scope == kExtensionPrefsScopeIncognitoSessionOnly &&
!GetProfile()->HasOffTheRecordProfile()) {
error_ = pref_keys::kIncognitoSessionOnlyErrorMessage;
return false;
}
scoped_refptr<ContentSettingsStore> store =
ContentSettingsService::Get(GetProfile())->content_settings_store();
store->SetExtensionContentSetting(extension_id(), primary_pattern,
secondary_pattern, content_type,
resource_identifier, setting, scope);
return true;
}
bool ContentSettingsContentSettingGetResourceIdentifiersFunction::RunAsync() {
ContentSettingsType content_type;
EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type));
if (content_type != CONTENT_SETTINGS_TYPE_PLUGINS) {
SendResponse(true);
return true;
}
PluginService::GetInstance()->GetPlugins(
base::Bind(&ContentSettingsContentSettingGetResourceIdentifiersFunction::
OnGotPlugins,
this));
return true;
}
void ContentSettingsContentSettingGetResourceIdentifiersFunction::OnGotPlugins(
const std::vector<content::WebPluginInfo>& plugins) {
PluginFinder* finder = PluginFinder::GetInstance();
std::set<std::string> group_identifiers;
base::ListValue* list = new base::ListValue();
for (std::vector<content::WebPluginInfo>::const_iterator it = plugins.begin();
it != plugins.end(); ++it) {
scoped_ptr<PluginMetadata> plugin_metadata(finder->GetPluginMetadata(*it));
const std::string& group_identifier = plugin_metadata->identifier();
if (group_identifiers.find(group_identifier) != group_identifiers.end())
continue;
group_identifiers.insert(group_identifier);
base::DictionaryValue* dict = new base::DictionaryValue();
dict->SetString(keys::kIdKey, group_identifier);
dict->SetString(keys::kDescriptionKey, plugin_metadata->name());
list->Append(dict);
}
SetResult(list);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, base::Bind(
&ContentSettingsContentSettingGetResourceIdentifiersFunction::
SendResponse,
this,
true));
}
} // namespace extensions
| [
"j.isorce@samsung.com"
] | j.isorce@samsung.com |
b9bf4fe68a27e059127a0a0ef4678c534758243c | 7f62f204ffde7fed9c1cb69e2bd44de9203f14c8 | /DboClient/Tool/TSTool/Attr_ACT_QItem.cpp | 6644cef1ff5c8993b35716bd83a5a836dbf90003 | [] | no_license | 4l3dx/DBOGLOBAL | 9853c49f19882d3de10b5ca849ba53b44ab81a0c | c5828b24e99c649ae6a2953471ae57a653395ca2 | refs/heads/master | 2022-05-28T08:57:10.293378 | 2020-05-01T00:41:08 | 2020-05-01T00:41:08 | 259,094,679 | 3 | 3 | null | 2020-04-29T17:06:22 | 2020-04-26T17:43:08 | null | UHC | C++ | false | false | 6,000 | cpp | // Attr_ACT_QItem.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "TSTool.h"
#include "Attr_ACT_QItem.h"
// CAttr_ACT_QItem 대화 상자입니다.
IMPLEMENT_SERIAL(CAttr_ACT_QItem, CAttr_Page, 1)
CAttr_ACT_QItem::CAttr_ACT_QItem()
: CAttr_Page(CAttr_ACT_QItem::IDD)
, m_taID(NTL_TS_TA_ID_INVALID)
, m_dwItemIdx0(0xffffffff)
, m_nItemCnt0(255)
, m_fItemProb0(1.f)
, m_dwItemIdx1(0xffffffff)
, m_nItemCnt1(255)
, m_fItemProb1(1.f)
, m_dwItemIdx2(0xffffffff)
, m_nItemCnt2(255)
, m_fItemProb2(1.f)
{
}
CAttr_ACT_QItem::~CAttr_ACT_QItem()
{
}
CString CAttr_ACT_QItem::GetPageData( void )
{
UpdateData( TRUE );
CString strData;
strData += PakingPageData( _T("taid"), m_taID );
if ( m_ctrCreateBtn.GetCheck() == BST_CHECKED ) strData += PakingPageData( _T("type"), eQITEM_TYPE_CREATE );
else if ( m_ctrDeleteBtn.GetCheck() == BST_CHECKED ) strData += PakingPageData( _T("type"), eQITEM_TYPE_DELETE );
if ( 0xffffffff != m_dwItemIdx0 )
{
strData += PakingPageData( _T("iidx0"), m_dwItemIdx0 );
strData += PakingPageData( _T("icnt0"), m_nItemCnt0 );
strData += PakingPageData( _T("iprob0"), m_fItemProb0 );
}
if ( 0xffffffff != m_dwItemIdx1 )
{
strData += PakingPageData( _T("iidx1"), m_dwItemIdx1 );
strData += PakingPageData( _T("icnt1"), m_nItemCnt1 );
strData += PakingPageData( _T("iprob1"), m_fItemProb1 );
}
if ( 0xffffffff != m_dwItemIdx2 )
{
strData += PakingPageData( _T("iidx2"), m_dwItemIdx2 );
strData += PakingPageData( _T("icnt2"), m_nItemCnt2 );
strData += PakingPageData( _T("iprob2"), m_fItemProb2 );
}
return strData;
}
void CAttr_ACT_QItem::UnPakingPageData( CString& strKey, CString& strValue )
{
if ( _T("taid") == strKey )
{
m_taID = atoi( strValue.GetBuffer() );
}
else if ( _T("type") == strKey )
{
eQITEM_TYPE eType = (eQITEM_TYPE)atoi( strValue.GetBuffer() );
if ( eQITEM_TYPE_CREATE == eType )
{
m_ctrCreateBtn.SetCheck( BST_CHECKED );
m_ctrDeleteBtn.SetCheck( BST_UNCHECKED );
}
else if ( eQITEM_TYPE_DELETE == eType )
{
m_ctrCreateBtn.SetCheck( BST_UNCHECKED );
m_ctrDeleteBtn.SetCheck( BST_CHECKED );
}
}
else if ( _T("iidx0") == strKey )
{
m_dwItemIdx0 = atoi( strValue.GetBuffer() );
}
else if ( _T("icnt0") == strKey )
{
m_nItemCnt0 = atoi( strValue.GetBuffer() );
}
else if ( _T("iprob0") == strKey )
{
m_fItemProb0 = atof( strValue.GetBuffer() );
}
else if ( _T("iidx1") == strKey )
{
m_dwItemIdx1 = atoi( strValue.GetBuffer() );
}
else if ( _T("icnt1") == strKey )
{
m_nItemCnt1 = atoi( strValue.GetBuffer() );
}
else if ( _T("iprob1") == strKey )
{
m_fItemProb1 = atof( strValue.GetBuffer() );
}
else if ( _T("iidx2") == strKey )
{
m_dwItemIdx2 = atoi( strValue.GetBuffer() );
}
else if ( _T("icnt2") == strKey )
{
m_nItemCnt2 = atoi( strValue.GetBuffer() );
}
else if ( _T("iprob2") == strKey )
{
m_fItemProb2 = atof( strValue.GetBuffer() );
}
}
void CAttr_ACT_QItem::DoDataExchange(CDataExchange* pDX)
{
CAttr_Page::DoDataExchange(pDX);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_ID_EDITOR, m_taID);
DDV_MinMaxUInt(pDX, m_taID, 0, NTL_TS_TA_ID_INVALID);
DDX_Control(pDX, IDC_TS_ACT_ATTR_QITEM_CREATE_CHECK, m_ctrCreateBtn);
DDX_Control(pDX, IDC_TS_ACT_ATTR_QITEM_DELETE_CHECK, m_ctrDeleteBtn);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_0_ITEMIDX_EDITOR, m_dwItemIdx0);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_0_ITEMCNT_EDITOR, m_nItemCnt0);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_0_ITEMPROB_EDITOR, m_fItemProb0);
DDV_MinMaxFloat( pDX, m_fItemProb0, 0.f, 1.f);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_1_ITEMIDX_EDITOR, m_dwItemIdx1);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_1_ITEMCNT_EDITOR, m_nItemCnt1);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_1_ITEMPROB_EDITOR, m_fItemProb1);
DDV_MinMaxFloat( pDX, m_fItemProb1, 0.f, 1.f);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_2_ITEMIDX_EDITOR, m_dwItemIdx2);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_2_ITEMCNT_EDITOR, m_nItemCnt2);
DDX_Text(pDX, IDC_TS_ACT_ATTR_QITEM_2_ITEMPROB_EDITOR, m_fItemProb2);
DDV_MinMaxFloat( pDX, m_fItemProb2, 0.f, 1.f);
DDX_Control(pDX, IDC_TS_ACT_ATTR_QITEM_DELETE_ALL_BTN, m_ctrDelAllBtn);
}
BOOL CAttr_ACT_QItem::OnInitDialog()
{
CAttr_Page::OnInitDialog();
// TODO: 여기에 추가 초기화 작업을 추가합니다.
m_ctrCreateBtn.SetCheck( BST_CHECKED );
m_ctrDeleteBtn.SetCheck( BST_UNCHECKED );
m_ctrDelAllBtn.ShowWindow( SW_HIDE );
if ( m_strData.GetLength() > 0 ) SetPageData( m_strData );
return TRUE; // return TRUE unless you set the focus to a control
// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}
BEGIN_MESSAGE_MAP(CAttr_ACT_QItem, CAttr_Page)
ON_BN_CLICKED(IDC_TS_ACT_ATTR_QITEM_CREATE_CHECK, &CAttr_ACT_QItem::OnBnClickedTsActAttrQitemCreateCheck)
ON_BN_CLICKED(IDC_TS_ACT_ATTR_QITEM_DELETE_CHECK, &CAttr_ACT_QItem::OnBnClickedTsActAttrQitemDeleteCheck)
ON_BN_CLICKED(IDC_TS_ACT_ATTR_QITEM_DELETE_ALL_BTN, &CAttr_ACT_QItem::OnBnClickedTsActAttrQitemDeleteAllBtn)
END_MESSAGE_MAP()
// CAttr_ACT_QItem 메시지 처리기입니다.
void CAttr_ACT_QItem::OnBnClickedTsActAttrQitemCreateCheck()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
if ( BST_CHECKED == m_ctrCreateBtn.GetCheck() )
{
m_ctrDelAllBtn.ShowWindow( SW_HIDE );
m_ctrDeleteBtn.SetCheck( BST_UNCHECKED );
}
else
{
m_ctrDelAllBtn.ShowWindow( SW_SHOW );
m_ctrDeleteBtn.SetCheck( BST_CHECKED );
}
}
void CAttr_ACT_QItem::OnBnClickedTsActAttrQitemDeleteCheck()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
if ( BST_CHECKED == m_ctrDeleteBtn.GetCheck() )
{
m_ctrDelAllBtn.ShowWindow( SW_SHOW );
m_ctrCreateBtn.SetCheck( BST_UNCHECKED );
}
else
{
m_ctrDelAllBtn.ShowWindow( SW_HIDE );
m_ctrCreateBtn.SetCheck( BST_CHECKED );
}
}
void CAttr_ACT_QItem::OnBnClickedTsActAttrQitemDeleteAllBtn()
{
m_nItemCnt0 = 255;
m_fItemProb0 = 1.f;
m_nItemCnt1 = 255;
m_fItemProb1 = 1.f;
m_nItemCnt2 = 255;
m_fItemProb2 = 1.f;
UpdateData( FALSE );
}
| [
"64261665+dboguser@users.noreply.github.com"
] | 64261665+dboguser@users.noreply.github.com |
3c97182b673601e3a94fb6b289702fb4307da428 | 1aff94578525cc73b3f200a2008adf5d777937d5 | /plugins/experimental/traffic_dump/session_data.h | 7551501e9336899d86c49575bdd598c04c548921 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"ISC",
"HPND",
"Apache-2.0",
"BSD-2-Clause",
"TCL",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"OpenSSL",
"MIT",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-public-domain"
] | permissive | zds05/trafficserver | 7117c27248123470a65434e67dc9c1a49c42caf3 | 258c69b7628f5a4b90488e147c244a582222b5c8 | refs/heads/master | 2022-11-15T12:51:28.183536 | 2020-07-15T23:31:09 | 2020-07-15T23:31:09 | 277,029,063 | 0 | 0 | Apache-2.0 | 2020-07-04T03:11:46 | 2020-07-04T03:11:45 | null | UTF-8 | C++ | false | false | 6,407 | h | /** @session_handler.h
Traffic Dump session handling encapsulation.
@section license License
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.
*/
#pragma once
#include <atomic>
#include <cstdlib>
#include <mutex>
#include <string_view>
#include "ts/ts.h"
#include "tscore/ts_file.h"
namespace traffic_dump
{
/** The information associated with an individual session.
*
* This class is responsible for containing the members associated with a
* particular session and defines the session handler callback.
*/
class SessionData
{
public:
/// By default, Traffic Dump logs will go into a directory called "dump".
static char const constexpr *const default_log_directory = "dump";
/// By default, 1 out of 1000 sessions will be dumped.
static constexpr int64_t default_sample_pool_size = 1000;
/// By default, logging will stop after 10 MB have been dumped.
static constexpr int64_t default_max_disk_usage = 10 * 1000 * 1000;
private:
//
// Instance Variables
//
/// Log file descriptor for this session's dump file.
int log_fd = -1;
/// The count of the currently outstanding AIO operations.
int aio_count = 0;
/// The offset of the last point written to so for in the dump file for this
/// session.
int64_t write_offset = 0;
/// Whether this session has been closed.
bool ssn_closed = false;
/// The filename for this session's dump file.
ts::file::path log_name;
/// Whether the first transaction in this session has been written.
bool has_written_first_transaction = false;
TSCont aio_cont = nullptr; /// AIO continuation callback
TSCont txn_cont = nullptr; /// Transaction continuation callback
// The following has to be recursive because the stack does not unwind
// between event invocations.
std::recursive_mutex disk_io_mutex; /// The mutex for guarding IO calls.
//
// Static Variables
//
// The index to be used for the TS API for storing this SessionData on a
// per-session basis.
static int session_arg_index;
/// The rate at which to dump sessions. Every one out of sample_pool_size will
/// be dumped.
static std::atomic<int64_t> sample_pool_size;
/// The maximum space logs should take up before stopping the dumping of new
/// sessions.
static std::atomic<int64_t> max_disk_usage;
/// The amount of bytes currently written to dump files.
static std::atomic<int64_t> disk_usage;
/// The directory into which to put the dump files.
static ts::file::path log_directory;
/// Only sessions with this SNI will be dumped (if set).
static std::string sni_filter;
/// The running counter of all sessions dumped by traffic_dump.
static uint64_t session_counter;
public:
SessionData();
~SessionData();
/** The getter for the session_arg_index value. */
static int get_session_arg_index();
/** Initialize the cross-session values of managing sessions.
*
* @return True if initialization is successful, false otherwise.
*/
static bool init(std::string_view log_directory, int64_t max_disk_usage, int64_t sample_size);
static bool init(std::string_view log_directory, int64_t max_disk_usage, int64_t sample_size, std::string_view sni_filter);
/** Set the sample_pool_size to a new value.
*
* @param[in] new_sample_size The new value to set for sample_pool_size.
*/
static void set_sample_pool_size(int64_t new_sample_size);
/** Reset the disk usage counter to 0. */
static void reset_disk_usage();
/** Set the max_disk_usage to a new value.
*
* @param[in] new_max_disk_usage The new value to set for max_disk_usage.
*/
static void set_max_disk_usage(int64_t new_max_disk_usage);
#if 0
// TODO: This will eventually be used by TransactionData to dump
// the server protocol description in the "server-response" node,
// but the TS API does not yet support this.
/** Get the JSON string that describes the server session stack.
*
* @param[in] ssnp The reference to the server session.
*
* @return A JSON description of the server protocol stack.
*/
static std::string get_server_protocol_description(TSHttpSsn ssnp);
#endif
/** Write the string to the session's dump file.
*
* @param[in] content The content to write to the file.
*
* @return TS_SUCCESS if the write is successfully scheduled with the AIO
* system, TS_ERROR otherwise.
*/
int write_to_disk(std::string_view content);
/** Write the transaction to the session's dump file.
*
* @param[in] content The transaction content to write to the file.
*
* @return TS_SUCCESS if the write is successfully scheduled with the AIO
* system, TS_ERROR otherwise.
*/
int write_transaction_to_disk(std::string_view content);
private:
/** Write the string to the session's dump file.
*
* This assumes that the caller acquired the required AIO lock.
*
* @param[in] content The content to write to the file.
*
* @return TS_SUCCESS if the write is successfully scheduled with the AIO
* system, TS_ERROR otherwise.
*/
int write_to_disk_no_lock(std::string_view content);
/** Get the JSON string that describes the client session stack.
*
* @param[in] ssnp The reference to the client session.
*
* @return A JSON description of the client protocol stack.
*/
static std::string get_client_protocol_description(TSHttpSsn ssnp);
/** The handler callback for when async IO is done. Used for cleanup. */
static int session_aio_handler(TSCont contp, TSEvent event, void *edata);
/** The handler callback for session events. */
static int global_session_handler(TSCont contp, TSEvent event, void *edata);
};
} // namespace traffic_dump
| [
"randallmeyer@yahoo.com"
] | randallmeyer@yahoo.com |
a1d4b1f103464c7e5cbd5419cd3857d4d098b076 | e038ac953ef13d418c60a4d2a8e37e2d2799c07d | /Boost/boost/numeric/odeint/external/vexcl/vexcl_resize.hpp | 06b9b16b7e42b50772fea4470c3271ac5cdc609d | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | prianna/sir-models | 219703080e2fab8e1c4591540fda54e49022b3de | b4fc281c4713360ed0fef8a9ab91627b6b11c958 | refs/heads/master | 2021-01-01T19:01:24.347882 | 2015-01-28T21:41:10 | 2015-01-28T21:41:10 | 29,988,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,338 | hpp | /*
[auto_generated]
boost/numeric/odeint/external/vexcl/vexcl_resize.hpp
[begin_description]
Enable resizing for vexcl vector and multivector.
[end_description]
Copyright 2009-2011 Karsten Ahnert
Copyright 2009-2011 Mario Mulansky
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 BOOST_NUMERIC_ODEINT_EXTERNAL_VEXCL_VEXCL_RESIZE_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_EXTERNAL_VEXCL_VEXCL_RESIZE_HPP_INCLUDED
#include <vexcl/vector.hpp>
#include <vexcl/multivector.hpp>
#include <boost/numeric/odeint/util/is_resizeable.hpp>
#include <boost/numeric/odeint/util/resize.hpp>
#include <boost/numeric/odeint/util/same_size.hpp>
namespace boost {
namespace numeric {
namespace odeint {
/*
* specializations for vex::vector< T >
*/
template< typename T >
struct is_resizeable< vex::vector< T > > : boost::true_type { };
template< typename T >
struct resize_impl< vex::vector< T > , vex::vector< T > >
{
static void resize( vex::vector< T > &x1 , const vex::vector< T > &x2 )
{
x1.resize( x2.queue_list() , x2.size() );
}
};
template< typename T >
struct same_size_impl< vex::vector< T > , vex::vector< T > >
{
static bool same_size( const vex::vector< T > &x1 , const vex::vector< T > &x2 )
{
return x1.size() == x2.size();
}
};
/*
* specializations for vex::multivector< T >
*/
template< typename T , size_t N, bool own >
struct is_resizeable< vex::multivector< T , N , own > > : boost::true_type { };
template< typename T , size_t N, bool own >
struct resize_impl< vex::multivector< T , N , own > , vex::multivector< T , N , own > >
{
static void resize( vex::multivector< T , N , own > &x1 , const vex::multivector< T , N , own > &x2 )
{
x1.resize( x2.queue_list() , x2.size() );
}
};
template< typename T , size_t N, bool own >
struct same_size_impl< vex::multivector< T , N , own > , vex::multivector< T , N , own > >
{
static bool same_size( const vex::multivector< T , N , own > &x1 , const vex::multivector< T , N , own > &x2 )
{
return x1.size() == x2.size();
}
};
} // namespace odeint
} // namespace numeric
} // namespace boost
#endif // BOOST_NUMERIC_ODEINT_EXTERNAL_VEXCL_VEXCL_RESIZE_HPP_INCLUDED
| [
"prianna@g.ucla.edu"
] | prianna@g.ucla.edu |
0357f95b1b752057af8690cd6732f4b17dba076f | ad85e7585ab474d354f78a810ac0180552c9b874 | /lapindrome.cpp | d30d800673f8aacf282427233a55aaf8ec0f60b8 | [] | no_license | imtiyaz23/Data-Structures | 34082baff1a53f3c3bae4b97f33089f066737fa4 | 1ce31270584125c3d57db42d41b0ba67bfe04680 | refs/heads/master | 2022-08-28T20:54:29.266186 | 2022-08-11T07:46:01 | 2022-08-11T07:46:01 | 211,332,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 849 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int tc;cin>>tc;
while(tc--)
{
string s;
cin>>s;
int lFreq[26],rFreq[26];
for(int i=0;i<26;i++)
{
lFreq[i]=0;
rFreq[i]=0;
}
for(int i=0;i<s.length()/2;i++)
{
char cur=s[i];
lFreq[cur-'a']++;
}
for(int i=(s.length()+1)/2;i<s.length();i++)
{
char cur=s[i];
rFreq[cur-'a']++;
}
bool IsSame=true;
for(int i=0;i<26;i++)
{
if(lFreq[i]!=rFreq[i])
{
IsSame=false;
break;
}
}
if(IsSame)
{
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
e7b3d073851746561ff33975baf962e47f790a74 | a336c7fcf345a4bcadffd4063b0ed7570ff88e7a | /App/sh.cpp | 6e447b79c0e7cb18a42c836eeaa961ea63e2f995 | [
"MIT"
] | permissive | hsdxpro/FireRays_SDK | ffefcd6599613514e4e67ab13194a6279fe4dca6 | d97431e256d43bddcf73af388f75458eaf054b34 | refs/heads/master | 2021-01-09T08:02:57.885502 | 2016-06-10T08:18:03 | 2016-06-10T08:18:03 | 60,832,554 | 1 | 0 | null | 2016-06-10T07:59:38 | 2016-06-10T07:59:38 | null | UTF-8 | C++ | false | false | 5,677 | cpp | /**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
********************************************************************/
#include "sh.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <algorithm>
#include <vector>
using namespace FireRays;
// Taken from PBRT book
static void EvaluateLegendrePolynomial(float x, int lmax, float* out)
{
#define P(l,m) out[ShIndex(l,m)]
// Calculate 0-strip values
P(0,0) = 1.f;
P(1,0) = x;
for (int l = 2; l <= lmax; ++l)
{
P(l, 0) = ((2*l-1)*x*P(l-1,0) - (l-1)*P(l-2,0)) / l;
}
// Calculate edge values m=l
float neg = -1.f;
float dfact = 1.f;
float xroot = sqrtf(std::max(0.f, 1.f - x*x));
float xpow = xroot;
for (int l = 1; l <= lmax; ++l)
{
P(l, l) = neg * dfact * xpow;
neg *= -1.f;
dfact *= 2*l + 1;
xpow *= xroot;
}
// Calculate pre-edge values m=l-1
for (int l = 2; l <= lmax; ++l)
{
P(l, l-1) = x * (2*l-1) * P(l-1, l-1);
}
// Calculate the rest
for (int l = 3; l <= lmax; ++l)
{
for (int m = 1; m <= l-2; ++m)
{
P(l, m) = ((2 * (l-1) + 1) * x * P(l-1,m) - (l-1+m) * P(l-2,m)) / (l - m);
}
}
#undef P
}
// Calculates (a-|b|)! / (a + |b|)!
static float DivFact(int a, int b)
{
if (b == 0)
{
return 1.f;
}
float fa = (float)a;
float fb = std::fabs((float)b);
float v = 1.f;
for (float x = fa-fb+1.f; x <= fa+fb; x += 1.f)
{
v *= x;
}
return 1.f / v;
}
///< The function computes normalization constants for Y_l_m terms
static float K(int l, int m)
{
return std::sqrt((2.f * l + 1.f) * 1.f / (4 * PI) * DivFact(l, m));
}
///< Calculates sin(i*s) and cos(i*c) for i up to n
static void SinCosIndexed(float s, float c, int n, float *sout, float *cout)
{
float si = 0;
float ci = 1;
for (int i = 0; i < n; ++i)
{
*sout++ = si;
*cout++ = ci;
float oldsi = si;
si = si * c + ci * s;
ci = ci * c - oldsi * s;
}
}
///< The function evaluates the value of Y_l_m(p) coefficient up to lmax band.
///< coeffs array should have at least NumShTerms(lmax) elements.
void ShEvaluate(float3 const& p, int lmax, float* coefs)
{
// Initialize the array by the values of Legendre polynomials
EvaluateLegendrePolynomial(p.z, lmax, coefs);
// Normalization coefficients
std::vector<float> klm(NumShTerms(lmax));
for (int l = 0; l <= lmax; ++l)
{
for (int m = -l; m <= l; ++m)
{
klm[ShIndex(l, m)] = K(l, m);
}
}
// Calculate cos(mphi) and sin(mphi) values
std::vector<float> cosmphi(lmax + 1);
std::vector<float> sinmphi(lmax + 1);
float xylen = std::sqrt(std::max(0.f, 1.f - p.z*p.z));
// If degenerate set to 0 and 1
if (xylen == 0.f)
{
for (int i = 0; i <= lmax; ++i)
{
sinmphi[i] = 0.f;
cosmphi[i] = 1.f;
}
}
else
{
SinCosIndexed(p.y / xylen, p.x / xylen, lmax+1, &sinmphi[0], &cosmphi[0]);
}
// Multiply in normalization coeffs and sin and cos where needed
const float sqrt2 = sqrtf(2.f);
for (int l = 0; l <= lmax; ++l)
{
// For negative multiply by sin and Klm
for (int m = -l; m < 0; ++m)
{
coefs[ShIndex(l, m)] = sqrt2 * klm[ShIndex(l, m)] * coefs[ShIndex(l, -m)] * sinmphi[-m];
}
// For 0 multiply by Klm
coefs[ShIndex(l, 0)] *= klm[ShIndex(l, 0)];
// For positive multiply by cos and Klm
for (int m = 1; m <= l; ++m)
{
coefs[ShIndex(l, m)] *= sqrt2 * klm[ShIndex(l, m)] * cosmphi[m];
}
}
}
static inline float lambda(float l)
{
return sqrtf((4.f * (float)M_PI) / (2.f * l + 1.f));
}
void ShConvolveCosTheta(int lmax, float3 const* cin, float3* cout)
{
static const float s_costheta[18] = { 0.8862268925f, 1.0233267546f,
0.4954159260f, 0.0000000000f, -0.1107783690f, 0.0000000000f,
0.0499271341f, 0.0000000000f, -0.0285469331f, 0.0000000000f,
0.0185080823f, 0.0000000000f, -0.0129818395f, 0.0000000000f,
0.0096125342f, 0.0000000000f, -0.0074057109f, 0.0000000000f };
for (int l = 0; l <= lmax; ++l)
{
for (int m = -l; m <= l; ++m)
{
int o = ShIndex(l, m);
if (l < 18)
cout[o] = lambda((float)l) * cin[o] * s_costheta[l];
else
cout[o] = 0.f;
}
}
}
| [
"dmitry.a.kozlov@gmail.com"
] | dmitry.a.kozlov@gmail.com |
2e694d72caf93493a245b92d9af35ef39fb2d8f8 | 1817295bb117c18930fa04e2ada5b8a938e2ab2b | /src/Magnum/Math/Test/DualTest.cpp | 01ec3b44dc1df08b211cdf7c21c6cbb83b60e50f | [
"MIT"
] | permissive | torkos/magnum | eedd480ec04e1884dfa74691791eb57e784e4374 | e2bd3943003860d7a9819f0e0d99b7f952b50c59 | refs/heads/master | 2021-01-18T05:38:00.007157 | 2015-02-08T22:27:01 | 2015-02-08T22:32:59 | 30,578,141 | 0 | 1 | null | 2015-02-10T06:18:04 | 2015-02-10T06:18:04 | null | UTF-8 | C++ | false | false | 3,995 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <sstream>
#include <Corrade/TestSuite/Tester.h>
#include "Magnum/Math/Dual.h"
namespace Magnum { namespace Math { namespace Test {
struct DualTest: Corrade::TestSuite::Tester {
explicit DualTest();
void construct();
void constructDefault();
void constructCopy();
void compare();
void addSubtract();
void negated();
void multiplyDivide();
void conjugated();
void sqrt();
void debug();
};
typedef Math::Dual<Float> Dual;
DualTest::DualTest() {
addTests({&DualTest::construct,
&DualTest::constructDefault,
&DualTest::constructCopy,
&DualTest::compare,
&DualTest::addSubtract,
&DualTest::negated,
&DualTest::multiplyDivide,
&DualTest::conjugated,
&DualTest::sqrt,
&DualTest::debug});
}
void DualTest::construct() {
constexpr Dual a(2.0f, -7.5f);
constexpr Float b = a.real();
constexpr Float c = a.dual();
CORRADE_COMPARE(b, 2.0f);
CORRADE_COMPARE(c, -7.5f);
constexpr Dual d(3.0f);
CORRADE_COMPARE(d.real(), 3.0f);
CORRADE_COMPARE(d.dual(), 0.0f);
}
void DualTest::constructDefault() {
constexpr Dual a;
CORRADE_COMPARE(a, Dual(0.0f, 0.0f));
}
void DualTest::constructCopy() {
constexpr Dual a(2.0f, 3.0f);
constexpr Dual b(a);
CORRADE_COMPARE(b, Dual(2.0f, 3.0f));
}
void DualTest::compare() {
CORRADE_VERIFY(Dual(1.0f, 1.0f+TypeTraits<Float>::epsilon()/2) == Dual(1.0f, 1.0f));
CORRADE_VERIFY(Dual(1.0f, 1.0f+TypeTraits<Float>::epsilon()*2) != Dual(1.0f, 1.0f));
CORRADE_VERIFY(Dual(1.0f+TypeTraits<Float>::epsilon()/2, 1.0f) == Dual(1.0f, 1.0f));
CORRADE_VERIFY(Dual(1.0f+TypeTraits<Float>::epsilon()*2, 1.0f) != Dual(1.0f, 1.0f));
/* Compare to real part only */
CORRADE_VERIFY(Dual(1.0f, 0.0f) == 1.0f);
CORRADE_VERIFY(Dual(1.0f, 3.0f) != 1.0f);
}
void DualTest::addSubtract() {
Dual a(2.0f, -7.5f);
Dual b(-3.3f, 0.2f);
Dual c(-1.3f, -7.3f);
CORRADE_COMPARE(a + b, c);
CORRADE_COMPARE(c - b, a);
}
void DualTest::negated() {
CORRADE_COMPARE(-Dual(1.0f, -6.5f), Dual(-1.0f, 6.5f));
}
void DualTest::multiplyDivide() {
Dual a(1.5f, -4.0f);
Dual b(-2.0f, 0.5f);
Dual c(-3.0f, 8.75f);
CORRADE_COMPARE(a*b, c);
CORRADE_COMPARE(c/b, a);
}
void DualTest::conjugated() {
CORRADE_COMPARE(Dual(1.0f, -6.5f).conjugated(), Dual(1.0f, 6.5f));
}
void DualTest::sqrt() {
CORRADE_COMPARE(Math::sqrt(Dual(16.0f, 2.0f)), Dual(4.0f, 0.25f));
}
void DualTest::debug() {
std::ostringstream o;
Debug(&o) << Dual(2.5f, -0.3f);
CORRADE_COMPARE(o.str(), "Dual(2.5, -0.3)\n");
}
}}}
CORRADE_TEST_MAIN(Magnum::Math::Test::DualTest)
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.