text
stringlengths
8
6.88M
#include<stdio.h> #include <stdlib.h> #include<string.h> #include<ctype.h> #include<time.h> #define RETURNTIME 15 char catagories[][15]={"Samsung","Apple","Nokia","Sony","LG","HTC"}; void returnfunc(void); void mainmenu(void); void addstaff(void); void deletestaff(void); void editstaff(void); void searchstaff(void); void viewstaff(void); void closeapplication(void); int getdata(); int checkid(int); int t(void); void Password(); void issuerecord(); void loaderanim(); FILE *fp,*ft,*fs; int s; char findstaff; char password[10]={"pass"}; struct meroDate { int mm,dd,yy; }; struct staff { int id; char stname[20]; char name[20]; char available[20]; int qty; int price; int count; char *cat; struct meroDate issued; struct meroDate duedate; }; struct staff a; int main() { Password(); return 0; } void mainmenu() { int i; int choice; printf(" \t\tMAIN MENU \n"); printf("\t\t\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\n"); printf("<1> Add Mobile Record\n"); printf("<2> View Mobile list\n"); printf("<3> Search Mobile Record\n"); printf("<4> Edit Mobile Record\n"); printf("<5> Delete Mobile Record\n"); printf("<6> Close The Application\n"); t(); printf("Enter your choice:"); fflush(stdin); scanf("%d",&choice); switch(choice) { case 1: addstaff(); break; case 2: viewstaff(); break; case 3: searchstaff(); break; case 4: editstaff(); break; case 5: deletestaff(); break; case 6: { printf("\tMobile Store Management System\n"); printf("\tProject in C"); printf("is brought to you by\n"); printf("\tBATCH-2\n"); exit(0); } default: { printf("\n\aWrong Entry!!Please re-entered correct option"); mainmenu(); } } } void addstaff(void) { int i; int temp; printf("SELECT BRANDS\n"); printf("<1> Samsung\n"); printf("<2> Apple\n"); printf("<3> Nokia\n"); printf("<4> Sony\n"); printf("<5> LG\n"); printf("<6> HTC\n"); printf("<7> Back to main menu\n"); printf("Enter your choice:"); scanf("%d",&s); if(s==7) mainmenu() ; fp=fopen("stf.dat","ab+"); if(getdata()==1) { a.cat=catagories[s-1]; fseek(fp,0,SEEK_END); fwrite(&a,sizeof(a),1,fp); fclose(fp); printf("The record is sucessfully saved\n"); printf("Save any more?(1-y / 0-n):"); fflush(stdin); scanf("%d",&temp); if(temp==0) mainmenu(); else addstaff(); } } void deletestaff() { int d,b; int another=1; while(another==1) { findstaff='f'; printf("Enter the Mobile ID to delete:"); scanf("%d",&d); fp=fopen("stf.dat","rb+"); rewind(fp); while(fread(&a,sizeof(a),1,fp)==1) { if(a.id==d) { printf("\nThe Mobile record is available"); printf("\nStaff name is %s",a.name); findstaff='t'; } } if(findstaff!='t') { printf("\nNo record is found modify the search\n"); mainmenu(); } if(findstaff=='t' ) { printf("\nDo you want to delete it?(1-Y/0-N):"); fflush(stdin); scanf("%d",&b); if(b==1) { ft=fopen("test.dat","wb+"); rewind(fp); while(fread(&a,sizeof(a),1,fp)==1) { if(a.id!=d) { fseek(ft,0,SEEK_CUR); fwrite(&a,sizeof(a),1,ft); } } fclose(ft); fclose(fp); remove("stf.dat"); rename("test.dat","stf.dat"); fp=fopen("stf.dat","rb+"); if(findstaff=='t') { printf("\nThe record is sucessfully deleted\n"); printf("\n\tDelete another record?(Y/N)"); } fclose(fp); } else mainmenu(); fflush(stdin); printf("\n\tDelete another record?(Y/N)"); scanf("%d",&another); } } mainmenu(); } void searchstaff() { int d; int c,e; printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2xB2\Xb 2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2Search Mobile\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); printf("\n1. Search By ID\n"); printf("2. Search By model Name\n"); printf("Enter Your Choice:"); fflush(stdin); scanf("%d",&c); fp=fopen("stf.dat","rb+"); rewind(fp); switch(c) { case 1: { printf("\xB2\xB2\xB2\xB2\xB2\xB2Search Mobile By Id\xB2\xB2\xB2\xB2\xB2\xB2"); printf("Enter the Mobile id:"); scanf("%d",&d); while(fread(&a,sizeof(a),1,fp)==1) { if(a.id==d) { printf("The Mobile is available\n"); printf("\nID:%d",a.id); printf("\nBrand:%s",a.cat); printf("\nName:%s",a.name); printf("\nAvailability:%s ",a.available); printf("\nQuantity:%i ",a.qty); printf("Price:%i ",a.price); findstaff='t'; } } if(findstaff!='t') { printf("\aNo Record Found\n"); } fclose(fp); printf("Try another search?(1-y/0-n)"); fflush(stdin); scanf("%d",&e); if(e==1) searchstaff(); else mainmenu(); break; } case 2: { char s[15]; printf("\xB2\xB2\xB2\xB2\xB2\xB2Search Mobile By model Name\xB2\xB2\xB2\xB2\xB2\xB2"); printf("\nEnter Model Name:"); scanf("%s",s); int d=0; while(fread(&a,sizeof(a),1,fp)==1) { if(strcmp(a.name,(s))==0) { printf("\nThe Staff is available"); printf("\nID:%d",a.id); printf("\nName:%s",a.name); printf("\nAvailability:%s",a.available); printf("\nQuantity:%i",a.qty); printf("\nPrice:%i",a.price); d+=6; } } if(d==0) printf("\n\aNo Record Found"); printf("\nTry another search?(1-Y/0-N)"); fflush(stdin); scanf("%d",&e); if(e==1) searchstaff(); else mainmenu(); break; } default : searchstaff(); } fclose(fp); } void viewstaff(void) { int i=0,j; printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2Mobile List\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); printf("\n BRAND\t\tID\tMODEL NAME\tAVAILABILITY\tQUANTITY\tPRICE\n"); j=4; fp=fopen("stf.dat","rb"); while(fread(&a,sizeof(a),1,fp)==1) { printf("%s",a.cat); printf("\t\t%d",a.id); printf("\t%s",a.name); printf("\t\t%s",a.available); printf("\t%i",a.qty); printf("\t\t%i",a.price); printf("\n\n"); j++; } fclose(fp); returnfunc(); } void editstaff(void) { int c=0; int d,e; printf("\n\xB2\xB2\xB2\xB2\xB2\xB2Edit Mobile Section \xB2\xB2\xB2\xB2\xB2\xB2"); int another=1; while(another==1) { printf("\nEnter Mobile Id to be edited:"); scanf("%d",&d); fp=fopen("stf.dat","rb+"); while(fread(&a,sizeof(a),1,fp)==1) { if(checkid(d)==0) { printf("\nThe Mobile is availble"); printf("\nThe Mobile ID:%d",a.id); printf("\nEnter new name:"); scanf("%s",a.name); printf("\nEnter new Availability Status:"); scanf("%s",a.available); printf("\nEnter new Quantity:"); scanf("%i",&a.qty); printf("\nEnter new Price:"); scanf("%i",&a.price); printf("\nThe record is modified"); fseek(fp,ftell(fp)-sizeof(a),0); fwrite(&a,sizeof(a),1,fp); fclose(fp); c=1; } if(c==0) { printf("\nNo record found"); } } printf("\nModify another Record?(1-Y/0-N)"); fflush(stdin); scanf("%d",&another); //another=getch() ; } returnfunc(); } void returnfunc(void) { mainmenu(); } int getdata() { int t; printf("\nEnter the Information Below"); printf("\nBrand:"); printf("%s",catagories[s-1]); printf("\nMBL ID:\t"); scanf("%d",&t); if(checkid(t) == 0) { printf("\n\aThe id already exists\a\n\n"); mainmenu(); return 0; } a.id=t; printf("\nModel Name:"); scanf("%s",a.name); printf("\nAvailability:"); scanf("%s",a.available); printf("\nQuantity:"); scanf("%i",&a.qty); printf("\nPrice:"); scanf("%i",&a.price); return 1; } int checkid(int t) { rewind(fp); while(fread(&a,sizeof(a),1,fp)==1) if(a.id==t) return 0; return 1; } int t(void) { time_t t; time(&t); printf("\nDate and time:%s\n",ctime(&t)); return 0 ; } void Password(void) { char d[25]="Password Protected"; char ch,pass[10]; int i=0,j; printf("\t\t\t\tWELCOME\n\t\t\t\t To \n\t\t \xB2\xB2\xB2\xB2\xB2\xB2 Mobile Store Management System \xB2\xB2\xB2\xB2\xB2\xB2\n"); printf("\t \n\n\n Enter Password:"); scanf("%s",&pass); /*while(ch!=13) { ch=getch(); if(ch!=13 && ch!=8) { putch('*'); pass[i] = ch; i++; } } pass[i] = '\0'; */ if(strcmp(pass,password)==0) { printf("\n\n\n\t\tPassword matched!!"); printf("\n\n\tPress any key to countinue....."); mainmenu(); } else { printf("\n\n\n\t\t\aWarning!! \n\t Incorrect Password"); Password(); } }
#include "qcolorwidget.h" #include <qcolordialog.h> QColorWidget::QColorWidget(QWidget *parent) : QWidget(parent) { this->color = QColor(Qt::white); this->setMinimumSize(50, 20); } QColor QColorWidget::getColor() { return this->color; } void QColorWidget::setColor(const QColor &color) { this->color = color; } void QColorWidget::setWidth(int width) { this->setMinimumWidth(width); this->setMaximumWidth(width); } void QColorWidget::setHeight(int height) { this->setMinimumHeight(height); this->setMaximumHeight(height); } void QColorWidget::mousePressEvent(QMouseEvent *) { QColor color = QColorDialog::getColor(this->color); if (color.isValid()) { this->color = color; emit colorChanged(color); } } void QColorWidget::paintEvent(QPaintEvent *) { int w = this->width(); int h = this->height(); QPainter paint(this); // draw paint.setPen(QColor(Qt::black)); paint.setBrush(QBrush(this->color, Qt::SolidPattern)); paint.drawRect(0, 0, w - 1, h - 1); } QPaintEngine *QColorWidget::paintEngine() const { return nullptr; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.UI.Input.Inking.Analysis.0.h" #include "Windows.Foundation.0.h" #include "Windows.UI.Input.Inking.0.h" #include "Windows.UI.Input.Inking.1.h" #include "Windows.Foundation.Collections.1.h" #include "Windows.Foundation.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::UI::Input::Inking::Analysis { struct __declspec(uuid("ee049368-6110-4136-95f9-ee809fc20030")) __declspec(novtable) IInkAnalysisInkBullet : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecognizedText(hstring * value) = 0; }; struct __declspec(uuid("6a85ed1f-1fe4-4e15-898c-8e112377e021")) __declspec(novtable) IInkAnalysisInkDrawing : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_DrawingKind(winrt::Windows::UI::Input::Inking::Analysis::InkAnalysisDrawingKind * value) = 0; virtual HRESULT __stdcall get_Center(Windows::Foundation::Point * value) = 0; virtual HRESULT __stdcall get_Points(Windows::Foundation::Collections::IVectorView<Windows::Foundation::Point> ** value) = 0; }; struct __declspec(uuid("4bd228ad-83af-4034-8f3b-f8687dfff436")) __declspec(novtable) IInkAnalysisInkWord : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecognizedText(hstring * value) = 0; virtual HRESULT __stdcall get_TextAlternates(Windows::Foundation::Collections::IVectorView<hstring> ** value) = 0; }; struct __declspec(uuid("a06d048d-2b8d-4754-ad5a-d0871193a956")) __declspec(novtable) IInkAnalysisLine : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecognizedText(hstring * value) = 0; virtual HRESULT __stdcall get_IndentLevel(int32_t * value) = 0; }; struct __declspec(uuid("b4e3c23f-c4c3-4c3a-a1a6-9d85547ee586")) __declspec(novtable) IInkAnalysisListItem : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecognizedText(hstring * value) = 0; }; struct __declspec(uuid("30831f05-5f64-4a2c-ba37-4f4887879574")) __declspec(novtable) IInkAnalysisNode : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Id(uint32_t * value) = 0; virtual HRESULT __stdcall get_Kind(winrt::Windows::UI::Input::Inking::Analysis::InkAnalysisNodeKind * value) = 0; virtual HRESULT __stdcall get_BoundingRect(Windows::Foundation::Rect * value) = 0; virtual HRESULT __stdcall get_RotatedBoundingRect(Windows::Foundation::Collections::IVectorView<Windows::Foundation::Point> ** value) = 0; virtual HRESULT __stdcall get_Children(Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::Analysis::IInkAnalysisNode> ** value) = 0; virtual HRESULT __stdcall get_Parent(Windows::UI::Input::Inking::Analysis::IInkAnalysisNode ** value) = 0; virtual HRESULT __stdcall abi_GetStrokeIds(Windows::Foundation::Collections::IVectorView<uint32_t> ** strokeIds) = 0; }; struct __declspec(uuid("d9ad045c-0cd1-4dd4-a68b-eb1f12b3d727")) __declspec(novtable) IInkAnalysisParagraph : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecognizedText(hstring * value) = 0; }; struct __declspec(uuid("8948ba79-a243-4aa3-a294-1f98bd0ff580")) __declspec(novtable) IInkAnalysisResult : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Status(winrt::Windows::UI::Input::Inking::Analysis::InkAnalysisStatus * value) = 0; }; struct __declspec(uuid("3fb6a3c4-2fde-4061-8502-a90f32545b84")) __declspec(novtable) IInkAnalysisRoot : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecognizedText(hstring * value) = 0; virtual HRESULT __stdcall abi_FindNodes(winrt::Windows::UI::Input::Inking::Analysis::InkAnalysisNodeKind nodeKind, Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::Analysis::IInkAnalysisNode> ** result) = 0; }; struct __declspec(uuid("dd6d6231-bd16-4663-b5ae-941d3043ef5b")) __declspec(novtable) IInkAnalysisWritingRegion : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecognizedText(hstring * value) = 0; }; struct __declspec(uuid("f12b8f95-0866-4dc5-8c77-f88614dfe38c")) __declspec(novtable) IInkAnalyzer : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_AnalysisRoot(Windows::UI::Input::Inking::Analysis::IInkAnalysisRoot ** value) = 0; virtual HRESULT __stdcall get_IsAnalyzing(bool * value) = 0; virtual HRESULT __stdcall abi_AddDataForStroke(Windows::UI::Input::Inking::IInkStroke * stroke) = 0; virtual HRESULT __stdcall abi_AddDataForStrokes(Windows::Foundation::Collections::IIterable<Windows::UI::Input::Inking::InkStroke> * strokes) = 0; virtual HRESULT __stdcall abi_ClearDataForAllStrokes() = 0; virtual HRESULT __stdcall abi_RemoveDataForStroke(uint32_t strokeId) = 0; virtual HRESULT __stdcall abi_RemoveDataForStrokes(Windows::Foundation::Collections::IIterable<uint32_t> * strokeIds) = 0; virtual HRESULT __stdcall abi_ReplaceDataForStroke(Windows::UI::Input::Inking::IInkStroke * stroke) = 0; virtual HRESULT __stdcall abi_SetStrokeDataKind(uint32_t strokeId, winrt::Windows::UI::Input::Inking::Analysis::InkAnalysisStrokeKind strokeKind) = 0; virtual HRESULT __stdcall abi_AnalyzeAsync(Windows::Foundation::IAsyncOperation<Windows::UI::Input::Inking::Analysis::InkAnalysisResult> ** result) = 0; }; struct __declspec(uuid("29138686-1963-49d8-9589-e14384c769e3")) __declspec(novtable) IInkAnalyzerFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_CreateAnalyzer(Windows::UI::Input::Inking::Analysis::IInkAnalyzer ** result) = 0; }; } namespace ABI { template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisInkBullet> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisInkBullet; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisInkDrawing> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisInkDrawing; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisInkWord> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisInkWord; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisLine> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisLine; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisListItem> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisListItem; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisNode> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisNode; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisParagraph> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisParagraph; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisResult> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisResult; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisRoot> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisRoot; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisWritingRegion> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalysisWritingRegion; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalyzer> { using default_interface = Windows::UI::Input::Inking::Analysis::IInkAnalyzer; }; } namespace Windows::UI::Input::Inking::Analysis { template <typename D> struct WINRT_EBO impl_IInkAnalysisInkBullet { hstring RecognizedText() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisInkDrawing { Windows::UI::Input::Inking::Analysis::InkAnalysisDrawingKind DrawingKind() const; Windows::Foundation::Point Center() const; Windows::Foundation::Collections::IVectorView<Windows::Foundation::Point> Points() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisInkWord { hstring RecognizedText() const; Windows::Foundation::Collections::IVectorView<hstring> TextAlternates() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisLine { hstring RecognizedText() const; int32_t IndentLevel() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisListItem { hstring RecognizedText() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisNode { uint32_t Id() const; Windows::UI::Input::Inking::Analysis::InkAnalysisNodeKind Kind() const; Windows::Foundation::Rect BoundingRect() const; Windows::Foundation::Collections::IVectorView<Windows::Foundation::Point> RotatedBoundingRect() const; Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::Analysis::IInkAnalysisNode> Children() const; Windows::UI::Input::Inking::Analysis::IInkAnalysisNode Parent() const; Windows::Foundation::Collections::IVectorView<uint32_t> GetStrokeIds() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisParagraph { hstring RecognizedText() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisResult { Windows::UI::Input::Inking::Analysis::InkAnalysisStatus Status() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisRoot { hstring RecognizedText() const; Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::Analysis::IInkAnalysisNode> FindNodes(Windows::UI::Input::Inking::Analysis::InkAnalysisNodeKind nodeKind) const; }; template <typename D> struct WINRT_EBO impl_IInkAnalysisWritingRegion { hstring RecognizedText() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalyzer { Windows::UI::Input::Inking::Analysis::InkAnalysisRoot AnalysisRoot() const; bool IsAnalyzing() const; void AddDataForStroke(const Windows::UI::Input::Inking::InkStroke & stroke) const; void AddDataForStrokes(iterable<Windows::UI::Input::Inking::InkStroke> strokes) const; void ClearDataForAllStrokes() const; void RemoveDataForStroke(uint32_t strokeId) const; void RemoveDataForStrokes(iterable<uint32_t> strokeIds) const; void ReplaceDataForStroke(const Windows::UI::Input::Inking::InkStroke & stroke) const; void SetStrokeDataKind(uint32_t strokeId, Windows::UI::Input::Inking::Analysis::InkAnalysisStrokeKind strokeKind) const; Windows::Foundation::IAsyncOperation<Windows::UI::Input::Inking::Analysis::InkAnalysisResult> AnalyzeAsync() const; }; template <typename D> struct WINRT_EBO impl_IInkAnalyzerFactory { Windows::UI::Input::Inking::Analysis::InkAnalyzer CreateAnalyzer() const; }; } namespace impl { template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisInkBullet> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisInkBullet; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisInkBullet<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisInkDrawing> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisInkDrawing; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisInkDrawing<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisInkWord> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisInkWord; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisInkWord<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisLine> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisLine; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisLine<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisListItem> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisListItem; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisListItem<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisNode> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisNode; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisNode<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisParagraph> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisParagraph; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisParagraph<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisResult> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisResult; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisResult<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisRoot> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisRoot; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisRoot<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalysisWritingRegion> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalysisWritingRegion; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalysisWritingRegion<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalyzer> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalyzer; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalyzer<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::IInkAnalyzerFactory> { using abi = ABI::Windows::UI::Input::Inking::Analysis::IInkAnalyzerFactory; template <typename D> using consume = Windows::UI::Input::Inking::Analysis::impl_IInkAnalyzerFactory<D>; }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisInkBullet> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisInkBullet; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisInkBullet"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisInkDrawing> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisInkDrawing; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisInkDrawing"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisInkWord> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisInkWord; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisInkWord"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisLine> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisLine; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisLine"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisListItem> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisListItem; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisListItem"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisNode> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisNode; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisNode"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisParagraph> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisParagraph; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisParagraph"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisResult> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisResult; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisResult"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisRoot> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisRoot; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisRoot"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalysisWritingRegion> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalysisWritingRegion; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalysisWritingRegion"; } }; template <> struct traits<Windows::UI::Input::Inking::Analysis::InkAnalyzer> { using abi = ABI::Windows::UI::Input::Inking::Analysis::InkAnalyzer; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.Input.Inking.Analysis.InkAnalyzer"; } }; } }
#ifndef LETTERS_H_INCLUDED #define LETTERS_H_INCLUDED #include <iostream> #include <string> #include <windows.h> using namespace std; /// --- REQUIRED FUNCS --- /// void gotoxy (int x, int y){ //With this func we can control cursor's position. COORD coordinates; // coordinates is declared as COORD coordinates.X = x; // defining x-axis coordinates.Y = y; //defining y-axis SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coordinates); } string to_lower(string word){ //This func turns capital letters into lower. int length = word.size(); //Input word's length for(int i = 0; i < length; i++){ //We'll control all letter of this word. for(int j = 65; j < 91; j++){ //This loop gets A-Z letters as ASCII code. if(word[i] == (char)j){ //This condition controls if a letter of word is capital. word[i] = (char)j + 32; //If any capital letter exist, it turns into lower one as ASCII code } } } return word; ///New all lower word is returned } string to_upper(string word){ //This func turns lower letters into capital. int length = word.size(); //Input word's length for(int i = 0; i < length; i++){ //We'll control all letter of this word. for(int j = 97; j < 123; j++){ //This loop gets a-z letters as ASCII code. if(word[i] == (char)j){ //This condition controls if a letter of word is lower. word[i] = (char)j - 32; //If any lower letter exist, it turns into capital one as ASCII code } } } return word; } /// --- INIT --- /// struct letter{ int height, weight; }; letter letters_array[26]; //This array keeps height and weight values of letters that printing with stars void setAlphabet(){ //This function sets the alphabet with height and weight values //into letters_array for(int i = 0; i < 26; i++){ //Identifying letters height values if(i == 16){ // Q = 16. order, it's height should be 6. letters_array[i].height = 6; } else{ //Other's height should be 5. letters_array[i].height = 5; } //Identifying letters weight values if(i == 2 || i == 4 || i == 5 || i == 8 || i == 11 || i == 19){ //C, E, F, I, L, T should be 3. letters_array[i].weight = 3; } else if(i == 12 || i == 22){ //M, W should be 5. letters_array[i].weight = 5; } else{ //C, E, F, I, L, T should be 3. letters_array[i].weight = 4; } } } /// --- INIT END --- /// /// --- LETTERS --- /// void print_A(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 5; j++){ if(i == 1 && !(j == 1 || j == 4)){ cout<<"* "; } else if((j == 1 || j == 4) && i != 1){ cout<<"* "; } else if(i == 4){ cout<<"* "; } else{ cout<<" "; } } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[0].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_B(int totalWeight){ for(int i = 1; i <= 5; i++){ cout<<"* "; for(int j = 1; j <= 4; j++){ if((i == 1 || i == 3 || i == 5) && j < 3) cout<<"* "; else if(j == 3 && i != 1 && i != 3 && i != 5) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[1].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_C(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 4; j++){ if(j == 1 && !(i == 1 || i == 5)) cout<<"* "; else if((i == 1 || i == 5) && j != 1) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[2].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_D(int totalWeight){ for(int i = 1; i <= 5; i++){ cout<<"* "; for(int j = 1; j <= 4; j++){ if((i == 1 || i == 5) && j < 3) cout<<"* "; else if(j == 3 && i != 1 && i != 5) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[3].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_E(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <=3 ; j++){ if(j == 1) cout<<"*"; else if (i ==1 || i == 3 || i == 5 ) cout<<"*"; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[4].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_F(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 4; j++){ if(i == 1 || i == 3) cout<<"* "; else if(j == 1) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[5].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_G(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <=4 ; j++){ if(i==1 && j != 1) cout<<"* "; else if(i==2 && j==1) cout<<"* "; else if(i==3 && (j==3 || j==4)) cout<<"* "; else if(i==4 && j==4) cout<<"* "; else if(i==5 && j !=1) cout<<"* "; else if(j==1) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[6].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_H(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <=4 ; j++){ if(j==1 || j==4) cout<<"*"; else if(i==3) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[7].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_I(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 4; j++){ if(i == 1 || i == 5) cout<<"* "; else if(j == 2) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[8].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_J(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <=4 ; j++){ if(i==1 && j==3) cout<<"*"; else if(j==4 && i!=5) cout<<"*"; else if(i==4 && j==1) cout<<"*"; else if(i==5 && (j==2 || j==3)) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[9].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_K(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 5; j++){ if(j==1) cout<<"*"; else if((i==1 || i==5) && j==4) cout<<"*"; else if((i==2 || i==4) && j==3) cout<<"*"; else if(i==3 && j==2) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[10].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_L(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 3; j++){ if(i == 5 || j == 1) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[11].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_M(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 5; j++){ if(j == 1 || j == 5) cout<<"* "; else if(((i == 2) && (j != 3)) || (i == 3 && j != 2 && j != 4)) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[12].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_N(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 4; j++){ if(i == 1 && (j == 4 || j == 1)) cout<<"*"; else if(i == 2 && j !=3) cout<<"*"; else if(i == 3 && j !=2) cout<<"*"; else if(i == 4 && (j == 4 || j == 1)) cout<<"*"; else if(i == 5 && (j == 4 || j == 1)) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[13].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_O(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 5; j++){ if((i == 1 || i == 5) && !(j == 1 || j == 4)) cout<<"* "; else if((j == 1 || j == 4) && !(i == 1 || i == 5)) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[14].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_P(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 5; j++){ if(j == 1) cout<<"* "; else if((i == 1 || i == 4) && j != 4) cout<<"* "; else if((i == 2 || i == 3) && j == 4) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[15].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_Q(int totalWeight){ for(int i = 1; i <= 6; i++){ for(int j = 1; j <= 4; j++){ if((j == 1 || j == 4) && !(i == 1 || i == 5 || i == 6)) cout<<"*"; else if((j==2 || j==3)&&(i==1||i==5)) cout<<"*"; else if(i==6&&j==4) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[16].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_R(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 4; j++){ if(i == 1 && j !=4) cout<<"*"; else if(i == 2 && (j == 4 || j == 1)) cout<<"*"; else if(i == 3 && (j == 4 || j == 1)) cout<<"*"; else if(i == 4 && j !=4) cout<<"*"; else if(i == 5 && (j == 4 || j == 1)) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[17].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_S(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 4; j++){ if(i == 1 && j != 1) cout<<"*"; else if(i == 2 && j == 1) cout<<"*"; else if(i == 3 && (j == 2 || j == 3)) cout<<"*"; else if(i == 4 && j == 4) cout<<"*"; else if(i == 5 && j != 4) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[18].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_T(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 4; j++){ if(i == 1) cout<<"* "; else if(j == 2) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[19].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_U(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 4; j++){ if(i == 5 || j == 1 || j == 4) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[20].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_V(int totalWeight){ for(int i = 1; i < 6; i++){ for(int j = 1; j < 5; j++){ if(j == 1 && i != 5) cout<<"* "; else if(i == 5 && j == 2) cout<<"* "; else if(j == 3 && (i == 3 || i == 4)) cout<<"* "; else if(j == 4 && (i == 1 || i == 2)) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[21].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_W(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 5 ; j++){ if(i==1 && (j==1 || j==5)) cout<<"*"; else if(i==2 && (j==1 || j==5)) cout<<"*"; else if(i==3 && (j==1 || j==5)) cout<<"*"; else if(i==4 && (j==1 || j==5)) cout<<"*"; else if((i!=1 && i!=5) &&j==3) cout<<"*"; else if(i==5 && (j==2 || j==4)) cout<<"*"; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[22].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_X(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 4; j++){ if((j == 1 || j == 4) && i != 3) cout<<"* "; else if(i == 3 && !(j == 1 || j == 4)) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[23].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_Y(int totalWeight){ for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 4; j++){ if(((j == 1) && (i != 3) && (i != 4) && (i != 5)) || (j == 4 && i != 5)) cout<<"* "; else if(((i == 3) && (j != 1)) || (i == 5 && (j != 1 && j != 4))) cout<<"* "; else cout<<" "; } gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[24].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } void print_Z(int totalWeight){ int z = 3; for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 3; j++){ if(i == 1 || i == 5 || j == z + 1) cout<<"* "; else cout<<" "; } z--; gotoxy(totalWeight, i); } gotoxy(totalWeight + (letters_array[25].weight)*2 + 1, 0); //Avoid cursor's position end on letter's bottom } /// --- LETTERS END --- /// /// --- PRINT FUNC --- /// void str2stars(string word){ //This func prints input string as star letters. int length = word.length(); //Input word's length int totalWeight = 0; //Total weight of letters. This variable must be change after every letter printed. for(int i = 0; i < length; i++){ if(word[i] == 'a'){ print_A(totalWeight); totalWeight += (letters_array[0].weight)*2 + 1; } else if(word[i] == 'b'){ print_B(totalWeight); totalWeight += (letters_array[1].weight)*2 + 1; } else if(word[i] == 'c'){ print_C(totalWeight); totalWeight += (letters_array[2].weight)*2 + 1; } else if(word[i] == 'd'){ print_D(totalWeight); totalWeight += (letters_array[3].weight)*2 + 1; } else if(word[i] == 'e'){ print_E(totalWeight); totalWeight += (letters_array[4].weight)*2 + 1; } else if(word[i] == 'f'){ print_F(totalWeight); totalWeight += (letters_array[5].weight)*2 + 1; } else if(word[i] == 'g'){ print_G(totalWeight); totalWeight += (letters_array[6].weight)*2 + 1; } else if(word[i] == 'h'){ print_H(totalWeight); totalWeight += (letters_array[7].weight)*2 + 1; } else if(word[i] == 'i'){ print_I(totalWeight); totalWeight += (letters_array[8].weight)*2 + 1; } else if(word[i] == 'j'){ print_J(totalWeight); totalWeight += (letters_array[9].weight)*2 + 1; } else if(word[i] == 'k'){ print_K(totalWeight); totalWeight += (letters_array[10].weight)*2 + 1; } else if(word[i] == 'l'){ print_L(totalWeight); totalWeight += (letters_array[11].weight)*2 + 1; } else if(word[i] == 'm'){ print_M(totalWeight); totalWeight += (letters_array[12].weight)*2 + 1; } else if(word[i] == 'n'){ print_N(totalWeight); totalWeight += (letters_array[13].weight)*2 + 1; } else if(word[i] == 'o'){ print_O(totalWeight); totalWeight += (letters_array[14].weight)*2 + 1; } else if(word[i] == 'p'){ print_P(totalWeight); totalWeight += (letters_array[15].weight)*2 + 1; } else if(word[i] == 'q'){ print_Q(totalWeight); totalWeight += (letters_array[16].weight)*2 + 1; } else if(word[i] == 'r'){ print_R(totalWeight); totalWeight += (letters_array[17].weight)*2 + 1; } else if(word[i] == 's'){ print_S(totalWeight); totalWeight += (letters_array[18].weight)*2 + 1; } else if(word[i] == 't'){ print_T(totalWeight); totalWeight += (letters_array[19].weight)*2 + 1; } else if(word[i] == 'u'){ print_U(totalWeight); totalWeight += (letters_array[20].weight)*2 + 1; } else if(word[i] == 'v'){ print_V(totalWeight); totalWeight += (letters_array[21].weight)*2 + 1; } else if(word[i] == 'w'){ print_W(totalWeight); totalWeight += (letters_array[22].weight)*2 + 1; } else if(word[i] == 'x'){ print_X(totalWeight); totalWeight += (letters_array[23].weight)*2 + 1; } else if(word[i] == 'y'){ print_Y(totalWeight); totalWeight += (letters_array[24].weight)*2 + 1; } else if(word[i] == 'z'){ print_Z(totalWeight); totalWeight += (letters_array[25].weight)*2 + 1; } } } #endif // LETTERS_H_INCLUDED
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* ** Copyright UCAR (c) 1992 - 1999 ** University Corporation for Atmospheric Research(UCAR) ** National Center for Atmospheric Research(NCAR) ** Research Applications Program(RAP) ** P.O.Box 3000, Boulder, Colorado, 80307-3000, USA ** All rights reserved. Licenced use only. ** Do not copy or distribute without authorization ** 1999/03/14 14:18:54 *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ ///////////////////////////////////////////////////////////// // Pulse.hh // // Mike Dixon, RAP, NCAR // P.O.Box 3000, Boulder, CO, 80307-3000, USA // // April 2006 // /////////////////////////////////////////////////////////////// #ifndef Pulse_hh #define Pulse_hh #include <string> #include <vector> #include <deque> #include "Params.hh" #include "Complex.hh" using namespace std; //////////////////////// // This class class Pulse { public: // constructor // iqc: copolar IQ data, [i,q, i,q, i,q, ...] // Must be set. // iqx: cross-opolar IQ data, [i,q, i,q, i,q, ...] // Set to NULL if no cross-pol data Pulse(const Params &params, long long seqNum, int nGates, double time, double prt, double el, double az, bool isHoriz, const float *iqc, const float *iqx = NULL); ~Pulse(); // printing void print(ostream &out) const; // get methods int getNGates() const { return _nGates; } long long getSeqNum() const { return _seqNum; } double getTime() const { return _time; } // secs in decimal double getPrt() const { return _prt; } double getPrf() const { return _prf; } double getEl() const { return _el; } double getAz() const { return _az; } bool isHoriz() const { return _isHoriz; } // is horizontally polarized? const float *getIqc() const { return _iqc; } const float *getIqx() const { return _iqx; } // Memory management. // This class uses the notion of clients to decide when it should be deleted. // If removeClient() returns 0, the object should be deleted. int addClient(const string &clientName); int removeClient(const string &clientName); protected: private: const Params &_params; int _nClients; long long _seqNum; int _nGates; double _time; double _prt; double _prf; double _el; double _az; bool _isHoriz; // floating point IQ data // stored: // (i,q,i,q,i,q,.... ) for iqc and iqx float *_iqc; float *_iqx; }; #endif
#include <Common.h> #include <cassert> #include <memory> #include <string> enum class Token : int { Multiply = '*', Plus = '+', LParens = '(', RParens = ')', Number = 1, Eof = -1, }; class Lexer { public: /// Token consumes a buffer of input Lexer(const std::string &buffer) : buffer(buffer){}; /// Look at the current token in the stream. Token getCurToken() { return curTok; } /// Move to the next token in the stream and return it. Token getNextToken() { return curTok = getTok(); } /// Move to the next token in the stream and return it. long getNumVal() { return numVal; } /// Consume a token from the input void match(Token tok) { if (tok != curTok) assert(tok == curTok && "Token mismatch"); getNextToken(); } private: /// Get the next character from the input stream int getNextChar() { if (idx == buffer.size()) return EOF; return buffer[idx++]; } /// Get the next token from the stream Token getTok() { // ignore whitespace while (isspace(curChar)) curChar = getNextChar(); if (isdigit(curChar)) { std::string numStr; do { numStr += static_cast<char>(curChar); curChar = getNextChar(); } while (isdigit(curChar)); numVal = std::stol(numStr); return Token::Number; } if (curChar == EOF) return Token::Eof; Token thisChar = Token(curChar); curChar = getNextChar(); return thisChar; } /// Number matched from input long numVal; /// Current token lookahead Token curTok; /// Last character read from the string buffer int curChar = ' '; /// Current location in the string buffer std::size_t idx = 0; const std::string buffer = ""; }; class ParserP2 { public: ParserP2(Lexer &lexer) : lexer(lexer) {} /// S := expr $ long parseExpression() { /// Prime the lexer at the beginning lexer.getNextToken(); return parseExpr(); } private: /// expr := factor expr' /// expr' := '*' factor expr' | /// := ε long parseExpr() { long result = parseFactor(); while (lexer.getCurToken() == Token::Multiply) { if (lexer.getCurToken() == Token::Multiply) { lexer.match(Token::Multiply); result *= parseFactor(); } } return result; } /// factor := term factor' /// factor' := '+' term factor' | /// := ε long parseFactor() { long result = parseTerm(); while (lexer.getCurToken() == Token::Plus) { if (lexer.getCurToken() == Token::Plus) { lexer.match(Token::Plus); result += parseTerm(); } } return result; } /// term := '(' expr ')' | /// := <num> long parseTerm() { long result; if (lexer.getCurToken() == Token::LParens) { lexer.match(Token::LParens); result = parseExpr(); lexer.match(Token::RParens); } else { lexer.match(Token::Number); result = lexer.getNumVal(); } return result; } Lexer &lexer; }; class ParserP1 { public: ParserP1(Lexer &lexer) : lexer(lexer) {} /// S := expr $ long parseExpression() { /// Prime the lexer at the beginning lexer.getNextToken(); return parseExpr(); } private: /// expr := factor expr' /// expr' := '+' factor expr' | /// := '*' factor expr' | /// := factor long parseExpr() { long result = parseTerm(); while (lexer.getCurToken() == Token::Plus || lexer.getCurToken() == Token::Multiply) { if (lexer.getCurToken() == Token::Plus) { lexer.match(Token::Plus); result += parseTerm(); } else if (lexer.getCurToken() == Token::Multiply) { lexer.match(Token::Multiply); result *= parseTerm(); } } return result; } /// term := '(' expr ')' | /// := <num> long parseTerm() { long result; if (lexer.getCurToken() == Token::LParens) { lexer.match(Token::LParens); result = parseExpr(); lexer.match(Token::RParens); } else { lexer.match(Token::Number); result = lexer.getNumVal(); } return result; } Lexer &lexer; }; /// Over-engineered parser int main() { auto lines = getLines(getFileContents("../input/Day18/input.txt")); long s1 = 0; long s2 = 0; for (const auto &line : lines) { Lexer l1(line); Lexer l2(line); ParserP1 p1(l1); ParserP2 p2(l2); s1 += p1.parseExpression(); s2 += p2.parseExpression(); } std::cout << s1 << "\n"; std::cout << s2 << "\n"; }
#include <initializer_list> #include <string_view> #include <unordered_set> #include "gtest/gtest.h" #include "move.h" #include "movegen.h" #include "position.h" using apollo::Move; using apollo::Position; using apollo::Square; template <typename First> void AssertHasMoveInSet(const std::unordered_set<Move>& move_set, First mov) { ASSERT_TRUE(move_set.find(mov) != move_set.end()); } template <typename First, typename... Rest> void AssertHasMoveInSet(const std::unordered_set<Move>& move_set, First mov, Rest... rest) { ASSERT_TRUE(move_set.find(mov) != move_set.end()); AssertHasMoveInSet(move_set, rest...); } template <typename First, typename... Rest> void AssertHasMove(const Position& pos, First mov, Rest... rest) { std::vector<Move> moves = pos.PseudolegalMoves(); std::unordered_set<Move> move_set(moves.begin(), moves.end()); AssertHasMoveInSet(move_set, mov, rest...); } template <typename First> void AssertDoesNotHaveMoveInSet(const std::unordered_set<Move>& move_set, First mov) { ASSERT_TRUE(move_set.find(mov) == move_set.end()); } template <typename First, typename... Rest> void AssertDoesNotHaveMoveInSet(const std::unordered_set<Move>& move_set, First mov, Rest... rest) { ASSERT_TRUE(move_set.find(mov) == move_set.end()); AssertDoesNotHaveMoveInSet(move_set, rest...); } template <typename First, typename... Rest> void AssertDoesNotHaveMove(const Position& pos, First mov, Rest... rest) { std::vector<Move> moves = pos.PseudolegalMoves(); std::unordered_set<Move> move_set(moves.begin(), moves.end()); AssertDoesNotHaveMoveInSet(move_set, mov, rest...); } TEST(MoveGenTest, PawnSmoke) { Position p("8/8/8/8/4P3/8/8/8 w - -"); ASSERT_NO_FATAL_FAILURE( AssertHasMove(p, Move::Quiet(Square::E4, Square::E5))); } TEST(MoveGenTest, PawnDoublePush) { Position p("8/8/8/8/8/8/4P3/8 w - -"); ASSERT_NO_FATAL_FAILURE( AssertHasMove(p, Move::DoublePawnPush(Square::E2, Square::E4))); } TEST(MoveGenTest, PawnCapture) { Position p("8/8/8/8/5p2/4P3/8/8 w - -"); ASSERT_NO_FATAL_FAILURE( AssertHasMove(p, Move::Capture(Square::E3, Square::F4))); ASSERT_NO_FATAL_FAILURE( AssertDoesNotHaveMove(p, Move::Capture(Square::E3, Square::D4))); } TEST(MoveGenTest, PawnSmokeBlack) { Position p("8/8/8/4p3/8/8/8/8 b - -"); ASSERT_NO_FATAL_FAILURE( AssertHasMove(p, Move::Quiet(Square::E5, Square::E4))); } TEST(MoveGenTest, PawnPromoSmoke) { Position p("8/4P3/8/8/8/8/8/8 w - -"); ASSERT_NO_FATAL_FAILURE( AssertHasMove(p, Move::Promotion(Square::E7, Square::E8, apollo::kKnight), Move::Promotion(Square::E7, Square::E8, apollo::kBishop), Move::Promotion(Square::E7, Square::E8, apollo::kRook), Move::Promotion(Square::E7, Square::E8, apollo::kQueen))); } TEST(MoveGenTest, PawnPromoSmokeBlack) { Position p("8/8/8/8/8/8/4p3/8 b - -"); ASSERT_NO_FATAL_FAILURE( AssertHasMove(p, Move::Promotion(Square::E2, Square::E1, apollo::kKnight), Move::Promotion(Square::E2, Square::E1, apollo::kBishop), Move::Promotion(Square::E2, Square::E1, apollo::kRook), Move::Promotion(Square::E2, Square::E1, apollo::kQueen))); } TEST(MoveGenTest, KnightSmoke) { Position p("8/8/4n3/8/3N4/8/8/8 w - -"); ASSERT_NO_FATAL_FAILURE(AssertHasMove( p, Move::Quiet(Square::D4, Square::F5), Move::Quiet(Square::D4, Square::F3), Move::Quiet(Square::D4, Square::E2), Move::Quiet(Square::D4, Square::C2), Move::Quiet(Square::D4, Square::B3), Move::Quiet(Square::D4, Square::B5), Move::Quiet(Square::D4, Square::C6), Move::Capture(Square::D4, Square::E6))); } TEST(MoveGenTest, CastleWithNoRook) { // Bug fix - even if allowed to castle, White can't castle unless there's // actually a rook in its starting position. Position p("r3k2r/ppp2pp1/2n4p/3P4/8/bP4P1/P1PBBP1P/R3K2b w KQkq - 0 4"); ASSERT_NO_FATAL_FAILURE( AssertDoesNotHaveMove(p, Move::KingsideCastle(Square::E1, Square::G1))); } TEST(MoveGenTest, CheckKing) { Position p("8/3r2k1/p3R3/P1B2NNp/1PP3pK/8/3R2PP/8 b - - 0 50"); ASSERT_NO_FATAL_FAILURE( AssertHasMove(p, Move::Quiet(Square::G7, Square::H8))); }
#ifndef __RESOURCE_H__ #define __RESOURCE_H__ #include "Globals.h" #include <xstring> #include <string> #define INVALID_RESOURCE_UID 0 #define TO_STRING( x ) #x class JSONFile; typedef unsigned int uint; //**************** // CLASS_DECLARATION // // This macro must be included in the declaration of any subclass of Component. // It declares variables used in type checking. //**************** #define RESOURCE_DECLARATION( classname ) \ public: \ static const uint type; \ virtual bool IsClassType( const unsigned int classType ) const override; \ virtual unsigned int GetType() override; \ //**************** // CLASS_DEFINITION // // This macro must be included in the class definition to properly initialize // variables used in type checking. Take special care to ensure that the // proper parentclass is indicated or the run-time type information will be // incorrect. Only works on single-inheritance RTTI. //**************** #define RESOURCE_DEFINITION( parentclass, childclass ) \ const uint childclass::type = std::hash< std::string >()( TO_STRING( childclass ) ); \ bool childclass::IsClassType( const uint classType ) const { \ if ( classType == childclass::type ) \ return true; \ return parentclass::IsClassType( classType ); \ } \ unsigned int childclass::GetType()\ {\ return childclass::type;\ }\ class Resource { public: static const uint type; public: Resource(); bool StartUsingResource(); uint GetReferenceCount() const; bool StopUsingResource(); void SaveModifiedDate(JSONFile * meta_file, const char * asset_path); UID GetUID() const; virtual bool IsClassType(const uint classType) const { return classType == type; } virtual uint GetType() { return type; } virtual const char * GetTypeString() = 0; protected: //INFO: Saves the resource with custom format in the Resources folder virtual bool SaveFileData() = 0; virtual bool LoadFileData() = 0; virtual bool ReleaseData() = 0; virtual void CleanUp() {}; //Helpers for LoadFileData() and SaveFileData() void SaveVariable(void* info, char ** data_cursor, size_t bytes); void LoadVariable(void* info, char ** data_cursor, size_t bytes); protected: UID uid = 0u; uint reference_count = 0u;//How many GameObjects are currently using this resource public: std::string asset_source;//The path to the asset that this resource was generated from friend class ModuleResourceManager; friend class ResourceModel; }; #endif
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * 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. */ #ifndef MVDISCRIMHISTVIEW_H #define MVDISCRIMHISTVIEW_H #include "mvabstractviewfactory.h" #include "mvhistogramgrid.h" class MVDiscrimHistViewPrivate; class MVDiscrimHistView : public MVHistogramGrid { Q_OBJECT public: friend class MVDiscrimHistViewPrivate; MVDiscrimHistView(MVAbstractContext* context); virtual ~MVDiscrimHistView(); void setClusterNumbers(const QList<int>& cluster_numbers); void prepareCalculation() Q_DECL_OVERRIDE; void runCalculation() Q_DECL_OVERRIDE; void onCalculationFinished() Q_DECL_OVERRIDE; void wheelEvent(QWheelEvent* evt); signals: private slots: void slot_zoom_in_horizontal(double factor = 1.2); void slot_zoom_out_horizontal(double factor = 1.2); void slot_pan_left(double units = 0.1); void slot_pan_right(double units = 0.1); private: MVDiscrimHistViewPrivate* d; }; class MVDiscrimHistFactory : public MVAbstractViewFactory { Q_OBJECT public: MVDiscrimHistFactory(MVMainWindow* mw, QObject* parent = 0); QString id() const Q_DECL_OVERRIDE; QString name() const Q_DECL_OVERRIDE; QString title() const Q_DECL_OVERRIDE; MVAbstractView* createView(MVAbstractContext* context) Q_DECL_OVERRIDE; bool isEnabled(MVAbstractContext* context) const; }; #endif // MVDISCRIMHISTVIEW_H
/*************************************************************************** dialogocolores.cpp - description ------------------- begin : jue abr 1 2004 copyright : (C) 2004 by Oscar G. Duarte email : ogduarte@ing.unal.edu.co ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "dialogocolores.h" BEGIN_EVENT_TABLE(DialogoColores, wxDialog) EVT_PAINT(DialogoColores::OnPaint) END_EVENT_TABLE() DialogoColores::DialogoColores(ListaColores col, wxWindow *parent,const wxString& title) :wxDialog(parent,-1,title) { Colores=col; } DialogoColores::~DialogoColores() { } void DialogoColores::OnPaint(wxPaintEvent&) { wxPaintDC dc(this); wxBrush Brush; int AlturaCaja=20,Offset=20,AnchoCaja=40; int h,v,HT,VT; int i,tam; tam=Colores.Colores.GetCount(); VT=(tam+1)*AlturaCaja+2*Offset; HT=0; for(i=0;i<tam;i++) { dc.GetTextExtent(Colores.Nombres.Item(i),&h,&v); if(HT<h){HT=h;} } HT=HT+3*Offset+AnchoCaja; SetSize(HT,VT); for(i=0;i<tam;i++) { Brush.SetColour(Colores.Colores.Item(i)); dc.SetBrush (Brush); dc.DrawRectangle(Offset,Offset+i*AlturaCaja,AnchoCaja,AlturaCaja); dc.GetTextExtent(Colores.Nombres.Item(i),&h,&v); dc.DrawText(Colores.Nombres.Item(i),AnchoCaja+2*Offset,Offset+i*AlturaCaja+2); } }
// // Created by 王润基 on 2017/4/19. // #ifndef INC_2RAYTRACE_UVMAP_H #define INC_2RAYTRACE_UVMAP_H #include "../Geometry/Vector3.h" class UVMap { public: virtual Vector3f getUV (Vector3f const& point) const; }; #endif //INC_2RAYTRACE_UVMAP_H
#include "Singularity.Particles.h" namespace Singularity { namespace Particles { class ParticleVertex { private: #pragma region Static Variables static Singularity::Graphics::VertexDeclaration* g_pVertexDeclaration; #pragma endregion public: #pragma region Static Methods static Singularity::Graphics::VertexDeclaration* GetVertexDeclaration(); #pragma endregion #pragma region Variables Vector3 position; Color color; Vector3 velocity; Vector3 acceleration; float size; float timestamp; float lifetime; float rotation; float type; #pragma endregion #pragma region Constructors and Finalizers ParticleVertex(); ParticleVertex(float x, float y, float z, float velX, float velY, float velZ, float accX, float accY, float accZ, float r, float g, float b, float a, float size, float timestamp, float lifetime, float rotation, float type); ParticleVertex(Vector3 position, Vector3 velocity, Vector3 acceleration, Color color, float size, float timstamp, float lifetime, float rotation, float type); #pragma endregion }; } }
#ifndef TYPECHECK_EXCEPTIONS_H #define TYPECHECK_EXCEPTIONS_H #include "../exceptions.h" #include "../syntaxtree/node.h" #include "../syntaxtree/returnstmt.h" #include "../syntaxtree/funcall.h" #include "../syntaxtree/assign.h" using namespace std; /** * Common abstract superclass of all errors detected when * doing a typecheck */ class TypeCheckError: public Exception { public: /** * @param node the abstract syntax tree node where the error occured */ TypeCheckError(Node* node,string errname,string description): Exception(description),descr_(description),errname_(errname),node_(node) { } virtual ~TypeCheckError(); /** * @return a string description of this kind of error */ virtual string description() const { return descr_; } /** * @return the name of this kind of error */ virtual string errname() const { return errname_; } /** * @return the line number where the error occured */ virtual int lineno() const; /** * @see description() */ string what(); virtual ostream& report(ostream& errstream=cerr) const; private: string descr_; string errname_; Node* node_; }; /** * Thrown when an illegal assignment occurs (incompatible types), * or when an illegal type is returned. */ class TypeMismatchError: public TypeCheckError { public: TypeMismatchError(string description,Type expected,Type given,Node* node): TypeCheckError(node,"Type Mismatch",description), expected_(expected),given_(given) { } virtual string description() const; private: Type expected_; Type given_; }; /** * Thrown when an illegal assignment occurs */ class AssignmentError: public TypeMismatchError { public: AssignmentError(Type expected,Type given,Assignment* node): TypeMismatchError("Illegal Types in Assignment",expected,given,node) { } }; /** * Thrown when an incompatible type is returned */ class ReturnError: public TypeMismatchError { public: ReturnError(Type expected,Type given,ReturnStatement* node): TypeMismatchError("Type of returned expression does not match returntype", expected,given,node) { } }; /** * Thrown when an operator receives an argument of invalid type */ class OperatorTypeError: public TypeCheckError { public: OperatorTypeError(Type given,Node* node): TypeCheckError(node,"Type Error","Invalid argument type given to operator"), givenType_(given) { } virtual string description() const; private: Type givenType_; }; /** * Thrown when an invalid number of arguments is passed * in a function call */ class ArityError: public TypeCheckError { public: ArityError(int expectedArgs,int givenArgs,Funcall* node): TypeCheckError(node,"Arity Error","Invalid number of arguments passed"), expectedArgs_(expectedArgs),givenArgs_(givenArgs) { } virtual string description() const; private: int expectedArgs_; int givenArgs_; }; /** * Thrown when an invalid index type is given to index an array */ class IllegalIndexError: public TypeCheckError { public: IllegalIndexError(int nth,Type given,Node* node): TypeCheckError(node,"Invalid Index","Invalid index type to index an array"), nth_(nth),givenType_(given) { } virtual string description() const; private: int nth_; Type givenType_; }; /** * Thrown when one accesses an array with an invalid number of indices */ class ArrayDimensionError: public TypeCheckError { public: ArrayDimensionError(int expected,int given,Node* node): TypeCheckError(node,"Dimension Mismatch", "Invalid dimension specified for array"), expectedDim_(expected),givenDim_(given) { } virtual string description() const; private: int expectedDim_; int givenDim_; }; /** * Thrown when an actual argument does not match it's formal counterpart */ class ParameterTypeError: public TypeMismatchError { public: ParameterTypeError(int nr,Type expected, Type given, Funcall* fun): TypeMismatchError("Mismatched type in passing argument",expected,given,fun), nth_(nr) { } virtual string description() const; private: int nth_; /**< it is the n'th argument causing problems */ }; /** * Thrown when conditions do not evaluate to an integral value */ class ConditionError: public TypeCheckError { public: ConditionError(Type given,Expression* condition): TypeCheckError(condition,"Type Error", "Condition does not evaluate to an integral value"), given_(given) { } virtual string description() const; private: Type given_; }; /** * Thrown when a 'read function' or 'write function' is encountered */ class UnexpectedFunctionError: public TypeCheckError { public: UnexpectedFunctionError(Node* node): TypeCheckError(node,"Unexpected function", "Invalid use of variable denoting a function") { } }; /** * Thrown when one wants to take the length of something other than an * array, or when we are not indexing an array */ class ArrayExpectedError: public TypeCheckError { public: ArrayExpectedError(Node* node): TypeCheckError(node,"Array expected", "This operation requires an array reference") { } }; /** * Thrown when one wants to read into an entire array or wants to write * out an entire array, or when one wants to assign to an array */ class UnexpectedArrayError: public TypeCheckError { public: UnexpectedArrayError(Node* node): TypeCheckError(node,"Unexpected array", "Invalid use of variable denoting an array") { } }; /* * Thrown when an actual argument array has a different base type than * its formal counterpart */ class ArrayBaseMismatch: public TypeMismatchError { public: ArrayBaseMismatch(int nr,Type expected, Type given, Funcall* fun): TypeMismatchError( "Mismatched array base types in passing argument",expected,given,fun), nth_(nr) { } virtual string description() const; private: int nth_; /**< it is the n'th argument causing problems */ }; /* * Thrown when an actual argument array has a different dimensionality than * its formal counterpart */ class DimensionMismatch: public ArrayDimensionError { public: DimensionMismatch(int nr,int expected, int given, Funcall* fun): ArrayDimensionError(expected,given,fun), nth_(nr) { } virtual string description() const; private: int nth_; /**< it is the n'th argument causing problems */ }; #endif
/** * @author NageshAC * @email nagesh.ac.aralaguppe@fau.de * @create date 2021-07-28 09:50:26 * @modify date 2021-07-28 09:50:26 * @desc Reads input from ./data/*.in file. */ #pragma once #include<iostream> #include<fstream> #include<thrust/host_vector.h> #include "./particle.cpp" using namespace std; using namespace thrust; inline void printInput(particle* p,int &N){ cout<<N<<endl; for(int j=0;j<N;++j){ double m = p[j].g_mass(); double* pos = p[j].g_position(); double* vel = p[j].g_velocity(); cout << m; for(auto i=0; i<3; i++) cout <<"\t" << pos[i]; for(auto i=0; i<3; i++) cout <<"\t" << vel[i]; cout << endl; } } inline host_vector<particle> readInput(string in_file, int &N){ fstream f; f.open(in_file, ios::in); if(f.is_open()){ f>>N; double out; int count = 0; host_vector<particle> temp_p(N); // cout<<"\n\nsize of temp: "<<temp_p.size(); while (count < N) { // cout<<"\n"<<count<<endl; f>>out; // cout<<out<<"\t"; temp_p[count].s_mass(out); for(int i=0;i<3;i++){ f>>out; // cout<<out<<"\t"; temp_p[count].s_position(out,i); } for(int i=0;i<3;i++){ f>>out; // cout<<out<<"\t"; temp_p[count].s_velocity(out,i); } // cout<<endl; count++; } cout << "\033[1;32m\n\tDone reading .in file.\n\033[0m\n"; return temp_p; } else{ cout<<"\033[1;31m\n\tThe .in file cannot be opened.\n\033[0m\n"; exit(202); } }
#include <iostream> void uppgift1(); void uppgift2(); void uppgift3(); int main() { int uppgift; std::cout<<"Vilken upgift vill du se?:"; std::cin>>uppgift; switch(uppgift) { case 1: std::cout<< "visar uppgift 1\n"; uppgift1(); break; case 2: std::cout<< "visar uppgift 2\n"; uppgift2(); break; case 3: std::cout<< "visar uppgift 3\n"; uppgift3(); break; } return 0; } void uppgift1(){ std::string vag; std::cout << "Ska du aka rakt eller hoger:"<< std::endl; std::cin>>vag; if(vag=="rakt"){ std::cout<<"du aker rakt!"<<'\n'; } else if(vag=="hager"){ std::cout<<"du aker hager!"<<'\n'; } else{ std::cout<<"ogiltigt svar!"<<'\n'; } } void uppgift2(){ int hemligtal=2; int svar; std::cout<<"Gissa mitt tal (mellan 1-3): "; std::cin>>svar; if (svar==hemligtal){ std::cout<<"Du svara rätt på första försöket!"; } else{ std::cout<<"Fel svar giss en gång till: "; std::cin>>svar; } if(svar==hemligtal){ std::cout<<"Du giss rätt på andra försöket!"; } else{ std::cout<<"Du lyckades inte klara det på två försök"; } } void uppgift3(){ int storre[2]={12,3}; int mindre[2]={5,8}; std::cout<<"kön\n"; std::cout<<"Lön"<<"Man"<<"Kvinna\n"; std::cout<<"Minst 20000kr"<<storre[0]<<storre[1]<<std::endl; std::cout<<"Mindre än 20000kr"<<mindre[0]<<mindre[1]<<std::endl; }
// // ClassSelector.hpp // DDCSSParser // // Created by 1m0nster on 2018/8/7. // Copyright © 2018 1m0nster. All rights reserved. // #ifndef ClassSelector_hpp #define ClassSelector_hpp #include <stdio.h> #include <iostream> #include "Selector.hpp" namespace future { class ClassSelector: public Selector { public: ClassSelector(const std::string& cls) { m_class = cls; m_selectorType = Selector::ClassSelector; }; inline std::string getClassIdentifier() { return m_class; } bool isBaseSelector(); int weight(); virtual std::string description(); private: std::string m_class; }; } #endif /* ClassSelector_hpp */
#include<iostream> using namespace std; bool marked[101][101]; int a[101][101]; int ans; int m, n; int go[8][2] = { 1,0, -1,0, 0,1, 0,-1, 1,1, 1,-1, -1,1, -1,-1 }; bool leagl(int i, int j) { if (i<1 || i>m)return false; if (j<1 || j>n)return false; return true; } void DFS(int i, int j) { for (int k = 0;k < 8;k++) { int newi = i + go[k][0]; int newj = j + go[k][1]; if (leagl(newi, newj)&&a[newi][newj]==1&& !marked[newi][newj]) { marked[newi][newj] = true; DFS(newi, newj); } } } void func() { char tmp; while (cin >> m >> n) { if (m == 0)break; ans = 0; for (int i = 1;i <= m;i++) { for (int j = 1;j <= n;j++) { marked[i][j] = false; cin>>tmp; if (tmp == '@') { a[i][j] = 1; } else { a[i][j] = 0; } } } for (int i = 1;i <= m;i++) { for (int j = 1;j <= n;j++) { if (marked[i][j] == false && a[i][j] == 1) { marked[i][j] = true; DFS(i, j); ans++; } } } cout << ans << endl; } } int main() { func(); return 0; }
#include <bits/stdc++.h> using namespace std; #define N 1010 typedef long long ll; int n, m, mat[N][N]; int getRand(ll n){ return (((ll)rand()<<30)^ll(rand())) % n; } int main(){ int n, m; n=getRand(1000)+1; m=getRand(1000)+1; printf("%d %d\n", n, m); for(int i=0; i<n; i++) for(int j=0; j<m; j++) printf("%d%c", getRand(1000000), j==m-1 ? '\n' : ' '); }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.ApplicationModel.SocialInfo.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_c210bbd7_2f56_5076_bb0e_b7497726cf95 #define WINRT_GENERIC_c210bbd7_2f56_5076_bb0e_b7497726cf95 template <> struct __declspec(uuid("c210bbd7-2f56-5076-bb0e-b7497726cf95")) __declspec(novtable) IVector<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> : impl_IVector<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> {}; #endif #ifndef WINRT_GENERIC_fabcf39f_fd48_5550_8f47_a0f1573e1f53 #define WINRT_GENERIC_fabcf39f_fd48_5550_8f47_a0f1573e1f53 template <> struct __declspec(uuid("fabcf39f-fd48-5550-8f47-a0f1573e1f53")) __declspec(novtable) IIterator<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> : impl_IIterator<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> {}; #endif #ifndef WINRT_GENERIC_5d102c6d_92c3_59f3_b1dc_5986c56445a5 #define WINRT_GENERIC_5d102c6d_92c3_59f3_b1dc_5986c56445a5 template <> struct __declspec(uuid("5d102c6d-92c3-59f3-b1dc-5986c56445a5")) __declspec(novtable) IIterable<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> : impl_IIterable<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> {}; #endif #ifndef WINRT_GENERIC_9a3e6d46_e880_5deb_9006_92fe5c43ace1 #define WINRT_GENERIC_9a3e6d46_e880_5deb_9006_92fe5c43ace1 template <> struct __declspec(uuid("9a3e6d46-e880-5deb-9006-92fe5c43ace1")) __declspec(novtable) IVectorView<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> : impl_IVectorView<Windows::ApplicationModel::SocialInfo::SocialItemThumbnail> {}; #endif } namespace Windows::ApplicationModel::SocialInfo { struct ISocialFeedChildItem : Windows::Foundation::IInspectable, impl::consume<ISocialFeedChildItem> { ISocialFeedChildItem(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISocialFeedChildItem is deprecated and might not work on all platforms. For more info, see MSDN.")]] ISocialFeedChildItem; struct ISocialFeedContent : Windows::Foundation::IInspectable, impl::consume<ISocialFeedContent> { ISocialFeedContent(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISocialFeedContent is deprecated and might not work on all platforms. For more info, see MSDN.")]] ISocialFeedContent; struct ISocialFeedItem : Windows::Foundation::IInspectable, impl::consume<ISocialFeedItem> { ISocialFeedItem(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISocialFeedItem is deprecated and might not work on all platforms. For more info, see MSDN.")]] ISocialFeedItem; struct ISocialFeedSharedItem : Windows::Foundation::IInspectable, impl::consume<ISocialFeedSharedItem> { ISocialFeedSharedItem(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISocialFeedSharedItem is deprecated and might not work on all platforms. For more info, see MSDN.")]] ISocialFeedSharedItem; struct ISocialItemThumbnail : Windows::Foundation::IInspectable, impl::consume<ISocialItemThumbnail> { ISocialItemThumbnail(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISocialItemThumbnail is deprecated and might not work on all platforms. For more info, see MSDN.")]] ISocialItemThumbnail; struct ISocialUserInfo : Windows::Foundation::IInspectable, impl::consume<ISocialUserInfo> { ISocialUserInfo(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISocialUserInfo is deprecated and might not work on all platforms. For more info, see MSDN.")]] ISocialUserInfo; } }
// // Created by zander on 2018/01/03. // #ifndef PICPNG_H #define PICOPNG_H #include <vector> //die function is verklaar in aparte file extern int decodePNG(std::vector<unsigned char> &out_image, unsigned long &image_width, unsigned long &image_height, const unsigned char *in_png, size_t in_size, bool convert_to_rgba32 = true); #endif //PICOPNG_H
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "UE4VoxelTerrain.h" #include "UE4VoxelTerrainPlayerController.h" #include "SandboxTerrainController.h" #include "SandboxCharacter.h" #include "VoxelIndex.h" #include "VoxelDualContouringMeshComponent.h" AUE4VoxelTerrainPlayerController::AUE4VoxelTerrainPlayerController() { tool_mode = 1; } void AUE4VoxelTerrainPlayerController::PlayerTick(float DeltaTime) { Super::PlayerTick(DeltaTime); } void AUE4VoxelTerrainPlayerController::SetupInputComponent() { // set up gameplay key bindings Super::SetupInputComponent(); InputComponent->BindAction("0", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool0); InputComponent->BindAction("1", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool1); InputComponent->BindAction("2", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool2); InputComponent->BindAction("3", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool3); InputComponent->BindAction("4", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool4); InputComponent->BindAction("5", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool5); InputComponent->BindAction("6", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool6); InputComponent->BindAction("7", IE_Pressed, this, &AUE4VoxelTerrainPlayerController::setTool7); } void AUE4VoxelTerrainPlayerController::OnMainActionPressed() { SetDestinationPressed(); } void AUE4VoxelTerrainPlayerController::OnMainActionReleased() { SetDestinationReleased(); } void AUE4VoxelTerrainPlayerController::OnAltActionPressed() { ASandboxCharacter* pawn = Cast<ASandboxCharacter>(GetCharacter()); FHitResult Hit = TracePlayerActionPoint(); if (Hit.bBlockingHit) { UE_LOG(LogTemp, Warning, TEXT("test point -> %f %f %f"), Hit.ImpactPoint.X, Hit.ImpactPoint.Y, Hit.ImpactPoint.Z); UVoxelDualContouringMeshComponent* DualContouringVoxelMesh = Cast<UVoxelDualContouringMeshComponent>(Hit.Component.Get()); if (DualContouringVoxelMesh != nullptr) { if (tool_mode == 1) { DualContouringVoxelMesh->EditMeshDeleteSphere(Hit.ImpactPoint, 80, 5); } } ASandboxTerrainController* terrain = Cast<ASandboxTerrainController>(Hit.Actor.Get()); if (terrain != NULL) { TVoxelIndex ZoneIndex = terrain->GetZoneIndex(Hit.ImpactPoint); FVector ZoneIndexTmp(ZoneIndex.X, ZoneIndex.Y, ZoneIndex.Z); UE_LOG(LogTemp, Warning, TEXT("zIndex -> %f %f %f"), ZoneIndexTmp.X, ZoneIndexTmp.Y, ZoneIndexTmp.Z); if (tool_mode == 1) { terrain->DigTerrainRoundHole(Hit.ImpactPoint, 80, 5); GetWorld()->GetTimerManager().SetTimer(timer, this, &AUE4VoxelTerrainPlayerController::PerformAction, 0.1, true); } if (tool_mode == 2) { terrain->DigTerrainCubeHole(Hit.ImpactPoint, 110); } if (tool_mode == 3) { static const float GridRange = 100; FVector Tmp(Hit.ImpactPoint); Tmp /= GridRange; Tmp.Set(std::round(Tmp.X), std::round(Tmp.Y), std::round(Tmp.Z)); Tmp *= GridRange; FVector Position((int)Tmp.X, (int)Tmp.Y, (int)Tmp.Z); terrain->DigTerrainCubeHole(Position, 110); } if (tool_mode == 4) { terrain->FillTerrainRound(Hit.ImpactPoint, 60, 3); //sand } if (tool_mode == 5) { terrain->FillTerrainRound(Hit.ImpactPoint, 60, 4); //basalt } if (tool_mode == 6) { terrain->FillTerrainRound(Hit.ImpactPoint, 60, 5); //gravel } if (tool_mode == 7) { static const float GridRange = 100; FVector Tmp(Hit.ImpactPoint); Tmp /= GridRange; Tmp.Set(std::round(Tmp.X), std::round(Tmp.Y), std::floor(Tmp.Z)); Tmp *= GridRange; FVector Position((int)Tmp.X, (int)Tmp.Y, ((int)Tmp.Z) + GridRange); terrain->FillTerrainCube(Position, 55, 4); // basalt } } } } void AUE4VoxelTerrainPlayerController::OnAltActionReleased() { GetWorld()->GetTimerManager().ClearTimer(timer); } void AUE4VoxelTerrainPlayerController::setTool0() { tool_mode = 0; } void AUE4VoxelTerrainPlayerController::setTool1() { tool_mode = 1; } void AUE4VoxelTerrainPlayerController::setTool2() { tool_mode = 2; } void AUE4VoxelTerrainPlayerController::setTool3() { tool_mode = 3; } void AUE4VoxelTerrainPlayerController::setTool4() { tool_mode = 4; } void AUE4VoxelTerrainPlayerController::setTool5() { tool_mode = 5; } void AUE4VoxelTerrainPlayerController::setTool6() { tool_mode = 6; } void AUE4VoxelTerrainPlayerController::setTool7() { tool_mode = 7; } void AUE4VoxelTerrainPlayerController::PerformAction() { ASandboxCharacter* pawn = Cast<ASandboxCharacter>(GetCharacter()); if (pawn->GetSandboxPlayerView() != PlayerView::TOP_DOWN) { return; } FHitResult Hit; GetHitResultUnderCursor(ECC_WorldStatic, false, Hit); if (Hit.bBlockingHit) { ASandboxTerrainController* terrain = Cast<ASandboxTerrainController>(Hit.Actor.Get()); if (terrain != NULL) { if (tool_mode == 1) { terrain->DigTerrainRoundHole(Hit.ImpactPoint, 80, 5); } } } } FHitResult AUE4VoxelTerrainPlayerController::TracePlayerActionPoint() { ASandboxCharacter* pawn = Cast<ASandboxCharacter>(GetCharacter()); if (pawn->GetSandboxPlayerView() == PlayerView::THIRD_PERSON) { float MaxUseDistance = 800; if (pawn->GetCameraBoom() != NULL) { MaxUseDistance = pawn->GetCameraBoom()->TargetArmLength + 800; } FVector CamLoc; FRotator CamRot; GetPlayerViewPoint(CamLoc, CamRot); const FVector StartTrace = CamLoc; const FVector Direction = CamRot.Vector(); const FVector EndTrace = StartTrace + (Direction * MaxUseDistance); FCollisionQueryParams TraceParams(FName(TEXT("")), true, this); //TraceParams.bTraceAsyncScene = true; TraceParams.bReturnPhysicalMaterial = false; TraceParams.bTraceComplex = true; TraceParams.AddIgnoredActor(pawn); FHitResult Hit(ForceInit); GetWorld()->LineTraceSingleByChannel(Hit, StartTrace, EndTrace, ECC_Visibility, TraceParams); return Hit; } if (pawn->GetSandboxPlayerView() == PlayerView::TOP_DOWN) { FHitResult Hit; GetHitResultUnderCursor(ECC_Visibility, false, Hit); return Hit; } return FHitResult(); }
#pragma once #include "Common.h" #include "GraphicStructures.h" #include "FileUtils.h" class AnimSet { private: friend class AnimController; struct BoneOutput { hash nameHash; FloatVec scaleTime; VectorVec scaleValue; FloatVec rotationTime; QuaternionVec rotationValue; FloatVec translationTime; VectorVec translationValue; }; typedef vector< BoneOutput > BoneOutputVec; string animFileName; string animName; float durationTicks; float ticksPerSecond; BoneOutputVec boneOutputs; HashVecVec bonesHierarchy; public: void SetData( const string& fname, const string& name, float ticks, float tps ); void AddBoneOutput( HashVec hierarchy, const FloatVec& st, const VectorVec& sv, const FloatVec& rt, const QuaternionVec& rv, const FloatVec& tt, const VectorVec& tv ); const string& GetFileName(); const string& GetName(); uint GetBoneOutputCount(); float GetDuration(); HashVecVec& GetBonesHierarchy(); void Save( File& file ); void Load( File& file ); }; typedef vector< AnimSet* > AnimSetVec; class AnimController { private: struct Output { hash nameHash; Matrix* matrix; // Data for tracks blending BoolVec valid; FloatVec factor; VectorVec scale; QuaternionVec rotation; VectorVec translation; }; typedef vector< Output > OutputVec; typedef vector< Output* > OutputPtrVec; struct Track { struct Event { enum EType { Enable, Speed, Weight }; Event( EType t, float v, float start, float smooth ): type( t ), valueFrom( -1.0f ), valueTo( v ), startTime( start ), smoothTime( smooth ) {} EType type; float valueFrom; float valueTo; float startTime; float smoothTime; }; typedef vector< Event > EventVec; bool enabled; float speed; float weight; float position; AnimSet* anim; OutputPtrVec animOutput; EventVec events; }; typedef vector< Track > TrackVec; bool cloned; AnimSetVec* sets; OutputVec* outputs; TrackVec tracks; float curTime; bool interpolationDisabled; public: AnimController(); ~AnimController(); static AnimController* Create( uint track_count ); AnimController* Clone(); void RegisterAnimationOutput( hash bone_name_hash, Matrix& output_matrix ); void RegisterAnimationSet( AnimSet* animation ); AnimSet* GetAnimationSet( uint index ); AnimSet* GetAnimationSetByName( const string& name ); float GetTrackPosition( uint track ); uint GetNumAnimationSets(); void SetTrackAnimationSet( uint track, AnimSet* anim ); void ResetBonesTransition( uint skip_track, const HashVec& bone_name_hashes ); void Reset(); float GetTime(); void AddEventEnable( uint track, bool enable, float start_time ); void AddEventSpeed( uint track, float speed, float start_time, float smooth_time ); void AddEventWeight( uint track, float weight, float start_time, float smooth_time ); void SetTrackEnable( uint track, bool enable ); void SetTrackPosition( uint track, float position ); void SetInterpolation( bool enabled ); void AdvanceTime( float time ); private: template< class T > void FindSRTValue( float time, FloatVec& times, vector< T >& values, T& result ) { for( uint n = 0, m = (uint) times.size(); n < m; n++ ) { if( n + 1 < m ) { if( time >= times[ n ] && time < times[ n + 1 ] ) { result = values[ n ]; T& value = values[ n + 1 ]; float factor = ( time - times[ n ] ) / ( times[ n + 1 ] - times[ n ] ); Interpolate( result, value, factor ); return; } } else { result = values[ n ]; } } } void Interpolate( Quaternion& q1, const Quaternion& q2, float factor ); void Interpolate( Vector& v1, const Vector& v2, float factor ); };
#include "PEngine/graphics/spritesheet.h" #include "PEngine/app/resource_manager.h" #include <iostream> namespace pear { namespace graphics { SpriteSheet::SpriteSheet(const glm::vec4& pos_and_dim, const char* texture_name, float depth) : Renderable2D( RenderableType::SPRITESHEET, pos_and_dim, texture_name, depth ), spriteSheetID( ResourceManager::getRenderable2DCount() ), currAnimation( -1 ), currFrame( nullptr ) { addAnimationWithRegDim( 7, 2, 0, 13 ); } SpriteSheet::~SpriteSheet() { } bool SpriteSheet::ready() { if( currAnimation == -1 ) { return false; } return true; } glm::vec4* SpriteSheet::getCurrFrame() { if( currFrame == nullptr ) nextFrame(); return currFrame; } void SpriteSheet::nextFrame() { if( currAnimation >= 0 ) currFrame = animations[currAnimation].getFrame(); else std::cout << "SS_AnimationError! \"currAnimation\" is less than 0!" << std::endl; } void SpriteSheet::startAnimation( unsigned int ani_num ) { currAnimation = ani_num; } void SpriteSheet::addAnimationWithRegDim( int nosh, int nosv, int first_sprite, int last_sprite ) { animations.push_back( SS_Animation( texture->filename.c_str(), nosh, nosv, first_sprite, last_sprite ) ); startAnimation( 0 ); } void SpriteSheet::addAnimationWithSP( const char* animation_name ) { animations.push_back( SS_Animation( texture->filename.c_str(), animation_name ) ); startAnimation( 0 ); } } }
#include <bits/stdc++.h> using namespace std; int main() { int n, ans = 0; cin>>n; while(n--) { int a, b, c, cnt = 0; cin>>a>>b>>c; if(a) cnt++; if(b) cnt++; if(c) cnt++; if(cnt>=2) ans++; } cout<<ans<<endl; }
///////////////////////////////////////////////////////////////////////////// // Name: src/gtk/colour.cpp // Purpose: // Author: Robert Roebling // Id: $Id: colour.cpp 58757 2009-02-08 11:45:59Z VZ $ // Copyright: (c) 1998 Robert Roebling // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #include "wx/colour.h" #include "wx/gtk/private.h" #include <gdk/gdk.h> //----------------------------------------------------------------------------- // wxColour //----------------------------------------------------------------------------- class wxColourRefData : public wxGDIRefData { public: wxColourRefData(guint16 red, guint16 green, guint16 blue, wxByte alpha = 0xff) { m_color.red = m_red = red; m_color.green = m_green = green; m_color.blue = m_blue = blue; m_alpha = alpha; m_color.pixel = 0; m_colormap = NULL; } virtual ~wxColourRefData() { FreeColour(); } void FreeColour(); void AllocColour( GdkColormap* cmap ); GdkColor m_color; GdkColormap *m_colormap; // gdk_colormap_alloc_color may change the RGB values in m_color, so we need separate copies guint16 m_red; guint16 m_green; guint16 m_blue; wxByte m_alpha; wxDECLARE_NO_COPY_CLASS(wxColourRefData); }; void wxColourRefData::FreeColour() { if (m_colormap) { gdk_colormap_free_colors(m_colormap, &m_color, 1); m_colormap = NULL; m_color.pixel = 0; } } void wxColourRefData::AllocColour( GdkColormap *cmap ) { if (m_colormap != cmap) { FreeColour(); m_color.red = m_red; m_color.green = m_green; m_color.blue = m_blue; if (gdk_colormap_alloc_color(cmap, &m_color, FALSE, TRUE)) { m_colormap = cmap; } } } //----------------------------------------------------------------------------- #define M_COLDATA static_cast<wxColourRefData*>(m_refData) // GDK's values are in 0..65535 range, ours are in 0..255 #define SHIFT 8 IMPLEMENT_DYNAMIC_CLASS(wxColour,wxGDIObject) wxColour::wxColour(const GdkColor& gdkColor) { m_refData = new wxColourRefData(gdkColor.red, gdkColor.green, gdkColor.blue); } wxColour::~wxColour() { } bool wxColour::operator == ( const wxColour& col ) const { if (m_refData == col.m_refData) return true; if (!m_refData || !col.m_refData) return false; wxColourRefData* refData = M_COLDATA; wxColourRefData* that_refData = static_cast<wxColourRefData*>(col.m_refData); return refData->m_red == that_refData->m_red && refData->m_green == that_refData->m_green && refData->m_blue == that_refData->m_blue && refData->m_alpha == that_refData->m_alpha; } void wxColour::InitRGBA(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha) { UnRef(); m_refData = new wxColourRefData( (guint16(red) << SHIFT) + red, (guint16(green) << SHIFT) + green, (guint16(blue) << SHIFT) + blue, alpha); } unsigned char wxColour::Red() const { wxCHECK_MSG( Ok(), 0, wxT("invalid colour") ); return wxByte(M_COLDATA->m_red >> SHIFT); } unsigned char wxColour::Green() const { wxCHECK_MSG( Ok(), 0, wxT("invalid colour") ); return wxByte(M_COLDATA->m_green >> SHIFT); } unsigned char wxColour::Blue() const { wxCHECK_MSG( Ok(), 0, wxT("invalid colour") ); return wxByte(M_COLDATA->m_blue >> SHIFT); } unsigned char wxColour::Alpha() const { wxCHECK_MSG( Ok(), 0, wxT("invalid colour") ); return M_COLDATA->m_alpha; } void wxColour::CalcPixel( GdkColormap *cmap ) { if (!Ok()) return; M_COLDATA->AllocColour( cmap ); } int wxColour::GetPixel() const { wxCHECK_MSG( Ok(), 0, wxT("invalid colour") ); return M_COLDATA->m_color.pixel; } const GdkColor *wxColour::GetColor() const { wxCHECK_MSG( Ok(), NULL, wxT("invalid colour") ); return &M_COLDATA->m_color; } bool wxColour::FromString(const wxString& str) { GdkColor colGDK; if ( gdk_color_parse( wxGTK_CONV_SYS( str ), &colGDK ) ) { *this = wxColour(colGDK); return true; } return wxColourBase::FromString(str); }
#include "components\scripting\Singularity.Components.Scripting.h" namespace Singularity { namespace Components { namespace Scripting { class LuaMethods { private: #pragma region Static Variables static LuaMethods* g_iInstance; #pragma endregion #pragma region Static Methods static int lua_GetGameObject(lua_State* l); #pragma endregion #pragma region Constructors and Finalizers LuaMethods() { }; ~LuaMethods() { }; #pragma endregion public: #pragma region Static Methods static LuaMethods* Register(); #pragma endregion }; } } }
#include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1000000007 ll util(int n,int m,vector<vector<ll> > &dp){ if(n==2 && m==1) return 1; if(n==1 && m==2) return 1; if(n==0 && m==0) return 1; if(n<=0 || m<=0) return 0; if(dp[n][m]!=-1) return dp[n][m]; return dp[n][m]=(util(n,m-2,dp)+util(n-1,m,dp)+util(n-2,m,dp)+util(n,m-1,dp)-util(n-1,m-2,dp)-util(n-2,m-1,dp)); } int main(){ ll n,m;cin>>n>>m; vector<vector<ll> > dp(n+1,vector<ll>(m+1,-1)); cout<<util(n,m,dp); }
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2021, 4Paradigm Inc. */ #ifndef LOG4P_H #define LOG4P_H #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) #include <iostream> #include <limits> #include <string> #include <stdio.h> #include <stdarg.h> #define LOG4P_LEVEL_ERROR 0 #define LOG4P_LEVEL_WARNING 1 #define LOG4P_LEVEL_INFO 2 #define LOG4P_LEVEL_DEBUG 3 #define LOG4P_LEVEL LOG4P_LEVEL_INFO const static char* _LOG4P_LEVEL_PREFIX[] = { " \033[1;31mE: ", " \033[1;35mW: ", " ", " \033[1;33mD: " }; static void _LOG4P(int logLevel, const char* file, const char* func, unsigned int line, const char* format, ...) { // if (logLevel > LOG4P_LEVEL) // return; char message[512]; va_list args; va_start(args, format); vsnprintf(message, 512, format, args); va_end(args); std::cout << file << ":" << line << " \033[1;36m" << func << "\033[0m" << _LOG4P_LEVEL_PREFIX[logLevel] << message << "\033[0m" << std::endl; } #define LOG4P(logLevel, format, ...) \ {_LOG4P(logLevel, __FILENAME__, __func__, __LINE__, format, ##__VA_ARGS__);} #if (LOG4P_LEVEL>=LOG4P_LEVEL_ERROR) #define LOG4P_ERROR(format, ...) \ LOG4P(LOG4P_LEVEL_ERROR, format, ##__VA_ARGS__) #else #define LOG4P_ERROR(format, ...) {} #endif #if (LOG4P_LEVEL>=LOG4P_LEVEL_WARNING) #define LOG4P_WARNING(format, ...) \ LOG4P(LOG4P_LEVEL_WARNING, format, ##__VA_ARGS__) #else #define LOG4P_WARNING(format, ...) {} #endif #if (LOG4P_LEVEL>=LOG4P_LEVEL_INFO) #define LOG4P_INFO(format, ...) \ LOG4P(LOG4P_LEVEL_INFO, format, ##__VA_ARGS__) #else #define LOG4P_INFO(format, ...) {} #endif #if (LOG4P_LEVEL>=LOG4P_LEVEL_DEBUG) #define LOG4P_DEBUG(format, ...) \ LOG4P(LOG4P_LEVEL_DEBUG, format, ##__VA_ARGS__) #else #define LOG4P_DEBUG(format, ...) {} #endif #endif // LOG4P_H
// Copyright 2020 JD.com, Inc. Galileo 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 "vertex_worker.h" #include <stdlib.h> #include <string> #include "converter.h" #include "convertor/transform_help.h" #include "utils/string_util.h" #include "glog/logging.h" namespace galileo { namespace convertor { AllocIdManager VertexWorker::alloc_id_manager_; bool VertexWorker::ParseRecord(std::vector<std::vector<char*>>& fields) { uint8_t vtype = galileo::utils::strToUInt8(fields[0][0]); int tmp_idx = converter_->schema_.GetVFieldIdx(vtype, SCM_ENTITY); if (tmp_idx < 0) { LOG(ERROR) << "get vertex entity field idx fail.vtype:" << std::to_string(vtype); return false; } size_t entity_idx = static_cast<size_t>(tmp_idx); assert(1 == fields[entity_idx].size()); if (1 != fields[entity_idx].size()) { LOG(ERROR) << "entity_idx error:" << fields[entity_idx].size(); return false; } char* entity = fields[entity_idx][0]; std::string entity_dtype = converter_->schema_.GetVFieldDtype(vtype, entity_idx); int partitions = converter_->slice_count_; int slice_id = TransformHelp::GetSliceId(entity, entity_dtype, partitions); if (slice_id < 0) { LOG(ERROR) << "get the vertex slice id fail,the entity dtype is:" << entity_dtype; return false; } if (!TransformHelp::TransformVertex(converter_->schema_, fields, record_)) { return false; } return this->WriteRecord(slice_id, record_); } } // namespace convertor } // namespace galileo
#include <iterator> #include <vector> #include <iostream> int main() { std::vector<double> vec = {1.1, 2.2, 3.3, 4.4, 5.5}; // Declaring iterator to a vector std::vector<double>::iterator iter; // Printing vector elements using begin() and end() std::cout << "The vector elements are: "; for (iter = vec.begin(); iter < vec.end(); iter++){ std::cout << *iter << " "; } }
// // Created by Peter Chen on 5/29/16. // #ifndef CUBEWORLD_DAYCYCLEMANAGER_H #define CUBEWORLD_DAYCYCLEMANAGER_H class DayCycleManager { }; #endif //CUBEWORLD_DAYCYCLEMANAGER_H
#include "Functions.h" #include <cmath> double FunctionsToIntegrate::UserFunction(double ST) { return PDFofStockPrice(ST)*PayOff(ST); } double FunctionsToIntegrate::PDFofStockPrice(double ST) { double s = m_sigma * sqrt(m_T); double m = log(m_S0) + (m_r - 0.5*m_sigma*m_sigma)*m_T; return (1 / (ST*s*sqrt(2 * Pi)))*exp(-pow((log(ST) - m), 2) / (2 * s*s)); } double EurCallOption::PayOff(double ST) { if (ST >= m_K) { return ST - m_K; } else return 0; } double EurPutOption::PayOff(double ST) { if (ST <= m_K) { return m_K - ST; } else return 0; }
#ifndef FTPWINDOW_H #define FTPWINDOW_H #include <QWidget> #include <QDialog> #include <QHash> #include <QNetworkConfigurationManager> QT_BEGIN_NAMESPACE class QDialogButtonBox; class QFile; class QFtp; class QLabel; class QLineEdit; class QTreeWidget; class QTreeWidgetItem; class QProgressDialog; class QPushButton; class QUrlInfo; class QNetworkSession; QT_END_NAMESPACE namespace Ui { class ftpwindow; } class ftpwindow : public QDialog { Q_OBJECT public: explicit ftpwindow(QWidget *parent = nullptr); ~ftpwindow(); QSize sizeHint() const; private slots: void connectOrDisconnect(); void downloadFile(); void connectToFtp(); void ftpCommandFinished(int commandId, bool error); void addToList(const QUrlInfo &urlInfo); void processItem(QTreeWidgetItem *item, int column); void cdToParent(); void enableDownloadButton(); void enableConnectButton(); private: QLabel *ftpServerLabel; QLineEdit *ftpServerLineEdit; QLabel *statusLabel; QTreeWidget *fileList; QPushButton *cdToParentButton; QPushButton *connectButton; QPushButton *downloadButton; QPushButton *quitButton; QHash<QString, bool> isDirectory; QString currentPath; QFtp *ftp; QFile *file; QNetworkSession *networkSession; QNetworkConfigurationManager manager; Ui::ftpwindow *ui; }; #endif // FTPWINDOW_H
#include "zenlang.hpp" #include "base/base.hpp" #include "base/XcodeGenerator.hpp" #include "base/compiler.hpp" class z::XcodeGenerator::Impl : public z::Generator::Impl { public: inline Impl(const z::Ast::Project& project) : Generator::Impl(project) {} public: void run(); private: inline void generateConfig(const z::Ast::Config& config, z::ofile& os); inline void generateProject(); inline void generatePCHFile(); inline void generatePListFile(); }; inline void z::XcodeGenerator::Impl::generateConfig(const z::Ast::Config& config, z::ofile& os) { z::Compiler compiler(_project, config); compiler.compile(); os() << "/* Begin XCBuildConfiguration section */" << std::endl; os() << " " << _project.name() << "_Debug_ProjectConfig = {" << std::endl; os() << " isa = XCBuildConfiguration;" << std::endl; os() << " buildSettings = {" << std::endl; os() << " ALWAYS_SEARCH_USER_PATHS = NO;" << std::endl; os() << " ARCHS = \"$(ARCHS_STANDARD_64_BIT)\";" << std::endl; os() << " CLANG_CXX_LANGUAGE_STANDARD = \"gnu++0x\";" << std::endl; // os() << " CLANG_CXX_LIBRARY = \"libc++\";" << std::endl; os() << " CLANG_CXX_LIBRARY = \"libstdc++\";" << std::endl; os() << " CLANG_ENABLE_OBJC_ARC = YES;" << std::endl; os() << " CLANG_WARN_EMPTY_BODY = YES;" << std::endl; os() << " CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;" << std::endl; os() << " COPY_PHASE_STRIP = NO;" << std::endl; os() << " GCC_C_LANGUAGE_STANDARD = gnu99;" << std::endl; os() << " GCC_DYNAMIC_NO_PIC = NO;" << std::endl; os() << " GCC_ENABLE_OBJC_EXCEPTIONS = YES;" << std::endl; os() << " GCC_OPTIMIZATION_LEVEL = 0;" << std::endl; os() << " GCC_PREPROCESSOR_DEFINITIONS = (" << std::endl; os() << " \"DEBUG=1\"," << std::endl; if(config.gui()) { os() << " \"GUI=1\"," << std::endl; } if(config.buildMode() == z::Ast::Config::BuildMode::Executable) { os() << " \"Z_EXE=1\"," << std::endl; } os() << " \"$(inherited)\"," << std::endl; os() << " );" << std::endl; os() << " GCC_SYMBOLS_PRIVATE_EXTERN = NO;" << std::endl; os() << " GCC_WARN_64_TO_32_BIT_CONVERSION = YES;" << std::endl; os() << " GCC_WARN_ABOUT_RETURN_TYPE = YES;" << std::endl; os() << " GCC_WARN_UNINITIALIZED_AUTOS = YES;" << std::endl; os() << " GCC_WARN_UNUSED_VARIABLE = YES;" << std::endl; os() << " MACOSX_DEPLOYMENT_TARGET = 10.8;" << std::endl; os() << " ONLY_ACTIVE_ARCH = YES;" << std::endl; os() << " SDKROOT = macosx;" << std::endl; os() << " };" << std::endl; os() << " name = Debug;" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_Release_ProjectConfig = {" << std::endl; os() << " isa = XCBuildConfiguration;" << std::endl; os() << " buildSettings = {" << std::endl; os() << " ALWAYS_SEARCH_USER_PATHS = NO;" << std::endl; os() << " ARCHS = \"$(ARCHS_STANDARD_64_BIT)\";" << std::endl; os() << " CLANG_CXX_LANGUAGE_STANDARD = \"gnu++0x\";" << std::endl; // os() << " CLANG_CXX_LIBRARY = \"libc++\";" << std::endl; os() << " CLANG_CXX_LIBRARY = \"libstdc++\";" << std::endl; os() << " CLANG_ENABLE_OBJC_ARC = YES;" << std::endl; os() << " CLANG_WARN_EMPTY_BODY = YES;" << std::endl; os() << " CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;" << std::endl; os() << " COPY_PHASE_STRIP = YES;" << std::endl; os() << " DEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";" << std::endl; os() << " GCC_PREPROCESSOR_DEFINITIONS = (" << std::endl; if(config.gui()) { os() << " \"GUI=1\"," << std::endl; } if(config.buildMode() == z::Ast::Config::BuildMode::Executable) { os() << " \"Z_EXE=1\"," << std::endl; } os() << " \"$(inherited)\"," << std::endl; os() << " );" << std::endl; os() << " GCC_C_LANGUAGE_STANDARD = gnu99;" << std::endl; os() << " GCC_ENABLE_OBJC_EXCEPTIONS = YES;" << std::endl; os() << " GCC_WARN_64_TO_32_BIT_CONVERSION = YES;" << std::endl; os() << " GCC_WARN_ABOUT_RETURN_TYPE = YES;" << std::endl; os() << " GCC_WARN_UNINITIALIZED_AUTOS = YES;" << std::endl; os() << " GCC_WARN_UNUSED_VARIABLE = YES;" << std::endl; os() << " MACOSX_DEPLOYMENT_TARGET = 10.8;" << std::endl; os() << " SDKROOT = macosx;" << std::endl; os() << " };" << std::endl; os() << " name = Release;" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_OSX_Debug_TargetConfig = {" << std::endl; os() << " isa = XCBuildConfiguration;" << std::endl; os() << " buildSettings = {" << std::endl; os() << " CLANG_ENABLE_OBJC_ARC = NO;" << std::endl; os() << " COMBINE_HIDPI_IMAGES = YES;" << std::endl; os() << " GCC_PRECOMPILE_PREFIX_HEADER = YES;" << std::endl; os() << " GCC_PREFIX_HEADER = \"" << _project.name() << "-OSX-Prefix.pch\";" << std::endl; os() << " HEADER_SEARCH_PATHS = \"" << _project.zlibPath() << "\";" << std::endl; os() << " INFOPLIST_FILE = \"" << _project.name() << "-OSX-Info.plist\";" << std::endl; os() << " PRODUCT_NAME = \"$(TARGET_NAME)\";" << std::endl; os() << " WRAPPER_EXTENSION = app;" << std::endl; os() << " };" << std::endl; os() << " name = Debug;" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_OSX_Release_TargetConfig = {" << std::endl; os() << " isa = XCBuildConfiguration;" << std::endl; os() << " buildSettings = {" << std::endl; os() << " CLANG_ENABLE_OBJC_ARC = NO;" << std::endl; os() << " COMBINE_HIDPI_IMAGES = YES;" << std::endl; os() << " GCC_PRECOMPILE_PREFIX_HEADER = YES;" << std::endl; os() << " GCC_PREFIX_HEADER = \"" << _project.name() << "-OSX-Prefix.pch\";" << std::endl; os() << " HEADER_SEARCH_PATHS = \"" << _project.zlibPath() << "\";" << std::endl; os() << " INFOPLIST_FILE = \"" << _project.name() << "-OSX-Info.plist\";" << std::endl; os() << " PRODUCT_NAME = \"$(TARGET_NAME)\";" << std::endl; os() << " WRAPPER_EXTENSION = app;" << std::endl; os() << " };" << std::endl; os() << " name = Release;" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_IOS_Debug_TargetConfig = {" << std::endl; os() << " isa = XCBuildConfiguration;" << std::endl; os() << " buildSettings = {" << std::endl; os() << " \"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\";" << std::endl; os() << " CLANG_ENABLE_OBJC_ARC = NO;" << std::endl; os() << " FRAMEWORK_SEARCH_PATHS = (" << std::endl; os() << " \"$(inherited)\"," << std::endl; os() << " \"\\\"$(SYSTEM_APPS_DIR)/Xcode.app/Contents/Developer/Library/Frameworks\\\"\"," << std::endl; os() << " );" << std::endl; os() << " GCC_PRECOMPILE_PREFIX_HEADER = YES;" << std::endl; os() << " GCC_PREFIX_HEADER = \"" << _project.name() << "-IOS-Prefix.pch\";" << std::endl; os() << " HEADER_SEARCH_PATHS = \"" << _project.zlibPath() << "\";" << std::endl; os() << " INFOPLIST_FILE = \"" << _project.name() << "-IOS-Info.plist\";" << std::endl; os() << " IPHONEOS_DEPLOYMENT_TARGET = 6.0;" << std::endl; os() << " PRODUCT_NAME = \"$(TARGET_NAME)\";" << std::endl; os() << " SDKROOT = iphoneos;" << std::endl; os() << " TARGETED_DEVICE_FAMILY = \"1,2\";" << std::endl; os() << " WRAPPER_EXTENSION = app;" << std::endl; os() << " };" << std::endl; os() << " name = Debug;" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_IOS_Release_TargetConfig = {" << std::endl; os() << " isa = XCBuildConfiguration;" << std::endl; os() << " buildSettings = {" << std::endl; os() << " \"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\";" << std::endl; os() << " CLANG_ENABLE_OBJC_ARC = NO;" << std::endl; os() << " FRAMEWORK_SEARCH_PATHS = (" << std::endl; os() << " \"$(inherited)\"," << std::endl; os() << " \"\\\"$(SYSTEM_APPS_DIR)/Xcode.app/Contents/Developer/Library/Frameworks\\\"\"," << std::endl; os() << " );" << std::endl; os() << " GCC_PRECOMPILE_PREFIX_HEADER = YES;" << std::endl; os() << " GCC_PREFIX_HEADER = \"" << _project.name() << "-IOS-Prefix.pch\";" << std::endl; os() << " HEADER_SEARCH_PATHS = \"" << _project.zlibPath() << "\";" << std::endl; os() << " INFOPLIST_FILE = \"" << _project.name() << "-IOS-Info.plist\";" << std::endl; os() << " IPHONEOS_DEPLOYMENT_TARGET = 6.0;" << std::endl; os() << " OTHER_CFLAGS = \"-DNS_BLOCK_ASSERTIONS=1\";" << std::endl; os() << " PRODUCT_NAME = \"$(TARGET_NAME)\";" << std::endl; os() << " SDKROOT = iphoneos;" << std::endl; os() << " TARGETED_DEVICE_FAMILY = \"1,2\";" << std::endl; os() << " VALIDATE_PRODUCT = YES;" << std::endl; os() << " WRAPPER_EXTENSION = app;" << std::endl; os() << " };" << std::endl; os() << " name = Release;" << std::endl; os() << " };" << std::endl; os() << "/* End XCBuildConfiguration section */" << std::endl; os() << "" << std::endl; os() << "/* Begin XCConfigurationList section */" << std::endl; os() << " Project_ConfigList = {" << std::endl; os() << " isa = XCConfigurationList;" << std::endl; os() << " buildConfigurations = (" << std::endl; os() << " " << _project.name() << "_Debug_ProjectConfig," << std::endl; os() << " " << _project.name() << "_Release_ProjectConfig," << std::endl; os() << " );" << std::endl; os() << " defaultConfigurationIsVisible = 0;" << std::endl; os() << " defaultConfigurationName = Release;" << std::endl; os() << " };" << std::endl; os() << " OSX_Target_ConfigList = {" << std::endl; os() << " isa = XCConfigurationList;" << std::endl; os() << " buildConfigurations = (" << std::endl; os() << " " << _project.name() << "_OSX_Debug_TargetConfig," << std::endl; os() << " " << _project.name() << "_OSX_Release_TargetConfig," << std::endl; os() << " );" << std::endl; os() << " defaultConfigurationIsVisible = 0;" << std::endl; os() << " defaultConfigurationName = Release;" << std::endl; os() << " };" << std::endl; os() << " IOS_Target_ConfigList = {" << std::endl; os() << " isa = XCConfigurationList;" << std::endl; os() << " buildConfigurations = (" << std::endl; os() << " " << _project.name() << "_IOS_Debug_TargetConfig," << std::endl; os() << " " << _project.name() << "_IOS_Release_TargetConfig," << std::endl; os() << " );" << std::endl; os() << " defaultConfigurationIsVisible = 0;" << std::endl; os() << " defaultConfigurationName = Release;" << std::endl; os() << " };" << std::endl; os() << "/* End XCConfigurationList section */" << std::endl; } inline void z::XcodeGenerator::Impl::generatePCHFile() { z::ofile os1(_gendir + "/" + _project.name() + "-OSX-Prefix.pch"); os1() << "#ifdef __OBJC__" << std::endl; os1() << "#import <Cocoa/Cocoa.h>" << std::endl; os1() << "#endif" << std::endl; z::ofile os2(_gendir + "/" + _project.name() + "-IOS-Prefix.pch"); os2() << "#ifdef __OBJC__" << std::endl; os2() << "#import <UIKit/UIKit.h>" << std::endl; os2() << "#import <Foundation/Foundation.h>" << std::endl; os2() << "#endif" << std::endl; } inline void z::XcodeGenerator::Impl::generatePListFile() { z::ofile os1(_gendir + "/" + _project.name() + "-OSX-Info.plist"); os1() << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl; os1() << "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << std::endl; os1() << "<plist version=\"1.0\">" << std::endl; os1() << "<dict>" << std::endl; os1() << "<key>CFBundleDevelopmentRegion</key>" << std::endl; os1() << "<string>en</string>" << std::endl; os1() << "<key>CFBundleExecutable</key>" << std::endl; os1() << "<string>${EXECUTABLE_NAME}</string>" << std::endl; os1() << "<key>CFBundleIconFile</key>" << std::endl; os1() << "<string></string>" << std::endl; os1() << "<key>CFBundleIdentifier</key>" << std::endl; os1() << "<string>test.${PRODUCT_NAME:rfc1034identifier}</string>" << std::endl; os1() << "<key>CFBundleInfoDictionaryVersion</key>" << std::endl; os1() << "<string>6.0</string>" << std::endl; os1() << "<key>CFBundleName</key>" << std::endl; os1() << "<string>${PRODUCT_NAME}</string>" << std::endl; os1() << "<key>CFBundlePackageType</key>" << std::endl; os1() << "<string>APPL</string>" << std::endl; os1() << "<key>CFBundleShortVersionString</key>" << std::endl; os1() << "<string>1.0</string>" << std::endl; os1() << "<key>CFBundleSignature</key>" << std::endl; os1() << "<string>\?\?\?\?</string>" << std::endl; os1() << "<key>CFBundleVersion</key>" << std::endl; os1() << "<string>1</string>" << std::endl; os1() << "<key>LSMinimumSystemVersion</key>" << std::endl; os1() << "<string>${MACOSX_DEPLOYMENT_TARGET}</string>" << std::endl; os1() << "<key>NSHumanReadableCopyright</key>" << std::endl; os1() << "<string>Copyright © 2012 Renji Panicker. All rights reserved.</string>" << std::endl; os1() << "<key>NSPrincipalClass</key>" << std::endl; os1() << "<string>NSApplication</string>" << std::endl; os1() << "</dict>" << std::endl; os1() << "</plist>" << std::endl; z::ofile os2(_gendir + "/" + _project.name() + "-IOS-Info.plist"); os2() << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl; os2() << "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << std::endl; os2() << "<plist version=\"1.0\">" << std::endl; os2() << "<dict>" << std::endl; os2() << "<key>CFBundleDevelopmentRegion</key>" << std::endl; os2() << "<string>en</string>" << std::endl; os2() << "<key>CFBundleDisplayName</key>" << std::endl; os2() << "<string>${PRODUCT_NAME}</string>" << std::endl; os2() << "<key>CFBundleExecutable</key>" << std::endl; os2() << "<string>${EXECUTABLE_NAME}</string>" << std::endl; os2() << "<key>CFBundleIdentifier</key>" << std::endl; os2() << "<string>test.${PRODUCT_NAME:rfc1034identifier}</string>" << std::endl; os2() << "<key>CFBundleInfoDictionaryVersion</key>" << std::endl; os2() << "<string>6.0</string>" << std::endl; os2() << "<key>CFBundleName</key>" << std::endl; os2() << "<string>${PRODUCT_NAME}</string>" << std::endl; os2() << "<key>CFBundlePackageType</key>" << std::endl; os2() << "<string>APPL</string>" << std::endl; os2() << "<key>CFBundleShortVersionString</key>" << std::endl; os2() << "<string>1.0</string>" << std::endl; os2() << "<key>CFBundleSignature</key>" << std::endl; os2() << "<string>\?\?\?\?</string>" << std::endl; os2() << "<key>CFBundleVersion</key>" << std::endl; os2() << "<string>1.0</string>" << std::endl; os2() << "<key>LSRequiresIPhoneOS</key>" << std::endl; os2() << "<true/>" << std::endl; os2() << "<key>UIRequiredDeviceCapabilities</key>" << std::endl; os2() << "<array>" << std::endl; os2() << " <string>armv7</string>" << std::endl; os2() << "</array>" << std::endl; os2() << "<key>UISupportedInterfaceOrientations</key>" << std::endl; os2() << "<array>" << std::endl; os2() << " <string>UIInterfaceOrientationPortrait</string>" << std::endl; os2() << " <string>UIInterfaceOrientationLandscapeLeft</string>" << std::endl; os2() << " <string>UIInterfaceOrientationLandscapeRight</string>" << std::endl; os2() << "</array>" << std::endl; os2() << "<key>UISupportedInterfaceOrientations~ipad</key>" << std::endl; os2() << "<array>" << std::endl; os2() << " <string>UIInterfaceOrientationPortrait</string>" << std::endl; os2() << " <string>UIInterfaceOrientationPortraitUpsideDown</string>" << std::endl; os2() << " <string>UIInterfaceOrientationLandscapeLeft</string>" << std::endl; os2() << " <string>UIInterfaceOrientationLandscapeRight</string>" << std::endl; os2() << "</array>" << std::endl; os2() << "</dict>" << std::endl; os2() << "</plist>" << std::endl; } inline void z::XcodeGenerator::Impl::generateProject() { z::dir::mkpath(_gendir + "/" + _project.name() + ".xcodeproj/"); z::ofile os(_gendir + "/" + _project.name() + ".xcodeproj/project.pbxproj"); os() << "// !$*UTF8*$!" << std::endl; os() << "{" << std::endl; os() << " archiveVersion = 1;" << std::endl; os() << " classes = {" << std::endl; os() << " };" << std::endl; os() << " objectVersion = 46;" << std::endl; os() << " objects = {" << std::endl; os() << "/* Begin PBXBuildFile section */" << std::endl; os() << " Sqlite3_OSX_Framework_BuildFile = {isa = PBXBuildFile; fileRef = Sqlite3_OSX_Framework_FileRef; };" << std::endl; os() << " Sqlite3_IOS_Framework_BuildFile = {isa = PBXBuildFile; fileRef = Sqlite3_IOS_Framework_FileRef; };" << std::endl; os() << " WebKit_Framework_BuildFile = {isa = PBXBuildFile; fileRef = WebKit_Framework_FileRef; };" << std::endl; os() << " Cocoa_Framework_BuildFile = {isa = PBXBuildFile; fileRef = Cocoa_Framework_FileRef; };" << std::endl; os() << " UIKit_Framework_BuildFile = {isa = PBXBuildFile; fileRef = UIKit_Framework_FileRef; };" << std::endl; os() << " Foundation_Framework_BuildFile = {isa = PBXBuildFile; fileRef = Foundation2_Framework_FileRef; };" << std::endl; os() << " CoreGraphics_Framework_BuildFile = {isa = PBXBuildFile; fileRef = CoreGraphics_Framework_FileRef ; };" << std::endl; os() << " zenlang_cpp_BuildFile = {isa = PBXBuildFile; fileRef = zenlang_cpp_FileRef; settings = {COMPILER_FLAGS = \"-x objective-c++\"; }; };" << std::endl; for(FileList::const_iterator it = _hppFileList.begin(), ite = _hppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_hpp_BuildFile = {isa = PBXBuildFile; fileRef = " << basename << "_hpp_FileRef; };" << std::endl; } for(FileList::const_iterator it = _cppFileList.begin(), ite = _cppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_cpp_BuildFile = {isa = PBXBuildFile; fileRef = " << basename << "_cpp_FileRef; };" << std::endl; } for(FileList::const_iterator it = _zppFileList.begin(), ite = _zppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_zpp_BuildFile = {isa = PBXBuildFile; fileRef = " << basename << "_zpp_FileRef; };" << std::endl; } for(FileList::const_iterator it = _otherFileList.begin(), ite = _otherFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); z::string ext = z::dir::getExtention(filename); if(ext == "re") { os() << " " << basename << "_re_BuildFile = {isa = PBXBuildFile; fileRef = " << basename << "_re_FileRef; };" << std::endl; } else if(ext == "y") { os() << " " << basename << "_y_BuildFile = {isa = PBXBuildFile; fileRef = " << basename << "_y_FileRef; };" << std::endl; } else { throw z::Exception("XcodeGenerator", zfmt(z::Ast::Token(filename, 0, 0, ""), "1-Unknown file type for: %{s}").arg("s", filename)); } } for(FileList::const_iterator it = _guiFileList.begin(), ite = _guiFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_htm_BuildFile = {isa = PBXBuildFile; fileRef = " << basename << "_htm_FileRef; };" << std::endl; } os() << "/* End PBXBuildFile section */" << std::endl; os() << "" << std::endl; os() << "/* Begin PBXBuildRule section */" << std::endl; os() << " lemon_BuildRule = {" << std::endl; os() << " isa = PBXBuildRule;" << std::endl; os() << " compilerSpec = com.apple.compilers.proxy.script;" << std::endl; os() << " filePatterns = \"*.y\";" << std::endl; os() << " fileType = pattern.proxy;" << std::endl; os() << " isEditable = 1;" << std::endl; os() << " outputFiles = (" << std::endl; os() << " \"${DERIVED_FILE_DIR}/${INPUT_FILE_BASE}.cpp\"," << std::endl; os() << " );" << std::endl; os() << " script = \"" << _project.zlibPath() << "/lemon.osx o=.cpp d=${DERIVED_FILE_DIR} -q ${INPUT_FILE_PATH}\";" << std::endl; os() << " };" << std::endl; os() << "" << std::endl; os() << " re2c_BuildRule = {" << std::endl; os() << " isa = PBXBuildRule;" << std::endl; os() << " compilerSpec = com.apple.compilers.proxy.script;" << std::endl; os() << " filePatterns = \"*.re\";" << std::endl; os() << " fileType = pattern.proxy;" << std::endl; os() << " isEditable = 1;" << std::endl; os() << " outputFiles = (" << std::endl; os() << " \"${DERIVED_FILE_DIR}/${INPUT_FILE_BASE}.cpp\"," << std::endl; os() << " );" << std::endl; os() << " script = \"" << _project.zlibPath() << "/re2c.osx -f -u -c -o ${DERIVED_FILE_DIR}/${INPUT_FILE_BASE}.cpp ${INPUT_FILE_PATH}\";" << std::endl; os() << " };" << std::endl; os() << " zenlang_BuildRule = {" << std::endl; os() << " isa = PBXBuildRule;" << std::endl; os() << " compilerSpec = com.apple.compilers.proxy.script;" << std::endl; os() << " filePatterns = \"*.zpp\";" << std::endl; os() << " fileType = pattern.proxy;" << std::endl; os() << " isEditable = 1;" << std::endl; os() << " outputFiles = (" << std::endl; os() << " \"${PROJECT_DIR}/${INPUT_FILE_BASE}.ipp\"," << std::endl; os() << " \"${PROJECT_DIR}/${INPUT_FILE_BASE}.hpp\"," << std::endl; os() << " \"${PROJECT_DIR}/${INPUT_FILE_BASE}.cpp\"," << std::endl; os() << " );" << std::endl; os() << " script = \"" << _project.zexePath() << " -g -c ${INPUT_FILE_PATH}\";" << std::endl; os() << " };" << std::endl; os() << "/* End PBXBuildRule section */" << std::endl; os() << "/* Begin PBXFileReference section */" << std::endl; os() << " Sqlite3_OSX_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = \"compiled.mach-o.dylib\"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; };" << std::endl; os() << " Sqlite3_IOS_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = \"compiled.mach-o.dylib\"; name = libsqlite3.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk/usr/lib/libsqlite3.dylib; sourceTree = DEVELOPER_DIR; };" << std::endl; os() << " WebKit_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; };" << std::endl; os() << " Cocoa_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; };" << std::endl; os() << " AppKit_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; };" << std::endl; os() << " CoreData_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = System/Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; };" << std::endl; os() << " Foundation1_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };" << std::endl; os() << " UIKit_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; };" << std::endl; os() << " Foundation2_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; };" << std::endl; os() << " CoreGraphics_Framework_FileRef = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = Library/Frameworks/CoreGraphics.framework; sourceTree = DEVELOPER_DIR; };" << std::endl; os() << " " << _project.name() << "_Univ_Info_FileRef = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = \"" << _project.name() << "-IOS-Info.plist\"; path = \"" << _project.name() << "-IOS-Info.plist\"; sourceTree = \"<group>\"; };" << std::endl; os() << " " << _project.name() << "_Univ_Prefix_FileRef = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = \"" << _project.name() << "-IOS-Prefix.pch\"; path = \"" << _project.name() << "-IOS-Prefix.pch\"; sourceTree = \"<group>\"; };" << std::endl; os() << " " << _project.name() << "_app_FileRef = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = " << _project.name() << ".app; sourceTree = BUILT_PRODUCTS_DIR; };" << std::endl; os() << " " << _project.name() << "_Info_FileRef = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = \"" << _project.name() << "-OSX-Info.plist\"; path = \"" << _project.name() << "-OSX-Info.plist\"; sourceTree = \"<group>\"; };" << std::endl; os() << " " << _project.name() << "_PCH_FileRef = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = \"" << _project.name() << "-OSX-Prefix.pch\"; path = \"" << _project.name() << "-OSX-Prefix.pch\"; sourceTree = \"<group>\"; };" << std::endl; os() << " " << _project.name() << "_Univ_app_FileRef = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = \"" << _project.name() << "-univ.app\"; sourceTree = BUILT_PRODUCTS_DIR; };" << std::endl; os() << " zenlang_cpp_FileRef = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = zenlang.cpp; path = \"" << _project.zlibPath() << "/zenlang.cpp\"; sourceTree = \"<absolute>\"; };" << std::endl; for(FileList::const_iterator it = _hppFileList.begin(), ite = _hppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_hpp_FileRef = {isa = PBXFileReference; lastKnownFileType = sourcecode.hpp.objhpp; name = " << z::dir::getFilename(filename) << "; path = " << filename << "; sourceTree = \"<group>\"; };" << std::endl; } for(FileList::const_iterator it = _cppFileList.begin(), ite = _cppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_cpp_FileRef = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = " << z::dir::getFilename(filename) << "; path = " << filename << "; sourceTree = \"<group>\"; };" << std::endl; } for(FileList::const_iterator it = _zppFileList.begin(), ite = _zppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_zpp_FileRef = {isa = PBXFileReference; lastKnownFileType = sourcecode.zpp; name = " << z::dir::getFilename(filename) << "; path = " << filename << "; sourceTree = \"<group>\"; };" << std::endl; } for(FileList::const_iterator it = _otherFileList.begin(), ite = _otherFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); z::string ext = z::dir::getExtention(filename); if(ext == "re") { os() << " " << basename << "_re_FileRef = {isa = PBXFileReference; lastKnownFileType = sourcecode.re; name = " << z::dir::getFilename(filename) << "; path = " << filename << "; sourceTree = \"<group>\"; };" << std::endl; } else if(ext == "y") { os() << " " << basename << "_y_FileRef = {isa = PBXFileReference; lastKnownFileType = sourcecode.y; name = " << z::dir::getFilename(filename) << "; path = " << filename << "; sourceTree = \"<group>\"; };" << std::endl; } else { throw z::Exception("XcodeGenerator", zfmt(z::Ast::Token(filename, 0, 0, ""), "1-Unknown file type for: %{s}").arg("s", filename)); } } for(FileList::const_iterator it = _guiFileList.begin(), ite = _guiFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_htm_FileRef = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; name = " << z::dir::getFilename(filename) << "; path = " << filename << "; sourceTree = \"<group>\"; };" << std::endl; } os() << "/* End PBXFileReference section */" << std::endl; os() << "" << std::endl; os() << "/* Begin PBXFrameworksBuildPhase section */" << std::endl; os() << " OSX_Frameworks_BuildPhase = {" << std::endl; os() << " isa = PBXFrameworksBuildPhase;" << std::endl; os() << " buildActionMask = 2147483647;" << std::endl; os() << " files = (" << std::endl; os() << " Sqlite3_OSX_Framework_BuildFile," << std::endl; os() << " WebKit_Framework_BuildFile," << std::endl; os() << " Cocoa_Framework_BuildFile," << std::endl; os() << " );" << std::endl; os() << " runOnlyForDeploymentPostprocessing = 0;" << std::endl; os() << " };" << std::endl; os() << " IOS_Frameworks_BuildPhase = {" << std::endl; os() << " isa = PBXFrameworksBuildPhase;" << std::endl; os() << " buildActionMask = 2147483647;" << std::endl; os() << " files = (" << std::endl; os() << " Sqlite3_IOS_Framework_BuildFile," << std::endl; os() << " UIKit_Framework_BuildFile," << std::endl; os() << " Foundation_Framework_BuildFile," << std::endl; os() << " CoreGraphics_Framework_BuildFile," << std::endl; os() << " );" << std::endl; os() << " runOnlyForDeploymentPostprocessing = 0;" << std::endl; os() << " };" << std::endl; os() << "/* End PBXFrameworksBuildPhase section */" << std::endl; os() << "" << std::endl; os() << "/* Begin PBXGroup section */" << std::endl; os() << " Top_Group = {" << std::endl; os() << " isa = PBXGroup;" << std::endl; os() << " children = (" << std::endl; os() << " " << _project.name() << "_Univ_Prefix_FileRef," << std::endl; os() << " " << _project.name() << "_Univ_Info_FileRef," << std::endl; os() << " " << _project.name() << "_Info_FileRef," << std::endl; os() << " zenlang_cpp_FileRef," << std::endl; for(FileList::const_iterator it = _hppFileList.begin(), ite = _hppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_hpp_FileRef," << std::endl; } for(FileList::const_iterator it = _cppFileList.begin(), ite = _cppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_cpp_FileRef," << std::endl; } for(FileList::const_iterator it = _zppFileList.begin(), ite = _zppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_zpp_FileRef," << std::endl; } for(FileList::const_iterator it = _otherFileList.begin(), ite = _otherFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); z::string ext = z::dir::getExtention(filename); if(ext == "re") { os() << " " << basename << "_re_FileRef," << std::endl; } else if(ext == "y") { os() << " " << basename << "_y_FileRef," << std::endl; } else { throw z::Exception("XcodeGenerator", zfmt(z::Ast::Token(filename, 0, 0, ""), "1-Unknown file type for: %{s}").arg("s", filename)); } } for(FileList::const_iterator it = _guiFileList.begin(), ite = _guiFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_htm_FileRef," << std::endl; } os() << " " << _project.name() << "_PCH_FileRef," << std::endl; os() << " Frameworks_Group," << std::endl; os() << " Products_Group," << std::endl; os() << " );" << std::endl; os() << " sourceTree = \"<group>\";" << std::endl; os() << " };" << std::endl; os() << " Products_Group = {" << std::endl; os() << " isa = PBXGroup;" << std::endl; os() << " children = (" << std::endl; os() << " " << _project.name() << "_app_FileRef," << std::endl; os() << " " << _project.name() << "_Univ_app_FileRef," << std::endl; os() << " );" << std::endl; os() << " name = Products;" << std::endl; os() << " sourceTree = \"<group>\";" << std::endl; os() << " };" << std::endl; os() << " Frameworks_Group = {" << std::endl; os() << " isa = PBXGroup;" << std::endl; os() << " children = (" << std::endl; os() << " Sqlite3_OSX_Framework_FileRef," << std::endl; os() << " Sqlite3_IOS_Framework_FileRef," << std::endl; os() << " WebKit_Framework_FileRef," << std::endl; os() << " Cocoa_Framework_FileRef," << std::endl; os() << " UIKit_Framework_FileRef," << std::endl; os() << " Foundation2_Framework_FileRef," << std::endl; os() << " CoreGraphics_Framework_FileRef," << std::endl; os() << " AppKit_Framework_FileRef," << std::endl; os() << " CoreData_Framework_FileRef," << std::endl; os() << " Foundation1_Framework_FileRef," << std::endl; os() << " );" << std::endl; os() << " name = Frameworks;" << std::endl; os() << " sourceTree = \"<group>\";" << std::endl; os() << " };" << std::endl; os() << "/* End PBXGroup section */" << std::endl; os() << "" << std::endl; os() << "/* Begin PBXNativeTarget section */" << std::endl; os() << " " << _project.name() << "_OSX_Target = {" << std::endl; os() << " isa = PBXNativeTarget;" << std::endl; os() << " buildConfigurationList = OSX_Target_ConfigList;" << std::endl; os() << " buildPhases = (" << std::endl; os() << " " << _project.name() << "_OSX_Sources," << std::endl; os() << " OSX_Frameworks_BuildPhase," << std::endl; os() << " " << _project.name() << "_OSX_Resources," << std::endl; os() << " );" << std::endl; os() << " buildRules = (" << std::endl; os() << " re2c_BuildRule," << std::endl; os() << " lemon_BuildRule," << std::endl; os() << " zenlang_BuildRule," << std::endl; os() << " );" << std::endl; os() << " dependencies = (" << std::endl; os() << " );" << std::endl; os() << " name = " << _project.name() << ";" << std::endl; os() << " productName = " << _project.name() << ";" << std::endl; os() << " productReference = " << _project.name() << "_app_FileRef;" << std::endl; os() << " productType = \"com.apple.product-type.application\";" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_IOS_Target = {" << std::endl; os() << " isa = PBXNativeTarget;" << std::endl; os() << " buildConfigurationList = IOS_Target_ConfigList;" << std::endl; os() << " buildPhases = (" << std::endl; os() << " " << _project.name() << "_IOS_Sources," << std::endl; os() << " IOS_Frameworks_BuildPhase," << std::endl; os() << " " << _project.name() << "_IOS_Resources," << std::endl; os() << " );" << std::endl; os() << " buildRules = (" << std::endl; os() << " re2c_BuildRule," << std::endl; os() << " lemon_BuildRule," << std::endl; os() << " zenlang_BuildRule," << std::endl; os() << " );" << std::endl; os() << " dependencies = (" << std::endl; os() << " );" << std::endl; os() << " name = \"" << _project.name() << "-univ\";" << std::endl; os() << " productName = \"" << _project.name() << "-univ\";" << std::endl; os() << " productReference = " << _project.name() << "_Univ_app_FileRef;" << std::endl; os() << " productType = \"com.apple.product-type.application\";" << std::endl; os() << " };" << std::endl; os() << "/* End PBXNativeTarget section */" << std::endl; os() << "" << std::endl; os() << "/* Begin PBXProject section */" << std::endl; os() << " " << _project.name() << "_Project = {" << std::endl; os() << " isa = PBXProject;" << std::endl; os() << " attributes = {" << std::endl; os() << " LastUpgradeCheck = 0450;" << std::endl; os() << " ORGANIZATIONNAME = \"Renji Panicker\";" << std::endl; os() << " };" << std::endl; os() << " buildConfigurationList = Project_ConfigList;" << std::endl; os() << " compatibilityVersion = \"Xcode 3.2\";" << std::endl; os() << " developmentRegion = English;" << std::endl; os() << " hasScannedForEncodings = 0;" << std::endl; os() << " knownRegions = (" << std::endl; os() << " en," << std::endl; os() << " );" << std::endl; os() << " mainGroup = Top_Group;" << std::endl; os() << " productRefGroup = Products_Group;" << std::endl; os() << " projectDirPath = \"\";" << std::endl; os() << " projectRoot = \"\";" << std::endl; os() << " targets = (" << std::endl; os() << " " << _project.name() << "_OSX_Target," << std::endl; os() << " " << _project.name() << "_IOS_Target," << std::endl; os() << " );" << std::endl; os() << " };" << std::endl; os() << "/* End PBXProject section */" << std::endl; os() << "" << std::endl; os() << "/* Begin PBXResourcesBuildPhase section */" << std::endl; os() << " " << _project.name() << "_OSX_Resources = {" << std::endl; os() << " isa = PBXResourcesBuildPhase;" << std::endl; os() << " buildActionMask = 2147483647;" << std::endl; os() << " files = (" << std::endl; for(FileList::const_iterator it = _guiFileList.begin(), ite = _guiFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_htm_BuildFile," << std::endl; } os() << " );" << std::endl; os() << " runOnlyForDeploymentPostprocessing = 0;" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_IOS_Resources = {" << std::endl; os() << " isa = PBXResourcesBuildPhase;" << std::endl; os() << " buildActionMask = 2147483647;" << std::endl; os() << " files = (" << std::endl; for(FileList::const_iterator it = _guiFileList.begin(), ite = _guiFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_htm_BuildFile," << std::endl; } os() << " );" << std::endl; os() << " runOnlyForDeploymentPostprocessing = 0;" << std::endl; os() << " };" << std::endl; os() << "/* End PBXResourcesBuildPhase section */" << std::endl; os() << "" << std::endl; os() << "/* Begin PBXSourcesBuildPhase section */" << std::endl; os() << " " << _project.name() << "_OSX_Sources = {" << std::endl; os() << " isa = PBXSourcesBuildPhase;" << std::endl; os() << " buildActionMask = 2147483647;" << std::endl; os() << " files = (" << std::endl; os() << " zenlang_cpp_BuildFile," << std::endl; for(FileList::const_iterator it = _otherFileList.begin(), ite = _otherFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); z::string ext = z::dir::getExtention(filename); if(ext == "re") { os() << " " << basename << "_re_BuildFile," << std::endl; } else if(ext == "y") { os() << " " << basename << "_y_BuildFile," << std::endl; } else { throw z::Exception("XcodeGenerator", zfmt(z::Ast::Token(filename, 0, 0, ""), "1-Unknown file type for: %{s}").arg("s", filename)); } } for(FileList::const_iterator it = _zppFileList.begin(), ite = _zppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_zpp_BuildFile," << std::endl; } for(FileList::const_iterator it = _hppFileList.begin(), ite = _hppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_hpp_BuildFile," << std::endl; } for(FileList::const_iterator it = _cppFileList.begin(), ite = _cppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_cpp_BuildFile," << std::endl; } os() << " );" << std::endl; os() << " runOnlyForDeploymentPostprocessing = 0;" << std::endl; os() << " };" << std::endl; os() << " " << _project.name() << "_IOS_Sources = {" << std::endl; os() << " isa = PBXSourcesBuildPhase;" << std::endl; os() << " buildActionMask = 2147483647;" << std::endl; os() << " files = (" << std::endl; os() << " zenlang_cpp_BuildFile," << std::endl; for(FileList::const_iterator it = _otherFileList.begin(), ite = _otherFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); z::string ext = z::dir::getExtention(filename); if(ext == "re") { os() << " " << basename << "_re_BuildFile," << std::endl; } else if(ext == "y") { os() << " " << basename << "_y_BuildFile," << std::endl; } else { throw z::Exception("XcodeGenerator", zfmt(z::Ast::Token(filename, 0, 0, ""), "1-Unknown file type for: %{s}").arg("s", filename)); } } for(FileList::const_iterator it = _zppFileList.begin(), ite = _zppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_zpp_BuildFile," << std::endl; } for(FileList::const_iterator it = _hppFileList.begin(), ite = _hppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_hpp_BuildFile," << std::endl; } for(FileList::const_iterator it = _cppFileList.begin(), ite = _cppFileList.end(); it != ite; ++it) { const z::string& filename = *it; z::string basename = z::dir::getBaseName(filename); os() << " " << basename << "_cpp_BuildFile," << std::endl; } os() << " );" << std::endl; os() << " runOnlyForDeploymentPostprocessing = 0;" << std::endl; os() << " };" << std::endl; os() << "/* End PBXSourcesBuildPhase section */" << std::endl; os() << "" << std::endl; for(z::Ast::Project::ConfigList::const_iterator it = _project.configList().begin(); it != _project.configList().end(); ++it) { const z::Ast::Config& config = z::ref(it->second); generateConfig(config, os); } os() << " };" << std::endl; os() << " rootObject = " << _project.name() << "_Project;" << std::endl; os() << "}" << std::endl; os() << "" << std::endl; generatePCHFile(); generatePListFile(); } void z::XcodeGenerator::Impl::run() { generateProject(); } z::XcodeGenerator::XcodeGenerator(const z::Ast::Project& project) : _impl(0) {_impl = new Impl(project);} z::XcodeGenerator::~XcodeGenerator() {delete _impl;} void z::XcodeGenerator::run() {return z::ref(_impl).run();}
#include <iostream> #include <string> #include <iomanip> #include <vector> #include <unordered_map> #include <cmath> #include "../../io/io.h" #include "game.h" #include "../../data/troop/troop.h" void Game::printTroop(int x, int y) { this->lg3.lock(); int freeCamp = this->resource->camp - this->resource->campUsed; std::vector<int> maxTrain = { freeCamp / Infantry::trainingCamp, freeCamp / Calvary::trainingCamp, freeCamp / SuicideBomber::trainingCamp, freeCamp / Artillery::trainingCamp, freeCamp / Logistic::trainingCamp, freeCamp / ArmoredCar::trainingCamp, freeCamp / Tank1::trainingCamp, freeCamp / Tank2::trainingCamp, freeCamp / TankOshimai::trainingCamp, std::min(freeCamp / Cas::trainingCamp, this->resource->airport - this->resource->airportUsed), std::min(freeCamp / Fighter::trainingCamp, this->resource->airport - this->resource->airportUsed), std::min(freeCamp / Bomber::trainingCamp, this->resource->airport - this->resource->airportUsed), std::min(freeCamp / Kamikaze::trainingCamp, this->resource->airport - this->resource->airportUsed)}; std::vector<int> maxRemove = { this->troop->infantry[0], this->troop->calvary[0], this->troop->suicideBomber[0], this->troop->artillery[0], this->troop->logistic[0], this->troop->armoredCar[0], this->troop->tank1[0], this->troop->tank2[0], this->troop->tankOshimai[0], this->troop->cas[0], this->troop->fighter[0], this->troop->bomber[0], this->troop->kamikaze[0]}; std::unordered_map<std::string, int> trainingC = {}; std::unordered_map<std::string, std::string> training = {}; for (int i = 0; i < this->troop->progressTrack.size(); i++) { std::string type = std::get<0>(this->troop->progressTrack[i]); std::string id = std::get<1>(this->troop->progressTrack[i]); if (trainingC.count(type) == 0) { trainingC[type] = 1; training[type] = " (" + std::to_string(this->troop->progress[id]->remain) + ", "; } else { trainingC[type]++; training[type] += std::to_string(this->troop->progress[id]->remain) + ", "; } } for (auto i : trainingC) { training[i.first] = std::to_string(i.second) + training[i.first].substr(0, training[i.first].size() - 2) + " days)"; } std::vector<std::vector<std::string>> actionPrefix = { {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" ", " ", " ", " ", " ", " "}, {" "}}; std::vector<std::vector<std::string>> action = { {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"1", "5", "10", "Max", "1", "All"}, {"Back"}}; for (int i = 0; i < action.size() - 1; i++) action[i][3] += " (" + std::to_string(maxTrain[i]) + ") "; for (int i = 0; i < action.size() - 1; i++) action[i][5] += " (" + std::to_string(maxRemove[i]) + ") "; for (int i = 0; i < action.size() - 1; i++) { if (maxTrain[i] < 10) action[i][2] = color(action[i][2], "red"); else action[i][2] = underline(action[i][2], "green"); if (maxTrain[i] < 5) action[i][1] = color(action[i][1], "red"); else action[i][1] = underline(action[i][1], "green"); if (maxTrain[i] < 1) { action[i][0] = color(action[i][0], "red"); action[i][3] = color(action[i][3], "red"); } else { action[i][0] = underline(action[i][0], "green"); action[i][3] = underline(action[i][3], "green"); } if (maxRemove[i] > 0) { action[i][4] = underline(action[i][4], "green"); action[i][5] = underline(action[i][5], "green"); } else { action[i][4] = color(action[i][4], "red"); action[i][5] = color(action[i][5], "red"); } } action[action.size() - 1][0] = underline(action[action.size() - 1][0], "green"); actionPrefix[x][y].erase(1, 1); actionPrefix[x][y].insert(1, color(">", "cyan")); std::cout << "\033[2J\033[1;1H"; std::cout << std::left << color("Troop Training: ", "magenta") << std::endl << std::endl; std::cout << color("Resources:", "green") << "\n" << "Food: " << this->troop->totalFoodRequired << "/" << this->resource->food << " Equipment: " << this->troop->totalEquipmentRequired << "/" << this->resource->equipment << " Manpower: " << (this->resource->manpower - this->resource->manpowerInUse) << "/" << this->resource->manpower << " Land: " << (this->resource->baseLand * this->resource->baseLandMul + this->resource->capturedLand - this->resource->usedLand) << "/" << this->resource->baseLand * this->resource->baseLandMul + this->resource->capturedLand << " Troop: " << this->troop->totalTroops << " Armies: " << this->army->total.size() << "/10" << " Camps: " << (this->resource->camp-this->resource->campUsed) << "/"<<this->resource->camp << " Airports: " << (this->resource->airport - this->resource->airportUsed) << "/"<<this->resource->airport << " Enemies: " << (this->enemies->totalEnemies.size() -this->enemies->defeated) << "/"<<this->enemies->totalEnemies.size() << std::endl << std::endl; std::cout << std::setw(50 + 11) << color("Train: ", "green") << std::setw(43 + 11) << color("Remove: ", "green") << color("Training: ", "green") << std::endl; std::cout << std::setw((x == 0 && y < 4 ? 105 : 94)) << "Infantry:" + std::string(15 - 8, ' ') + actionPrefix[0][0] + action[0][0] + actionPrefix[0][1] + action[0][1] + actionPrefix[0][2] + action[0][2] + actionPrefix[0][3] + action[0][3] << std::setw((x == 0 && y > 3 ? 76: 65)) << "Infantry:" + std::string(15 - 8, ' ') + actionPrefix[0][4] + action[0][4] + actionPrefix[0][5] + action[0][5] << "Infantry:" + std::string(18 - 8, ' ') + (training.count("infantry") == 0 ? "0" : training["infantry"]) << std::endl; std::cout << std::setw((x == 1 && y < 4 ? 105 : 94)) << "Calvary:" + std::string(15 - 7, ' ') + actionPrefix[1][0] + action[1][0] + actionPrefix[1][1] + action[1][1] + actionPrefix[1][2] + action[1][2] + actionPrefix[1][3] + action[1][3] << std::setw((x == 1 && y > 3 ? 76: 65)) << "Calvary:" + std::string(15 - 7, ' ') + actionPrefix[1][4] + action[1][4] + actionPrefix[1][5] + action[1][5] << "Calvary:" + std::string(18 - 7, ' ') + (training.count("calvary") == 0 ? "0" : training["calvary"]) << std::endl; std::cout << std::setw((x == 2 && y < 4 ? 105 : 94)) << "Suicide Bomber:" + std::string(15 - 14, ' ') + actionPrefix[2][0] + action[2][0] + actionPrefix[2][1] + action[2][1] + actionPrefix[2][2] + action[2][2] + actionPrefix[2][3] + action[2][3] << std::setw((x == 2 && y > 3 ? 76: 65)) << "Suicide Bomber:" + std::string(15 - 14, ' ') + actionPrefix[2][4] + action[2][4] + actionPrefix[2][5] + action[2][5] << "Suicide Bomber:" + std::string(18 - 14, ' ') + (training.count("suicideBomber") == 0 ? "0" : training["suicideBomber"]) << std::endl; std::cout << std::setw((x == 3 && y < 4 ? 105 : 94)) << "Artillery:" + std::string(15 - 9, ' ') + actionPrefix[3][0] + action[3][0] + actionPrefix[3][1] + action[3][1] + actionPrefix[3][2] + action[3][2] + actionPrefix[3][3] + action[3][3] << std::setw((x == 3 && y > 3 ? 76: 65)) << "Artillery:" + std::string(15 - 9, ' ') + actionPrefix[3][4] + action[3][4] + actionPrefix[3][5] + action[3][5] << "Artillery:" + std::string(18 - 9, ' ') + (training.count("artillery") == 0 ? "0" : training["artillery"]) << std::endl; std::cout << std::setw((x == 4 && y < 4 ? 105 : 94)) << "Logistic:" + std::string(15 - 8, ' ') + actionPrefix[4][0] + action[4][0] + actionPrefix[4][1] + action[4][1] + actionPrefix[4][2] + action[4][2] + actionPrefix[4][3] + action[4][3] << std::setw((x == 4 && y > 3 ? 76: 65)) << "Logistic:" + std::string(15 - 8, ' ') + actionPrefix[4][4] + action[4][4] + actionPrefix[4][5] + action[4][5] << "Logistic:" + std::string(18 - 8, ' ') + (training.count("logistic") == 0 ? "0" : training["logistic"]) << std::endl; std::cout << std::setw((x == 5 && y < 4 ? 105 : 94)) << "Armored Car:" + std::string(15 - 11, ' ') + actionPrefix[5][0] + action[5][0] + actionPrefix[5][1] + action[5][1] + actionPrefix[5][2] + action[5][2] + actionPrefix[5][3] + action[5][3] << std::setw((x == 5 && y > 3 ? 76: 65)) << "Armored Car:" + std::string(15 - 11, ' ') + actionPrefix[5][4] + action[5][4] + actionPrefix[5][5] + action[5][5] << "Armored Car:" + std::string(18 - 11, ' ') + (training.count("armoredCar") == 0 ? "0" : training["armoredCar"]) << std::endl; std::cout << std::setw((x == 6 && y < 4 ? 105 : 94)) << "Tank 1:" + std::string(15 - 6, ' ') + actionPrefix[6][0] + action[6][0] + actionPrefix[6][1] + action[6][1] + actionPrefix[6][2] + action[6][2] + actionPrefix[6][3] + action[6][3] << std::setw((x == 6 && y > 3 ? 76: 65)) << "Tank 1:" + std::string(15 - 6, ' ') + actionPrefix[6][4] + action[6][4] + actionPrefix[6][5] + action[6][5] << "Tank 1:" + std::string(18 - 6, ' ') + (training.count("tank1") == 0 ? "0" : training["tank1"]) << std::endl; std::cout << std::setw((x == 7 && y < 4 ? 105 : 94)) << "Tank 2:" + std::string(15 - 6, ' ') + actionPrefix[7][0] + action[7][0] + actionPrefix[7][1] + action[7][1] + actionPrefix[7][2] + action[7][2] + actionPrefix[7][3] + action[7][3] << std::setw((x == 7 && y > 3 ? 76: 65)) << "Tank 2:" + std::string(15 - 6, ' ') + actionPrefix[7][4] + action[7][4] + actionPrefix[7][5] + action[7][5] << "Tank 2:" + std::string(18 - 6, ' ') + (training.count("tank2") == 0 ? "0" : training["tank2"]) << std::endl; std::cout << std::setw((x == 8 && y < 4 ? 105 : 94)) << "Tank Oshimai:" + std::string(15 - 12, ' ') + actionPrefix[8][0] + action[8][0] + actionPrefix[8][1] + action[8][1] + actionPrefix[8][2] + action[8][2] + actionPrefix[8][3] + action[8][3] << std::setw((x == 8 && y > 3 ? 76: 65)) << "Tank Oshimai:" + std::string(15 - 12, ' ') + actionPrefix[8][4] + action[8][4] + actionPrefix[8][5] + action[8][5] << "Tank Oshimai:" + std::string(18 - 12, ' ') + (training.count("tankOshimai") == 0 ? "0" : training["tankOshimai"]) << std::endl; std::cout << std::setw((x == 9 && y < 4 ? 105 : 94)) << "Cas:" + std::string(15 - 3, ' ') + actionPrefix[9][0] + action[9][0] + actionPrefix[9][1] + action[9][1] + actionPrefix[9][2] + action[9][2] + actionPrefix[9][3] + action[9][3] << std::setw((x == 9 && y > 3 ? 76: 65)) << "Cas:" + std::string(15 - 3, ' ') + actionPrefix[9][4] + action[9][4] + actionPrefix[9][5] + action[9][5] << "Cas:" + std::string(18 - 3, ' ') + (training.count("cas") == 0 ? "0" : training["cas"]) << std::endl; std::cout << std::setw((x == 10 && y < 4 ? 105 : 94)) << "Fighter:" + std::string(15 - 7, ' ') + actionPrefix[10][0] + action[10][0] + actionPrefix[10][1] + action[10][1] + actionPrefix[10][2] + action[10][2] + actionPrefix[10][3] + action[10][3] << std::setw((x == 10 && y > 3 ? 76: 65)) << "Fighter:" + std::string(15 - 7, ' ') + actionPrefix[10][4] + action[10][4] + actionPrefix[10][5] + action[10][5] << "Fighter:" + std::string(18 - 7, ' ') + (training.count("fighter") == 0 ? "0" : training["fighter"]) << std::endl; std::cout << std::setw((x == 11 && y < 4 ? 105 : 94)) << "Bomber:" + std::string(15 - 6, ' ') + actionPrefix[11][0] + action[11][0] + actionPrefix[11][1] + action[11][1] + actionPrefix[11][2] + action[11][2] + actionPrefix[11][3] + action[11][3] << std::setw((x == 11 && y > 3 ? 76: 65)) << "Bomber:" + std::string(15 - 6, ' ') + actionPrefix[11][4] + action[11][4] + actionPrefix[11][5] + action[11][5] << "Bomber:" + std::string(18 - 6, ' ') + (training.count("bomber") == 0 ? "0" : training["bomber"]) << std::endl; std::cout << std::setw((x == 12 && y < 4 ? 105 : 94)) << "Kamikaze:" + std::string(15 - 8, ' ') + actionPrefix[12][0] + action[12][0] + actionPrefix[12][1] + action[12][1] + actionPrefix[12][2] + action[12][2] + actionPrefix[12][3] + action[12][3] << std::setw((x == 12 && y > 3 ? 76: 65)) << "Kamikaze:" + std::string(15 - 8, ' ') + actionPrefix[12][4] + action[12][4] + actionPrefix[12][5] + action[12][5] << "Kamikaze:" + std::string(18 - 8, ' ') + (training.count("kamikaze") == 0 ? "0" : training["kamikaze"]) << std::endl << std::endl; std::cout << std::setw(55) << "(free, in army, in battle plan, in battle)" << actionPrefix[action.size() - 1][0] + action[action.size() - 1][0] + " (or spacebar)" << std::endl; std::cout << color("Overview:", "green") << std::endl << std::right << "Infantry:" + std::string(15 - 8, ' ') << std::setw(4) << this->troop->infantry[0] << "/" << std::setw(4) << this->troop->infantry[1] << "/" << std::setw(4) << this->troop->infantry[2] << "/" << std::setw(4) << this->troop->infantry[3] << " (" << std::setw(5) << (this->troop->infantry[0] + this->troop->infantry[1] + this->troop->infantry[2] + this->troop->infantry[3]) << " total)" << std::endl << "Calvary:" + std::string(15 - 7, ' ') << std::setw(4) << this->troop->calvary[0] << "/" << std::setw(4) << this->troop->calvary[1] << "/" << std::setw(4) << this->troop->calvary[2] << "/" << std::setw(4) << this->troop->calvary[3] << " (" << std::setw(5) << (this->troop->calvary[0] + this->troop->calvary[1] + this->troop->calvary[2] + this->troop->calvary[3]) << " total)" << std::endl << "Suicide Bomber:" + std::string(15 - 14, ' ') << std::setw(4) << this->troop->suicideBomber[0] << "/" << std::setw(4) << this->troop->suicideBomber[1] << "/" << std::setw(4) << this->troop->suicideBomber[2] << "/" << std::setw(4) << this->troop->suicideBomber[3] << " (" << std::setw(5) << (this->troop->suicideBomber[0] + this->troop->suicideBomber[1] + this->troop->suicideBomber[2] + this->troop->suicideBomber[3]) << " total)" << std::endl << "Artillery:" + std::string(15 - 9, ' ') << std::setw(4) << this->troop->artillery[0] << "/" << std::setw(4) << this->troop->artillery[1] << "/" << std::setw(4) << this->troop->artillery[2] << "/" << std::setw(4) << this->troop->artillery[3] << " (" << std::setw(5) << (this->troop->artillery[0] + this->troop->artillery[1] + this->troop->artillery[2] + this->troop->artillery[3]) << " total)" << std::endl << "Logistic:" + std::string(15 - 8, ' ') << std::setw(4) << this->troop->logistic[0] << "/" << std::setw(4) << this->troop->logistic[1] << "/" << std::setw(4) << this->troop->logistic[2] << "/" << std::setw(4) << this->troop->logistic[3] << " (" << std::setw(5) << (this->troop->logistic[0] + this->troop->logistic[1] + this->troop->logistic[2] + this->troop->logistic[3]) << " total)" << std::endl << "Armored Car:" + std::string(15 - 11, ' ') << std::setw(4) << this->troop->armoredCar[0] << "/" << std::setw(4) << this->troop->armoredCar[1] << "/" << std::setw(4) << this->troop->armoredCar[2] << "/" << std::setw(4) << this->troop->armoredCar[3] << " (" << std::setw(5) << (this->troop->armoredCar[0] + this->troop->armoredCar[1] + this->troop->armoredCar[2] + this->troop->armoredCar[3]) << " total)" << std::endl << "Tank 1:" + std::string(15 - 6, ' ') << std::setw(4) << this->troop->tank1[0] << "/" << std::setw(4) << this->troop->tank1[1] << "/" << std::setw(4) << this->troop->tank1[2] << "/" << std::setw(4) << this->troop->tank1[3] << " (" << std::setw(5) << (this->troop->tank1[0] + this->troop->tank1[1] + this->troop->tank1[2] + this->troop->tank1[3]) << " total)" << std::endl << "Tank 2:" + std::string(15 - 6, ' ') << std::setw(4) << this->troop->tank2[0] << "/" << std::setw(4) << this->troop->tank2[1] << "/" << std::setw(4) << this->troop->tank2[2] << "/" << std::setw(4) << this->troop->tank2[3] << " (" << std::setw(5) << (this->troop->tank2[0] + this->troop->tank2[1] + this->troop->tank2[2] + this->troop->tank2[3]) << " total)" << std::endl << "Tank Oshimai:" + std::string(15 - 12, ' ') << std::setw(4) << this->troop->tankOshimai[0] << "/" << std::setw(4) << this->troop->tankOshimai[1] << "/" << std::setw(4) << this->troop->tankOshimai[2] << "/" << std::setw(4) << this->troop->tankOshimai[3] << " (" << std::setw(5) << (this->troop->tankOshimai[0] + this->troop->tankOshimai[1] + this->troop->tankOshimai[2] + this->troop->tankOshimai[3]) << " total)" << std::endl << "Cas:" + std::string(15 - 3, ' ') << std::setw(4) << this->troop->cas[0] << "/" << std::setw(4) << this->troop->cas[1] << "/" << std::setw(4) << this->troop->cas[2] << "/" << std::setw(4) << this->troop->cas[3] << " (" << std::setw(5) << (this->troop->cas[0] + this->troop->cas[1] + this->troop->cas[2] + this->troop->cas[3]) << " total)" << std::endl << "Fighter:" + std::string(15 - 7, ' ') << std::setw(4) << this->troop->fighter[0] << "/" << std::setw(4) << this->troop->fighter[1] << "/" << std::setw(4) << this->troop->fighter[2] << "/" << std::setw(4) << this->troop->fighter[3] << " (" << std::setw(5) << (this->troop->fighter[0] + this->troop->fighter[1] + this->troop->fighter[2] + this->troop->fighter[3]) << " total)" << std::endl << "Bomber:" + std::string(15 - 6, ' ') << std::setw(4) << this->troop->bomber[0] << "/" << std::setw(4) << this->troop->bomber[1] << "/" << std::setw(4) << this->troop->bomber[2] << "/" << std::setw(4) << this->troop->bomber[3] << " (" << std::setw(5) << (this->troop->bomber[0] + this->troop->bomber[1] + this->troop->bomber[2] + this->troop->bomber[3]) << " total)" << std::endl << "Kamikaze:" + std::string(15 - 8, ' ') << std::setw(4) << this->troop->kamikaze[0] << "/" << std::setw(4) << this->troop->kamikaze[1] << "/" << std::setw(4) << this->troop->kamikaze[2] << "/" << std::setw(4) << this->troop->kamikaze[3] << " (" << std::setw(5) << (this->troop->kamikaze[0] + this->troop->kamikaze[1] + this->troop->kamikaze[2] + this->troop->kamikaze[3]) << " total)" << std::endl; this->lg3.unlock(); }
#include "Camera.h" #include "GameObject.h" #include "Transform.h" #include <functional> //constructor, assigns properties Camera::Camera(float inNP, float inFP, float inFOV, float inAR) : nearPlane(inNP), farPlane(inFP), fieldOfView(inFOV), aspectRatio(inAR) { } //recalculates the matrices void Camera::calculateMatrices() { projectionMatrix = glm::perspective(fieldOfView, aspectRatio, nearPlane, farPlane); viewMatrix = projectionMatrix * gameObject->transform->translationMatrix; } //initialisation void Camera::start() { gameObject->transform->inverted = true; function<void()> f = [this] { calculateMatrices(); }; gameObject->transform->OnTransformUpdate.push_back(f); calculateMatrices(); }
class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { int res = 0; findTargetSumWays(nums, S, 0, res); return res; } void findTargetSumWays(vector<int> & nums, unsigned int S, int start, int & res) { // use unsigned int, in case of "S=INT_MAX" if (start >= nums.size()) { if (S == 0) ++ res; // target found return; } findTargetSumWays(nums, S - nums[start], start + 1, res); // assume '+' for num[start] findTargetSumWays(nums, S + nums[start], start + 1, res); // assume '-' for num[start] } };
#include<iostream> #include<climits> using namespace std; int main(){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++){ cin>>a[i]; } int b[n+1]; b[0]=0; int sum; int maxSum=INT_MIN; for(int i=1;i<=n;i++){ if((b[i-1]+a[i-1])<0 ) b[i]=0; else b[i]=b[i-1]+a[i-1]; maxSum=max(maxSum,b[i]); } cout<<maxSum; }
#pragma once #include "BRenderPass.h" class BRTRenderPass: public BRenderPass { public: BRTRenderPass(); ~BRTRenderPass(); virtual void BeginPass(BViewport* InViewport); void DrawPrimitive(); };
#include "CommonHeader.h" SplashScreen::SplashScreen() { m_gameTitle = nullptr; m_gameTitleInPosition = false; m_mainMenuLoaded = false; } SplashScreen::~SplashScreen() { } void SplashScreen::LoadGameObjects() { m_gameTitle = AddGameObject("GameTitle", new GameObject(this, "GameTitle", Vector3(-10, 0, 0), vec3(0, 0, 0), vec3(1, 1, 1), g_pGame->GetMesh("Box"), g_pGame->GetShader("Texture"), g_pGame->GetTexture("FGTitle"))); m_gameTitle->SetCameraDrawerName(HUD_DEFAULT_CAMERA_NAME); m_gameTitle->SetElementOfHUD(true); //Set tween for game title m_gameTitle->SetTweenXPosition(0, 3.0, TweeningType_ElasticEaseout); } void SplashScreen::LoadContent(b2Vec2 worldGravity) { // create cameras // Game camera m_pGameObjects[HUD_DEFAULT_CAMERA_NAME] = new CameraObject(this, HUD_DEFAULT_CAMERA_NAME, SPLASH_SCREEN_CAMERA_DEFAULT_OFFSET, Vector3(0, 0, 0), Vector3(1, 1, 1), 0, 0,0); CameraObject*pGameCamera = (CameraObject*)m_pGameObjects[HUD_DEFAULT_CAMERA_NAME]; pGameCamera->SetCameraOffset(SPLASH_SCREEN_CAMERA_DEFAULT_OFFSET); pGameCamera->SetUseLookAt(false); LoadResources(worldGravity);//Load the textures,shaders,etc. This is done after the camera has been created so that we can set the camera view matrix LoadGameObjects();//Load the game itself } void SplashScreen::LoadResources(b2Vec2 worldGravity) { Scene::LoadContent(worldGravity); // create our shaders. { g_pGame->AddShader("Texture", new ShaderProgram("Data/Shaders/Texture.vert", "Data/Shaders/Texture.frag")); g_pGame->AddShader("PostEffectBW", new ShaderProgram("Data/Shaders/PostEffectTextureBlackAndWhite.vert", "Data/Shaders/PostEffectTextureBlackAndWhite.frag")); g_pGame->AddShader("PostEffectSepia", new ShaderProgram("Data/Shaders/PostEffectTextureSepia.vert", "Data/Shaders/PostEffectTextureSepia.frag")); g_pGame->AddShader("PostEffectNegative", new ShaderProgram("Data/Shaders/PostEffectTextureNegative.vert", "Data/Shaders/PostEffectTextureNegative.frag")); //g_pGame->AddShader("PostEffectVignette", new ShaderProgram("Data/Shaders/PostEffectTextureVignette.vert", "Data/Shaders/PostEffectTextureVignette.frag")); } // Create meshes. { g_pGame->AddMesh("Box", Mesh::CreateBox(vec2(1, 1))); } // load our textures. { g_pGame->AddTexture("MegamanX", LoadTexture("Data/Textures/MegamanX.png")); g_pGame->AddTexture("White", LoadTexture("Data/Textures/White.png")); g_pGame->AddTexture("FGTitle", LoadTexture("Data/Textures/FGTitle.png")); } g_pGame->GetSceneManager()->SetMainFBO(1024, 1024); g_pGame->GetSceneManager()->SetSecondaryFBO(1024, 1024); AddPostProcessingShader(g_pGame->GetShader("PostEffectNegative")); m_usePostProcessEffects = true; } bool SplashScreen::HandleInput(InputEvent& aInputevent, double aDelta) { Scene::HandleInput(aInputevent, aDelta); if (aInputevent.state == InputEventState_Held || aInputevent.state == InputEventState_Down) { if (aInputevent.keycode == VK_SPACE) { GoToMainMenu(); return true; } } return false; } void SplashScreen::Update(double TimePassed) { Scene::Update(TimePassed); if (m_gameTitle != nullptr) { //Check if the position tween is over if (m_gameTitleInPosition == false) { if (m_gameTitle->GetFloatTweenerOver(GAMEOBJECT_X_POSITION_TWEEN_NAME) == true) { //Set the scale tween m_gameTitle->SetTweenScale(Vector3(8, 8, 8), 4, TweeningType_BounceEaseInOut); m_gameTitleInPosition = true; m_usePostProcessEffects = false; } } else { //If the scale tween is over if (m_gameTitle->GetVec3TweenerOver(GAMEOBJECT_SCALE_TWEEN_NAME)==true) { GoToMainMenu();//Go to main menu } } } } void SplashScreen::GoToMainMenu() { SceneManager* sceneManager = g_pGame->GetSceneManager(); //Check if the menu hasn't been already loaded, this to prevent issues with high framerate if (m_mainMenuLoaded == true) { return; } if (sceneManager != nullptr) { //Disable the update and draw in this scene m_drawable = false; m_updateable = false; m_mainMenuLoaded = true; //Push the main menu sceneManager->PushAndLoadScene(new MainMenu()); } }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. 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. */ #ifndef __audio_decode_ffmpeg_h #define __audio_decode_ffmpeg_h #include <map> #include <pthread.h> #include <stdio.h> #include <unistd.h> #include "multimedia/mm_cpp_utils.h" #include "multimedia/mm_debug.h" #include "multimedia/mm_audio.h" #include "multimedia/component.h" #include "multimedia/mmmsgthread.h" #include "multimedia/media_attr_str.h" #include "multimedia/av_buffer_helper.h" #include "multimedia/media_monitor.h" #include "multimedia/codec.h" #ifdef __cplusplus extern "C" { #endif #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #ifdef __MM_NATIVE_BUILD__ #include <libavutil/time.h> #else #include <libavutil/avtime.h> #endif #include <libavutil/opt.h> #include <libavutil/common.h> #include <libswresample/swresample.h> #ifdef __cplusplus } #endif namespace YUNOS_MM { //#define DUMP_DECODE_FFMPEG_DATA class DataDump; class AudioDecodeFFmpeg; typedef MMSharedPtr <AudioDecodeFFmpeg> AudioDecodeFFmpegSP; class AudioDecodeFFmpeg : public FilterComponent, public MMMsgThread { public: class DecodeThread; typedef MMSharedPtr <DecodeThread> DecodeThreadSP; class DecodeThread : public MMThread { public: DecodeThread(AudioDecodeFFmpeg *decoder); ~DecodeThread(); void signalExit(); void signalContinue(); protected: virtual void main(); private: AudioDecodeFFmpeg *mDecoder; bool mContinue; }; AudioDecodeFFmpeg(const char *mimeType = NULL, bool isEncoder = false); virtual ~AudioDecodeFFmpeg(); virtual const char * name() const; COMPONENT_VERSION; virtual mm_status_t addSource(Component * component, MediaType mediaType); virtual mm_status_t addSink(Component * component, MediaType mediaType); virtual mm_status_t release(); virtual mm_status_t init(); virtual void uninit(); virtual mm_status_t prepare(); virtual mm_status_t start(); virtual mm_status_t resume(); virtual mm_status_t stop(); virtual mm_status_t pause(); virtual mm_status_t seek(int msec, int seekSequence) { return MM_ERROR_UNSUPPORTED; } virtual mm_status_t reset(); virtual mm_status_t flush(); virtual mm_status_t setParameter(const MediaMetaSP & meta) { return MM_ERROR_UNSUPPORTED; } virtual mm_status_t getParameter(MediaMetaSP & meta) const { return MM_ERROR_UNSUPPORTED; } virtual ReaderSP getReader(MediaType mediaType) { return ReaderSP((Reader*)NULL); } virtual WriterSP getWriter(MediaType mediaType) { return WriterSP((Writer*)NULL); } virtual mm_status_t drain() { return MM_ERROR_UNSUPPORTED; } // must return immediataly virtual mm_status_t read(MediaBufferSP & buf) { return MM_ERROR_UNSUPPORTED; } // must return immediataly virtual mm_status_t write(MediaBufferSP & buf) { return MM_ERROR_UNSUPPORTED; } virtual MediaMetaSP getMetaData() {return MediaMetaSP((MediaMeta*)NULL);} virtual mm_status_t setMetaData(const MediaMetaSP & metaData) { return MM_ERROR_UNSUPPORTED; } private: AVCodecID CodecId2AVCodecId(CowCodecID id); enum State { UNINITIALIZED, INITIALIZED, PREPARED, STARTED, STOPED }; State mState; //Component * mSource; //Component * mSink; //int mSourceComponentCount; pthread_mutex_t mMutex; int32_t mSampleRate; int32_t mChannelCount; adev_channel_mask_t * mChannelsMap; int32_t mFormat; int32_t mSampleRateOut; int32_t mChannelCountOut; int32_t mFormatOut; std::string mComponentName; MediaMetaSP mInputMetaData; MediaMetaSP mOutputMetaData; ReaderSP mReader; WriterSP mWriter; bool mIsPaused; bool mNeedFlush; AVCodecContext *mAVCodecContext; bool mAVCodecContextByUs; Lock *mAVCodecContextLock; AVCodec *mAVCodec; AVPacket *mAVPacket; AVFrame *mAVFrame; int32_t mCodecID; struct SwrContext *mAVResample; bool mHasResample; MonitorSP mMonitorWrite; Condition mCondition; Lock mLock; DecodeThreadSP mDecodeThread; #ifdef DUMP_DECODE_FFMPEG_DATA DataDump *mOutputDataDump; #endif int64_t mTargetTimeUs; DECLARE_MSG_LOOP() DECLARE_MSG_HANDLER(onPrepare) DECLARE_MSG_HANDLER(onStart) DECLARE_MSG_HANDLER(onResume) DECLARE_MSG_HANDLER(onPause) DECLARE_MSG_HANDLER(onStop) DECLARE_MSG_HANDLER(onFlush) DECLARE_MSG_HANDLER(onReset) MM_DISALLOW_COPY(AudioDecodeFFmpeg); }; } #endif //__audio_decode_ffmpeg_h
//============================================================================ // Name : C_structureEx.cpp // Author : Cristian Mosquera // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <stdlib.h> #include <time.h> #include <stdio.h> using namespace std; #define CARDS 52 #define FACES 13 // card structure definition struct card { const char *face; // define pointer face const char *suit; // define pointer suit }; // end struct card typedef struct card Card; // new type name for struct card // prototypes void fillDeck( Card * const wDeck, const char * wFace[], const char * wSuit[] ); void shuffle( Card * const wDeck ); void deal( const Card * const wDeck ); int main() { Card deck[ CARDS ]; // define array of Cards // initialize array of pointers const char *face[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; // initialize array of pointers const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"}; srand( time ( NULL ) ); // randomize fillDeck( deck, face, suit ); // load the deck with Cards shuffle( deck ); // put Cards in random order deal( deck ); // deal all 52 Cards return 0; } void fillDeck(Card * const wDeck , const char * wFace[], const char * wSuit[] ) { size_t i; // counter // loop through wDeck for ( i = 0; i < CARDS; ++i ) { wDeck[ i ].face = wFace[ i % FACES ]; wDeck[ i ].suit = wSuit[ i / FACES ]; } // end for } // end function fillDeck // shuffle cards void shuffle( Card * const wDeck ) { size_t i; // counter size_t j; // variable to hold random value between 0 - 51 Card temp; // define temporary structure for swapping Cards // loop through wDeck randomly swapping Cards for ( i = 0; i < CARDS; ++i ) { j = rand() % CARDS; temp = wDeck[ i ]; wDeck[ i ] = wDeck[ j ]; wDeck[ j ] = temp; } // end for } // end function shuffle // deal cards void deal(const Card * const wDeck) { size_t i; // counter // loop through wDeck for ( i = 0; i < CARDS; ++i ) { printf( "%5s of %-8s%s", wDeck[ i ].face, wDeck[ i ].suit, ( i + 1 ) % 4 ? " " : "\n" ); } }
// $Id: AAP_lp.hpp,v 1.2 2003/12/03 01:52:30 magh Exp $ /* ------------------------------------------------------------------------ Author: Matthew Galati (magh@lehigh.edu) (c) Copyright 2003 Lehigh University. All Rights Reserved. This software is licensed under the Common Public License. Please see accompanying file for terms. ---------------------------------------------------------------------------*/ #ifndef AT_LP_H #define AT_LP_H #include "BCP_lp_user.hpp" #include "BCP_parameters.hpp" #include "AT_lp_param.hpp" #include "AT_var.hpp" #include "AT_GRASP.h" #include <vector> #include <functional> using namespace std; const double tolerance = 0.0001; const double bigM = 100000; using namespace std; using std::make_pair; /*--------------------------------------------------------------------------*/ class is_less_than{ public: bool operator()( const pair< pair<int,int>,double> & x, const pair< pair<int,int>,double> & y) { if(x.second > y.second + tolerance){ return false; }else{ return true; } } }; /*--------------------------------------------------------------------------*/ //Class for the user-defined LP interface to BCP class AT_lp : public BCP_lp_user{ public: BCP_parameter_set<AT_lp_par> lp_par; //parameter list for LP AT * at; vector<AT_var*> generated_vars; //variables generated in compute LB //stores the mapping from strong branch candidate to original master variable vector<pair<int,pair<int,int> > > cand_to_variable; ofstream fdebug_vars; vector<double *> subprob_col_lb; vector<double *> subprob_col_ub; vector<double *> subprob_row_lb; vector<double *> subprob_row_ub; vector<CoinPackedMatrix *> subprob_M; public: AT_lp() : lp_par(), at(0) { fdebug_vars.open("debug_vars.txt"); subprob_col_lb.clear(); subprob_col_ub.clear(); subprob_row_lb.clear(); subprob_row_ub.clear(); subprob_M.clear(); } ~AT_lp() { delete at; fdebug_vars.close(); for(int i=0;i<=(int)subprob_col_lb.size()-1;i++){ if(subprob_col_lb[i]){ delete [] subprob_col_lb[i]; } } for(int i=0;i<=(int)subprob_col_ub.size()-1;i++){ if(subprob_col_ub[i]){ delete [] subprob_col_ub[i]; } } for(int i=0;i<=(int)subprob_row_lb.size()-1;i++){ if(subprob_row_lb[i]){ delete [] subprob_row_lb[i]; } } for(int i=0;i<=(int)subprob_row_ub.size()-1;i++){ if(subprob_row_ub[i]){ delete [] subprob_row_ub[i]; } } for(int i=0;i<=(int)subprob_M.size()-1;i++){ if(subprob_M[i]){ delete [] subprob_M[i]; } } subprob_col_lb.clear(); subprob_col_ub.clear(); subprob_row_lb.clear(); subprob_row_ub.clear(); subprob_M.clear(); }; public: virtual void unpack_module_data(BCP_buffer& buf); virtual void pack_var_algo(const BCP_var_algo* var, BCP_buffer& buf); virtual BCP_var_algo* unpack_var_algo(BCP_buffer& buf); virtual void pack_user_data(const BCP_user_data* ud, BCP_buffer& buf); virtual BCP_user_data* unpack_user_data(BCP_buffer& buf); public: virtual OsiSolverInterface* initialize_solver_interface(); virtual void vars_to_cols(const BCP_vec<BCP_cut*>& cuts, BCP_vec<BCP_var*>& vars, BCP_vec<BCP_col*>& cols, const BCP_lp_result& lpres, BCP_object_origin origin, bool allow_multiple); virtual void display_lp_solution(const BCP_lp_result& lpres, const BCP_vec<BCP_var*>& vars, const BCP_vec<BCP_cut*>& cuts, const bool final_lp_solution); virtual double compute_lower_bound(const double old_lower_bound, const BCP_lp_result& lpres, const BCP_vec<BCP_var*>& vars, const BCP_vec<BCP_cut*>& cuts); virtual void generate_vars_in_lp(const BCP_lp_result& lpres, const BCP_vec<BCP_var*>& vars, const BCP_vec<BCP_cut*>& cuts, const bool before_fathom, BCP_vec<BCP_var*>& new_vars, BCP_vec<BCP_col*>& new_cols); virtual void restore_feasibility(const BCP_lp_result& lpres, const std::vector<double*> dual_rays, const BCP_vec<BCP_var*>& vars, const BCP_vec<BCP_cut*>& cuts, BCP_vec<BCP_var*>& vars_to_add, BCP_vec<BCP_col*>& cols_to_add); public: virtual BCP_branching_decision select_branching_candidates(const BCP_lp_result& lpres, const BCP_vec<BCP_var*>& vars, const BCP_vec<BCP_cut*>& cuts, const BCP_lp_var_pool& local_var_pool, const BCP_lp_cut_pool& local_cut_pool, BCP_vec<BCP_lp_branching_object*>& cans); virtual void set_user_data_for_children(BCP_presolved_lp_brobj* best, const int selected); public: int solve_subproblem(int machine_id,double * costv,double * solution,double & objective_value); void construct_cost(const double * pi, const bool from_restore,int machine_id,double * costv); bool generate_vars(const BCP_vec<BCP_var*>& vars,const double * pi, const bool from_restore); void branch_close_to_half(const BCP_lp_result& lpres,const BCP_vec<BCP_var*>& vars,BCP_vec<BCP_lp_branching_object*>& cans); void append_branching_vars(const BCP_lp_result& lpres,const BCP_vec<BCP_var*>& vars ,const vector< pair<pair<int,int>,double> > & var_candidates ,BCP_vec<BCP_lp_branching_object*>& cans); void create_subprob_matrix(); int solve_subproblem_sim(int sim,double * costv,double * solution,double & objective_value); }; #endif
// AUTHOR: Sumit Prajapati #include <bits/stdc++.h> using namespace std; #define ull unsigned long long #define int long long #define pii pair<int, int> #define pll pair<ll, ll> #define pb push_back #define mk make_pair #define ff first #define ss second #define all(a) a.begin(),a.end() #define trav(x,v) for(auto &x:v) #define debug(x) cerr<<#x<<" = "<<x<<'\n' #define llrand() distribution(generator) #define rep(i,n) for(int i=0;i<n;i++) #define repe(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=a;i<=b;i++) #define printar(a,s,e) FOR(i,s,e)cout<<a[i]<<" ";cout<<'\n' #define curtime chrono::high_resolution_clock::now() #define timedif(start,end) chrono::duration_cast<chrono::nanoseconds>(end - start).count() auto time0 = curtime; random_device rd; default_random_engine generator(rd()); uniform_int_distribution<ull> distribution(0,0xFFFFFFFFFFFFFFFF); const int MD=1e9+7; const int MDL=998244353; const int INF=1e9; const int MX=15e5+5; int n; int segm[4*MX]; int query(int cur,int start,int end,int qs,int qe){ if(start>=qs && end<=qe) return segm[cur]; if(start>qe || end<qs) return 0; //INVALID RETURN int mid=(start+end)>>1; int A=query(2*cur,start,mid,qs,qe); int B=query(2*cur+1,mid+1,end,qs,qe); //MERGING STEP int res=max(A,B); return res; } void update(int cur,int start,int end,int ind,int val){ if(start==ind && start==end){ //DO UPDATE segm[cur]=max(segm[cur],val); return; } if(start>ind|| end<ind) return; //OUT OF RANGE int mid=(start+end)>>1; update(cur<<1,start,mid,ind,val); update((cur<<1)^1,mid+1,end,ind,val); //MERGING STEP segm[cur]=max(segm[2*cur],segm[2*cur+1]); } vector<int>to_compress; void solve(){ cin>>n; int x,y,z; map<int,int>mp; vector<pair<int,pii>>v(n); int cnt=1; rep(i,n){ cin>>x; v[i].ff=x; to_compress.pb(x); } rep(i,n){ cin>>y; to_compress.pb(y); v[i].ss.ff=y; } rep(i,n){ cin>>z; v[i].ss.ss=z; to_compress.pb(z); } sort(all(to_compress)); for(auto &el:to_compress) if(mp[el]==0) mp[el]=cnt++; rep(i,n){ v[i].ff=mp[v[i].ff]; v[i].ss.ff=mp[v[i].ss.ff]; v[i].ss.ss=mp[v[i].ss.ss]; } sort(all(v)); assert(cnt<MX); int ans=0; int cur=INF; vector<pii>temp; for(int i=n-1;i>=0;i--){ x=v[i].ff; y=v[i].ss.ff; z=v[i].ss.ss; if(cur!=x){ for(auto&el:temp) update(1,1,cnt,el.ff,el.ss); temp.clear(); cur=x; } temp.pb({y,z}); // cout<<x<<" "<<y<<" "<<z<<' '; // int l=i+1,r= int max_here=query(1,1,cnt,y+1,cnt); if(max_here>z){ // cout<<i<<" **"; ans++; } // cout<<'\n'; } cout<<ans<<'\n'; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); time0 = curtime; int t=1; // cin>>t; repe(tt,t){ // cout<<"Case #"<<tt<<": "; solve(); } // cerr<<"Execution Time: "<<timedif(time0,curtime)*1e-9<<" sec\n"; return 0; }
#ifndef FUZZYCORE_RULE_CONTROLLER_H #define FUZZYCORE_RULE_CONTROLLER_H #include <utility> #include <vector> #include "../../models/rule/Rule.h" class RulePresentation { public: static void createRule(std::string contents, const std::string &space_name); static void deleteRule(unsigned long); static std::vector<Rule> getSpaceRules(const std::string &space_name); }; #endif
// github.com/andy489 #include<algorithm> #include<iostream> #include<vector> int main() { using namespace std; // NOTE: These are sorted vector<int> nums { 41, 45, 61, 231, 764 }; int searchNum = 62; auto it = lower_bound(nums.begin(), nums.end(), searchNum); if (it != nums.end()) { if (searchNum == *it) { cout << "found " << *it << " at " << it - nums.begin() << endl; } else { cout << searchNum << " can be inserted at " << it - nums.begin() << " and the numbers will remain sorted"<< endl; } } else { cout << "not in range" << endl; } cout << endl; vector<int> copiedNums; copy(nums.begin(), nums.end(), copiedNums.begin()); for (int num : copiedNums) { cout << num << " "; } return 0; }
#pragma once #include <GL\glew.h> #include "Buffer.h" class VertexArray { private: GLuint value; GLuint index = 0; public: VertexArray(); ~VertexArray(); VertexArray * bind(); template <typename T> VertexArray * layout( Buffer<T> * buffer, GLint count, GLboolean normalized, GLsizei stride, GLsizei offset) { buffer->bindAs(GL_ARRAY_BUFFER); glEnableVertexAttribArray(index); glVertexAttribPointer( index++, count, buffer->type, normalized, sizeof(T) * stride, (const GLvoid *) (sizeof(T) * offset)); return this; } };
#pragma once #include "app.h" #include "game_save_section.h" class rival_info : public game_save_section { public: rival_info(u8* memory_pointer); ~rival_info(); u8* get_name(); private: u8* _name; };
// Copyright ⓒ 2020 Valentyn Bondarenko. All rights reserved. #include <StdAfx.hpp> #include <FileSystem.hpp> #include <Error.hpp> #include <Log.hpp> namespace be { using path = be::fs::path; string FileSystem::CONFIG_EXTENSION = ".cfg"s; string FileSystem::FONT_EXTENSION = ".ttf"s; string FileSystem::LEVEL_EXTENSION = ".lvl"s; string FileSystem::MESH_EXTENSION = ".dae"s; string FileSystem::SCRIPT_EXTENSION = ".lua"s; string FileSystem::SHADER_EXTENSION = ".hlsl"s; string FileSystem::SOUND_EXTENSION = ".ogg"s; string FileSystem::TEXTURE_EXTENSION = ".dds"s; path FileSystem::bins_data_directory = fs::current_path() / "bins"; path FileSystem::game_data_directory = fs::current_path() / "game"; path FileSystem::user_data_directory = fs::current_path() / "user"; array<path, 3> FileSystem::engine_directories{ FileSystem::bins_data_directory, FileSystem::game_data_directory, FileSystem::user_data_directory }; path FileSystem::configs_directory = (game_data_directory / "configs"s); path FileSystem::fonts_directory = (game_data_directory / "fonts"s); path FileSystem::levels_directory = (game_data_directory / "levels"s); path FileSystem::meshes_directory = (game_data_directory / "meshes"s); path FileSystem::scripts_directory = (game_data_directory / "scripts"s); path FileSystem::shaders_directory = (game_data_directory / "shaders"s); path FileSystem::sounds_directory = (game_data_directory / "sounds"s); path FileSystem::textures_directory = (game_data_directory / "textures"s); array<path, 8> FileSystem::game_data_directories{ configs_directory, fonts_directory, levels_directory, meshes_directory, scripts_directory, shaders_directory, sounds_directory, textures_directory }; path FileSystem::logs_directory = (user_data_directory / "logs"s); path FileSystem::saves_directory = (user_data_directory / "saves"s); path FileSystem::screenshots_directory = (user_data_directory / "screenshots"s); path FileSystem::settings_directory = (user_data_directory / "settings"s); array<path, 4> FileSystem::user_data_directories{ logs_directory, saves_directory, screenshots_directory, settings_directory }; void FileSystem::initialize() { checkGameDirectories(); checkDefaultGameFiles(); utils::log::info("File System is initialized"s); } void FileSystem::finalize() { utils::log::info("File System is finalized"s); } void FileSystem::checkGameDirectories() { auto checkGameDirectory = [](const fs::path& directory) { if (!fs::exists(directory)) { auto desc = "Can't find directory " + directory.string(); core::FatalError fe("FileSystem.cpp", 80u, core::Error::Type::FILESYSTEM, desc.c_str()); fe.finalize(); } }; for (auto engine_directory : engine_directories) checkGameDirectory(engine_directory); for (auto& game_directory : game_data_directories) checkGameDirectory(game_directory); for (auto& user_directory : user_data_directories) if (!fs::exists(user_directory)) { auto user_dir = user_directory.string().c_str(); utils::log::warn("Can't find directory {}"s, user_dir); fs::create_directories(user_directory); utils::log::info("Directory {} is created"s, user_dir); } } void FileSystem::checkDefaultGameFiles() { auto checkDefaultGameFile = [](const string& ext, const string& data_dir) { if (!fs::exists(getGameDataDirectory(data_dir) / ("default" + ext))) { auto desc = "Can't open default " + data_dir + " file"; core::FatalError fe("FileSystem.cpp", 109u, core::Error::Type::FILESYSTEM, desc.c_str()); fe.finalize(); } }; auto file = "font"s; checkDefaultGameFile(FONT_EXTENSION, file); file = "sound"s; checkDefaultGameFile(SOUND_EXTENSION, file); file = "texture"s; checkDefaultGameFile(TEXTURE_EXTENSION, file); } path FileSystem::getGameDataDirectory(const string& directory) { for (auto& game_d_directory : game_data_directories) { if ((game_d_directory.string().find(directory)) != std::string::npos) return game_d_directory; } return {}; } path FileSystem::getUserDataDirectory(const string& directory) { for (auto& user_d_directory : user_data_directories) { if ((user_d_directory.string().find(directory)) != std::string::npos) return user_d_directory; } return {}; } }
#ifndef DWIZ_COMMON_SIGNALS_CONNECTION_H #define DWIZ_COMMON_SIGNALS_CONNECTION_H #include <common/dwiz_std.h> #include <functional> #include <memory> namespace dwiz { template <typename... Args> class Connection { public: using SlotType = std::function<void(Args...)>; Connection(std::shared_ptr<SlotType> const& f_slot = nullptr); std::shared_ptr<SlotType> const& get_slot() const; void set_slot(std::shared_ptr<SlotType> const& f_slot); void disconnect(); private: std::shared_ptr<SlotType> m_slot; }; // class Connection template <typename... Args> inline Connection<Args...>::Connection(std::shared_ptr<SlotType> const& f_slot) : m_slot(f_slot) { } template <typename... Args> inline std::shared_ptr<typename Connection<Args...>::SlotType> const& Connection<Args...>::get_slot() const { return m_slot; } template <typename... Args> inline void Connection<Args...>::set_slot(std::shared_ptr<SlotType> const& f_slot) { m_slot = f_slot; } template <typename... Args> inline void Connection<Args...>::disconnect() { m_slot.reset(); } } // namespace dwiz #endif
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.ApplicationModel.Search.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e #define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {}; #endif #ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e #define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {}; #endif #ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90 #define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90 template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_3975ff72_971b_54b6_9b5f_cc442e2a87f0 #define WINRT_GENERIC_3975ff72_971b_54b6_9b5f_cc442e2a87f0 template <> struct __declspec(uuid("3975ff72-971b-54b6-9b5f-cc442e2a87f0")) __declspec(novtable) TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneVisibilityChangedEventArgs> : impl_TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneVisibilityChangedEventArgs> {}; #endif #ifndef WINRT_GENERIC_7ccd7da1_8767_5eef_972d_31d09f1bf308 #define WINRT_GENERIC_7ccd7da1_8767_5eef_972d_31d09f1bf308 template <> struct __declspec(uuid("7ccd7da1-8767-5eef-972d-31d09f1bf308")) __declspec(novtable) TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneQueryChangedEventArgs> : impl_TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneQueryChangedEventArgs> {}; #endif #ifndef WINRT_GENERIC_95088dc0_6c14_55b8_8a8f_9df1ca44d1d4 #define WINRT_GENERIC_95088dc0_6c14_55b8_8a8f_9df1ca44d1d4 template <> struct __declspec(uuid("95088dc0-6c14-55b8-8a8f-9df1ca44d1d4")) __declspec(novtable) TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneSuggestionsRequestedEventArgs> : impl_TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneSuggestionsRequestedEventArgs> {}; #endif #ifndef WINRT_GENERIC_5f05121b_61a6_5f6b_b007_20816dfe7009 #define WINRT_GENERIC_5f05121b_61a6_5f6b_b007_20816dfe7009 template <> struct __declspec(uuid("5f05121b-61a6-5f6b-b007-20816dfe7009")) __declspec(novtable) TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneQuerySubmittedEventArgs> : impl_TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneQuerySubmittedEventArgs> {}; #endif #ifndef WINRT_GENERIC_ec31e5d4_3b8c_5757_96bf_14096be946cd #define WINRT_GENERIC_ec31e5d4_3b8c_5757_96bf_14096be946cd template <> struct __declspec(uuid("ec31e5d4-3b8c-5757-96bf-14096be946cd")) __declspec(novtable) TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneResultSuggestionChosenEventArgs> : impl_TypedEventHandler<Windows::ApplicationModel::Search::SearchPane, Windows::ApplicationModel::Search::SearchPaneResultSuggestionChosenEventArgs> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_6c26b7be_5f01_5a60_9dd7_fd17be3a9dd6 #define WINRT_GENERIC_6c26b7be_5f01_5a60_9dd7_fd17be3a9dd6 template <> struct __declspec(uuid("6c26b7be-5f01-5a60-9dd7-fd17be3a9dd6")) __declspec(novtable) IVector<Windows::Storage::StorageFolder> : impl_IVector<Windows::Storage::StorageFolder> {}; #endif #ifndef WINRT_GENERIC_e20debc6_dc4e_542e_a2e7_a24d19c8dd62 #define WINRT_GENERIC_e20debc6_dc4e_542e_a2e7_a24d19c8dd62 template <> struct __declspec(uuid("e20debc6-dc4e-542e-a2e7-a24d19c8dd62")) __declspec(novtable) IVectorView<Windows::Storage::StorageFolder> : impl_IVectorView<Windows::Storage::StorageFolder> {}; #endif #ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236 #define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236 template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {}; #endif #ifndef WINRT_GENERIC_5aac96fb_b3b9_5a7f_a920_4b5a8df81168 #define WINRT_GENERIC_5aac96fb_b3b9_5a7f_a920_4b5a8df81168 template <> struct __declspec(uuid("5aac96fb-b3b9-5a7f-a920-4b5a8df81168")) __declspec(novtable) IIterator<Windows::Storage::StorageFolder> : impl_IIterator<Windows::Storage::StorageFolder> {}; #endif #ifndef WINRT_GENERIC_4669befc_ae5c_52b1_8a97_5466ce61e94e #define WINRT_GENERIC_4669befc_ae5c_52b1_8a97_5466ce61e94e template <> struct __declspec(uuid("4669befc-ae5c-52b1-8a97-5466ce61e94e")) __declspec(novtable) IIterable<Windows::Storage::StorageFolder> : impl_IIterable<Windows::Storage::StorageFolder> {}; #endif } namespace Windows::ApplicationModel::Search { struct ILocalContentSuggestionSettings : Windows::Foundation::IInspectable, impl::consume<ILocalContentSuggestionSettings> { ILocalContentSuggestionSettings(std::nullptr_t = nullptr) noexcept {} }; struct ISearchPane : Windows::Foundation::IInspectable, impl::consume<ISearchPane> { ISearchPane(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPane may be altered or unavailable for releases after Windows 10.")]] ISearchPane; struct ISearchPaneQueryChangedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISearchPaneQueryChangedEventArgs> { ISearchPaneQueryChangedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneQueryChangedEventArgs may be altered or unavailable for releases after Windows 10.")]] ISearchPaneQueryChangedEventArgs; struct ISearchPaneQueryLinguisticDetails : Windows::Foundation::IInspectable, impl::consume<ISearchPaneQueryLinguisticDetails> { ISearchPaneQueryLinguisticDetails(std::nullptr_t = nullptr) noexcept {} }; struct ISearchPaneQuerySubmittedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISearchPaneQuerySubmittedEventArgs> { ISearchPaneQuerySubmittedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneQuerySubmittedEventArgs may be altered or unavailable for releases after Windows 10.")]] ISearchPaneQuerySubmittedEventArgs; struct ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails : Windows::Foundation::IInspectable, impl::consume<ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails> { ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails may be altered or unavailable for releases after Windows 10.")]] ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails; struct ISearchPaneResultSuggestionChosenEventArgs : Windows::Foundation::IInspectable, impl::consume<ISearchPaneResultSuggestionChosenEventArgs> { ISearchPaneResultSuggestionChosenEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneResultSuggestionChosenEventArgs may be altered or unavailable for releases after Windows 10.")]] ISearchPaneResultSuggestionChosenEventArgs; struct ISearchPaneStatics : Windows::Foundation::IInspectable, impl::consume<ISearchPaneStatics> { ISearchPaneStatics(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneStatics may be altered or unavailable for releases after Windows 10.")]] ISearchPaneStatics; struct ISearchPaneStaticsWithHideThisApplication : Windows::Foundation::IInspectable, impl::consume<ISearchPaneStaticsWithHideThisApplication> { ISearchPaneStaticsWithHideThisApplication(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneStaticsWithHideThisApplication may be altered or unavailable for releases after Windows 10.")]] ISearchPaneStaticsWithHideThisApplication; struct ISearchPaneSuggestionsRequest : Windows::Foundation::IInspectable, impl::consume<ISearchPaneSuggestionsRequest> { ISearchPaneSuggestionsRequest(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneSuggestionsRequest may be altered or unavailable for releases after Windows 10.")]] ISearchPaneSuggestionsRequest; struct ISearchPaneSuggestionsRequestDeferral : Windows::Foundation::IInspectable, impl::consume<ISearchPaneSuggestionsRequestDeferral> { ISearchPaneSuggestionsRequestDeferral(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneSuggestionsRequestDeferral may be altered or unavailable for releases after Windows 10.")]] ISearchPaneSuggestionsRequestDeferral; struct ISearchPaneSuggestionsRequestedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISearchPaneSuggestionsRequestedEventArgs>, impl::require<ISearchPaneSuggestionsRequestedEventArgs, Windows::ApplicationModel::Search::ISearchPaneQueryChangedEventArgs> { ISearchPaneSuggestionsRequestedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneSuggestionsRequestedEventArgs may be altered or unavailable for releases after Windows 10.")]] ISearchPaneSuggestionsRequestedEventArgs; struct ISearchPaneVisibilityChangedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISearchPaneVisibilityChangedEventArgs> { ISearchPaneVisibilityChangedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("ISearchPaneVisibilityChangedEventArgs may be altered or unavailable for releases after Windows 10.")]] ISearchPaneVisibilityChangedEventArgs; struct ISearchQueryLinguisticDetails : Windows::Foundation::IInspectable, impl::consume<ISearchQueryLinguisticDetails> { ISearchQueryLinguisticDetails(std::nullptr_t = nullptr) noexcept {} }; struct ISearchQueryLinguisticDetailsFactory : Windows::Foundation::IInspectable, impl::consume<ISearchQueryLinguisticDetailsFactory> { ISearchQueryLinguisticDetailsFactory(std::nullptr_t = nullptr) noexcept {} }; struct ISearchSuggestionCollection : Windows::Foundation::IInspectable, impl::consume<ISearchSuggestionCollection> { ISearchSuggestionCollection(std::nullptr_t = nullptr) noexcept {} }; struct ISearchSuggestionsRequest : Windows::Foundation::IInspectable, impl::consume<ISearchSuggestionsRequest> { ISearchSuggestionsRequest(std::nullptr_t = nullptr) noexcept {} }; struct ISearchSuggestionsRequestDeferral : Windows::Foundation::IInspectable, impl::consume<ISearchSuggestionsRequestDeferral> { ISearchSuggestionsRequestDeferral(std::nullptr_t = nullptr) noexcept {} }; } }
class Solution { public: void solve(int n,int open,int close,string op,vector<string> &v){ if(n==0){ v.push_back(op); return; } if(open!=n){ string op1 = op; op1 += '('; solve(n-1,open+1,close,op1,v); } if(open>close){ string op2 = op; op2 += ')'; solve(n-1,open,close+1,op2,v); } } vector<string> generateParenthesis(int n) { int open=0; int close=0; string op=""; vector<string> v; solve(2*n,open,close,op,v); return v; } };
#include <iostream> #include <stdio.h> using namespace std; void main() { setlocale(LC_CTYPE, "Russian"); char m[33], g[3]; int i, n, p = 3; unsigned int A, r, B, l, q,C; const unsigned int mask1 = 1 << 31; cout << "Введите число A: "; cin >> A; cout << "Введите число B: "; cin >> B; _itoa_s(A, m, 2); cout << "Число А в двоичном виде:" << m << endl; _itoa_s(B, m, 2); cout << "Число B в двоичном виде:" << m << endl; C = B; cout << "Введите начальную позицию для извлечения битов вправо в числе А: "; cin >> i; cout << "Введите бит, начиная c которого необходимо вставить эти биты в числе В: "; cin >> q; cout << "Введите бит, начиная с которого вправо необходимо заменить данными битами в числе В: "; cin >> p; n = 0; r = p; for (n; n < 32 - (i + 1) ; n++) { A <<= 1; } for (n = 0; n <= 2; n++) { A <<= 1; g[n] = (mask1 & A ? '1' : '0'); } for (n = 0; n < i - 2; n++) { A <<= 1; } cout << " " << endl; cout << "Извлечённые биты: "; for (n = 0; n <= 2; n++) { cout << g[n]; } cout << " " << endl; cout << "Итоговое число B c вставленными битами: "; for (n = 0; n <= 32 - q ; n++) { putchar(mask1 & B ? '1' : '0'); B <<= 1; } cout << " "; for (n = 0; n <= 2; n++) { putchar(g[n]); } cout << " "; for (n; n < q + 2 ; n++) { putchar(mask1 & B ? '1' : '0'); B <<= 1; } cout << " " << endl; cout << "Итоговое число B c заменёнными битами: "; for (n = 0; n <= 32 - p; n++) { putchar(mask1 & C ? '1' : '0'); C <<= 1; } cout << " "; for (n = 0; n <= 2; n++) { putchar(g[n]); C <<= 1; } cout << " "; for (n = 0; n < p-4 ; n++) { putchar(mask1 & C ? '1' : '0'); C <<= 1; } cout << " " << endl; }
#pragma once #include <string> #include "model/Sprite.hpp" /** * @brief An Actor is an entity in control of a Sprite. * */ class Actor { Sprite* sprite; public: const std::string name; const std::string description; Actor(Sprite& sprite, std::string name, std::string description = ""); Sprite& getSprite(); void setSprite(Sprite& sprite); bool controlsSprite(Sprite& sprite); };
#include "cineimage.h" CINEIMAGE::CINEIMAGE(std::ifstream *input, int64_t imagePointer, const BITMAPINFOHEADER & bitmapheader) { int k; bitreader br(input); br.seekToByte(imagePointer); AnnotationSize = br.readDWORD(); if (AnnotationSize-8 >0) { Annotation = new BYTE[AnnotationSize-8]; for (k = 0; k < AnnotationSize-8; k++) { Annotation[k] = br.readBYTE(); } } else { Annotation = NULL; } ImageSize = br.readDWORD(); int totalPixels = bitmapheader.getbiWidth() * bitmapheader.getbiHeight(); if (bitmapheader.getbiBitCount() == 24 || bitmapheader.getbiBitCount() == 48) { samplesPerPixel = 3; } else { samplesPerPixel = 1; } totalPixels = totalPixels *samplesPerPixel; if (totalPixels > 0) { if (bitmapheader.getbiBitCount() == 16 || bitmapheader.getbiBitCount() == 48) { is16bit = true; im8 = NULL; im16 = br.readWORDArray(totalPixels); } else { is16bit = false; im8 = br.readBYTEArray(totalPixels); im16 = NULL; } } else { im8 = NULL; im16 = NULL; } bmh = &bitmapheader; } CINEIMAGE::~CINEIMAGE() { if (AnnotationSize - 8 > 0 ) { delete[] Annotation; } else { delete Annotation; } if (is16bit) { delete im8; delete[] im16; } else { delete[] im8; delete im16; } } /* void CINEIMAGE::saveToTIFF(char *filename) { TIFF *out = TIFFOpen(filename, "w"); LONG w = bmh->getbiWidth(); LONG h = bmh->getbiHeight(); WORD bitCount = bmh->getbiBitCount(); TIFFSetField(out, TIFFTAG_IMAGEWIDTH, w); TIFFSetField(out, TIFFTAG_IMAGELENGTH, h); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel); if (is16bit) { TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 16); } else { TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8); } TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); if (samplesPerPixel == 3) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); } tsize_t linebytes = w*samplesPerPixel; if (is16bit) linebytes = linebytes * 2; unsigned char *buf = (unsigned char *)_TIFFmalloc(linebytes); TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(out, linebytes)); for (int k = 0; k < h; k++) { if (is16bit) { memcpy(buf, &im16[(h-k-1)*linebytes], linebytes); } else { memcpy(buf, &im8[(h-k-1)*linebytes], linebytes); } TIFFWriteScanline(out, buf, k); } (void) TIFFClose(out); if (buf) _TIFFfree(buf); } */
#ifndef _INC__RPG2K__MAP_HPP #define _INC__RPG2K__MAP_HPP #include "Define.hpp" #include <map> #include <stdexcept> namespace rpg2kLib { namespace structure { template< typename Key, typename T > class Map { private: std::multimap< Key, T* > data_; typedef typename std::multimap< Key, T* >::value_type val_type; typedef typename std::multimap< Key, T* >::const_iterator iterator; typedef typename std::multimap< Key, T* >::const_reverse_iterator reverse_iterator; public: class Iterator { friend class Map< Key, T >; private: Map< Key, T > const& owner_; iterator it_; protected: Iterator(); Iterator(Map< Key, T > const& owner, iterator it) : owner_(owner), it_(it) { } public: bool operator !=(Iterator const& it) const { return this->it_ != it.it_; } bool operator ==(Iterator const& it) const { return this->it_ == it.it_; } Key const& first() const { return it_->first; } T& second() { return *(it_->second); } Iterator& operator ++() { ++it_; return *this; } Iterator& operator --() { --it_; return *this; } }; class ReverseIterator { friend class Map< Key, T >; private: Map< Key, T > const& owner_; reverse_iterator it_; protected: ReverseIterator(); ReverseIterator(Map< Key, T > const& owner, reverse_iterator it) : owner_(owner), it_(it) { } public: bool operator !=(ReverseIterator const& it) const { return this->it_ != it.it_; } bool operator ==(ReverseIterator const& it) const { return this->it_ == it.it_; } Key const& first() const { return it_->first; } T& second() { return *(it_->second); } ReverseIterator& operator ++() { ++it_; return *this; } ReverseIterator& operator --() { --it_; return *this; } }; Map() : data_() {} Map(Map< Key, T > const& src) : data_() { for(iterator it = src.data_.begin(); it != src.data_.end(); ++it) data_.insert( val_type( it->first, new T( *(it->second) ) ) ); } Map< Key, T >& operator =(Map< Key, T > const& src) { clear(); for(iterator it = src.data_.begin(); it != src.data_.end(); ++it) data_.insert( val_type( it->first, new T( *(it->second) ) ) ); return *this; } void clear() { for(iterator it = data_.begin(); it != data_.end(); ++it) delete it->second; data_.clear(); } virtual ~Map() { clear(); } uint size() const { return data_.size(); } bool exists(Key const& key) const { return data_.find(key) != data_.end(); } T& get(Key const& key) const { iterator it = data_.find(key); if( it != data_.end() ) return *(it->second); else throw std::invalid_argument("Key doesn't exist in Map."); } T& operator [](Key const& key) const { return *( data_.find(key)->second ); } // skips remove if doesn't exist void remove(Key const& key) { if( exists(key) ) { for(iterator it = data_.find(key); it->first == key; ++it) delete it->second; data_.erase(key); } } bool empty() const { return data_.empty(); } void addReference(Key const& key, T& inst) { data_.insert( val_type(key, &inst) ); } void add(Key const& key) { data_.insert( val_type( key, new T() ) ); } template< typename Arg1 > void add(Key const& key, Arg1& a1) { data_.insert( val_type( key, new T(a1) ) ); } template< typename Arg1, typename Arg2 > void add(Key const& key, Arg1& a1, Arg2& a2) { data_.insert( val_type( key, new T(a1, a2) ) ); } template< typename Arg1, typename Arg2, typename Arg3 > void add(Key const& key, Arg1& a1, Arg2& a2, Arg3& a3) { data_.insert( val_type( key, new T(a1, a2, a3) ) ); } template< typename Arg1, typename Arg2, typename Arg3, typename Arg4 > void add(Key const& key, Arg1& a1, Arg2& a2, Arg3& a3, Arg4& a4) { data_.insert( val_type( key, new T(a1, a2, a3, a4) ) ); } Iterator begin() const { return Iterator( *this, data_.begin() ); } Iterator end () const { return Iterator( *this, data_.end () ); } ReverseIterator rbegin() const { return ReverseIterator( *this, data_.rbegin() ); } ReverseIterator rend () const { return ReverseIterator( *this, data_.rend () ); } }; // class Map class Descriptor; typedef Map< uint, Descriptor > const& ArrayDefine; } // namespace structure } // namespace rpg2kLib #endif // _INC__RPG2K__MAP_HPP
#include <iostream> #include "Token.h" using namespace std; int main() { Token_stream ts {cin}; Calculator calc{ts}; calc.calculate(); return 0; }
#include <iostream> using namespace std; int main() { int index = 1; while (index <= 5){ cout << index << endl; index++; } int ind = 6; do{ cout << ind << endl; ind++; }while (ind <=5); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int n, k; cin>>n>>k; int ans = 0; for(int i=0; i<n; i++) { int v; cin>>v; if(v>k) { ans += v-k; k = v; } } cout<<ans<<endl; }
#include <iostream> using namespace std; int a[300][300]; int n, mark[300]; int main () { cin >> n; for (int i=1; i<=n; i++) { int tmp; cin>>tmp; while (tmp != 0) { a[i][tmp] = 1; cin>>tmp; } } for (int k=1; k<=n; k++) for (int i=1; i<=n; i++) for (int j=1; j<=n; j++) if (a[i][k]==1 && a[k][j]==1) a[i][j] = 1; int t=1; for (int i=1; i<=n; i++) if (mark[i] == 0) { for (int j=i; j<=n; j++) if (a[i][j]==1&&a[j][i]==1) mark[i] = mark[j] = t; t++; } cout<<t-1; system("pause"); return 0; }
// define connectors #define GATE 2 #define LED 13 int led = LOW; void setup() { // Configure D0 as input pinMode(GATE, INPUT); // Configure LED pin as output pinMode(LED, OUTPUT); } void loop() { int value; // Check digital input value = digitalRead(GATE); // Check if the digital input is high or low if (value == HIGH) { if (led == LOW) { led = HIGH; } else { led = LOW; } digitalWrite(LED, led); delay(1000); } }
/* * LineHashIndex.h * * Created on: Nov 15, 2010 * Author: root */ #ifndef LINEHASHINDEX_H_ #define LINEHASHINDEX_H_ class MemoryBuffer; class ChunkManager; class MMapBuffer; #include "TripleBit.h" class LineHashIndex { public: struct Point{ ID x; ID y; }; struct chunkMetaData //except the firstChunk , minIDx, minIDy and offsetBegin will not change with update //offsetEnd may change but I think it makes little difference to the result //by Frankfan { ID minIDx; //The minIDx of a chunk ID minIDy; //The minIDy of a chunk unsigned offsetBegin; //The beginoffset of a chunk(not include MetaData and relative to the startPtr) }; enum IndexType { SUBJECT_INDEX, OBJECT_INDEX}; enum XYType {XBIGTHANY, YBIGTHANX}; private: MemoryBuffer* idTable; ID* idTableEntries; ChunkManager& chunkManager; IndexType indexType; XYType xyType; size_t tableSize; //chunk number plus 1,because the end edge char* lineHashIndexBase; //used to do update //line parameters; double upperk[4]; double upperb[4]; double lowerk[4]; double lowerb[4]; ID startID[4]; public: //some useful thing about the chunkManager uchar *startPtr, *endPtr; vector<chunkMetaData> chunkMeta; private: void insertEntries(ID id); size_t searchChunkFrank(ID id); bool buildLine(int startEntry, int endEntry, int lineNo); ID MetaID(size_t index); ID MetaYID(size_t index); public: LineHashIndex(ChunkManager& _chunkManager, IndexType index_type, XYType xy_type); Status buildIndex(unsigned chunkType); void getOffsetPair(size_t offsetID, unsigned& offsetBegin, unsigned& offsetEnd); size_t searchChunk(ID xID, ID yID); bool searchChunk(ID xID, ID yID, size_t& offsetID); bool isQualify(size_t offsetId, ID xID, ID yID); unsigned int getTableSize() { return tableSize; } size_t save(MMapBuffer*& indexBuffer); void saveDelta(MMapBuffer*& indexBuffer, size_t& offset ,const size_t predicateSize); virtual ~LineHashIndex(); void updateChunkMetaData(int offsetId); void updateLineIndex(); private: bool isBufferFull(); public: static LineHashIndex* load(ChunkManager& manager, IndexType index_type, XYType xy_type, char* buffer, size_t& offset); }; #endif /* LINEHASHINDEX_H_ */
// // SMImageEditorListener.h // iPet // // Created by KimSteve on 2017. 4. 27.. // Copyright © 2017년 KimSteve. All rights reserved. // #ifndef SMImageEditorListener_h #define SMImageEditorListener_h #include <cocos2d.h> class SMImageEditorListener { public: virtual void onImageEditResult(cocos2d::Sprite * editImage) = 0; }; #endif /* SMImageEditorListener_h */
#include <iostream> #include <new> #include <cstdlib> using namespace std; int main() { int n; cout << "How many numbers would you like to enter?" << endl; cin >> n; int *arr; arr = new (nothrow) int[n]; if (arr == nullptr) { cout << "Error allocating space" << endl; exit(1); } for (int i = 0; i < n; i++) { cout << "Enter number " << i + 1 << endl; // printf("Enter the %dth number\n", i+1); cin >> arr[i]; } cout << "Printing out the entered numbers:" << endl; for (int i = 0; i < n; i++) { cout << arr[i] << endl; } delete[] arr; return 0; }
#include <iostream> #include <vector> struct Foo { int a; std::string s; Foo(int _a, const std::string& _s) : a{ _a }, s{ _s } { } }; int main() { std::vector<Foo> foo; foo.emplace_back(2018, "C++"); std::cout << foo[0].a << '\n' << foo[0].s << '\n'; return 0; }
#include "UnpackerA2Geant.h" #include "expconfig/ExpConfig.h" #include "tree/TEvent.h" #include "tree/TEventData.h" #include "base/WrapTFile.h" #include "base/Logger.h" #include "TTree.h" #include <memory> #include <random> using namespace std; using namespace ant; namespace ant { namespace unpacker { namespace geant { struct promptrandom_t { using tagger_t = shared_ptr<TaggerDetector_t>; promptrandom_t( tagger_t tagger, UnpackerA2GeantConfig::promptrandom_config_t config) : r_prompt(config.PromptOffset, config.PromptSigma), n_randoms(static_cast<unsigned>( // round-off error negligble config.TimeWindow.Length()*config.RandomPromptRatio) ), r_random_timing(config.TimeWindow.Start(), config.TimeWindow.Stop()), r_random_channel(make_r_tagg_ch(tagger)) { } double SmearPrompt(double in) { return in + r_prompt(r_gen); } struct hit_t { unsigned Channel; double Timing; }; std::vector<hit_t> GetRandomHits() { vector<hit_t> hits(n_randoms); for(unsigned i=0;i<n_randoms;i++) { auto& hit = hits[i]; hit.Timing = r_random_timing(r_gen); hit.Channel = r_random_channel(r_gen); } return hits; } protected: default_random_engine r_gen; normal_distribution<double> r_prompt; const unsigned n_randoms; uniform_real_distribution<double> r_random_timing; discrete_distribution<unsigned> r_random_channel; static decltype(r_random_channel) make_r_tagg_ch(tagger_t tagger) { /// \todo check if that channel weighting actually works here vector<double> weights; for(unsigned ch=0;ch<tagger->GetNChannels();ch++) { weights.emplace_back( tagger->IsIgnored(ch) ? 0.0 : 1.0/tagger->GetPhotonEnergy(ch) ); } return {weights.begin(), weights.end()}; } }; }}} using namespace ant::unpacker::geant; UnpackerA2Geant::UnpackerA2Geant() {} UnpackerA2Geant::~UnpackerA2Geant() { delete id; } bool UnpackerA2Geant::OpenFile(const string& filename) { // open a root file, ignore error silently inputfile = std_ext::make_unique<WrapTFileInput>(); try { inputfile->OpenFile(filename); } catch (const std::runtime_error&) { return false; } // setup the "expected" A2 geant tree if(!inputfile->GetObject("h12", geant)) return false; geant->SetBranchAddress("nhits",&fnhits); geant->SetBranchAddress("npart",&fnpart); geant->SetBranchAddress("ntaps",&fntaps); geant->SetBranchAddress("nvtaps",&fnvtaps); geant->SetBranchAddress("vhits",&fvhits); geant->SetBranchAddress("plab",plab); geant->SetBranchAddress("tctaps",tctaps); geant->SetBranchAddress("vertex",fvertex); geant->SetBranchAddress("beam",fbeam); geant->SetBranchAddress("dircos",dircos); geant->SetBranchAddress("ecryst",ecryst); geant->SetBranchAddress("tcryst",tcryst); geant->SetBranchAddress("ectapfs",ectapfs); geant->SetBranchAddress("ectapsl",ectapsl); geant->SetBranchAddress("elab",elab); geant->SetBranchAddress("eleak",&feleak); geant->SetBranchAddress("enai",&fenai); geant->SetBranchAddress("etot",&fetot); geant->SetBranchAddress("eveto",eveto); geant->SetBranchAddress("tveto",tveto); geant->SetBranchAddress("evtaps",evtaps); geant->SetBranchAddress("icryst",icryst); geant->SetBranchAddress("ictaps",ictaps); geant->SetBranchAddress("ivtaps",ivtaps); geant->SetBranchAddress("idpart",idpart); geant->SetBranchAddress("iveto",iveto); geant->SetBranchAddress("nmwpc",&fnmwpc); geant->SetBranchAddress("imwpc",imwpc); geant->SetBranchAddress("mposx",mposx); geant->SetBranchAddress("mposy",mposy); geant->SetBranchAddress("mposz",mposz); geant->SetBranchAddress("emwpc",emwpc); TTree* tid_tree = nullptr; if(inputfile->GetObject("h12_tid", tid_tree)) { if(tid_tree->GetEntries() != geant->GetEntries()) { throw Exception("Geant Tree and TID Tree size mismatch"); } geant->AddFriend(tid_tree); geant->SetBranchAddress("tid", &id); tid_from_file = true; } else { tid_from_file = false; /// \todo think of some better timestamp? id = new TID(static_cast<std::uint32_t>(std::time(nullptr)), 0, // start with 0 as lower ID std::list<TID::Flags_t>{TID::Flags_t::MC, TID::Flags_t::AdHoc} // mark as MC ); } if(geant->GetEntries() >= numeric_limits<std::uint32_t>::max()) { throw Exception("Tree file contains too many entries for building correct unique ID"); } geant->GetEntry(0); // try to get a config auto setup = ExpConfig::Setup::GetLastFound(); if(!setup) { throw ExpConfig::ExceptionNoConfig("No setup found. This unpacker requires a manually set setup name"); } auto config = dynamic_pointer_cast<UnpackerA2GeantConfig, ExpConfig::Setup>(setup); if(!config) { throw ExpConfig::ExceptionNoConfig("Found setup cannot configure this unpacker."); } // find some taggerdetectors // needed to create proper tagger hits from incoming photons for(const shared_ptr<Detector_t>& detector : config->GetDetectors()) { /// \todo check for multiply defined detectors... if(auto tagger = dynamic_pointer_cast<TaggerDetector_t, Detector_t>(detector)) taggerdetector = tagger; if(detector->Type == Detector_t::Type_t::CB) cb_detector = detector; if(detector->Type == Detector_t::Type_t::PID) pid_detector = detector; if(detector->Type == Detector_t::Type_t::TAPS) taps_detector = detector; if(detector->Type == Detector_t::Type_t::TAPSVeto) tapsveto_detector = detector; } if(!taggerdetector) LOG(WARNING) << "No tagger detector found in config, there will be no taggerhits generated"; else { // initialize randomness promptrandom = std_ext::make_unique<unpacker::geant::promptrandom_t>( taggerdetector, config->GetPromptRandomConfig() ); } LOG(INFO) << "Successfully opened '" << filename << "' with " << geant->GetEntries() << " entries" << (tid_from_file ? ", with TID match check" : ""); LOG_IF(!tid_from_file, WARNING) << "No TID match check enabled"; return true; } struct r_t { std::default_random_engine r_gen; std::normal_distribution<double> r_prompt; }; TEvent UnpackerA2Geant::NextEvent() noexcept { if(current_entry>=geant->GetEntriesFast()-1) return {}; geant->GetEntry(++current_entry); // start with an empty event with reconstructed ID set // MCTrue ID will be set by MCTrue reader, but this unpacker // knows the true vertex position... TEvent event(*id, TID()); // however, vertex is some MCTrue information! event.MCTrue().Target.Vertex = vec3(fvertex[0], fvertex[1], fvertex[2]); const auto n_total = static_cast<unsigned>(fnhits+fnpart+fntaps+fnvtaps+fvhits); // approx. 3 detector read hits per detector, we just want to prevent re-allocation vector<TDetectorReadHit>& hits = event.Reconstructed().DetectorReadHits; hits.reserve(3*n_total); // all energies from A2geant are in GeV, but here we need MeV... const double GeVtoMeV = 1000.0; // fill CB Hits for(int i=0;i<fnhits;i++) { const auto ch = static_cast<unsigned>(icryst[i]); // no -1 here! if(cb_detector->IsIgnored(ch)) continue; const Detector_t::Type_t det = Detector_t::Type_t::CB; hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Integral, ch}, vector<double>{GeVtoMeV*ecryst[i]} ); hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Timing, ch}, vector<double>{tcryst[i]} ); } // fill PID Hits for(int i=0;i<fvhits;i++) { /// @todo Make PID channel mapping/rotation a Setup option? const unsigned ch = (23 - (iveto[i]-1) + 11) % 24; if(pid_detector->IsIgnored(ch)) continue; const Detector_t::Type_t det = Detector_t::Type_t::PID; hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Integral, ch}, vector<double>{GeVtoMeV*eveto[i]} ); hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Timing, ch}, vector<double>{tveto[i]} ); } // fill TAPS Hits for(int i=0;i<fntaps;i++) { const auto ch = static_cast<unsigned>(ictaps[i]-1); if(taps_detector->IsIgnored(ch)) continue; const Detector_t::Type_t det = Detector_t::Type_t::TAPS; hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Integral, ch}, vector<double>{GeVtoMeV*ectapsl[i]} ); /// \todo check if the short gate actually makes sense? hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::IntegralShort, ch}, vector<double>{GeVtoMeV*ectapfs[i]} ); hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Timing, ch}, vector<double>{tctaps[i]} ); } // fill TAPSVeto Hits for(int i=0;i<fnvtaps;i++) { const auto ch = static_cast<unsigned>(ivtaps[i]-1); if(tapsveto_detector->IsIgnored(ch)) continue; const Detector_t::Type_t det = Detector_t::Type_t::TAPSVeto; hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Integral, ch}, vector<double>{GeVtoMeV*evtaps[i]} ); /// \todo check if there's really no veto timing? hits.emplace_back( LogicalChannel_t{det, Channel_t::Type_t::Timing, ch}, vector<double>{0} ); } // "reconstruct" a tagger electron from the photon const double photon_energy = GeVtoMeV*fbeam[4]; if(taggerdetector) { // could the prompt photon have been detected? unsigned ch; if(taggerdetector->TryGetChannelFromPhoton(photon_energy, ch) && !taggerdetector->IsIgnored(ch) ) { // then insert (possibly time-smeared) prompt hit hits.emplace_back( LogicalChannel_t{taggerdetector->Type, Channel_t::Type_t::Timing, ch}, std::vector<double>{promptrandom->SmearPrompt(0)} ); } // always fill some extra random hits for(auto& hit : promptrandom->GetRandomHits()) { hits.emplace_back( LogicalChannel_t{taggerdetector->Type, Channel_t::Type_t::Timing, hit.Channel}, std::vector<double>{hit.Timing} ); } } if(!tid_from_file) ++(*id); return event; } double UnpackerA2Geant::PercentDone() const { return double(current_entry) / double(geant->GetEntries()); }
/*========================================================================= Program: Visualization Toolkit Module: vtkExtractSelectedBlock.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkExtractSelectedBlock * @brief Extract-Selection filter to extract blocks. * * vtkExtractSelectedBlock extracts blocks from a composite dataset on input 0 * using a vtkSelection on input 1. * * IDs extracted can refer to leaf nodes or non-leaf nodes. When they refer to * non-leaf nodes, the entire subtree is extracted. * * Note: this filter uses `vtkCompositeDataSet::ShallowCopy`, as a result, datasets at * leaf nodes are simply passed through, rather than being shallow-copied * themselves. */ #ifndef vtkExtractSelectedBlock_h #define vtkExtractSelectedBlock_h #include "vtkExtractSelectionBase.h" #include "vtkFiltersExtractionModule.h" // For export macro class VTKFILTERSEXTRACTION_EXPORT vtkExtractSelectedBlock : public vtkExtractSelectionBase { public: static vtkExtractSelectedBlock* New(); vtkTypeMacro(vtkExtractSelectedBlock, vtkExtractSelectionBase); void PrintSelf(ostream& os, vtkIndent indent) override; protected: vtkExtractSelectedBlock(); ~vtkExtractSelectedBlock() override; // Generate the output. int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; /** * Sets up empty output dataset */ int RequestDataObject(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) override; int FillInputPortInformation(int port, vtkInformation* info) override; private: vtkExtractSelectedBlock(const vtkExtractSelectedBlock&) = delete; void operator=(const vtkExtractSelectedBlock&) = delete; }; #endif
/* * Copyright 2017 Roman Katuntsev <sbkarr@stappler.org> * * 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 <iostream> #include <iomanip> #include "Thread.h" #include "Environment.h" #include <string.h> namespace wasm { static void printType(std::ostream &stream, Type t) { switch (t) { case Type::I32: stream << "i32"; break; case Type::I64: stream << "i64"; break; case Type::F32: stream << "f32"; break; case Type::F64: stream << "f64"; break; case Type::Anyfunc: stream << "anyfunc"; break; case Type::Func: stream << "func"; break; case Type::Void: stream << "void"; break; case Type::Any: stream << "any"; break; } } static void printMemoryBlock(std::ostream &stream, const uint8_t *ptr, Index n) { for (Index i = 0; i < n; ++ i) { stream << std::hex << std::setw(2) << std::setfill('0') << int(ptr[i]) << std::dec << std::setw(1); } } template<typename MemType> Thread::Result Thread::GetAccessAddress(const Func::OpcodeRec * pc, void** out_address) { auto memory = _currentFrame->module->memory[pc->value32.v2]; uint64_t addr = static_cast<uint64_t>(Pop<uint32_t>()) + pc->value32.v1; TRAP_IF(addr + sizeof(MemType) > memory->size, MemoryAccessOutOfBounds); *out_address = memory->data + addr; return Result::Ok; } template<typename MemType> Thread::Result Thread::GetAtomicAccessAddress(const Func::OpcodeRec * pc, void** out_address) { auto memory = _currentFrame->module->memory[pc->value32.v2]; uint64_t addr = static_cast<uint64_t>(Pop<uint32_t>()) + pc->value32.v1; TRAP_IF(addr + sizeof(MemType) > memory->size, MemoryAccessOutOfBounds); TRAP_IF((addr & (sizeof(MemType) - 1)) != 0, AtomicMemoryAccessUnaligned); *out_address = memory->data + addr; return Result::Ok; } Value& Thread::Top() { return Pick(1); } Value& Thread::Pick(Index depth) { return _valueStack[_valueStackTop - depth]; } void Thread::Reset() { _valueStackTop = 0; _callStackTop = 0; } Thread::Result Thread::Push(Value value) { CHECK_STACK(); _valueStack[_valueStackTop++] = value; return Result::Ok; } Value Thread::Pop() { return _valueStack[--_valueStackTop]; } Value Thread::ValueAt(Index at) const { assert(at < _valueStackTop); return _valueStack[at]; } template<typename T> Thread::Result Thread::Push(T value) { return PushRep<T>(ToRep(value)); } template<typename T> T Thread::Pop() { return FromRep<T>(PopRep<T>()); } template<typename T> Thread::Result Thread::PushRep(ValueTypeRep<T> value) { return Push(MakeValue<T>(value)); } template<typename T> ValueTypeRep<T> Thread::PopRep() { return GetValue<T>(Pop()); } void Thread::StoreResult(Value *begin, Index stack, Index results) { const auto d = _valueStack.data(); auto resultsPtr = d + _valueStackTop - results; _valueStackTop = (begin - d) + stack + results; if (results > 0) { memmove(begin + stack, resultsPtr, results * sizeof(Value)); } } Thread::Result Thread::PushCall(const RuntimeModule &module, const Func &func) { TRAP_IF(_callStackTop >= _callStack.size(), CallStackExhausted); _callStack[_callStackTop] = CallStackFrame{&module, &func, _valueStack.data() + _valueStackTop - func.types.size(), func.opcodes.data()}; ++ _callStackTop; return Result::Ok; } Thread::Result Thread::PushCall(const RuntimeModule &module, Index idx, bool import) { TrySync(); if (!import) { return PushCall(module, *module.func[idx].first); } else { TRAP_IF(_callStackTop >= _callStack.size(), CallStackExhausted); auto &fn = module.func[idx]; if (fn.first) { if (auto rtMod = _runtime->getModule(fn.first->module)) { return PushCall(*rtMod, *module.func[idx].first); } } else if (fn.second) { Index newTop = _valueStackTop - fn.second->sig.params.size() + fn.second->sig.results.size(); TRAP_IF(newTop >= _valueStack.size(), ValueStackExhausted); if (fn.second->callback(this, fn.second, _valueStack.data() + _valueStackTop - fn.second->sig.params.size()) == wasm::Result::Ok) { _valueStackTop = newTop; return Result::Returned; } } } return Result::TrapHostTrapped; } void Thread::PopCall(Index idx) { const Index newTop = _currentFrame->locals - _valueStack.data() + idx; if (idx > 0) { memmove(_currentFrame->locals, _valueStack.data() + _valueStackTop - idx, idx * sizeof(Value)); } _valueStackTop = newTop; -- _callStackTop; } template <typename MemType, typename ResultType> Thread::Result Thread::Load(const Func::OpcodeRec * pc) { typedef typename ExtendMemType<ResultType, MemType>::type ExtendedType; static_assert(std::is_floating_point<MemType>::value == std::is_floating_point<ExtendedType>::value, "Extended type should be float iff MemType is float"); void* src; CHECK_TRAP(GetAccessAddress<MemType>(pc, &src)); MemType value; LoadFromMemory<MemType>(&value, src); return Push<ResultType>(static_cast<ExtendedType>(value)); } template <typename MemType, typename ResultType> Thread::Result Thread::Store(const Func::OpcodeRec * pc) { typedef typename WrapMemType<ResultType, MemType>::type WrappedType; WrappedType value = PopRep<ResultType>(); void* dst; CHECK_TRAP(GetAccessAddress<MemType>(pc, &dst)); StoreToMemory<WrappedType>(dst, value); return Result::Ok; } template <typename MemType, typename ResultType> Thread::Result Thread::AtomicLoad(const Func::OpcodeRec * pc) { typedef typename ExtendMemType<ResultType, MemType>::type ExtendedType; static_assert(!std::is_floating_point<MemType>::value, "AtomicLoad type can't be float"); void* src; CHECK_TRAP(GetAtomicAccessAddress<MemType>(pc, &src)); MemType value; LoadFromMemory<MemType>(&value, src); return Push<ResultType>(static_cast<ExtendedType>(value)); } template<typename MemType, typename ResultType> Thread::Result Thread::AtomicStore(const Func::OpcodeRec * pc) { typedef typename WrapMemType<ResultType, MemType>::type WrappedType; WrappedType value = PopRep<ResultType>(); void* dst; CHECK_TRAP(GetAtomicAccessAddress<MemType>(pc, &dst)); StoreToMemory<WrappedType>(dst, value); return Result::Ok; } template<typename MemType, typename ResultType> Thread::Result Thread::AtomicRmw(BinopFunc<ResultType, ResultType> func, const Func::OpcodeRec * pc) { typedef typename ExtendMemType<ResultType, MemType>::type ExtendedType; MemType rhs = PopRep<ResultType>(); void* addr; CHECK_TRAP(GetAtomicAccessAddress<MemType>(pc, &addr)); MemType read; LoadFromMemory<MemType>(&read, addr); StoreToMemory<MemType>(addr, func(read, rhs)); return Push<ResultType>(static_cast<ExtendedType>(read)); } template<typename MemType, typename ResultType> Thread::Result Thread::AtomicRmwCmpxchg(const Func::OpcodeRec * pc) { typedef typename ExtendMemType<ResultType, MemType>::type ExtendedType; MemType replace = PopRep<ResultType>(); MemType expect = PopRep<ResultType>(); void* addr; CHECK_TRAP(GetAtomicAccessAddress<MemType>(pc, &addr)); MemType read; LoadFromMemory<MemType>(&read, addr); if (read == expect) { StoreToMemory<MemType>(addr, replace); } return Push<ResultType>(static_cast<ExtendedType>(read)); } template<typename R, typename T> Thread::Result Thread::Unop(UnopFunc<R, T> func) { auto value = PopRep<T>(); return PushRep<R>(func(value)); } template<typename R, typename T> Thread::Result Thread::UnopTrap(UnopTrapFunc<R, T> func) { auto value = PopRep<T>(); ValueTypeRep<R> result_value; CHECK_TRAP(func(value, &result_value)); return PushRep<R>(result_value); } template<typename R, typename T> Thread::Result Thread::Binop(BinopFunc<R, T> func) { auto rhs_rep = PopRep<T>(); auto lhs_rep = PopRep<T>(); return PushRep<R>(func(lhs_rep, rhs_rep)); } template<typename R, typename T> Thread::Result Thread::BinopTrap(BinopTrapFunc<R, T> func) { auto rhs_rep = PopRep<T>(); auto lhs_rep = PopRep<T>(); ValueTypeRep<R> result_value; CHECK_TRAP(func(lhs_rep, rhs_rep, &result_value)); return PushRep<R>(result_value); } Thread::Thread(const Runtime *runtime, Index tag) : _runtime(runtime), _tag(tag) { } bool Thread::init(uint32_t valueStackSize, uint32_t callStackSize) { _callStackTop = 0; _valueStackTop = 0; _valueStack.resize(valueStackSize); _callStack.resize(callStackSize); return true; } void Thread::setSyncContext(ThreadContext *ctx) { _context = ctx; if (_context) { _contextLock = std::shared_lock<std::shared_timed_mutex>(_context->mutex, std::defer_lock_t()); } else { _contextLock = std::shared_lock<std::shared_timed_mutex>(); } } ThreadContext *Thread::getSyncContext() const { return _context; } void Thread::setUserContext(uint32_t ctx) { _userContext = ctx; } uint32_t Thread::getUserContext() const { return _userContext; } void Thread::setThreadContext(void *ctx) { _threadContext = ctx; } void *Thread::getThreadContext() const { return _threadContext; } void Thread::setUserStackPointer(uint32_t pointer, uint32_t guard) { _userStackPointer = pointer; _userStackGuard = guard; } uint32_t Thread::getUserStackPointer() const { return _userStackPointer; } uint32_t Thread::getUserStackGuard() const { return _userStackGuard; } Thread::Result Thread::allocStack(uint32_t size, uint32_t &result) { if (_userStackGuard + size > _userStackPointer) { return Result::TrapUserStackExhausted; } else { _userStackPointer -= size; result = _userStackPointer; return Result::Ok; } } void Thread::freeStack(uint32_t size) { _userStackPointer += size; } const uint8_t* GetIstream() { return nullptr; } Thread::Result Thread::Run(const RuntimeModule &module, const Func &func, Value *buffer, bool silent) { bool locked = false; if (_contextLock.mutex() && !_contextLock.owns_lock()) { _contextLock.lock(); locked = true; } auto origStack = _callStackTop; auto origValue = _valueStackTop; CHECK_TRAP(PushLocals(func, buffer)); CHECK_TRAP(PushCall(module, func)); auto res = Run(origStack); if (res == Result::Ok || res == Result::Returned) { Index nresults = func.sig->results.size(); memcpy(buffer, &_valueStack[_valueStackTop - nresults], nresults * sizeof(Value)); _valueStackTop -= nresults; } else { if (!silent) { _runtime->onThreadError(*this); } _callStackTop = origStack; _valueStackTop = origValue; } if (locked) { _contextLock.unlock(); } return res; } RuntimeMemory *Thread::GetMemoryPtr(Index memIndex) const { if (_currentFrame && memIndex < _currentFrame->module->memory.size()) { return _currentFrame->module->memory[memIndex]; } return nullptr; } uint8_t *Thread::GetMemory(Index memIndex, Index offset) const { if (_currentFrame && memIndex < _currentFrame->module->memory.size()) { auto mem = _currentFrame->module->memory[memIndex]; if (offset < mem->size) { return &mem->data[offset]; } } return nullptr; } uint8_t *Thread::GetMemory(Index memIndex, Index offset, Index size) const { if (_currentFrame && memIndex < _currentFrame->module->memory.size()) { auto mem = _currentFrame->module->memory[memIndex]; if (offset + size <= mem->size) { return &mem->data[offset]; } } return nullptr; } Thread::Result Thread::PushLocals(const Func &func, const Value *buffer, Index storeParams) { const Index paramsSpace = func.types.size() - storeParams; const Index extraStackSpace = std::max(paramsSpace, Index(func.sig->results.size())); const Index nParams = func.sig->params.size(); const Index nLocals = func.types.size(); if (_valueStackTop + extraStackSpace > _valueStack.size()) { return Result::TrapValueStackExhausted; } if (buffer) { auto ptr = _valueStack.data() + _valueStackTop; memcpy(ptr, buffer, (func.sig->params.size() - storeParams) * sizeof(Value)); } memset(_valueStack.data() + _valueStackTop + nParams, 0, sizeof(Value) * (nLocals - nParams)); _valueStackTop += paramsSpace; return Result::Ok; } bool Thread::GrowMemory(const RuntimeMemory *memory, Index pages) { bool ret = true; bool locked = _contextLock.owns_lock(); if (locked) { _contextLock.unlock(); _context->stopFlag.store(true); // flag to suspend others thread _context->mutex.lock(); // acquire exclusive lock; _context->stopFlag.store(false); } if (!_runtime->growMemory(*memory, pages)) { ret = false; } if (locked) { _context->mutex.unlock(); _context->cond.notify_all(); _contextLock.lock(); } return ret; } void Thread::TrySync() { if (_context && _context->stopFlag.load()) { if (_contextLock) { _context->cond.wait(_contextLock); } } } void Thread::PrintStackFrame(std::ostream &stream, const CallStackFrame &frame, Index maxOpcodes) const { StringView modName = _runtime->getModuleName(frame.module); auto funcName = _runtime->getModuleFunctionName(*frame.module, frame.func); if (frame.func && !frame.func->name.empty()) { stream << frame.func->name << ": "; } stream << "[" << funcName.first << "] " << modName << " " << funcName.second << ":\n"; stream << "\tLocals:"; Index i = 0; for (auto &it : frame.func->types) { stream << "\t\t"; if (i < frame.func->sig->params.size()) { stream << "param l" << i; } else { stream << "local l" << i; } stream << ": "; printType(stream, it); stream << " = "; switch (it) { case Type::I32: stream << "0x" << std::setw(8) << std::setfill('0') << std::hex << frame.locals[i].i32 << " memory:"; printMemoryBlock(stream, (const uint8_t *)&frame.locals[i].i32, 4); stream << " ( " << std::dec << std::setw(1) << frame.locals[i].i32 << " )"; break; case Type::I64: stream << "0x" << std::setw(16) << std::setfill('0') << std::hex << frame.locals[i].i64 << " memory:"; printMemoryBlock(stream, (const uint8_t *)&frame.locals[i].i64, 8); stream << " ( " << std::dec << std::setw(1) << frame.locals[i].i64 << " )"; break; case Type::F32: stream << "0x" << std::setw(8) << std::setfill('0') << std::hex << frame.locals[i].f32_bits << " memory:"; printMemoryBlock(stream, (const uint8_t *)&frame.locals[i].f32_bits, 4); stream << " ( " << std::dec << std::setw(1) << reinterpret_cast<float &>(frame.locals[i].f32_bits) << " ):"; break; case Type::F64: stream << "0x" << std::setw(16) << std::setfill('0') << std::hex << frame.locals[i].f64_bits << " memory:"; printMemoryBlock(stream, (const uint8_t *)&frame.locals[i].f64_bits, 8); stream << " ( " << std::dec << std::setw(1) << reinterpret_cast<double &>(frame.locals[i].f64_bits) << " ):"; break; default: break; } stream << "\n"; ++ i; } Index position = frame.position - frame.func->opcodes.data(); Index nOpcodes = std::min(maxOpcodes, position + 1); stream << "\tCode:\n"; auto data = frame.func->opcodes.data(); for (Index i = 0; i < nOpcodes; ++ i) { auto opcode = frame.position - nOpcodes + i + 1; stream << "\t\t(" << opcode - data << ") " << Opcode(opcode->opcode).GetName() << " "; switch (opcode->opcode) { case Opcode::I64Const: case Opcode::F64Const: stream << opcode->value64; break; default: stream << opcode->value32.v1 << " " << opcode->value32.v2; break; } stream << "\n"; } } void Thread::PrintStackTrace(std::ostream &stream, Index maxUnwind, Index maxOpcodes) const { stream << "Stack unwind:\n"; Index unwind = std::min(_callStackTop, maxUnwind); for (Index i = 0; i < unwind; ++ i) { auto frame = &_callStack[_callStackTop - 1 - i]; stream << "(" << i << ") "; PrintStackFrame(stream, *frame); } } void Thread::PrintMemoryDump(std::ostream &stream, Index memIndex, uint32_t address, uint32_t size) { if (auto mem = GetMemoryPtr(memIndex)) { mem->print(stream, address, size); } } void Thread::onThreadError() const { _runtime->onThreadError(*this); } }
/* ENGR 152 * Maker Competition * Remind Device * Last edited by Kyler Howard, 4-17-20 */ //================================================================================ // Declare Global Variables & Header Files //================================================================================ // including required libraries to run the I2C LCD #include <Wire.h> #include <LiquidCrystal_I2C.h> // starting the LCD at the I2C address and the parameters the microprocessor needs LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // sets constant state variables from 1 to 7 const int STATE_GENERAL_WAIT = 1; const int STATE_LCD_ON = 2; const int STATE_FILE_WAIT = 3; const int STATE_AUDIO_SELECT = 4; const int STATE_SPEAKER_PLAY = 5; const int STATE_ACKNOWLEDGE_WAIT = 6; const int STATE_MOTION_OFF = 7; // setting other variables int IndicatorLED = 8; int ConfirmationButton = 9; int ConfirmationButtonState = 1; // TO DO: button state variable, joystick state variable, motion sensor state variable, speaker count variable, and whatever WAVE needs // sets the currentState to STATE_WELCOME int currentState = 1; //================================================================================ // Main Initializing Function //================================================================================ void setup() { // Starting the LCD at 16 columns and 2 rows lcd.begin(16,2); // clearing the LCD and putting the cursor at 0,0 lcd.clear(); // start serial monitor at 9600 bpm Serial.begin(9600); // set the currentState to STATE_WELCOME currentState = STATE_GENERAL_WAIT; // MAKE THE LED TURN ON pinMode (IndicatorLED, OUTPUT); digitalWrite (IndicatorLED, HIGH); pinMode (ConfirmationButton, INPUT_PULLUP); lcd.print("~~TESTING~~"); } //================================================================================ // Main Loop //================================================================================ void loop() { // Starts state machine switch(currentState){ //============================= // State One //============================= // starts state one of state machine case STATE_GENERAL_WAIT: // If the joystick or button is pressed, move to STATE_LCD_ON // If the motion detector is sensed, set the speaker counter to 1 and move to STATE_SPEAKER_PLAY ConfirmationButtonState = digitalRead(ConfirmationButton); if (ConfirmationButtonState == LOW){ Serial.print("Button Pushed"); } // end the case break; //============================= // State Two //============================= // starts state two of state machine case STATE_LCD_ON: // Turn on LCD screen // Display Audio Files // Move to STATE_FILE_WAIT // end the case break; //============================= // State Three //============================= // starts state three of state machine case STATE_FILE_WAIT: // If the joystick is moved, move the LCD readout to reflect this // If a file is selected using the joystick, move to STATE_AUDIO_SELECT // IF no user input for 30 seconds, turn off the LCD screen, and move to STATE_GENERAL_WAIT // end the case break; //============================= // State Four //============================= // starts state four of state machine case STATE_AUDIO_SELECT: // Declare audio file as speaker output // Wait 30 seconds // Turn off LCD screen // Return to STATE_GENERAL_WAIT // end the case break; //============================= // State Five //============================= // starts state five of state machine case STATE_SPEAKER_PLAY: // Play the selected audio file out of the speaker // Move to STATE_ACKNOWLEDGE_WAIT // end the case break; //============================= // State Six //============================= // starts state six of state machine case STATE_ACKNOWLEDGE_WAIT: // If the acknowledge button is pressed, move to STATE_MOTION_OFF // If the acknowledge button is not pressed within 10 seconds, increase the speaker counter by 1 and move to STATE_SPEAKER_PLAY. // If the counter is above 12, go to STATE_GENERAL_WAIT // end the case break; //============================= // State Seven //============================= // starts state seven of state machine case STATE_MOTION_OFF: // Turn off motion sensor // If there is not button input in 30 minutes, move to STATE_GENERAL_WAIT // If there is a button input, move to STATE_LCD_ON // end the case break; } } // Go back to the beginning of the loop
/* Author: Nayeemul Islam Swad Idea: - For some query l r v, if we find an x such that a[x] = v, then we can just set y = x and thus have found a solution (x, y). - If there is no such x, then a pair (x, y) would be a solution iff l <= x <= y <= r and there exists two distinct subtrees of v such that * All a[i] lies in one of these subtrees * Each subtree has at least one a[i] between [x, y] Now, suppose we're iterating from x to y and keep track of which subtree we're currently in of the two subtrees. Then, there must be a point when we're change the current subtree to the other one. This implies that if there exists a solution (x, y) with x != y, then there also is a solution (x0, y0) such that y0 = x0 + 1. - So, we just maintain all the lca's of consecutive elements of the array and answer queries of second types using them. */ #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "debug.h" #endif typedef long long lint; typedef unsigned int uint; typedef pair<int, int> pii; #define x first #define y second #define size(a) (int)a.size() const int N = int(2e5) + 10, LOGN = 20; int n, m, q; vector<int> adj[N]; int a[N], lv[N], par[N], P[LOGN][N]; set<int> a_pos[N], lca_pos[N]; int lca(int u, int v) { if (lv[u] < lv[v]) { swap(u, v); } for (int i = LOGN - 1; i >= 0; i--) { if (lv[u] - (1 << i) >= lv[v]) { u = P[i][u]; } } if (u == v) { return u; } for (int i = LOGN - 1; i >= 0; i--) { if (P[i][u] != P[i][v]) { u = P[i][u]; v = P[i][v]; } } return par[u]; } void initSp() { memset(P, -1, sizeof P); for (int i = 0; i < n; i++) { P[0][i] = par[i]; } for (int i = 1; i < LOGN; i++) { for (int j = 0; j < n; j++) { if (P[i - 1][j] != -1) { P[i][j] = P[i - 1][P[i - 1][j]]; } } } } void dfs(int at, int p) { par[at] = p; lv[at] = (p >= 0 ? lv[p] : -1) + 1; for (int nxt : adj[at]) { if (nxt != p) dfs(nxt, at); } } int main() { #ifdef LOCAL freopen("in", "r", stdin); freopen("out", "w", stdout); #endif cin >> n >> m >> q; for (int i = 0; i < n - 1; i++) { int u, v; scanf("%d %d", &u, &v); u--, v--; adj[u].push_back(v); adj[v].push_back(u); } dfs(0, -1); initSp(); for(int i = 0; i < m; i++) { scanf("%d", &a[i]); a[i]--; a_pos[a[i]].insert(i); if (i > 0) lca_pos[lca(a[i - 1], a[i])].insert(i - 1); } for(int i = 0; i < q; i++) { int type; scanf("%d", &type); if (type == 1) { int pos, v; scanf("%d %d", &pos, &v); pos--, v--; a_pos[a[pos]].erase(pos); a_pos[v].insert(pos); if (pos > 0) { lca_pos[lca(a[pos - 1], a[pos])].erase(pos - 1); lca_pos[lca(a[pos - 1], v)].insert(pos - 1); } if (pos < m - 1) { lca_pos[lca(a[pos], a[pos + 1])].erase(pos); lca_pos[lca(v, a[pos + 1])].insert(pos); } a[pos] = v; } else { int l, r, v; scanf("%d %d %d", &l, &r, &v); l--, r--, v--; auto it = a_pos[v].lower_bound(l); if (it != a_pos[v].end() && *it <= r) { printf("%d %d\n", *it + 1, *it + 1); continue; } if (r > l) { it = lca_pos[v].lower_bound(l); if (it != lca_pos[v].end() && *it <= r - 1) { printf("%d %d\n", *it + 1, *it + 2); continue; } } printf("-1 -1\n"); } } return 0; }
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> findAnagrams(string s, string p) { int letters[26] = {0}; for (char c : p) letters[c - 'a']++; vector<int> result; int remaining = p.size(), j = 0; for (int i = 0; i < s.size(); i++) { while (j < s.size() && j - i < p.size()) { if (letters[s.at(j++) - 'a']-- > 0) remaining--; } if (remaining == 0 && j - i == p.size()) result.push_back(i); if (letters[s.at(i) - 'a']++ >= 0) remaining++; } return result; } };
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #include "BspSurfaceBuilder.h" #include "../../common/Common.h" #include "../../common/endian.h" idBspSurfaceBuilder::idBspSurfaceBuilder( const idStr& name, byte* fileBase ) { this->name = name; this->fileBase = fileBase; numVertexes = 0; vertexes = NULL; numEdges = 0; edges = NULL; numSurfEdges = 0; surfEdges = NULL; } idBspSurfaceBuilder::~idBspSurfaceBuilder() { } void idBspSurfaceBuilder::LoadVertexes( bsp_lump_t* l ) { if ( l->filelen % sizeof ( *vertexes ) ) { common->Error( "MOD_LoadBmodel: funny lump size in %s", name.CStr() ); } numVertexes = l->filelen / sizeof ( *vertexes ); vertexes = ( bsp_vertex_t* )( fileBase + l->fileofs ); } void idBspSurfaceBuilder::LoadEdges( bsp_lump_t* l ) { if ( l->filelen % sizeof ( *edges ) ) { common->Error( "MOD_LoadBmodel: funny lump size in %s", name.CStr() ); } numEdges = l->filelen / sizeof ( *edges ); edges = ( bsp_edge_t* )( fileBase + l->fileofs ); } void idBspSurfaceBuilder::LoadSurfedges( bsp_lump_t* l ) { if ( l->filelen % sizeof ( *surfEdges ) ) { common->Error( "MOD_LoadBmodel: funny lump size in %s", name.CStr() ); } numSurfEdges = l->filelen / sizeof ( *surfEdges ); surfEdges = ( int* )( fileBase + l->fileofs ); } void idBspSurfaceBuilder::BuildSurfaceVertexesList( idSurfaceFaceQ1Q2* fa, int firstedge, int numedges ) { // reconstruct the polygon fa->numVertexes = numedges; fa->vertexes = new idWorldVertex[ numedges ]; fa->bounds.Clear(); for ( int i = 0; i < numedges; i++ ) { int lindex = LittleLong( surfEdges[ firstedge + i ] ); float* vec; if ( lindex > 0 ) { vec = vertexes[ ( unsigned short )LittleShort( edges[ lindex ].v[ 0 ] ) ].point; } else { vec = vertexes[ ( unsigned short )LittleShort( edges[ -lindex ].v[ 1 ] ) ].point; } fa->vertexes[ i ].xyz.x = LittleFloat( vec[ 0 ] ); fa->vertexes[ i ].xyz.y = LittleFloat( vec[ 1 ] ); fa->vertexes[ i ].xyz.z = LittleFloat( vec[ 2 ] ); fa->bounds.AddPoint( fa->vertexes[ i ].xyz ); } fa->boundingSphere = fa->bounds.ToSphere(); } // Breaks a polygon up along axial 64 unit boundaries so that turbulent and // sky warps can be done reasonably. void idBspSurfaceBuilder::Subdivide( idSurfaceFaceQ1Q2* fa ) { polys = NULL; // // convert edges back to a normal polygon // idList<int> indexes; for ( int i = 0; i < fa->numVertexes; i++ ) { verts.Append( fa->vertexes[ i ].xyz ); indexes.Append( i ); } SubdividePolygon( indexes ); delete[] fa->vertexes; fa->numVertexes = verts.Num(); fa->vertexes = new idWorldVertex[ verts.Num() ]; const idVec3* v = verts.Ptr(); for ( int i = 0; i < verts.Num(); i++, v++ ) { fa->vertexes[ i ].xyz = *v; fa->vertexes[ i ].normal = fa->plane.Normal(); fa->vertexes[ i ].st.x = DotProduct( *v, fa->textureInfo->vecs[ 0 ] ) / 64.0f; fa->vertexes[ i ].st.y = DotProduct( *v, fa->textureInfo->vecs[ 1 ] ) / 64.0f; } for ( glpoly_t* p = polys; p; p = p->next ) { fa->numIndexes += ( p->numverts - 2 ) * 3; } fa->indexes = new int[ fa->numIndexes ]; int numIndexes = 0; for ( glpoly_t* p = polys; p; p = p->next ) { for ( int i = 0; i < p->numverts - 2; i++ ) { fa->indexes[ numIndexes + i * 3 + 0 ] = p->indexes[ 0 ]; fa->indexes[ numIndexes + i * 3 + 1 ] = p->indexes[ i + 1 ]; fa->indexes[ numIndexes + i * 3 + 2 ] = p->indexes[ i + 2 ]; } numIndexes += ( p->numverts - 2 ) * 3; } glpoly_t* poly = polys; while ( poly ) { glpoly_t* tmp = poly; poly = poly->next; Mem_Free( tmp ); } verts.Clear(); } void idBspSurfaceBuilder::SubdividePolygon( const idList<int>& vertIndexes ) { idBounds bounds = BoundPoly( vertIndexes ); for ( int i = 0; i < 3; i++ ) { float m = ( bounds[ 0 ][ i ] + bounds[ 1 ][ i ] ) * 0.5; m = SUBDIVIDE_SIZE * floor( m / SUBDIVIDE_SIZE + 0.5 ); if ( bounds[ 1 ][ i ] - m < 8 ) { continue; } if ( m - bounds[ 0 ][ i ] < 8 ) { continue; } // cut it idList<float> dist; for ( int j = 0; j < vertIndexes.Num(); j++ ) { dist.Append( verts[ vertIndexes[ j ] ][ i ] - m ); } // wrap cases dist.Append( dist[ 0 ] ); idList<int> front, back; for ( int j = 0; j < vertIndexes.Num(); j++ ) { int index1 = vertIndexes[ j ]; float dist1 = dist[ j ]; if ( dist1 >= 0 ) { front.Append( index1 ); } if ( dist1 <= 0 ) { back.Append( index1 ); } float dist2 = dist[ j + 1 ]; if ( dist1 == 0 || dist2 == 0 ) { continue; } if ( ( dist1 > 0 ) != ( dist2 > 0 ) ) { // clip point float frac = dist1 / ( dist1 - dist2 ); int index2 = vertIndexes[ ( j + 1 ) % vertIndexes.Num() ]; verts.Append( verts[ index1 ] + frac * ( verts[ index2 ] - verts[ index1 ] ) ); front.Append( verts.Num() - 1 ); back.Append( verts.Num() - 1 ); } } SubdividePolygon( front ); SubdividePolygon( back ); return; } EmitPolygon( vertIndexes ); } void idBspSurfaceBuilder::EmitPolygon( const idList<int>& vertIndexes ) { // add a point in the center to help keep warp valid glpoly_t* poly = ( glpoly_t* )Mem_Alloc( sizeof ( glpoly_t ) + ( ( vertIndexes.Num() - 4 ) + 2 ) * sizeof( int ) ); poly->next = polys; polys = poly; poly->numverts = vertIndexes.Num() + 2; idVec3 total; total.Zero(); for ( int i = 0; i < vertIndexes.Num(); i++ ) { poly->indexes[ i + 1 ] = vertIndexes[ i ]; total += verts[ vertIndexes[ i ] ]; } verts.Append( total / vertIndexes.Num() ); poly->indexes[ 0 ] = verts.Num() - 1; poly->indexes[ vertIndexes.Num() + 1 ] = poly->indexes[ 1 ]; } idBounds idBspSurfaceBuilder::BoundPoly( const idList<int>& vertIndexes ) { idBounds bounds; bounds.Clear(); for ( int i = 0; i < vertIndexes.Num(); i++ ) { bounds.AddPoint( verts[ vertIndexes[ i ] ] ); } return bounds; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "SloughingCellKiller.hpp" #include "AbstractCentreBasedCellPopulation.hpp" #include "Exception.hpp" template<unsigned DIM> SloughingCellKiller<DIM>::SloughingCellKiller(AbstractCellPopulation<DIM>* pCrypt, double sloughHeight, bool sloughSides, double sloughWidth) : AbstractCellKiller<DIM>(pCrypt), mSloughSides(sloughSides) { assert(sloughHeight > 0.0); mSloughHeight = sloughHeight; assert(sloughWidth > 0.0); mSloughWidth = sloughWidth; } template<unsigned DIM> bool SloughingCellKiller<DIM>::GetSloughSides() const { return mSloughSides; } template<unsigned DIM> double SloughingCellKiller<DIM>::GetSloughHeight() const { return mSloughHeight; } template<unsigned DIM> double SloughingCellKiller<DIM>::GetSloughWidth() const { return mSloughWidth; } template<unsigned DIM> void SloughingCellKiller<DIM>::CheckAndLabelCellsForApoptosisOrDeath() { switch (DIM) { case 1: { for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->mpCellPopulation->Begin(); cell_iter != this->mpCellPopulation->End(); ++cell_iter) { double x = this->mpCellPopulation->GetLocationOfCellCentre(*cell_iter)[0]; if (x > mSloughHeight) { // Mark the cell as killed and store removal information if required. this->mpCellPopulation->KillCell(*cell_iter, "SloughingCellKiller"); } } break; } case 2: { for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->mpCellPopulation->Begin(); cell_iter != this->mpCellPopulation->End(); ++cell_iter) { c_vector<double, 2> location; location = this->mpCellPopulation->GetLocationOfCellCentre(*cell_iter); double x = location[0]; double y = location[1]; if ((y>mSloughHeight) || (mSloughSides && ((x<0.0) || (x>mSloughWidth)))) { // Mark the cell as killed and store removal information if required. this->mpCellPopulation->KillCell(*cell_iter, "SloughingCellKiller"); } } break; } case 3: { EXCEPTION("SloughingCellKiller is not yet implemented in 3D"); break; } default: // This can't happen NEVER_REACHED; } } template<unsigned DIM> void SloughingCellKiller<DIM>::OutputCellKillerParameters(out_stream& rParamsFile) { *rParamsFile << "\t\t\t<SloughLength>" << mSloughHeight << "</SloughLength>\n"; *rParamsFile << "\t\t\t<SloughSides>" << mSloughSides << "</SloughSides>\n"; *rParamsFile << "\t\t\t<SloughWidth>" << mSloughWidth << "</SloughWidth>\n"; // Call method on direct parent class AbstractCellKiller<DIM>::OutputCellKillerParameters(rParamsFile); } // Explicit instantiation template class SloughingCellKiller<1>; template class SloughingCellKiller<2>; template class SloughingCellKiller<3>; // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" EXPORT_TEMPLATE_CLASS_SAME_DIMS(SloughingCellKiller)
/** * @file IteratorTest.cpp * @author seckler * @date 22.07.19 */ #include "IteratorTest.h" #include "testingHelpers/commonTypedefs.h" constexpr double cutoff = 1.; constexpr double skin = 0.2; constexpr std::array<double, 3> boxMin{0., 0., 0.}; constexpr std::array<double, 3> haloBoxMin{0. - skin - cutoff, 0. - skin - cutoff, 0. - skin - cutoff}; constexpr std::array<double, 3> boxMax{10., 10., 10.}; constexpr std::array<double, 3> haloBoxMax{10. + skin + cutoff, 10. + skin + cutoff, 10. + skin + cutoff}; template <typename AutoPasT> void defaultInit(AutoPasT &autoPas) { autoPas.setBoxMin(boxMin); autoPas.setBoxMax(boxMax); autoPas.setCutoff(cutoff); autoPas.setVerletSkin(skin); autoPas.setVerletRebuildFrequency(2); autoPas.setNumSamples(2); // init autopas autoPas.init(); } template <typename AutoPasT> void checkRegionIteratorForAllParticles(AutoPasT &autoPas, autopas::IteratorBehavior behavior) { for (auto iter1 = autoPas.begin(behavior); iter1.isValid(); ++iter1) { unsigned int count = 0; auto low = iter1->getR(); auto up = autopas::ArrayMath::addScalar(low, 1e-10); for (auto iter2 = autoPas.getRegionIterator(low, up, behavior); iter2.isValid(); ++iter2) { ++count; EXPECT_EQ(&(*iter1), &(*iter2)); } EXPECT_EQ(count, 1u); } } /** * Tests the addition and iteration over particles. * @param containerOption */ void testAdditionAndIteration(testingTuple options) { // create AutoPas object autopas::AutoPas<Molecule, FMCell> autoPas; auto containerOption = std::get<0>(options); auto cellSizeOption = std::get<1>(options); autoPas.setAllowedContainers(std::set<autopas::ContainerOption>{containerOption}); autoPas.setAllowedCellSizeFactors(autopas::NumberSetFinite<double>(std::set<double>({cellSizeOption}))); defaultInit(autoPas); constexpr size_t numParticles1dOwned = 3; constexpr size_t numParticles1dTotal = 10; auto getPossible1DPositions = [&](double min, double max) -> auto { return std::array<double, numParticles1dTotal>{min - cutoff - skin + 1e-10, min - cutoff, min - skin / 4, min, min + skin / 4, max - skin / 4, max, max + skin / 4, max + cutoff, max + cutoff + skin - 1e-10}; // ensure that all particles are at most skin away from halo! }; size_t id = 0; for (auto x : getPossible1DPositions(boxMin[0], boxMax[0])) { for (auto y : getPossible1DPositions(boxMin[1], boxMax[1])) { for (auto z : getPossible1DPositions(boxMin[2], boxMax[2])) { std::array<double, 3> pos{x, y, z}; Molecule p(pos, {0., 0., 0.}, id); ++id; // add the two particles! if (autopas::utils::inBox(pos, boxMin, boxMax)) { autoPas.addParticle(p); } else { autoPas.addOrUpdateHaloParticle(p); } } } } { size_t count = 0; for (auto iter = autoPas.begin(autopas::IteratorBehavior::ownedOnly); iter.isValid(); ++iter) { ++count; EXPECT_TRUE(iter->isOwned()); } EXPECT_EQ(count, numParticles1dOwned * numParticles1dOwned * numParticles1dOwned); } // check number of halo particles { size_t count = 0; for (auto iter = autoPas.begin(autopas::IteratorBehavior::haloOnly); iter.isValid(); ++iter) { ++count; EXPECT_FALSE(iter->isOwned()); } EXPECT_EQ(count, numParticles1dTotal * numParticles1dTotal * numParticles1dTotal - numParticles1dOwned * numParticles1dOwned * numParticles1dOwned); } // check number of particles { size_t count = 0; for (auto iter = autoPas.begin(autopas::IteratorBehavior::haloAndOwned); iter.isValid(); ++iter) { ++count; } EXPECT_EQ(count, numParticles1dTotal * numParticles1dTotal * numParticles1dTotal); } // check number of halo particles for region iterator { size_t count = 0; for (auto iter = autoPas.getRegionIterator(haloBoxMin, haloBoxMax, autopas::IteratorBehavior::haloOnly); iter.isValid(); ++iter) { ++count; EXPECT_FALSE(iter->isOwned()); } EXPECT_EQ(count, numParticles1dTotal * numParticles1dTotal * numParticles1dTotal - numParticles1dOwned * numParticles1dOwned * numParticles1dOwned); } // check number of particles for region iterator { size_t count = 0; for (auto iter = autoPas.getRegionIterator(haloBoxMin, haloBoxMax, autopas::IteratorBehavior::haloAndOwned); iter.isValid(); ++iter) { ++count; } EXPECT_EQ(count, numParticles1dTotal * numParticles1dTotal * numParticles1dTotal); } // check number of owned particles for region iterator { size_t count = 0; for (auto iter = autoPas.getRegionIterator(haloBoxMin, haloBoxMax, autopas::IteratorBehavior::ownedOnly); iter.isValid(); ++iter) { ++count; } EXPECT_EQ(count, numParticles1dOwned * numParticles1dOwned * numParticles1dOwned); } // check all particles are in region iterator of their position, ownedOnly checkRegionIteratorForAllParticles(autoPas, autopas::IteratorBehavior::ownedOnly); // check all particles are in region iterator of their position, haloOnly checkRegionIteratorForAllParticles(autoPas, autopas::IteratorBehavior::haloOnly); // check all particles are in region iterator of their position, haloAndOwned checkRegionIteratorForAllParticles(autoPas, autopas::IteratorBehavior::haloAndOwned); // now move particles by at most skin/2, as this is the maximal distance they are allowed to move for (auto iter = autoPas.begin(autopas::IteratorBehavior::haloAndOwned); iter.isValid(); ++iter) { auto pos = iter->getR(); for (auto d = 0; d < 3; ++d) { if (pos[d] < boxMin[d]) { pos[d] += skin / 2; } else if (pos[d] >= boxMax[d]) { pos[d] -= skin / 2; } else if (pos[d] < (boxMax[d] + boxMin[d]) / 2) { pos[d] -= skin / 2; } else { pos[d] += skin / 2; } } iter->setR(pos); } // check all particles are in region iterator of their position, ownedOnly checkRegionIteratorForAllParticles(autoPas, autopas::IteratorBehavior::ownedOnly); // check all particles are in region iterator of their position, haloOnly checkRegionIteratorForAllParticles(autoPas, autopas::IteratorBehavior::haloOnly); // check all particles are in region iterator of their position, haloAndOwned checkRegionIteratorForAllParticles(autoPas, autopas::IteratorBehavior::haloAndOwned); } TEST_P(IteratorTest, ParticleAdditionAndIteratorTestNormal) { auto options = GetParam(); testAdditionAndIteration(options); } using ::testing::Combine; using ::testing::UnorderedElementsAreArray; using ::testing::Values; using ::testing::ValuesIn; INSTANTIATE_TEST_SUITE_P(Generated, IteratorTest, // proper indent Combine(ValuesIn([]() -> std::set<autopas::ContainerOption> { auto allContainerOptions = autopas::allContainerOptions; /// @TODO no verletClusterLists yet, so we erase it for now. allContainerOptions.erase( allContainerOptions.find(autopas::ContainerOption::verletClusterLists)); return allContainerOptions; }()), Values(0.5, 1., 1.5)), IteratorTest::PrintToStringParamName());
/** * * @file LoadConfigBase.cpp * @author Naoki Takahashi * **/ #include "LoadConfigBase.hpp" #include <stdexcept> namespace IO { namespace LoadConfig { LoadConfigBase::~LoadConfigBase() { } void LoadConfigBase::update() { throw std::runtime_error("Unoverride"); } void LoadConfigBase::force_update() { throw std::runtime_error("Unoverride"); } } }
#include <esp-helper.h> #include "esp_system.h" #include "esp_wifi.h" void udp_echo_handler(void*); extern "C" void app_main() { init_flash(); #ifdef FEATURE_IDF_DEFAULT_EVENT_LOOP wifi_init_sta(); #else wifi_init_sta(event_handler); #endif xTaskCreate(udp_echo_handler, "udp_echo_handler", 4096, nullptr, 4, nullptr); }
#include <math.h> #include <time.h> #include "..\..\..\..\card\naborCards.h" #include "TurnTree.h" #include "..\..\..\..\Util\TemplateFileRec.h" #include "..\..\..\..\Util\Sort.h" #include "..\..\..\Common\HoldemTree.h" #include "..\..\..\Common\FlopAllIn.h" #include "..\..\..\..\util\Clasters.h" #include "..\..\AppRiverTrees\Source\clRiverBanks.h" #include "..\..\..\..\Util\Matrix.h" #include "..\..\..\..\Util\AnyType.h" #include "..\..\..\..\Util\AnyTemplate.h" //bool glTurnDatNew = true; class clTurnDatDat { public: void Init10(); void Init16(); void Init20(); int GetNbHand(int pos, int i) { return _nbHand[pos][i]; } int &Force(int nbPl, int k, int nbH) { return _force[nbPl][nbH*CN_CARD_COL + k]; } clMatrixCub <tp2Int> _matrix; int _nbHand[2][CN_STREETDAT_UNIT]; clCard _board[5]; tpBooleanDeck _deck; int _force[2][CN_CARD_COL*CN_STREETDAT_UNIT]; } glTDD; //--------------------------------------------------------------------------------------------------------------------------------------------------- void InitTurnDatDat() { if (CN_STREETDAT_UNIT == 10) glTDD.Init10(); else if (CN_STREETDAT_UNIT == 16) glTDD.Init16(); else if (CN_STREETDAT_UNIT == 20) glTDD.Init20(); } //--------------------------------------------------------------------------------------------------------------------------------------------------- int *GetNbHandTurnDatDat(int nb) { return glTDD._nbHand[nb]; } //--------------------------------------------------------------------------------------------------------------------------------------------------- void clTurnDatDat::Init10() { _board[0] = Card(C_5, S_C); _board[1] = Card(C_6, S_C); _board[2] = Card(C_8, S_S); _board[3] = Card(C_T, S_S); _deck.SetDeck(true); _deck.Skip(_board[0]); _deck.Skip(_board[1]); _deck.Skip(_board[2]); _deck.Skip(_board[3]); clHand hand[CN_STREETDAT_UNIT]; hand[0].SetHand(Card(C_9, S_D), Card(C_7, S_D)); hand[1].SetHand(Card(C_T, S_D), Card(C_5, S_D)); hand[2].SetHand(Card(C_T, S_D), Card(C_7, S_D)); hand[3].SetHand(Card(C_T, S_D), Card(C_A, S_D)); hand[4].SetHand(Card(C_K, S_D), Card(C_8, S_D)); hand[5].SetHand(Card(C_J, S_D), Card(C_9, S_D)); hand[6].SetHand(Card(C_K, S_D), Card(C_4, S_D)); hand[7].SetHand(Card(C_Q, S_D), Card(C_Q, S_C)); hand[8].SetHand(Card(C_3, S_D), Card(C_3, S_C)); hand[9].SetHand(Card(C_K, S_D), Card(C_2, S_D)); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { _nbHand[0][i] = hand[i].NbHandAll(); hand[i][0].suit = S_H; hand[i][1].suit = (hand[i][0].face == hand[i][1].face) ? S_S : S_H; _nbHand[1][i] = hand[i].NbHandAll(); } ZeroMemory(_force, sizeof(_force)); tpBooleanDeck deck = _deck; tpCard cards[5] = { _board[0], _board[1], _board[2], _board[3] }; for (int i = 0; i < CN_STREETDAT_UNIT; i++) { int nbH = GetNbHand(0, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(0, k, i) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } for (int i = 0; i < CN_STREETDAT_UNIT; i++) { int nbH = GetNbHand(1, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(1, k, i) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } _matrix.SetDim(CN_STREETDAT_UNIT, CN_STREETDAT_UNIT, CN_CARD_COL); _matrix.ZeroData(); for (int i0 = 0; i0 < CN_STREETDAT_UNIT; i0++) { int nb0 = GetNbHand(0, i0); tpHand hand0(nb0); deck[hand0[0]] = false; deck[hand0[1]] = false; for (int i1 = 0; i1 < CN_STREETDAT_UNIT; i1++) { int nb1 = GetNbHand(1, i1); tpHand hand1(nb1); deck[hand1[0]] = false; deck[hand1[1]] = false; tp2Int *v0 = _matrix.Array(i0, i1); for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { v0[k]._val2 = 1; int f0 = Force(0, k, i0), f1 = Force(1, k, i1); if (f0 > f1) v0[k]._val1 = 1; else if (f1 > f0) v0[k]._val1 = -1; else v0[k]._val1 = 0; } deck[hand1[0]] = true; deck[hand1[1]] = true; } deck[hand0[0]] = true; deck[hand0[1]] = true; } } //--------------------------------------------------------------------------------------------------------------------------------------------------- void clTurnDatDat::Init16() { //glTrasser.WriteMessage((clAnsiString)"A"); _board[0] = Card(C_5, S_C); _board[1] = Card(C_6, S_C); _board[2] = Card(C_8, S_S); _board[3] = Card(C_T, S_S); _deck.SetDeck(true); _deck.Skip(_board[0]); _deck.Skip(_board[1]); _deck.Skip(_board[2]); _deck.Skip(_board[3]); clHand hand[CN_STREETDAT_UNIT]; hand[0].SetHand(Card(C_9, S_D), Card(C_7, S_D)); hand[1].SetHand(Card(C_4, S_D), Card(C_7, S_D)); hand[2].SetHand(Card(C_T, S_D), Card(C_8, S_D)); hand[3].SetHand(Card(C_T, S_D), Card(C_7, S_D)); hand[4].SetHand(Card(C_5, S_D), Card(C_7, S_D)); hand[5].SetHand(Card(C_T, S_D), Card(C_A, S_D)); hand[6].SetHand(Card(C_K, S_D), Card(C_8, S_D)); hand[7].SetHand(Card(C_Q, S_D), Card(C_6, S_D)); hand[8].SetHand(Card(C_J, S_D), Card(C_9, S_D)); hand[9].SetHand(Card(C_J, S_D), Card(C_7, S_D)); hand[10].SetHand(Card(C_Q, S_D), Card(C_3, S_D)); hand[11].SetHand(Card(C_K, S_D), Card(C_4, S_D)); hand[12].SetHand(Card(C_Q, S_D), Card(C_Q, S_C)); hand[13].SetHand(Card(C_3, S_D), Card(C_3, S_C)); hand[14].SetHand(Card(C_A, S_D), Card(C_Q, S_D)); hand[15].SetHand(Card(C_K, S_D), Card(C_2, S_D)); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { _nbHand[0][i] = hand[i].NbHandAll(); hand[i][0].suit = S_H; hand[i][1].suit = (hand[i][0].face == hand[i][1].face) ? S_S : S_H; _nbHand[1][i] = hand[i].NbHandAll(); } ZeroMemory(_force, sizeof(_force)); tpBooleanDeck deck = _deck; tpCard cards[5] = { _board[0], _board[1], _board[2], _board[3] }; for (int i = 0; i < CN_STREETDAT_UNIT; i++) { int nbH = GetNbHand(0, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(0, k, i) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } for (int i = 0; i < CN_STREETDAT_UNIT; i++) { int nbH = GetNbHand(1, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(1, k, i) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } } //--------------------------------------------------------------------------------------------------------------------------------------------------- void clTurnDatDat::Init20() { //glTrasser.WriteMessage((clAnsiString)"A"); _board[0] = Card(C_5, S_C); _board[1] = Card(C_7, S_C); _board[2] = Card(C_7, S_S); _board[3] = Card(C_9, S_S); _deck.SetDeck(true); _deck.Skip(_board[0]); _deck.Skip(_board[1]); _deck.Skip(_board[2]); _deck.Skip(_board[3]); clHand hand[CN_STREETDAT_UNIT]; hand[0].SetHand(Card(C_9, S_D), Card(C_7, S_D)); hand[1].SetHand(Card(C_8, S_D), Card(C_6, S_D)); hand[2].SetHand(Card(C_A, S_D), Card(C_7, S_D)); hand[3].SetHand(Card(C_8, S_D), Card(C_7, S_D)); hand[4].SetHand(Card(C_2, S_D), Card(C_7, S_D)); hand[5].SetHand(Card(C_K, S_D), Card(C_9, S_D)); hand[6].SetHand(Card(C_9, S_D), Card(C_3, S_D)); hand[7].SetHand(Card(C_Q, S_D), Card(C_5, S_D)); hand[8].SetHand(Card(C_5, S_D), Card(C_4, S_D)); hand[9].SetHand(Card(C_K, S_D), Card(C_K, S_C)); hand[10].SetHand(Card(C_4, S_D), Card(C_4, S_C)); hand[11].SetHand(Card(C_T, S_D), Card(C_8, S_D)); hand[12].SetHand(Card(C_6, S_D), Card(C_4, S_D)); hand[13].SetHand(Card(C_A, S_D), Card(C_8, S_D)); hand[14].SetHand(Card(C_K, S_D), Card(C_6, S_D)); hand[15].SetHand(Card(C_J, S_D), Card(C_T, S_D)); hand[16].SetHand(Card(C_K, S_D), Card(C_A, S_D)); hand[17].SetHand(Card(C_A, S_D), Card(C_T, S_D)); hand[18].SetHand(Card(C_Q, S_D), Card(C_4, S_D)); hand[19].SetHand(Card(C_3, S_D), Card(C_2, S_D)); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { _nbHand[0][i] = hand[i].NbHandAll(); hand[i][0].suit = S_H; hand[i][1].suit = (hand[i][0].face == hand[i][1].face) ? S_S : S_H; _nbHand[1][i] = hand[i].NbHandAll(); } ZeroMemory(_force, sizeof(_force)); tpBooleanDeck deck = _deck; tpCard cards[5] = { _board[0], _board[1], _board[2], _board[3] }; for (int i = 0; i < CN_STREETDAT_UNIT; i++) { int nbH = GetNbHand(0, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(0, k, i) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } for (int i = 0; i < CN_STREETDAT_UNIT; i++) { int nbH = GetNbHand(1, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(1, k, i) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } } //--------------------------------------------------------------------------------------------------------------------------------------------------- void RecalcStreetDat(clStreetDat &datQ, clStreetDat &dat100) { clStreetDat dat; for (int nbPl = 0; nbPl < 2; nbPl++) { vector <tpStreetDatGH> &vectQ = datQ._vectUnit[nbPl]; vector <tpStreetDatGH> &vect100 = dat100._vectUnit[nbPl]; vector <tpStreetDatGH> &vect = dat._vectUnit[nbPl]; int dim = vectQ.size(); int dim100 = vect100.size(); vect.resize(dim); int nbR[ALL_CN_HAND]; memset(nbR, -1, sizeof(nbR)); for (int i = 0; i < dim100; i++) nbR[vect100[i]._nb] = i; for (int i = 0; i < dim; i++) { int nb = vectQ[i]._nb; if (nbR[nb] != -1) vect[i] = vect100[nbR[nb]]; else vect[i]._nb = -1; } int nbF = 0; for (; nbF < dim; nbF++) if (vect[nbF]._nb != -1) break; for (int i = 0; i < nbF; i++) { vect[i]._force = vect[nbF]._force; vect[i]._force50 = vect[nbF]._force50; vect[i]._nb = vectQ[i]._nb; vect[i]._weight = vectQ[i]._weight; } int nbL = dim-1; for (; nbF >= 0; nbF--) if (vect[nbF]._nb != -1) break; for (int i = dim-1; i > nbL; i--) { vect[i]._force = vect[nbL]._force; vect[i]._force50 = vect[nbL]._force50; vect[i]._nb = vectQ[i]._nb; vect[i]._weight = vectQ[i]._weight; } int j = nbF+1; while (j < nbL) { for (; j <= nbL; j++) if (vect[j]._nb != -1) break; for (int i = nbF + 1; i < j; i++) { float dF = vectQ[nbF].Distance(vectQ[i]); float dL = vectQ[j].Distance(vectQ[i]); float sum = dF + dL; if (sum > DOUBLE_0) { float kF = dL / sum; float kL = dF / sum; vect[i]._force = vect[nbF]._force*kF + vect[j]._force*kL; vect[i]._force50 = vect[nbF]._force50*kF + vect[j]._force50*kL; vect[i]._nb = vectQ[i]._nb; vect[i]._weight = vectQ[i]._weight; } } nbF = j++; } } dat.Copy50AndSort(); datQ = dat; } //--------------------------------------------------------------------------------------------------------------------------------------------------- bool clRootStreetTree::CreateTurnDatQuick(clStreetDat &dat) { int dim0 = CnHand(0), dim1 = CnHand(1); dat._vectUnit[0].resize(dim0); dat._vectUnit[1].resize(dim1); for (int i = 0; i < dim0; i++) { glTrasser.WriteMessage(i); int nb = NbHand(0, i); tpHand hand(nb); int nbF = GetTurnHandIndex(_cards, hand); dat._vectUnit[0][i] = { nb,0,glVectTurnEV100[nbF],glVectTurnEV50[nbF] }; } for (int i = 0; i < dim1; i++) { int nb = NbHand(1, i); tpHand hand(nb); int nbF = GetTurnHandIndex(_cards, hand); dat._vectUnit[1][i] = { nb,0,glVectTurnEV100[nbF],glVectTurnEV50[nbF] }; } float w = 0; for (int i0 = 0; i0 < dim0; i0++) { int nb0 = NbHand(0, i0); for (int i1 = 0; i1 < dim1; i1++) { int nb1 = NbHand(1, i1); if (!HandCrossHandNB(nb0, nb1)) { float ww = _gh[0][nb0] * _gh[1][nb1]; dat._vectUnit[0][i0]._weight += ww; dat._vectUnit[1][i1]._weight += ww; w += ww; } } } for (int i = 0; i < dim0; i++) dat._vectUnit[0][i]._weight /= w; for (int i = 0; i < dim1; i++) dat._vectUnit[1][i]._weight /= w; dat.Copy50AndSort(); clRootStreetTree rr; rr._sit = _sit; rr._gh[0] = _gh[0]; rr._gh[1] = _gh[1]; rr.CompactGH(0.01, 100, dat); clStreetDat dd; if (!rr.CreateStreetDat(dd)) return false; RecalcStreetDat(dat, dd); dat._k = 1; dat._stack[0] = _sit.PlayerMoney(0); dat._stack[1] = _sit.PlayerMoney(1); dat._pot = _sit.TotalPot(); return true; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- #ifdef TURN_FULLTREE #else //-------------------------------------------------------------------------------------------------------------------------------------------------------------- int clRootStreetTree::ReadFileAndPrepare(int handle) { clRoot::ReadFile(handle); CalcAll(); return 0; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::operator = (clRootStreetTree &root) { *((clRoot *)this) = *((clRoot*)&root); _force = root._force; _prAllIn = root._prAllIn; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CreateTreeNL() { _tree.ClearAllBranch(); _tree.GetSit() = _sit; BuildTreeNLAuto(&_tree, _sit, _sit.NameTrade()); CalcAll(); int arrCls[] = { CnHand(0),CnHand(1) }; _tree.SetStartParam(arrCls); _tree.SetResSit(); #ifdef NB_NODE int nb = 0; int cnNode = _tree.SetNbNode(nb); #endif } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void CutTreeS(clHoldemTree *node) { if (node->Indicator() == -1 && node->CnBranch() == 1) node->ClearAllBranch(); else for (int i = 0; i < node->CnBranch(); i++) CutTreeS(node->Branch(i)); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CutTree() { CutTreeS(&_tree); _tree.SetResSit(); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::CalcForceFlop() { _force.resize(ALL_CN_HAND*CN_CARD_COL*CN_CARD_COL); ZeroMemory(&_force[0], ALL_CN_HAND*CN_CARD_COL*CN_CARD_COL * sizeof(int)); tpBooleanDeck deck; tpCard cards[5]; for (int i = 0; i < 3; i++) { cards[i] = _sit.CardsTable()[i]; deck.Skip(cards[i]); } bool calcH[ALL_CN_HAND]; ZeroMemory(calcH, sizeof(calcH)); int dim = CnHand(0); for (int i = 0; i < dim; i++) { int nbH = NbHand(0, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[3] = k; for (int k1 = k + 1; k1 < CN_CARD_COL; k1++) if (deck[k1]) { cards[4] = k1; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); int f = glVectRiverHandGame[nbR].ToInt(); Force(k, k1, nbH) = f; Force(k1, k, nbH) = f; } } deck[hand[0]] = true; deck[hand[1]] = true; calcH[nbH] = true; } dim = CnHand(1); for (int i = 0; i < dim; i++) { int nbH = NbHand(1, i); if (calcH[nbH]) continue; tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[3] = k; for (int k1 = k + 1; k1 < CN_CARD_COL; k1++) if (deck[k1]) { cards[4] = k1; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); int f = glVectRiverHandGame[nbR].ToInt(); Force(k, k1, nbH) = f; Force(k1, k, nbH) = f; } } deck[hand[0]] = true; deck[hand[1]] = true; } }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CalcAllIn() { if (_sit.NameTrade() == TRADE_TURN) CalcAllInTurn(); //else //CalcAllInFlop(); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CalcAllInTurn() { if (_force.size() == 0) CalcForceTurn(_force); tpBooleanDeck deck; tpCard cards[5]; int cnRiver = 44; for (int i = 0; i < 4; i++) { cards[i] = _sit.CardsTable()[i]; deck.Skip(cards[i]); } int dim0 = CnHand(0), dim1 = CnHand(1); _prAllIn.SetDim(dim0, dim1); _prAllIn.ZeroData(); for (int k0 = 0; k0 < dim0; k0++) { int nb0 = NbHand(0, k0); tpHand hand0(nb0); deck[hand0[0]] = false; deck[hand0[1]] = false; for (int k1 = 0; k1 < dim1; k1++) { int nb1 = NbHand(1, k1); if (HandCrossHandNB(nb0, nb1)) continue; tpHand hand1(nb1); deck[hand1[0]] = false; deck[hand1[1]] = false; //tpFloat val = _gh[0][nb0] * _gh[1][nb1]; tpFloat ev = 0; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { if (Force(k, nb0) > Force(k, nb1)) ev += 1; else if (Force(k, nb0) == Force(k, nb1)) ev += 0.5; } _prAllIn.Element(k0, k1, 0) = ev / cnRiver; deck[hand1[0]] = true; deck[hand1[1]] = true; } deck[hand0[0]] = true; deck[hand0[1]] = true; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::CalcAllInFlop() { if (_force.size() == 0) CalcForceFlop(); InitDeck(); int dim0 = CnHand(0), dim1 = CnHand(1); _prAllIn.SetDim(dim0, dim1); _prAllIn.ZeroData(); for (int k0 = 0; k0 < dim0; k0++) { int nb0 = NbHand(0, k0); tpHand hand0(nb0); for (int k1 = 0; k1 < dim1; k1++) { int nb1 = NbHand(1, k1); if (HandCrossHandNB(nb0, nb1)) continue; tpHand hand1(nb1); _prAllIn.Element(k0, k1, 0) = FlopAllInResult(nb0, nb1, _cards); } } }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CalcMultiHandsTree(size_t cnCalc) { vector <tpFloat> gh[2]; vector <float> ev[2]; CreateCompactGH(gh); ev[0].resize(CnHand(0)); ev[1].resize(CnHand(1)); for (int i = 0; i < cnCalc; i++) { //glTrasser.WriteMessage(i); CalcNeshMultiHandsTree(&_tree, 0, gh[0], gh[1], ev[0]); CalcNeshMultiHandsTree(&_tree, 1, gh[1], gh[0], ev[1]); } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CalcEVMultiHands(clHoldemTree *node, int nbHero, vector <tpFloat> &kH, vector <tpFloat> &kOpp, vector <float> &ev) { int ind = node->Indicator(); if (node->EndedNode()) return ResultMultiHandsTree(node, nbHero, kH, kOpp, ev); int dim = node->AtrTree()->CnClasters(); int cnB = node->CnBranch(); tpFloat *w = new tpFloat[cnB*dim]; ZeroMemory(w, cnB*dim * sizeof(tpFloat)); ZeroMemory(&ev[0], ev.size() * sizeof(float)); if (ind == nbHero) { node->AtrTree()->GetAllWeightStrat(cnB, w); vector <float> evCur[MAX_CN_BRANCH]; vector <tpFloat> kCur; for (int k = 0; k < cnB; k++) { kCur = kH; evCur[k].resize(dim); for (int i = 0; i < dim; i++) kCur[i] *= w[i*cnB + k]; CalcEVMultiHands(node->Branch(k), nbHero, kCur, kOpp, evCur[k]); for (int i = 0; i < dim; i++) ev[i] += evCur[k][i] * w[i*cnB + k]; } } else { int dimEV = ev.size(); node->AtrTree()->GetAllWeightStrat(cnB, w); vector <float> evCur(dimEV); vector <tpFloat> kCur; for (int k = 0; k < cnB; k++) { kCur = kOpp; for (int i = 0; i < dim; i++) kCur[i] *= w[i*cnB + k]; CalcEVMultiHands(node->Branch(k), nbHero, kH, kCur, evCur); for (int i = 0; i < dimEV; i++) ev[i] += evCur[i]; } } delete w; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CalcEvTree(vector <float> *evIn, tpUnfindTree *ut) { evIn[0].resize(ALL_CN_HAND); evIn[1].resize(ALL_CN_HAND); ZeroMemory(&evIn[0][0], ALL_CN_HAND * sizeof(float)); ZeroMemory(&evIn[1][0], ALL_CN_HAND * sizeof(float)); vector <tpFloat> gh[2]; vector <float> ev[2]; CreateCompactGH(gh); int dim0 = CnHand(0), dim1 = CnHand(1); ev[0].resize(dim0); ev[1].resize(dim1); CalcEVMultiHands(&_tree, 0, gh[0], gh[1], ev[0]); CalcEVMultiHands(&_tree, 1, gh[1], gh[0], ev[1]); for (int i = 0; i < dim0; i++) { int nbH = NbHand(0, i); tpFloat k = 0; for (int i1 = 0; i1 < dim1; i1++) if (!HandCrossHandNB(nbH, NbHand(1, i1))) k += gh[1][i1]; if (k > DOUBLE_0) evIn[0][nbH] = ev[0][i] / k; } for (int i = 0; i < dim1; i++) { int nbH = NbHand(1, i); tpFloat k = 0; for (int i0 = 0; i0 < dim0; i0++) if (!HandCrossHandNB(nbH, NbHand(0, i0))) k += gh[0][i0]; if (k > DOUBLE_0) evIn[1][nbH] = ev[1][i] / k; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::ResultMultiHands(clHoldemTree *node, int nbHero, vector <tpFloat> &kH, vector <tpFloat> &kOpp, vector <float> &ev, tpUnfindTree *ut) { int *ptr = (int *)&node->AtrTree()->_param[0]; int opp = (nbHero == 0) ? 1 : 0; int dimH = CnHand(nbHero); int dimOpp = CnHand(opp); ZeroMemory(&ev[0], dimH * sizeof(float)); if (node->GetSit().CNPlayerIsCard() == 1) //Fold { for (int i0 = 0; i0 < dimH; i0++) { int nbH = NbHand(nbHero, i0); for (int i1 = 0; i1 < dimOpp; i1++) if (!HandCrossHandNB(nbH, NbHand(opp, i1))) ev[i0] += ptr[nbHero] * kOpp[i1]; } } else if (node->GetSit().CNPlayerInTrade() < 2) //AllIn { if (nbHero == 0) for (int i0 = 0; i0 < dimH; i0++) { int nbH = NbHand(nbHero, i0); for (int i1 = 0; i1 < dimOpp; i1++) if (!HandCrossHandNB(nbH, NbHand(opp, i1))) { float win = PrAllIn(i0, i1); float res0 = ptr[0] * win + ptr[4] * (1 - win); ev[i0] += res0 * kOpp[i1]; } } else for (int i0 = 0; i0 < dimH; i0++) { int nbH = NbHand(nbHero, i0); for (int i1 = 0; i1 < dimOpp; i1++) if (!HandCrossHandNB(nbH, NbHand(opp, i1))) { float win = PrAllIn(i1, i0); tpFloat resH = ptr[5] * (1 - win) + ptr[1] * win; ev[i0] += resH * kOpp[i1]; } } } else { clNodeBank *bank; if (_sit.NameTrade() == TRADE_TURN) { bank = &glTurnNodeBank; } else { bank = &glFlopNodeBank; } clRootStreetTree root; root._sit = node->GetSit(); root._gh[nbHero].SetDim(ALL_CN_HAND); root._gh[nbHero].ClearDat(); for (int i = 0; i < dimH; i++) root._gh[nbHero][NbHand(nbHero, i)] = kH[i]; root._gh[opp].SetDim(ALL_CN_HAND); root._gh[opp].ClearDat(); for (int i = 0; i < dimOpp; i++) root._gh[opp][NbHand(opp, i)] = kOpp[i]; root.CalcIndex(); if (root.CnHand(0) == 0 || root.CnHand(1) == 0) return; root.CalcForce(); vector <float> evCur(ALL_CN_HAND); int stB = bank->FillEV(&root, nbHero, evCur, ut); double mult = ((double)root._sit.PlMoney(0)) / stB; for (int i = 0; i < dimH; i++) ev[i] = evCur[NbHand(nbHero, i)] * mult; for (int i = 0; i < dimH; i++) { int nbH = NbHand(nbHero, i); double sum = 0; for (int iOpp = 0; iOpp < dimOpp; iOpp++) { int nbOpp = NbHand(opp, iOpp); if (HandCrossHandNB(nbH, nbOpp)) continue; sum += kOpp[iOpp]; } ev[i] *= sum; } } }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void CalcKHand(clRoot *root, vector <float> *kHand) { ZeroMemory(&kHand[0][0], kHand[0].size() * sizeof(float)); ZeroMemory(&kHand[1][0], kHand[1].size() * sizeof(float)); int dim0 = root->CnHand(0), dim1 = root->CnHand(1); for (int i0 = 0; i0 < dim0; i0++) { int nb0 = root->NbHand(0, i0); for (int i1 = 0; i1 < dim1; i1++) { int nb1 = root->NbHand(1, i1); if (!HandCrossHandNB(nb0, nb1)) { kHand[0][nb0] += root->_gh[1][nb1]; kHand[1][nb1] += root->_gh[0][nb0]; } } } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::ResultMultiHandsTree(clHoldemTree *node, int nbHero, vector <tpFloat> &kH, vector <tpFloat> &kOpp, vector <float> &ev) { int *ptr = (int *)&node->AtrTree()->_param[0]; int opp = (nbHero == 0) ? 1 : 0; int dimH = CnHand(nbHero); int dimOpp = CnHand(opp); ZeroMemory(&ev[0], dimH * sizeof(float)); if (node->GetSit().CNPlayerIsCard() == 1) //Fold { for (int i0 = 0; i0 < dimH; i0++) { int nbH = NbHand(nbHero, i0); for (int i1 = 0; i1 < dimOpp; i1++) if (!HandCrossHandNB(nbH, NbHand(opp, i1))) ev[i0] += ptr[nbHero] * kOpp[i1]; } } else if (node->GetSit().CNPlayerInTrade() < 2) //AllIn { if (nbHero == 0) for (int i0 = 0; i0 < dimH; i0++) { int nbH = NbHand(nbHero, i0); for (int i1 = 0; i1 < dimOpp; i1++) if (!HandCrossHandNB(nbH, NbHand(opp, i1))) { float win = PrAllIn(i0, i1); float res0 = ptr[0] * win + ptr[4] * (1 - win); ev[i0] += res0 * kOpp[i1]; } } else for (int i0 = 0; i0 < dimH; i0++) { int nbH = NbHand(nbHero, i0); for (int i1 = 0; i1 < dimOpp; i1++) if (!HandCrossHandNB(nbH, NbHand(opp, i1))) { float win = PrAllIn(i1, i0); tpFloat resH = ptr[5] * (1 - win) + ptr[1] * win; ev[i0] += resH * kOpp[i1]; } } } else { clRootRiverTree rr; rr._sit = node->GetSit(); rr._sit.ExecAct(HistAction(NB_DILER, ACT_DELRIVER, 0)); vector <float> evCur(ALL_CN_HAND); vector <float> kHand[2] = { vector <float>(ALL_CN_HAND),vector <float>(ALL_CN_HAND) }; ev.resize(ALL_CN_HAND); ZeroMemory(&ev[0], ALL_CN_HAND * sizeof(float)); float w0[ALL_CN_HAND]; ZeroMemory(w0, sizeof(w0)); tpBooleanDeck deck; for (int i = 0; i < _sit.CnCardTable(); i++) deck.Skip(_sit.CardsTable()[i].Number()); clHandsGroupEx ghIn[2]; ghIn[0]._vect.resize(ALL_CN_HAND); ghIn[0].ClearDat(); ghIn[1]._vect.resize(ALL_CN_HAND); ghIn[1].ClearDat(); for (int i = 0; i < dimH; i++) ghIn[nbHero][NbHand(nbHero, i)] = kH[i]; for (int i = 0; i < dimOpp; i++) ghIn[opp][NbHand(opp, i)] = kOpp[i]; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { //glTrasser.WriteMessage(k); rr._gh[0] = ghIn[0]; rr._gh[1] = ghIn[1]; rr._gh[0].SkipPreFlopAllHands(k); rr._gh[1].SkipPreFlopAllHands(k); rr.CalcIndex(); CalcKHand(&rr, kHand); rr._gh[0].Norm(); rr._gh[1].Norm(); rr._sit.CardsTable()[4] = CardNB(k); if (rr.CnHand(0) == 0 || rr.CnHand(1) == 0) continue; rr.CalcForce(); glTime2 = k; int st0 = glBankRiver.FillRiverEV(&rr, nbHero, evCur); tpFloat f0 = (tpFloat)_sit.PlMoney(0) / st0; for (int i = 0; i < rr.CnHand(nbHero); i++) { int nb = rr.NbHand(nbHero, i); ev[nb] += evCur[nb] * kHand[nbHero][nb] * f0; w0[nb] += kHand[nbHero][nb]; } } for (int i = 0; i < dimH; i++) { int nbH = NbHand(nbHero, i); if (w0[nbH] > DOUBLE_0) { double sum = 0; for (int iOpp = 0; iOpp < dimOpp; iOpp++) { int nbOpp = NbHand(opp, iOpp); if (HandCrossHandNB(nbH, nbOpp)) continue; sum += kOpp[iOpp]; } ev[i] *= sum / w0[nbH]; } } } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::AddResEVMultiHands(clHoldemTree *node, int nbHero, int cnB, vector <float> &resEV, vector <float> *evCur, tpFloat *w, vector <tpFloat> &kH, vector <tpFloat> &kOpp) { int opp = (nbHero == 0) ? 1 : 0; int dim = CnHand(nbHero), dimOpp = CnHand(opp); for (int i = 0; i < dim; i++) { int nbH = NbHand(nbHero, i); tpFloat ev[MAX_CN_BRANCH]; for (int k = 0; k < cnB; k++) ev[k] = evCur[k][i]; tpFloat kOpp1 = 0; for (int i1 = 0; i1 < dimOpp; i1++) if (!HandCrossHandNB(nbH, NbHand(opp, i1))) kOpp1 += kOpp[i1]; clCalcParam cls = node->AtrTree()->CalcParam(i); cls.AddResEV(cnB, resEV[i], w + i*cnB, ev, kH[i], kOpp1); #ifdef VIEW_PARAM tpCalcParam par0; par0.LoadParam(cls, cnB); par0; #endif } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::CalcNeshMultiHands(clHoldemTree *node, int nbHero, vector <tpFloat> &kH, vector <tpFloat> &kOpp, vector <float> &ev, tpUnfindTree *ut) { //glTrasser.WriteMessage(node->_val->_nbNode); int ind = node->Indicator(); if (node->EndedNode()) return ResultMultiHands(node, nbHero, kH, kOpp, ev, ut); int dim = node->AtrTree()->CnClasters(); int cnB = node->CnBranch(); tpFloat *w = new tpFloat[cnB*dim]; ZeroMemory(w, cnB*dim * sizeof(tpFloat)); ZeroMemory(&ev[0], ev.size() * sizeof(float)); if (ind == nbHero) { node->AtrTree()->GetAllWeightNoNull(cnB, w); vector <float> evCur[MAX_CN_BRANCH]; vector <tpFloat> kCur; for (int k = 0; k < cnB; k++) { kCur = kH; evCur[k].resize(dim); for (int i = 0; i < dim; i++) kCur[i] *= w[i*cnB + k]; CalcNeshMultiHands(node->Branch(k), nbHero, kCur, kOpp, evCur[k], ut); //vector <float> vvv; vvv = evCur[k]; for (int i = 0; i < dim; i++) ev[i] += evCur[k][i] * w[i*cnB + k]; } AddResEVMultiHands(node, nbHero, cnB, ev, evCur, w, kH, kOpp); } else { int dimEV = ev.size(); node->AtrTree()->GetAllWeight(cnB, w); vector <float> evCur(dimEV); vector <tpFloat> kCur; for (int k = 0; k < cnB; k++) { kCur = kOpp; for (int i = 0; i < dim; i++) kCur[i] *= w[i*cnB + k]; CalcNeshMultiHands(node->Branch(k), nbHero, kH, kCur, evCur, ut); for (int i = 0; i < dimEV; i++) ev[i] += evCur[i]; } } delete w; }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CalcNeshMultiHandsTree(clHoldemTree *node, int nbHero, vector <tpFloat> &kH, vector <tpFloat> &kOpp, vector <float> &ev) { //glTrasser.WriteMessage(node->_val->_nbNode); int ind = node->Indicator(); if (node->EndedNode()) return ResultMultiHandsTree(node, nbHero, kH, kOpp, ev); int dim = node->AtrTree()->CnClasters(); int cnB = node->CnBranch(); tpFloat *w = new tpFloat[cnB*dim]; ZeroMemory(w, cnB*dim * sizeof(tpFloat)); ZeroMemory(&ev[0], ev.size() * sizeof(float)); if (ind == nbHero) { node->AtrTree()->GetAllWeightNoNull(cnB, w); vector <float> evCur[MAX_CN_BRANCH]; vector <tpFloat> kCur; for (int k = 0; k < cnB; k++) { kCur = kH; evCur[k].resize(dim); for (int i = 0; i < dim; i++) kCur[i] *= w[i*cnB + k]; CalcNeshMultiHandsTree(node->Branch(k), nbHero, kCur, kOpp, evCur[k]); vector <float> vvv; vvv = evCur[k]; for (int i = 0; i < dim; i++) ev[i] += evCur[k][i] * w[i*cnB + k]; } AddResEVMultiHands(node, nbHero, cnB, ev, evCur, w, kH, kOpp); } else { int dimEV = ev.size(); node->AtrTree()->GetAllWeight(cnB, w); vector <float> evCur(dimEV); vector <tpFloat> kCur; for (int k = 0; k < cnB; k++) { kCur = kOpp; for (int i = 0; i < dim; i++) kCur[i] *= w[i*cnB + k]; CalcNeshMultiHandsTree(node->Branch(k), nbHero, kH, kCur, evCur); for (int i = 0; i < dimEV; i++) ev[i] += evCur[i]; } } delete w; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::SetWeightStrat() { _tree.ClearStatWeight(); int cn0 = CnHand(0), cn1 = CnHand(1); enNameTrade trade = _sit.NameTrade(); for (int i0 = 0; i0 < cn0; i0++) { int nb0 = NbHand(0, i0); for (int i1 = 0; i1 < cn1; i1++) { int nb1 = NbHand(1, i1); if (HandCrossHandNB(nb0, nb1)) continue; tpTreePlayerInfo info; info._nbCls[trade][0] = i0; info._nbCls[trade][1] = i1; double w0[] = { _gh[0][nb0],_gh[1][nb1] }; _tree.SetWeightStrat(&info, w0); } } _tree.CalcWeightStat(); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- bool clRootStreetTree::CreateStreetDat(clStreetDat &dat) { if (_sit.NameTrade() == TRADE_TURN) return CreateTurnDat(dat); else { /* if (CnHand(0) > CN_HANDS_FORBD || CnHand(1) > CN_HANDS_FORBD) { clStreetDat datC, datQ; clRootStreetTree root = *this; CreateFlopDatQuick(dat); root.CompactGH(1, CN_HANDS_FORBD, &dat); root.CreateFlopDatQuick(datQ); + root.CreateFlopDat(datC); ReCalcFlopDat(dat, datQ, datC); } else CreateFlopDat(dat);*/ //CreateFlopDatQuick(dat); } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::CreateStreetDatQuick(clStreetDat &dat) { if (_sit.NameTrade() == TRADE_TURN) CreateTurnDatQuick(dat); else CreateFlopDatQuick(dat); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- size_t clRootStreetTree::CnMultiHandsCalc() { int cn= CnHand(_tree.Indicator()); if (cn == 0) { CalcIndex(); cn = CnHand(_tree.Indicator()); } return _tree.CnCalc() / cn; }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- struct tp3Float { float _force, _force50, _weight; }; bool Compare3Float(tp3Float val1, tp3Float val2) { return (val1._force50 < val2._force50); } /*void FillDatFlop(clRootStreetTree *root, int nbHero, vector <tpStreetDatGH> &vect, tp2Float *val, tpFloat wSum) { tpBooleanDeck deck; for (int i = 0; i < root->_sit.CnCardTable(); i++) deck.Skip(root->_sit.CardsTable()[i].Number()); int dim = root->CnHand(nbHero); tp3Float *arr = new tp3Float[dim*CN_CARD_COL]; ZeroMemory(arr, dim*CN_CARD_COL * sizeof(tp3Float)); vect.resize(dim); for (int i = 0; i < dim; i++) { int nb = root->NbHand(nbHero, i); tpHand hand(nb); deck[hand[0]] = false; deck[hand[1]] = false; for (int kT = 0; kT < CN_CARD_COL; kT++) if (deck[kT]) for (int kR = kT + 1; kR < CN_CARD_COL; kR++) if (deck[kR]) { int ind = i*CN_CARD_COL*CN_CARD_COL + kT*CN_CARD_COL + kR; int indR = i*CN_CARD_COL*CN_CARD_COL + kR*CN_CARD_COL + kT; if (val[ind]._weight > DOUBLE_0) val[ind]._force /= val[ind]._weight; else val[ind]._force = 0; val[indR] = val[ind]; // заполняем реверсные поля } vect[i]._nb = nb; tp2Float *ptrT = &val[i*CN_CARD_COL*CN_CARD_COL]; for (int kT = 0; kT < CN_CARD_COL; kT++) if (deck[kT]) { tp2Float *ptr = ptrT + kT*CN_CARD_COL; SortShell(CN_CARD_COL, ptr, Compare2Float); float sum = 0, wk = 0; int k = 0; for (; k < CN_CARD_COL / 2; k++) { sum += ptr[k]._force*ptr[k]._weight; wk += ptr[k]._weight; } float sum1 = 0, wk1 = 0; for (; k < CN_CARD_COL; k++) { sum1 += ptr[k]._force*ptr[k]._weight; wk1 += ptr[k]._weight; } int ind = i*CN_CARD_COL + kT; arr[ind]._weight += wk + wk1; arr[ind]._force = (sum + sum1) / (wk + wk1); arr[ind]._force50 = sum / wk; } tp3Float *ptr = arr + i*CN_CARD_COL; SortShell(CN_CARD_COL, ptr, Compare3Float); int k = 0; float sum = 0, wk = 0, sum50 = 0; for (; k < CN_CARD_COL / 2; k++) { sum += ptr[k]._force*ptr[k]._weight; sum50 += ptr[k]._force50*ptr[k]._weight; wk += ptr[k]._weight; } float wk1 = 0; for (; k < CN_CARD_COL; k++) { sum += ptr[k]._force*ptr[k]._weight; wk1 += ptr[k]._weight; } vect[i]._weight = (wk + wk1) / wSum; vect[i]._force = sum / (wk + wk1); vect[i]._force50 = sum50 / wk; deck[hand[0]] = true; deck[hand[1]] = true; } delete arr; }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::CreateFlopDat(clStreetDat &dat) { dat._k = K_FOR_FLOPDAT; InitDeck(); int dim0 = CnHand(0); int dim1 = CnHand(1); dat._vectUnit[0].resize(dim0); dat._vectUnit[1].resize(dim1); vector <tpStreetDatGH> &vect0 = dat._vectUnit[0]; vector <tpStreetDatGH> &vect1 = dat._vectUnit[1]; ZeroMemory(&vect0[0], dim0 * sizeof(tpStreetDatGH)); ZeroMemory(&vect1[0], dim1 * sizeof(tpStreetDatGH)); double w = 0; for (int i0 = 0; i0 < dim0; i0++) { int nb0 = NbHand(0, i0); for (int i1 = 0; i1 < dim1; i1++) { int nb1 = NbHand(1, i1); if (HandCrossHandNB(nb0, nb1)) continue; double ww = _gh[0][nb0] * _gh[1][nb1]; float evF = FlopAllInResult(nb0, nb1, _cards); vect0[i0]._force += evF*ww; vect0[i0]._weight += ww; vect1[i1]._force += (1-evF)*ww; vect1[i1]._weight += ww; w += ww; } } for (int i0 = 0; i0 < dim0; i0++) { tpStreetDatGH &datE = vect0[i0]; datE._nb = NbHand(0,i0); if (datE._weight > DOUBLE_0) datE._force /= datE._weight; datE._weight /= w; tpHand hand(datE._nb); int nbF = GetFlopHandIndex(_cards, hand); datE._force50 = glVectFlopEV50[nbF]; } for (int i1 = 0; i1 < dim1; i1++) { tpStreetDatGH &datE = vect1[i1]; datE._nb = NbHand(1, i1); if (datE._weight > DOUBLE_0) datE._force /= datE._weight; datE._weight /= w; tpHand hand(datE._nb); int nbF = GetFlopHandIndex(_cards, hand); datE._force50 = glVectFlopEV50[nbF]; } dat.Copy50AndSort(); }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::CreateFlopDat(clStreetDat &dat) { if (_force.size() == 0) CalcForceFlop(); tpBooleanDeck deck; for (int i = 0; i < _sit.CnCardTable(); i++) deck.Skip(_sit.CardsTable()[i].Number()); int dim0 = CnHand(0), dim1 = CnHand(1); tp2Float *val0 = new tp2Float[dim0*CN_CARD_COL*CN_CARD_COL]; tp2Float *val1 = new tp2Float[dim1*CN_CARD_COL*CN_CARD_COL]; ZeroMemory(val0, dim0*CN_CARD_COL*CN_CARD_COL * sizeof(tp2Float)); ZeroMemory(val1, dim1*CN_CARD_COL*CN_CARD_COL * sizeof(tp2Float)); float w = 0; for (int i0 = 0; i0 < dim0; i0++) { int nb0 = NbHand(0, i0); tpHand hand0(nb0); deck[hand0[0]] = false; deck[hand0[1]] = false; for (int i1 = 0; i1 < dim1; i1++) { int nb1 = NbHand(1, i1); if (!HandCrossHandNB(nb0, nb1)) { tpHand hand1(nb1); deck[hand1[0]] = false; deck[hand1[1]] = false; for (int kT = 0; kT < CN_CARD_COL; kT++) if (deck[kT]) for (int kR = kT + 1; kR < CN_CARD_COL; kR++) if (deck[kR]) { float ww = _gh[0][nb0] * _gh[1][nb1]; int ind0 = i0*CN_CARD_COL*CN_CARD_COL + kT*CN_CARD_COL + kR, ind1 = i1*CN_CARD_COL*CN_CARD_COL + kT*CN_CARD_COL + kR; val0[ind0]._weight += ww; val1[ind1]._weight += ww; w += ww; int f0 = Force(kT, kR, nb0), f1 = Force(kT, kR, nb1); if (f0 > f1) val0[ind0]._force += ww; else if (f1 > f0) val1[ind1]._force += ww; else { val0[ind0]._force += ww / 2; val1[ind1]._force += ww / 2; } } deck[hand1[0]] = true; deck[hand1[1]] = true; } } deck[hand0[0]] = true; deck[hand0[1]] = true; } FillDatFlop(this, 0, dat._vectUnit[0], val0, w); FillDatFlop(this, 1, dat._vectUnit[1], val1, w); delete val0; delete val1; dat.Copy50AndSort(); }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void clRootStreetTree::CreateFlopDatQuick(clStreetDat &dat) { dat._k = K_FOR_FLOPDAT; InitDeck(); int dim0 = CnHand(0), dim1 = CnHand(1); dat._vectUnit[0].resize(dim0); dat._vectUnit[1].resize(dim1); for (int i = 0; i < dim0; i++) { int nb = NbHand(0, i); tpHand hand(nb); int nbF = GetFlopHandIndex(_cards, hand); dat._vectUnit[0][i] = { nb,0,glVectFlopEV100[nbF],glVectFlopEV50[nbF] }; } for (int i = 0; i < dim1; i++) { int nb = NbHand(1, i); tpHand hand(nb); int nbF = GetFlopHandIndex(_cards, hand); dat._vectUnit[1][i] = { nb,0,glVectFlopEV100[nbF],glVectFlopEV50[nbF] }; } float w = 0; for (int i0 = 0; i0 < dim0; i0++) { int nb0 = NbHand(0, i0); for (int i1 = 0; i1 < dim1; i1++) { int nb1 = NbHand(1, i1); if (!HandCrossHandNB(nb0, nb1)) { float ww = _gh[0][nb0] * _gh[1][nb1]; dat._vectUnit[0][i0]._weight += ww; dat._vectUnit[1][i1]._weight += ww; w += ww; } } } for (int i = 0; i < dim0; i++) dat._vectUnit[0][i]._weight /= w; for (int i = 0; i < dim1; i++) dat._vectUnit[1][i]._weight /= w; dat.Copy50AndSort(); }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void CreateSitStreet(clSitHoldem &sit, int stack, int pot, enNameTrade trade) { clStacks st; st.Init(100, 0, stack, stack); sit.Init(st); sit._arrAct.Clear(); sit.AddAct(POS_SB, ACT_POSTSB, sit.BigBlind() / 2); sit.AddAct(POS_BB, ACT_POSTBB, sit.BigBlind()); sit.AddAct(NB_DILER, ACT_DELCARD, 0); if (pot > 2 * sit.BigBlind()) { sit.AddAct(POS_SB, ACT_RAISE, pot / 2 - 0.5*sit.BigBlind()); sit.AddAct(POS_BB, ACT_CALL, pot / 2 - sit.BigBlind()); } else { sit.AddAct(POS_SB, ACT_CALL, 0.5*sit.BigBlind()); sit.AddAct(POS_BB, ACT_CHECK, 0); } sit.AddAct(NB_DILER, ACT_DELFLOP, 0); if (trade == TRADE_TURN) { sit.AddAct(POS_BB, ACT_CHECK, 0); sit.AddAct(POS_SB, ACT_CHECK, 0); sit.AddAct(NB_DILER, ACT_DELTURN, 0); } sit.ExecHist(sit.PtrHistory()); } //--------------------------------------------------------------------------------------------------------------------------------------------------- #endif struct tp2Float { float _force, _weight; }; bool CompareForce(tpStreetDatGH val1, tpStreetDatGH val2) { return (val1._force < val2._force); } bool CompareForce50(tpStreetDatGH val1, tpStreetDatGH val2) { return (val1._force50 < val2._force50); } bool clRootStreetTree::CreateTurnDat(clStreetDat &dat) { dat._k = 1; int stPl = (_sit.PlayerMoney(0) > _sit.PlayerMoney(1)) ? _sit.PlayerMoney(1) : _sit.PlayerMoney(0); dat._stack[0] = stPl; dat._stack[1] = stPl; dat._pot = _sit.TotalPot(); #ifdef TURN_FULLTREE vector <int> forceFull; CalcForceTurn(forceFull); #else if (_force.size() == 0) CalcForceTurn(_force); #endif tpBooleanDeck deck; for (int i = 0; i < _sit.CnCardTable(); i++) deck.Skip(_sit.CardsTable()[i].Number()); int dim0 = CnHand(0), dim1 = CnHand(1); tp2Float *val0 = new tp2Float[dim0*CN_CARD_COL]; tp2Float *val1 = new tp2Float[dim1*CN_CARD_COL]; ZeroMemory(val0, dim0*CN_CARD_COL * sizeof(tp2Float)); ZeroMemory(val1, dim1*CN_CARD_COL * sizeof(tp2Float)); float w = 0; for (int i0 = 0; i0 < dim0; i0++) { int nb0 = NbHand(0, i0); tpHand hand0(nb0); deck[hand0[0]] = false; deck[hand0[1]] = false; for (int i1 = 0; i1 < dim1; i1++) { int nb1 = NbHand(1, i1); if (!HandCrossHandNB(nb0, nb1)) { tpHand hand1(nb1); deck[hand1[0]] = false; deck[hand1[1]] = false; float ww = _gh[0][nb0] * _gh[1][nb1]; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { int ind0 = i0*CN_CARD_COL + k, ind1 = i1*CN_CARD_COL + k; val0[ind0]._weight += ww; val1[ind1]._weight += ww; w += ww; #ifdef TURN_FULLTREE int f0 = Force(forceFull, k, nb0), f1 = Force(forceFull, k, nb1); #else int f0 = Force(k, nb0), f1 = Force(k, nb1); #endif if (f0 > f1) val0[ind0]._force += ww; else if (f1 > f0) val1[ind1]._force += ww; else { val0[ind0]._force += ww / 2; val1[ind1]._force += ww / 2; } } deck[hand1[0]] = true; deck[hand1[1]] = true; } } deck[hand0[0]] = true; deck[hand0[1]] = true; } if (w < DOUBLE_0) return false; dat._vectUnit[0].resize(dim0); for (int i = 0; i < dim0; i++) { dat._vectUnit[0][i]._nb = NbHand(0, i); tp2Float *ptr = &val0[i*CN_CARD_COL]; int k = 0; float sum = 0, wk = 0, sum2 = 0; for (; k < CN_CARD_COL; k++) if (ptr[k]._weight > DOUBLE_0) { sum += ptr[k]._force; wk += ptr[k]._weight; sum2 += ptr[k]._force*ptr[k]._force / ptr[k]._weight; } if (wk > DOUBLE_0) { dat._vectUnit[0][i]._weight = wk / w; dat._vectUnit[0][i]._force = sum / wk; dat._vectUnit[0][i]._force50 = sqrt(sum2 / wk); } else { dat._vectUnit[0][i]._weight = 0; dat._vectUnit[0][i]._force = 0; dat._vectUnit[0][i]._force50 = 0; } } dat._vectUnit[1].resize(dim1); for (int i = 0; i < dim1; i++) { dat._vectUnit[1][i]._nb = NbHand(1, i); tp2Float *ptr = &val1[i*CN_CARD_COL]; int k = 0; float sum = 0, wk = 0, sum2 = 0; for (; k < CN_CARD_COL; k++) if (ptr[k]._weight > DOUBLE_0) { sum += ptr[k]._force; wk += ptr[k]._weight; sum2 += ptr[k]._force*ptr[k]._force / ptr[k]._weight; } if (wk > DOUBLE_0) { dat._vectUnit[1][i]._weight = wk / w; dat._vectUnit[1][i]._force = sum / wk; dat._vectUnit[1][i]._force50 = sqrt(sum2 / wk); } else { dat._vectUnit[1][i]._weight = 0; dat._vectUnit[1][i]._force = 0; dat._vectUnit[1][i]._force50 = 0; } } delete val0; delete val1; dat.Copy50AndSort(); return true; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void CompactRight(vector <tpStreetDatGH> &vect, int nb, double min) { int dim = vect.size(); int nb1 = FindUnit(vect, nb, dim, min); if (nb1 == -1) { tpStreetDatGH v; for (int i = nb + 1; i < dim; i++) { nb1 = CreateUnitVirtual(vect, i, dim, min, v); if(nb1 != -1) } } CompactBetween(vect, nb, nb1, min); CompactRight(vect, nb1, min); } int FindUnit(vector <tpStreetDatGH> &vect, int nb0, int nb1, double min) { for (int i = nb0; i < nb1; i++) if (vect[i]._weight > min) return i; return -1; } int CreateUnit(vector <tpStreetDatGH> &vect, int nb1, int nb2, double min) { int i = nb1; for (; i < nb2; i++) { if (vect[i]._weight > min) break; vect[i + 1] += vect[i]; vect[i]._weight = 0; } return i; } int CompactLeft(vector <tpStreetDatGH> &vect, int nb1, int nb2, double min) { int nb = nb1; tpStreetDatGH v = vect[nb1]; if (v._weight < min) for (nb++; nb < nb2; nb++) { v += vect[nb]; vect[nb]._weight = 0; if (v._weight > min) break; } if (nb < nb2 && vect[nb].Distance(v) < vect[nb].Distance(vect[nb2])) { CompactBetween(vect, nb, nb2, min); } else { vect[nb2] += v; for (int i = nb + 1; i < nb2; i++) { vect[nb2] += vect[i]; vect[i]._weight = 0; } } return nb2; } void CompactVectDat(vector <tpStreetDatGH> &vect, double min) { int dim = vect.size(), nb = 0; if (dim <= CN_STREETDAT_UNIT) return; if (vect[0]._weight < min) { nb = FindUnit(vect, 1, dim, min); if (nb == -1) nb = CreateUnit(vect, 0, dim, min); else nb = CompactLeft(vect, 0, nb); } CompactRight(vect, nb); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void CompactStreetDat(clStreetDat &dat, double min) { CompactVectDat(dat._vectUnit[0], min); CompactVectDat(dat._vectUnit[1], min); CompactVectDat(dat._vectUnit50[0], min); CompactVectDat(dat._vectUnit50[1], min); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CreateStreetDatMin(clStreetDat &dat, clStreetDat *datIn0) { clStreetDat dd; if (datIn0 == NULL) CreateStreetDat(dd); else dd = *datIn0; CompactStreetDat(dd, 0.01); ReCalcParam(&dd); CalcIndex(); //root.CalcForce(); FindMinParam(dd); CreateStreetDat(dat); }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CreateStreetDatMin(clStreetDat &dat, clStreetDat *datIn0) { clStreetDat *datIn = datIn0, dd; if (datIn0 == NULL) { CreateStreetDat(dd); datIn = &dd; } ReCalcParam(datIn); CalcIndex(); //root.CalcForce(); FindMinParam(*datIn); CreateStreetDat(dat); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CompactGH_H(double minW, int cnMin, int *nbIn, clStreetDat dat) { for (int nbPl = 0; nbPl < 2; nbPl++) { vector <tpStreetDatGH> &vect = dat._vectUnit[nbPl]; int nbH = nbIn[nbPl]; while (true) { int dim = vect.size(); //glTrasser.WriteMessage(dim); if (dim <= cnMin) break; int nb = (vect[0]._nb != nbH) ? 0 : 1; for (int i = 1; i < dim; i++) if (vect[i]._nb != nbH) if (vect[i]._weight < vect[nb]._weight) nb = i; if (vect[nb]._weight > minW) break; int nb1 = (nb == 0) ? 1 : 0; float dist = vect[nb].Distance(vect[nb1]); for (int i = nb1 + 1; i < dim; i++) { float val = vect[nb].Distance(vect[i]); if (val < dist) { dist = val; nb1 = i; } } vect[nb1]._weight += vect[nb]._weight; vect.erase(vect.begin() + nb); } _gh[nbPl].ClearDat(); int dim = vect.size(); for (int i = 0; i < dim; i++) _gh[nbPl][vect[i]._nb] = vect[i]._weight; _gh[nbPl].Norm(); } CalcIndex(); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clStreetDat::Copy50AndSort() { _vectUnit50[0] = _vectUnit[0]; _vectUnit50[1] = _vectUnit[1]; int dim0 = _vectUnit[0].size(), dim1 = _vectUnit[1].size(); SortShell(dim0, &_vectUnit[0][0], CompareForce); SortShell(dim1, &_vectUnit[1][0], CompareForce); SortShell(dim0, &_vectUnit50[0][0], CompareForce50); SortShell(dim1, &_vectUnit50[1][0], CompareForce50); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- tpFloat clStreetDat::Distance(clStreetDat &dat) { float res = 0; for (int k = 0; k < 2; k++) { int i = 0, j = 0; vector <tpStreetDatGH> &vectI = dat._vectUnit[k], &vectJ = _vectUnit[k]; int dimI = vectI.size(), dimJ = vectJ.size(); float ost = vectJ[j]._weight, weight = vectI[i]._weight; while (i < dimI) { if (weight < ost) { float val = vectJ[j]._force - vectI[i]._force; res += val*val*weight; ost -= weight; i++; if (i == dimI) break; weight = vectI[i]._weight; if (weight < DOUBLE_0) break; } else { float val = vectJ[j]._force - vectI[i]._force; res += val*val*ost; weight -= ost; j++; if (j == dimJ) break; ost = vectJ[j]._weight; } } } float res50 = 0; for (int k = 0; k < 2; k++) { int i = 0, j = 0; vector <tpStreetDatGH> &vectI = dat._vectUnit50[k], &vectJ = _vectUnit50[k]; int dimI = vectI.size(), dimJ = vectJ.size(); float ost = vectJ[j]._weight, weight = vectI[i]._weight; while (i < dimI) { if (weight < ost) { float val = vectJ[j]._force50 - vectI[i]._force50; res50 += val*val*weight; ost -= weight; i++; if (i == dimI) break; weight = vectI[i]._weight; if (weight < DOUBLE_0) break; } else { float val = vectJ[j]._force50 - vectI[i]._force50; res50 += val*val*ost; weight -= ost; j++; if (j == dimJ) break; ost = vectJ[j]._weight; } } } res = sqrt((res + _k*res50) / (1 + _k)); float st = float(_stack[0]) / _pot, datSt = float(dat._stack[0]) / dat._pot; float ds = (datSt > st) ? (datSt - st) / datSt : (st - datSt) / st; return (res + ds); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CalcForceTurn(vector <int> &force) { force.resize(ALL_CN_HAND*CN_CARD_COL); ZeroMemory(&force[0], ALL_CN_HAND*CN_CARD_COL * sizeof(int)); tpBooleanDeck deck; tpCard cards[5]; for (int i = 0; i < 4; i++) { cards[i] = _sit.CardsTable()[i]; deck.Skip(cards[i]); } int dim = CnHand(0); for (int i = 0; i < dim; i++) { int nbH = NbHand(0, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(force, k, nbH) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } dim = CnHand(1); for (int i = 0; i < dim; i++) { int nbH = NbHand(1, i); tpHand hand(nbH); deck[hand[0]] = false; deck[hand[1]] = false; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { if (Force(force, k, nbH) != 0) break; cards[4] = k; int nbT, nbR = GetTurnAndRiverHandIndex(cards, hand, nbT); Force(force, k, nbH) = glVectRiverHandGame[nbR].ToInt(); } deck[hand[0]] = true; deck[hand[1]] = true; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::ReCalcParam(clStreetDat *datIn) { clStreetDat datCur, *dat; if (datIn == NULL) { dat = &datCur; CreateStreetDat(*dat); } else dat = datIn; for (int nbPl = 0; nbPl < 2; nbPl++) { clClasters <tpStreetDatGH> cls; vector <tpStreetDatGH> &vect = dat->_vectUnit[nbPl]; int dim = vect.size(); cls.Resize(CN_STREETDAT_UNIT); if (CN_STREETDAT_UNIT > dim) { for (int i = 0; i < CN_STREETDAT_UNIT; i++) { cls[i].resize(1); if (i < dim) cls[i][0] = vect[i]; else cls[i][0] = { i,0,0,0 }; } } else { /*int cur = 0; for (int i = 0; i < CN_STREETDAT_UNIT; i++) { int cn = (dim - cur) / (CN_STREETDAT_UNIT - i); cls[i].resize(cn); memcpy(&cls[i][0], &vect[cur], cn * sizeof(tpStreetDatGH)); cur += cn; }*/ int k = 0, cur = 0; float step = 1. / CN_STREETDAT_UNIT, sum = 0, val = 0; for (int i = 0; i < CN_STREETDAT_UNIT - 1; i++) { val += step; for (; k < dim; k++) { sum += vect[k]._weight; if (sum >= val) break; } if (dim - k < CN_STREETDAT_UNIT - i) k = dim - CN_STREETDAT_UNIT + i; k++; int cn = k - cur; cls[i].resize(cn); memcpy(&cls[i][0], &vect[cur], cn * sizeof(tpStreetDatGH)); cur = k; } int cn = dim - cur; cls[CN_STREETDAT_UNIT - 1].resize(cn); memcpy(&cls[CN_STREETDAT_UNIT - 1][0], &vect[cur], cn * sizeof(tpStreetDatGH)); for (int i = 0; i < 5; i++) if (!cls.ReStraightClasters()) break; } dim = cls.CnClasters(); double w0[200]; for (int i = 0; i < dim; i++) { int dim0 = cls[i].size(); for (int k = 1; k < dim0; k++) cls[i][0]._weight += cls[i][k]._weight; w0[i] = cls[i][0]._weight; if (w0[i] < DOUBLE_0) w0[i] = 10 * DOUBLE_0; } _gh[nbPl].ClearDat(); for (int i = 0; i < dim; i++) _gh[nbPl][glTDD.GetNbHand(nbPl, i)] = w0[i]; _gh[nbPl].Norm(); } memcpy(_sit.CardsTable(), glTDD._board, sizeof(glTDD._board)); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- /*void NormDatTurnEx(vector <float> &gh, int nbH, double w0) { double sum = 0; int dim = gh.size(); for (int i = 0; i < dim; i++) sum += gh[i]; for (int i = 0; i < dim; i++) gh[i] /= sum; }*/ //-------------------------------------------------------------------------------------------------------------------------------------------------------------- float CreateStreetDatForMinNew(clStreetDat &dat, vector <float> *gh) { ErrMessage("CreateStreetDatForMinNew ", "Не реализованная функция"); tp2Float *val0 = new tp2Float[CN_STREETDAT_UNIT*CN_CARD_COL]; tp2Float *val1 = new tp2Float[CN_STREETDAT_UNIT*CN_CARD_COL]; ZeroMemory(val0, CN_STREETDAT_UNIT*CN_CARD_COL * sizeof(tp2Float)); ZeroMemory(val1, CN_STREETDAT_UNIT*CN_CARD_COL * sizeof(tp2Float)); float w = 0; for (int i0 = 0; i0 < CN_STREETDAT_UNIT; i0++) { int nb0 = glTDD.GetNbHand(0, i0); for (int i1 = 0; i1 < CN_STREETDAT_UNIT; i1++) { int nb1 = glTDD.GetNbHand(1, i1); float ww = gh[0][i0] * gh[1][i1]; tp2Float *v0 = val0 + i0*CN_CARD_COL; tp2Float *v1 = val1 + i1*CN_CARD_COL; for (int k = 0; k < CN_CARD_COL; k++) if (glTDD._matrix.Element(i0, i1, k)._val2) { v0[k]._weight += ww; v1[k]._weight += ww; w += ww; int f0 = glTDD._matrix.Element(i0, i1, k)._val1; if (f0 == 1) v0[k]._force += ww; else if (f0 == -1) v1[k]._force += ww; else { v0[k]._force += ww / 2; v1[k]._force += ww / 2; } } } } dat._vectUnit[0].resize(CN_STREETDAT_UNIT); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { dat._vectUnit[0][i]._nb = glTDD.GetNbHand(0, i); tp2Float *ptr = &val0[i*CN_CARD_COL]; int k = 0; float sum = 0, wk = 0, sum2 = 0; for (; k < CN_CARD_COL; k++) if (ptr[k]._weight > DOUBLE_0) { sum += ptr[k]._force; wk += ptr[k]._weight; sum2 += ptr[k]._force*ptr[k]._force / ptr[k]._weight; } dat._vectUnit[0][i]._weight = wk / w; dat._vectUnit[0][i]._force = sum / wk; dat._vectUnit[0][i]._force50 = sqrt(sum2 / wk); } dat._vectUnit[1].resize(CN_STREETDAT_UNIT); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { //glTrasser.WriteMessage(i); dat._vectUnit[1][i]._nb = glTDD.GetNbHand(1, i); tp2Float *ptr = &val1[i*CN_CARD_COL]; int k = 0; float sum = 0, wk = 0, sum2 = 0; for (; k < CN_CARD_COL; k++) if (ptr[k]._weight > DOUBLE_0) { sum += ptr[k]._force; wk += ptr[k]._weight; sum2 += ptr[k]._force*ptr[k]._force / ptr[k]._weight; } dat._vectUnit[1][i]._weight = wk / w; dat._vectUnit[1][i]._force = sum / wk; dat._vectUnit[1][i]._force50 = sqrt(sum2 / wk); } delete val0; delete val1; dat.Copy50AndSort(); return w; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void CreateStreetDatForMin(clStreetDat &dat, vector <float> *gh) { tpBooleanDeck &deck = glTDD._deck; tp2Float *val0 = new tp2Float[CN_STREETDAT_UNIT*CN_CARD_COL]; tp2Float *val1 = new tp2Float[CN_STREETDAT_UNIT*CN_CARD_COL]; ZeroMemory(val0, CN_STREETDAT_UNIT*CN_CARD_COL * sizeof(tp2Float)); ZeroMemory(val1, CN_STREETDAT_UNIT*CN_CARD_COL * sizeof(tp2Float)); float w = 0; for (int i0 = 0; i0 < CN_STREETDAT_UNIT; i0++) { int nb0 = glTDD.GetNbHand(0, i0); tpHand hand0(nb0); deck[hand0[0]] = false; deck[hand0[1]] = false; for (int i1 = 0; i1 < CN_STREETDAT_UNIT; i1++) { int nb1 = glTDD.GetNbHand(1, i1); tpHand hand1(nb1); deck[hand1[0]] = false; deck[hand1[1]] = false; float ww = gh[0][i0] * gh[1][i1]; tp2Float *v0 = val0 + i0*CN_CARD_COL; tp2Float *v1 = val1 + i1*CN_CARD_COL; for (int k = 0; k < CN_CARD_COL; k++) if (deck[k]) { v0[k]._weight += ww; v1[k]._weight += ww; w += ww; int f0 = glTDD.Force(0, k, i0), f1 = glTDD.Force(1, k, i1); if (f0 > f1) v0[k]._force += ww; else if (f1 > f0) v1[k]._force += ww; else { v0[k]._force += ww / 2; v1[k]._force += ww / 2; } } deck[hand1[0]] = true; deck[hand1[1]] = true; } deck[hand0[0]] = true; deck[hand0[1]] = true; } dat._vectUnit[0].resize(CN_STREETDAT_UNIT); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { dat._vectUnit[0][i]._nb = glTDD.GetNbHand(0, i); tp2Float *ptr = &val0[i*CN_CARD_COL]; int k = 0; float sum = 0, wk = 0, sum2 = 0; for (; k < CN_CARD_COL; k++) if (ptr[k]._weight > DOUBLE_0) { sum += ptr[k]._force; wk += ptr[k]._weight; sum2 += ptr[k]._force*ptr[k]._force / ptr[k]._weight; } dat._vectUnit[0][i]._weight = wk / w; dat._vectUnit[0][i]._force = sum / wk; dat._vectUnit[0][i]._force50 = sqrt(sum2 / wk); } dat._vectUnit[1].resize(CN_STREETDAT_UNIT); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { //glTrasser.WriteMessage(i); dat._vectUnit[1][i]._nb = glTDD.GetNbHand(1, i); tp2Float *ptr = &val1[i*CN_CARD_COL]; int k = 0; float sum = 0, wk = 0, sum2 = 0; for (; k < CN_CARD_COL; k++) if (ptr[k]._weight > DOUBLE_0) { sum += ptr[k]._force; wk += ptr[k]._weight; sum2 += ptr[k]._force*ptr[k]._force / ptr[k]._weight; } dat._vectUnit[1][i]._weight = wk / w; dat._vectUnit[1][i]._force = sum / wk; dat._vectUnit[1][i]._force50 = sqrt(sum2 / wk); } delete val0; delete val1; dat.Copy50AndSort(); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::FindMinParam(clStreetDat &datIn) { clStreetDat dat1; vector <float> ghEx[2], g0, g1; int dim00 = CnHand(0), dim11 = CnHand(1); if (dim00 != dim11) { ErrMessage("", " FindMinParam"); } ghEx[0].resize(CN_STREETDAT_UNIT); ghEx[1].resize(CN_STREETDAT_UNIT); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { ghEx[0][i] = _gh[0][glTDD.GetNbHand(0, i)]; ghEx[1][i] = _gh[1][glTDD.GetNbHand(1, i)]; } memcpy(dat1._stack, datIn._stack, sizeof(dat1._stack)); dat1._pot = datIn._pot; CreateStreetDatForMin(dat1, ghEx); double min = dat1.Distance(datIn); double w0 = 0.1; int nb0 = 0, cn = 0, nb, nbPl; while (w0 > 0.001) { if (nb0 < CN_STREETDAT_UNIT) { nbPl = 0; nb = nb0; } else { nbPl = 1; nb = nb0 - CN_STREETDAT_UNIT; } vector <float> ghCur = ghEx[nbPl]; ghEx[nbPl][nb] += w0; //NormDatTurnEx(ghEx[nbPl], nb, w0); TempNormVect(CN_STREETDAT_UNIT, &ghEx[nbPl][0], 1); CreateStreetDatForMin(dat1, ghEx); double d0 = dat1.Distance(datIn); if (d0 < min) { min = d0; cn = -1; } else { ghEx[nbPl] = ghCur; if (ghEx[nbPl][nb] >= w0) { ghEx[nbPl][nb] -= w0; //NormDatTurnEx(ghEx[nbPl], nb, -w0); TempNormVect(CN_STREETDAT_UNIT, &ghEx[nbPl][0], 1); CreateStreetDatForMin(dat1, ghEx); double d0 = dat1.Distance(datIn); if (d0 < min) { min = d0; cn = -1; } else ghEx[nbPl] = ghCur; } } nb0++; cn++; if (nb0 >= CN_STREETDAT_UNIT + CN_STREETDAT_UNIT) nb0 = 0; if (cn == CN_STREETDAT_UNIT + CN_STREETDAT_UNIT) { cn = 0; w0 /= 2; } g0 = ghEx[0]; g1 = ghEx[1]; } //CreateRiverDatForMin(dat1, ghEx); //double d0 = dat1.Distance(datIn); for (int i = 0; i < CN_STREETDAT_UNIT; i++) { _gh[0][glTDD.GetNbHand(0, i)] = ghEx[0][i]; _gh[1][glTDD.GetNbHand(1, i)] = ghEx[1][i]; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void tpStreetDatGH::operator +=(tpStreetDatGH &val) { if (val._weight > DOUBLE_0) { float w0 = _weight + val._weight; _force = (_force*_weight + val._force*val._weight) / w0; _force50 = (_force50*_weight + val._force50*val._weight) / w0; _weight = w0; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- int tpStreetDatGH::FindNbCenterElement(vector <tpStreetDatGH> &vect) { int dim = vect.size(); tpStreetDatGH res = { 0,0,0,0 }; for (int i = 0; i < dim; i++) { res._force += vect[i]._weight*vect[i]._force; res._force50 += vect[i]._weight*vect[i]._force50; res._weight += vect[i]._weight; } if (res._weight < DOUBLE_0) return 0; res._force /= res._weight; res._force50 /= res._weight; int nb = 0; double dist = vect[0].DistanceSqr(res); for (int i = 1; i < dim; i++) { double d = vect[i].DistanceSqr(res); if (d < dist) { dist = d; nb = i; } } return nb; } //--------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CompactGH(double minW, int cnMin, clStreetDat *datIn) { if (datIn == NULL) { clStreetDat dat; CreateStreetDat(dat); CompactGH(minW, cnMin, dat); } else CompactGH(minW, cnMin, *datIn); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- void clRootStreetTree::CompactGH(clInComeDataRoot *id, double minW, int cnMin, clStreetDat dat) { for (int nbPl = 0; nbPl < 2; nbPl++) { vector <tpStreetDatGH> &vect = dat._vectUnit[nbPl]; while (true) { int dim = vect.size(); //glTrasser.WriteMessage(dim); if (dim <= cnMin) break; int nb = 0; for (int i = 1; i < dim; i++) if (vect[i]._weight < vect[nb]._weight) nb = i; if (vect[nb]._weight > minW) break; int nb1 = (nb == 0) ? 1 : 0; float dist = vect[nb].Distance(vect[nb1]); for (int i = nb1 + 1; i < dim; i++) { float val = vect[nb].Distance(vect[i]); if (val < dist) { val = dist; nb1 = i; } } vect[nb1]._weight += vect[nb]._weight; vect.erase(vect.begin() + nb); } id->_gh[nbPl].ClearDat(); int dim = vect.size(); for (int i = 0; i < dim; i++) id->_gh[nbPl][vect[i]._nb] = vect[i]._weight; id->_gh[nbPl].Norm(); } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------- bool CreateStreetDatRoot(clRoot &root, clStreetDat &dat) { clRootStreetTree rr; rr._sit = root._sit; rr._gh[0] = root._gh[0]; rr._gh[1] = root._gh[1]; rr.CalcIndex(); return rr.CreateStreetDat(dat); } //--------------------------------------------------------------------------------------------------------------------------------------------------- void CompactGHTurn(clRoot &root, double val, int cnHand, int *nbH) { clRootStreetTree rr; rr._sit = root._sit; rr._gh[0] = root._gh[0]; rr._gh[1] = root._gh[1]; rr.CalcIndex(); rr.CompactGHQuickH(val, cnHand, nbH); root._gh[0] = rr._gh[0]; root._gh[1] = rr._gh[1]; root.CalcIndex(); } //---------------------------------------------------------------------------------------------------------------------------------------------------
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ // TextDoc.cpp : implementation file // #include "stdafx.h" #include "AppState.h" #include "MessageDoc.h" #include "Text.h" #include "Message.h" #include "MessageSource.h" #include "MessageHeaderFile.h" #include "format.h" #include "NounsAndCases.h" #include "ResourceContainer.h" #include "PerfTimer.h" #include "ResourceMap.h" #include "Sync.h" #include "AudioCacheResourceSource.h" #include "Audio.h" #include "AudioMap.h" #include "AudioNegative.h" #include <numeric> #include "ResourceBlob.h" using namespace std; IMPLEMENT_DYNCREATE(CMessageDoc, CResourceDocument) CMessageDoc::CMessageDoc() : _selectedIndex(-1), _estimatedAudioSize(0), _originalResourceNumber(-1) { } void CMessageDoc::SetSelectedIndex(int index, bool force) { if (force || (index != _selectedIndex)) { _selectedIndex = index; UpdateAllViewsAndNonViews(nullptr, 0, &WrapHint(MessageChangeHint::Selection)); } } void CMessageDoc::_PreloadAudio() { PerfTimer timer("preloadAudio"); const TextComponent &text = GetResource()->GetComponent<TextComponent>(); _audioResources.clear(); _audioModified.clear(); _originalTuplesWithAudio.clear(); _originalResourceNumber = GetResource()->ResourceNumber; CResourceMap &map = appState->GetResourceMap(); std::unordered_map<uint32_t, std::unique_ptr<ResourceEntity>> _temporaryMap; if (appState->GetVersion().HasSyncResources) { // If we're sourced from the cache files, we want to *only* include entries from the cached audiomap (i.e. not // combine them with audio resources enumerated from resource.aud). Otherwise, you could delete an audio resource from // a message entry, and it would keeping "returning" when you re-opened the message resource (until you rebuilt audio files) std::unique_ptr<std::unordered_set<uint32_t>> restrictToTheseTuples; unique_ptr<ResourceBlob> amBlob = appState->GetResourceMap().Helper().MostRecentResource(ResourceType::AudioMap, GetResource()->ResourceNumber, ResourceEnumFlags::IncludeCacheFiles); if (amBlob && (amBlob->GetSourceFlags() == ResourceSourceFlags::AudioMapCache)) { std::unique_ptr<ResourceEntity> amResource = CreateResourceFromResourceData(*amBlob); if (amResource) { restrictToTheseTuples = std::make_unique<std::unordered_set<uint32_t>>(); for (const auto &entry : amResource->GetComponent<AudioMapComponent>().Entries) { restrictToTheseTuples->insert(GetMessageTuple(entry)); } } } // Get all the resources from the audio map int mapResourceNumber = GetResource()->ResourceNumber; auto resourceContainer = appState->GetResourceMap().Resources(ResourceTypeFlags::Audio, ResourceEnumFlags::MostRecentOnly | ResourceEnumFlags::IncludeCacheFiles | ResourceEnumFlags::AddInDefaultEnumFlags, mapResourceNumber); for (auto resource : *resourceContainer) { // Again, as mentioned above, we only want to take our audio resources from a single source: the cache files, or the actual game resources. if (!restrictToTheseTuples || (restrictToTheseTuples->find(resource->GetBase36()) != restrictToTheseTuples->end())) { _temporaryMap[resource->GetBase36()] = CreateResourceFromResourceData(*resource); _originalTuplesWithAudio.insert(resource->GetBase36()); } } } // Now assign them slots based on the text entry indices. // Using this system (instead of looking them up by tuples), since we want an easy way to keep // track of things when the user changes the message entry tuple. for (const TextEntry &entry : text.Texts) { _audioResources.push_back(std::move(_temporaryMap[GetMessageTuple(entry)])); _audioModified.push_back(false); } assert(_audioResources.size() == text.Texts.size()); // Add the negatives in. NOTE: This might be slow, we could do this on demand. But we'd need to pull them in // whenever one was set to modified (or else we'd remove the negative upon save). int mapContext = GetResource()->ResourceNumber; std::unique_ptr<AudioCacheResourceSource> resourceSource = std::make_unique<AudioCacheResourceSource>(&map, map.Helper(), mapContext, ResourceSourceAccessFlags::Read); for (auto &audioResource : _audioResources) { if (audioResource) { resourceSource->MaybeAddNegative(*audioResource); } } _RecalcAudioSize(); } void CMessageDoc::_RecalcAudioSize() { _estimatedAudioSize = std::accumulate(_audioResources.begin(), _audioResources.end(), 0, [](uint32_t sum, const std::unique_ptr<ResourceEntity> &resource) { return sum + (resource ? AudioEstimateSize(*resource) : 0); } ); } bool CMessageDoc::v_DoPreResourceSave() { if (_estimatedAudioSize >= (256 * 256 * 256)) { // Disabled for now. Depending on the type of audio map (32bit or 24bit offsets), it could be larger. // Games typically have around 16MB as a max, but sometimes a bit over (e.g. some in EcoQuest), and it appears to be ok. /* AfxMessageBox("The audio resources associated with this message resources are too large. The maximum size is 16 MB.", MB_ICONERROR); return false;*/ } return true; } void CMessageDoc::PostSuccessfulSave(const ResourceEntity *pResource) { if (appState->GetVersion().HasSyncResources) { if (pResource->ResourceNumber != _originalResourceNumber) { // This was a "save as". We need to do a bit of extra work to get things working. int newNumber = pResource->ResourceNumber; // First get the original audiomap and save it under the number, just sowe have something in the right place. unique_ptr<ResourceBlob> amBlob = appState->GetResourceMap().Helper().MostRecentResource(ResourceType::AudioMap, _originalResourceNumber, ResourceEnumFlags::IncludeCacheFiles); if (amBlob) { amBlob->SetNumber(newNumber); amBlob->SetSourceFlags(ResourceSourceFlags::AudioMapCache); appState->GetResourceMap().AppendResource(*amBlob); } // Now, update this: _originalResourceNumber = newNumber; // Next, mark everything as modified, and change the resource numbers for (size_t i = 0; i < _audioResources.size(); i++) { _audioModified[i] = true; _audioResources[i]->ResourceNumber = newNumber; // We don't need to bother setting resource flags, we always append to the cache files } // Then, proceed as usual... } std::vector<ResourceEntity*> audioNegatives; // Save any modified or new audio resources std::set<uint32_t> currentTextEntryTuplesWithAudio; const TextComponent &text = pResource->GetComponent<TextComponent>(); CResourceMap &map = appState->GetResourceMap(); DeferResourceAppend defer(map); for (size_t i = 0; i < text.Texts.size(); i++) { const TextEntry &entry = text.Texts[i]; uint32_t textEntryTuple = GetMessageTuple(entry); ResourceEntity *companionAudio = _audioResources[i].get(); if (companionAudio) { currentTextEntryTuplesWithAudio.insert(textEntryTuple); } if (_audioModified[i]) { if (companionAudio) { // Now endow this audio resource with up-to-date information based on the text entry companionAudio->SourceFlags = ResourceSourceFlags::AudioCache; companionAudio->Base36Number = textEntryTuple; map.AppendResource(*companionAudio); audioNegatives.push_back(companionAudio); } else { // Probably deletion. We no longer know what the original tuple for this guy is at this point // (we *could* track that info... but it gets complicated, since it could have // been removed or added many times). } } else { assert(!companionAudio || (textEntryTuple == companionAudio->Base36Number)); } } defer.Commit(); // Save the negatives if (!audioNegatives.empty()) { int mapContext = pResource->ResourceNumber; std::unique_ptr<AudioCacheResourceSource> resourceSource = std::make_unique<AudioCacheResourceSource>(&map, map.Helper(), mapContext, ResourceSourceAccessFlags::ReadWrite); resourceSource->SaveOrRemoveNegatives(audioNegatives); } // Ok, we've commited the modified/new entries. // Now, we want to delete any tuples that existed previously, which are *not* in the current set of text entry tuples std::vector<uint32_t> deletedTuples; for (uint32_t originalTuple : _originalTuplesWithAudio) { if (currentTextEntryTuplesWithAudio.find(originalTuple) == currentTextEntryTuplesWithAudio.end()) { deletedTuples.push_back(originalTuple); } } // These tuples need to get deleted from the audio map too... so we should go through the proper channels. // We can't go through the CResourceMap, because that relies on having an exact identical version of the thing // we are deleting. All we want to do is invoke the AudioCacheResourceSource directly and tell it to delete things. if (!deletedTuples.empty()) { int mapContext = pResource->ResourceNumber; std::unique_ptr<AudioCacheResourceSource> resourceSource = std::make_unique<AudioCacheResourceSource>(&map, map.Helper(), mapContext, ResourceSourceAccessFlags::ReadWrite); resourceSource->RemoveEntries(mapContext, deletedTuples); } // Keep our list of original tuples up-to-date _originalTuplesWithAudio.clear(); for (auto &resource : _audioResources) { if (resource) { _originalTuplesWithAudio.insert(resource->Base36Number); } } // Finally, clear out the modified flags std::fill(_audioModified.begin(), _audioModified.end(), false); } } void CMessageDoc::AddEntry(const TextEntry &entry) { int index = GetSelectedIndex(); index++; ApplyChangesWithPost<TextComponent>( [index, &entry](TextComponent &text) { text.Texts.insert(text.Texts.begin() + index, entry); return WrapHint(MessageChangeHint::Changed); }, [index, this](ResourceEntity &resource) { this->_audioResources.insert(this->_audioResources.begin() + index, nullptr); // "false" for modified is ok, since there is no audio resource yet. this->_audioModified.insert(this->_audioModified.begin() + index, false); } ); // Now select it SetSelectedIndex(index); } void CMessageDoc::DeleteCurrentEntry() { int selected = GetSelectedIndex(); if (selected != -1) { bool ok = true; if (_audioResources[selected]) { ok = (IDYES == AfxMessageBox("This entry contains an associated audio resources. This will delete the audio resource too. Continue?", MB_YESNO | MB_ICONWARNING)); } if (ok) { int newSelected = selected; ApplyChangesWithPost<TextComponent>( [selected, &newSelected](TextComponent &text) { TextChangeHint hint = text.DeleteString(selected); newSelected = max(0, min(selected, (int)(text.Texts.size() - 1))); return WrapHint(hint); }, [selected, &newSelected, this](ResourceEntity &resource) { this->_audioResources.erase(this->_audioResources.begin() + selected); this->_audioModified.erase(this->_audioModified.begin() + selected); } ); SetSelectedIndex(newSelected, true); } } } const char c_szMessageTxtFilter[] = "txt files (*.txt)|*.txt|All Files|*.*|"; void CMessageDoc::ImportMessage() { ApplyChanges<TextComponent>( [&](TextComponent &text) { MessageChangeHint hint = MessageChangeHint::None; CFileDialog fileDialog(TRUE, nullptr, nullptr, OFN_HIDEREADONLY | OFN_NOCHANGEDIR, c_szMessageTxtFilter); if (IDOK == fileDialog.DoModal()) { CString strFileName = fileDialog.GetPathName(); ImportMessageFromFile(text, (PCSTR)strFileName); hint |= MessageChangeHint::Changed; // Fill with empty spots: this->_audioResources.resize(text.Texts.size()); this->_audioModified.resize(text.Texts.size(), false); } return WrapHint(hint); } ); } void CMessageDoc::ExportMessage() { const ResourceEntity *resource = GetResource(); if (resource) { CFileDialog fileDialog(FALSE, nullptr, fmt::format("{0}.txt", resource->ResourceNumber).c_str(), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR, c_szMessageTxtFilter); if (IDOK == fileDialog.DoModal()) { CString strFileName = fileDialog.GetPathName(); ExportMessageToFile(resource->GetComponent<TextComponent>(), (PCSTR)strFileName); } } } void CMessageDoc::SetEntry(const TextEntry &newEntry) { int selected = GetSelectedIndex(); if (selected != -1) { bool tupleChanged = false; ApplyChanges<TextComponent>( [selected, newEntry, &tupleChanged](TextComponent &text) { MessageChangeHint hint = MessageChangeHint::None; if (newEntry != text.Texts[selected]) { tupleChanged = GetMessageTuple(newEntry) != GetMessageTuple(text.Texts[selected]); text.Texts[selected] = newEntry; hint |= MessageChangeHint::ItemChanged; } return WrapHint(hint); } ); if (tupleChanged) { // Not really necessary, we could detect this easily... _audioModified[selected] = true; } } } ResourceEntity *CMessageDoc::GetAudioResource() { ResourceEntity *resource = nullptr; if (_selectedIndex != -1) { resource = _audioResources[_selectedIndex].get(); } return resource; } const TextEntry *CMessageDoc::GetEntry() { const TextEntry *entry = nullptr; const ResourceEntity *resource = GetResource(); if (resource) { const TextComponent &text = resource->GetComponent<TextComponent>(); int index = GetSelectedIndex(); if ((index != -1) && (index < (int)text.Texts.size())) { entry = &text.Texts[index]; } } return entry; } ResourceEntity *CMessageDoc::GetAudioResource(int index) { ResourceEntity *resource = nullptr; if (index >= 0 && index < (int)_audioResources.size()) { resource = _audioResources[index].get(); } return resource; } void CMessageDoc::SetAudioResource(std::unique_ptr<ResourceEntity> audioResource) { assert(_selectedIndex != -1); _audioResources[_selectedIndex] = std::move(audioResource); _audioModified[_selectedIndex] = true; SetModifiedFlag(TRUE); _RecalcAudioSize(); UpdateAllViewsAndNonViews(nullptr, 0, &WrapHint(MessageChangeHint::ItemChanged)); } void CMessageDoc::SetMessageResource(std::unique_ptr<ResourceEntity> pMessage, int id) { _checksum = id; if (pMessage) { // Add a nouns/cases component pMessage->AddComponent<NounsAndCasesComponent>( std::make_unique<NounsAndCasesComponent>(appState->GetResourceMap().Helper().GetMsgFolder(), pMessage->ResourceNumber) ); } AddFirstResource(move(pMessage)); _UpdateTitle(); _PreloadAudio(); UpdateAllViewsAndNonViews(nullptr, 0, &WrapHint(MessageChangeHint::Changed | MessageChangeHint::AllMessageFiles)); } BEGIN_MESSAGE_MAP(CMessageDoc, TCLASS_2(CUndoResource, CResourceDocument, ResourceEntity)) END_MESSAGE_MAP() void CMessageDoc::v_OnUndoRedo() { UpdateAllViewsAndNonViews(nullptr, 0, &WrapHint(MessageChangeHint::Changed)); } const MessageSource *GetMessageSourceFromType(CMessageDoc *pDoc, MessageSourceType sourceType, bool reload) { if (pDoc) { const ResourceEntity *resource = pDoc->GetResource(); switch (sourceType) { case MessageSourceType::Conditions: return resource ? &resource->GetComponent<NounsAndCasesComponent>().GetCases() : nullptr; case MessageSourceType::Verbs: return appState->GetResourceMap().GetVerbsMessageSource(reload); case MessageSourceType::Talkers: return appState->GetResourceMap().GetTalkersMessageSource(reload); case MessageSourceType::Nouns: return resource ? &resource->GetComponent<NounsAndCasesComponent>().GetNouns() : nullptr; } } return nullptr; } // Since we modify audio resources in a significant way, we prevent undos if audio is supported for messages. bool CMessageDoc::v_PreventUndos() const { return appState->GetVersion().HasSyncResources; } // CMessageDoc diagnostics #ifdef _DEBUG void CMessageDoc::AssertValid() const { CDocument::AssertValid(); } void CMessageDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CMessageDoc serialization void CMessageDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } // CMessageDoc commands
#include "./home_view.hpp" #include <iostream> #include <memory> using namespace std; namespace ltui { home_view::home_view(std::shared_ptr<router> router) : view(), _router(std::move(router)), _container(ftxui::Container::Vertical()), _menu() {} void home_view::initialize_ui() { _menu.entries.emplace_back(L"Add Entry"); _menu.entries.emplace_back(L"Quit"); _menu.on_enter = [&]() { this->on_menu_selected(this->_menu.selected); }; _container.Add(&_menu); Add(&_container); } void home_view::on_menu_selected(int option) { if (option == 0) { _router->navigate("ledger_entry/new", std::any()); } else { close(); } } } // namespace ltui
#include <sstream> #include <string.h> #include "iException.h" using namespace std; namespace stdext { Exception :: Exception(const int iErrno, const string sFunc , const string sErrMsg, const string sFile , const int iLine ) { _iErrNo = iErrno; _sErrMsg = sErrMsg; _sFile = sFile; _sFunc = sFunc; _iLine = iLine; } Exception :: Exception(const string sErrMsg, const string sFunc , const string sFile , const int iLine ) { _sErrMsg = sErrMsg; _sFile = sFile; _sFunc = sFunc; _iLine = iLine; _iErrNo = 0; } Exception :: Exception(const int iErrno, const string sFunc , const string sFile , const int iLine ) { _sErrMsg = ""; _iErrNo = iErrno; _sFile = sFile; _sFunc = sFunc; _iLine = iLine; } Exception::~Exception(){} const string Exception::what() { char buf[1024] = {0}; if( _sErrMsg.empty() && _iErrNo == 0 ) return string("No enough error info"); else if( _iErrNo < 0 ) return _sErrMsg; else if( _sErrMsg.empty() && _iErrNo >= 0 ) return string( strerror_r(_iErrNo, buf , 1024)); else return string( strerror_r(_iErrNo, buf , 1024))+" -> "+_sErrMsg; } const string Exception :: GetErrMsg() { return what(); } const string Exception :: GetMsg() { stringstream oss; oss<<_sFile<<":"<<_sFunc<<":"<<_iLine<<what(); return oss.str(); } const int Exception :: GetErrNo() { return _iErrNo; } }
/* Emrah YILDIRIM 111044056 HW07 */ #include "Ivector.h" namespace HW07 { // Ivector::Ivector() : sizeV(0), capacityV(10) { nums = new int[capacityV]; } // Ivector::Ivector(int wcapacity) : sizeV(0), capacityV(wcapacity) { nums = new int[capacityV]; } // Ivector::Ivector(const Ivector& other) : sizeV(other.sizeV), capacityV(other.capacityV) { nums = new int[capacityV]; for (int i = 0; i < other.sizeV; ++i) nums[i] = other.nums[i]; } // Ivector::~Ivector() { delete[] nums; nums = NULL; } //sayinin varligini kontrol eder bool Ivector::exist(int num) const { for (int i = 0; i < sizeV; ++i) if (num == nums[i]) return true; return false; } // bool Ivector::push_back(int num) { if (exist(num)) return false; if ((capacityV - sizeV) > 0) { nums[sizeV] = num; sizeV++; return true; } else { Ivector temp(*this); delete[] nums; capacityV += 10; nums = new int[capacityV]; for (int i = 0; i < temp.sizeV; ++i) nums[i] = temp.nums[i]; nums[sizeV] = num; sizeV++; return true; } } // bool Ivector::pop_back(void) { if (sizeV > 0) sizeV--; else return false; return true; } // bool Ivector::erase(int index) { if (sizeV > 0) { Ivector temp(*this); delete[] nums; nums = new int[capacityV]; for (int i = 0, j = 0; i < sizeV; ++i) { if (i != index) { nums[j] = temp.nums[i]; j++; } } sizeV--; return true; } else return false; } void Ivector::sort(void) { int temp; for (int i = 0; i < sizeV; ++i) for (int j = 0; j < sizeV; ++j) if (nums[i] < nums[j]) { temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } const Ivector Ivector::operator+(const Ivector& other) { Ivector temp = *this; for (int i = 0; i < other.size(); ++i) if (!temp.exist(other[i])) temp.push_back(other[i]); temp.sort(); return temp; } // const Ivector& Ivector::operator=(const Ivector& other) { if (this == &other) return *this; else { sizeV = other.sizeV; capacityV = other.capacityV; delete[] nums; nums = new int[capacityV]; for (int i = 0; i < other.sizeV; ++i) nums[i] = other.nums[i]; return *this; } } // bool Ivector::operator ==(const Ivector& other) const { if (sizeV == other.sizeV && capacityV == other.capacityV) { for (int i = 0; i < sizeV; ++i) if (nums[i] != other.nums[i]) return false; } else return false; return true; } bool Ivector::operator !=(const Ivector& other) const { if (sizeV != other.sizeV || capacityV != other.capacityV) return true; else { for (int i = 0; i < sizeV; ++i) if (nums[i] != other.nums[i]) return true; } return false; } // ostream& operator << (ostream& out, const Ivector& vector) { for (int i = 0; i < vector.sizeV; ++i) out << vector.nums[i] << " "; out << endl; return out; } }
#include <iostream> #include <tuple> int main() { std::tuple<int, char, bool> tuple{ 10, 'A', true }; int a; bool b; std::tie(a, std::ignore, b) = tuple; std::cout << a << '\n' << b << '\n'; return 0; }
#include <iostream> #include <cstring> #include "rsa.h" using namespace std; enum TYPE_CIPHER { RSA_CIPHER = 1 }; enum TYPE_COMMAND { ENCODE_COMMAND = 1, DECODE_COMMAND }; int main(void) { TYPE_CIPHER flag_cipher; TYPE_COMMAND flag_command; // Выбор алгоритма do { cout << "Введите номер алгоритма," << endl << "с которым будем работать: "; cin >> flag_cipher; } while ( !flag_cipher ); // Выбор шифрования или дешифрования do { cout << "Введите \"e\" для шифрования," << endl << "\"d\" для дешифрования или \"c\" для выхода: "; cin >> flag_command; } while ( !flag_command ); RSA *cipher = new RSA; (flag == "e")?cipher->rsa_encode():cipher->rsa_decode(); return 0; }
#include<bits/stdc++.h> #include<stdio.h> using namespace std; int main() { int x1,x2,y1,y2,x,y,z,l,q,r; cin>>x1>>y1>>x2>>y2>>x>>y; l=abs(x1-x2); r=abs(y1-y2); if( l%x==0 && r%y==0 && (l/x)%2 ==(r/y)%2 ) cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; }
// ***************************************************************** // This file is part of the CYBERMED Libraries // // Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve), // Federal University of Paraiba and University of São Paulo. // All rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. // ***************************************************************** /** * A interface CybSock define os métodos necessários para a construção de um * socket em linguagem C. Veja que aqui ainda não há métodos para envio e recep- * ção de dados. Isto irá acontecer a partir da utilização do socket criado, na * definição de um servidor ou de um cliente. * **/ #ifndef _CYBSOCK_H #define _CYBSOCK_H #include "cybNetwork.h" #include "cybNodeAddress.h" class CybSock { public: /** */ void connectToPort(int s, CybNodeAddress* addr); /** */ virtual void createSock(void) = 0; /** */ virtual int getSock(void) = 0; }; #endif /* _CYBSOCK_H */
#pragma once #include "../EngineLayer/MetaMorpheusEngine.h" #include "../EngineLayer/MetaMorpheusEngineResults.h" #include <string> #include <vector> #include "stringbuilder.h" //C# TO C++ CONVERTER NOTE: Forward class declarations: namespace EngineLayer { class MetaMorpheusEngine; } using namespace EngineLayer; using namespace NUnit::Framework; namespace Test { //C# TO C++ CONVERTER NOTE: The following .NET attribute has no direct equivalent in native C++: //ORIGINAL LINE: [TestFixture] public static class MyEngineTest class MyEngineTest final { public: //C# TO C++ CONVERTER NOTE: The following .NET attribute has no direct equivalent in native C++: //ORIGINAL LINE: [Test] public static void TestMyEngine() static void TestMyEngine(); private: class TestEngine : public MetaMorpheusEngine { public: TestEngine(int level); protected: MetaMorpheusEngineResults *RunSpecific() override; private: class TestResults : public MetaMorpheusEngineResults { public: TestResults(MetaMorpheusEngine *e); std::wstring ToString() override; }; }; }; }
#include <cstdio> #include <cstdlib> int exit_with_errstr(const char* errstr, int errnumber) { printf("%s\n", errstr); exit(errnumber); return errnumber; }
#pragma once #include <string> #include <vector> struct PyEXRImage { PyEXRImage(const std::string &filename); PyEXRImage(int width, int height); ~PyEXRImage(); float getPixel(int x, int y, int channel); float get(int i); float *data() { return out_rgba; } void set(int i, int channel, float value); void save(const std::string &filename); std::string filename; float* out_rgba; // width * height * RGBA int width; int height; int ret; const char* err; };
#include "price_update.h" #include "ui_price_update.h" price_update::price_update(QWidget *parent) : QDialog(parent), ui(new Ui::price_update) { ui->setupUi(this); update_state = 0; } price_update::~price_update() { delete ui; } void price_update::on_checkBox_stateChanged(int arg1) { if(ui->checkBox->isChecked()){ update_state = 1; } else if (!ui->checkBox->isChecked()) { update_state = 0; } } void price_update::on_buy_price_editingFinished() { } void price_update::on_profit_editingFinished() { double buy_price = ui->buy_price->text().toDouble(); double prof_num = ui->profit->text().toDouble(); if(!ui->profit->text().isEmpty()){ double profit_perc_lo = (prof_num/buy_price)*100; double sell_price = buy_price + prof_num; ui->sell_price->setText(QString::number(sell_price)); ui->profit_perc->setText(QString::number(profit_perc_lo)); sell = ui->sell_price->text().toDouble(); buy = ui->buy_price->text().toDouble(); profit = ui->profit->text().toDouble(); profit_perc = ui->profit_perc->text().toDouble(); } } void price_update::on_profit_perc_editingFinished() { double buy_price = ui->buy_price->text().toDouble(); double prof_num = ui->profit_perc->text().toDouble(); if(!ui->profit_perc->text().isEmpty()){ double prof_inc = buy_price * prof_num/100; double sell_price = buy_price + prof_inc; ui->sell_price->setText(QString::number(sell_price)); ui->profit->setText(QString::number(prof_inc)); sell = ui->sell_price->text().toDouble(); buy = ui->buy_price->text().toDouble(); profit = ui->profit->text().toDouble(); profit_perc = ui->profit_perc->text().toDouble(); } } void price_update::on_sell_price_editingFinished() { if(!ui->buy_price->text().isEmpty()){ double buy_price = ui->buy_price->text().toDouble(); double sell_price = ui->sell_price->text().toDouble(); double profit_lo = sell_price - buy_price; double profit_perc_lo = (profit_lo/buy_price)*100; ui->profit->setText(QString::number(profit_lo)); ui->profit_perc->setText(QString::number(profit_perc_lo)); sell = ui->sell_price->text().toDouble(); buy = ui->buy_price->text().toDouble(); profit = ui->profit->text().toDouble(); profit_perc = ui->profit_perc->text().toDouble();} } void price_update::on_pushButton_clicked() { this->accept(); ui->profit->clear(); ui->buy_price->clear(); ui->sell_price->clear(); ui->profit_perc->clear(); ui->checkBox->setChecked(false); update_state = 0; } void price_update::on_pushButton_2_clicked() { ui->profit->clear(); ui->buy_price->clear(); ui->sell_price->clear(); ui->profit_perc->clear(); ui->checkBox->setChecked(false); update_state = 0; this->reject(); } void price_update::on_buy_price_returnPressed() { ui->profit->setFocus(); } void price_update::on_profit_returnPressed() { ui->profit_perc->setFocus(); } void price_update::on_profit_perc_returnPressed() { ui->sell_price->setFocus(); } void price_update::on_sell_price_returnPressed() { ui->pushButton->click(); }
#include <bits/stdc++.h> using namespace std; int goldMine(int M[][100],int m,int n){ int dp[m][n]; memset(dp,0,sizeof(dp)); for(int j=0;j<n;j++){ for(int i=0;i<m;i++){ int x = (i==0||j==0) ? 0 : dp[i-1][j-1]; int y = (j==0) ? 0 : dp[i][j-1]; int z = (i==m-1||j==0) ? 0 : dp[i+1][j-1]; dp[i][j] = M[i][j] + max(x,max(y,z)); } } int res = dp[0][0]; for(int i=0;i<m;i++){ res = max(res,dp[i][n-1]); } return res; } int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t-- > 0) { int m,n; cin>>m>>n; int M[100][100]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ cin>>M[i][j]; } } cout<<goldMine(M,m,n)<<endl; } return 0; }
#pragma once #include <iostream> #include <iterator> #include <sstream> #include <string> #include <typeinfo> using std::bad_cast; using std::iterator; using std::ostream; using std::random_access_iterator_tag; using std::string; using std::stringstream; namespace lab3 { enum direction_t { DIR_NORTH, DIR_EAST, DIR_SOUTH, DIR_WEST }; direction_t random_direction(); class Identifiable { public: typedef unsigned int identifier_t; private: const identifier_t id; Identifiable(const Identifiable&) = delete; Identifiable& operator=(const Identifiable&) = delete; static identifier_t next_id; inline static identifier_t get_new_identifier() { return next_id++; } protected: Identifiable() : id(get_new_identifier()) {} Identifiable(Identifiable&& other) : id(other.id) {} public: virtual ~Identifiable() {} inline identifier_t get_id() const { return id; } inline bool operator==(const Identifiable& other) const { return id == other.id; } inline bool operator!=(const Identifiable& other) const { return !(*this == other); } inline bool operator< (const Identifiable& other) const { return id < other.id; } virtual string get_name() const = 0; virtual string get_description() const = 0; }; struct Coord { typedef size_t coord_t; coord_t x; coord_t y; Coord(const coord_t& x, const coord_t& y) : x(x), y(y) {} inline bool operator==(const Coord& rhs) const { return x == rhs.x && y == rhs.y; } inline bool operator!=(const Coord& rhs) const { return !(*this == rhs); } Coord step(direction_t direction, unsigned int distance = 1) const; }; ostream& operator<<(ostream& os, const Coord& coord); struct WorldCoord : Coord { Identifiable::identifier_t map_id; WorldCoord(Identifiable::identifier_t map_id, coord_t x, coord_t y); WorldCoord(Identifiable::identifier_t map_id, const Coord& original); WorldCoord& operator=(const WorldCoord& other); inline bool operator==(const WorldCoord& rhs) const { return map_id == rhs.map_id && x == rhs.x && y == rhs.y; } inline bool operator!=(const WorldCoord& rhs) const { return !(*this == rhs); } WorldCoord step(direction_t direction, unsigned int distance = 1) const; }; ostream& operator<<(ostream& os, const WorldCoord& coord); struct CoordRectangle { Coord top_left; Coord btm_right; class const_iterator; const_iterator begin() const; const_iterator end() const; inline bool operator==(const CoordRectangle& rhs) const { return top_left == rhs.top_left && btm_right == rhs.btm_right; } inline bool operator!=(const CoordRectangle& rhs) const { return !(*this == rhs); } }; ostream& operator<<(ostream& os, const CoordRectangle& rect); class CoordRectangle::const_iterator : public iterator<random_access_iterator_tag, const Coord> { const CoordRectangle& rectangle; Coord current_coord; public: const_iterator(const CoordRectangle& rectangle); const_iterator(const CoordRectangle& rectangle, const Coord& begin_coord); const_iterator(const const_iterator& original); const_iterator& operator=(const const_iterator& original); const_iterator& operator++(); const_iterator operator++(int); const_iterator& operator+=(difference_type); const_iterator operator+(difference_type) const; const_iterator& operator--(); const_iterator operator--(int); const_iterator& operator-=(difference_type); const_iterator operator-(difference_type offset) const; difference_type operator-(const const_iterator& other) const; bool operator==(const const_iterator& rhs) const; bool operator!=(const const_iterator& rhs) const; bool operator<(const const_iterator& rhs) const; bool operator>(const const_iterator& rhs) const; bool operator>=(const const_iterator& rhs) const; bool operator<=(const const_iterator& rhs) const; const Coord& operator[](difference_type index) const; const Coord& operator*(); }; template<class T, class U> bool is_type(const U& object) { try { dynamic_cast<const T&>(object); return true; } catch(bad_cast e) { return false; } } template<class T, class U> bool points_to_type(const U& object) { try { dynamic_cast<const T&>(*object); return true; } catch(bad_cast e) { return false; } } class EasyStringStream { stringstream ss; public: EasyStringStream() {} EasyStringStream(const EasyStringStream& ess) { ss << static_cast<string>(ess); } template<class T> EasyStringStream& operator<<(const T& arg) { ss << arg; return *this; } inline operator string() const { return ss.str(); } }; EasyStringStream easyss(); }
// // Shaft Robotica // 08 fev 2019 // Vitor Domingues // github.com/vitorshaft // instagram.com/shaftrobotica // vtrshaft@gmail.com // // código adaptado a partir do FirebaseDemo_ESP8266.ino. Copyright 2015 Google Inc. // Licença Apache versão 2.0 #include <ESP8266WiFi.h> #include <FirebaseArduino.h> // configuração de rede e acesso ao Firebase #define FIREBASE_HOST "bancodedados.firebaseio.com" #define FIREBASE_AUTH "INSIRA A CHAVE AQUI" #define WIFI_SSID "SSID da rede WiFi" #define WIFI_PASSWORD "senhadoWiFi" void setup() { Serial.begin(9600); // conecta ao WiFi WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); // Firebase.begin(FIREBASE_HOST); } int n = 0; void loop() { // envia valor Float a "number" Firebase.setFloat("number", 42.0); // em caso de erro if (Firebase.failed()) { Serial.print("setting /number failed:"); Serial.println(Firebase.error()); return; } delay(1000); // atualiza valor de "number" Firebase.setFloat("number", 43.0); // em caso de erro ... if (Firebase.failed()) { Serial.print("setting /number failed:"); Serial.println(Firebase.error()); return; } delay(1000); // get value Serial.print("number: "); Serial.println(Firebase.getFloat("number")); delay(1000); // remove value Firebase.remove("number"); delay(1000); // set string value Firebase.setString("message", "hello world"); // handle error if (Firebase.failed()) { Serial.print("setting /message failed:"); Serial.println(Firebase.error()); return; } delay(1000); // set bool value Firebase.setBool("truth", false); // handle error if (Firebase.failed()) { Serial.print("setting /truth failed:"); Serial.println(Firebase.error()); return; } delay(1000); // insere valor Int a "logs" String name = Firebase.pushInt("logs", n++); // handle error if (Firebase.failed()) { Serial.print("pushing /logs failed:"); Serial.println(Firebase.error()); return; } Serial.print("pushed: /logs/"); Serial.println(name); delay(1000); }
#include "stdafx.h" #include "MainDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // Dialog::Dialog(CWnd *parent) : CDialog(IDD_MAIN_DIALOG,parent) { } BEGIN_MESSAGE_MAP(Dialog, CDialog) ON_WM_CREATE() ON_WM_DESTROY() ON_WM_SIZE() ON_COMMAND(ID_CONTEXT_MENU_POP, OnContextMenuPop) ON_COMMAND(ID_CONTEXT_MENU_PUSH, OnContextMenuPush) ON_COMMAND(ID_CONTEXT_MENU_MANAGE, OnContextMenuManage) ON_BN_CLICKED(IDC_RADIO11,OnBnClickedRadio11) ON_BN_CLICKED(IDC_RADIO12,OnBnClickedRadio12) ON_BN_CLICKED(IDC_RADIO13,OnBnClickedRadio13) ON_BN_CLICKED(IDC_RADIO14,OnBnClickedRadio14) ON_BN_CLICKED(IDC_RADIO21,OnBnClickedRadio21) ON_BN_CLICKED(IDC_RADIO22,OnBnClickedRadio22) ON_BN_CLICKED(IDC_RADIO23,OnBnClickedRadio23) ON_BN_CLICKED(IDC_RADIO31,OnBnClickedRadio31) ON_BN_CLICKED(IDC_RADIO32,OnBnClickedRadio32) ON_BN_CLICKED(IDC_RADIO33,OnBnClickedRadio33) ON_BN_CLICKED(IDC_RADIO34,OnBnClickedRadio34) ON_BN_CLICKED(IDC_RADIO41,OnBnClickedRadio41) ON_BN_CLICKED(IDC_RADIO42,OnBnClickedRadio42) ON_BN_CLICKED(IDC_CHECK11,OnBnClickedCheck11) ON_BN_CLICKED(IDC_CHECK12,OnBnClickedCheck12) ON_BN_CLICKED(IDC_CHECK21,OnBnClickedCheck21) ON_BN_CLICKED(IDC_CHECK22,OnBnClickedCheck22) ON_BN_CLICKED(IDC_CHECK23,OnBnClickedCheck23) ON_BN_CLICKED(IDC_CHECK24,OnBnClickedCheck24) END_MESSAGE_MAP() int Dialog::OnCreate(LPCREATESTRUCT lpCreateStruct) { if(CDialog::OnCreate(lpCreateStruct) == -1) return -1; // if( !m_OutlookTabCtrl.Create(this,WS_CHILD | WS_VISIBLE,CRect(0,0,0,0),100) ) return -1; m_Style2.Install(&m_OutlookTabCtrl); // m_OutlookTabCtrl.SetAbilityManager(this); m_OutlookTabCtrl.SetNotifyManager(this); // m_OutlookTabCtrl.CreateStripesImages(NULL,IDB_STRIPE_NORMAL,IDB_STRIPE_DISABLE,true,24); m_OutlookTabCtrl.CreateButtonsImages(NULL,IDB_BUTTON_NORMAL,IDB_BUTTON_DISABLE,true,16); // m_OutlookTabCtrl.SetCaptionFont( GetTahomaBoldFont() ); m_OutlookTabCtrl.SetStripesFont( GetTahomaBoldFont() ); m_OutlookTabCtrl.SetButtonsFont( GetTahomaFont() ); // m_OutlookTabCtrl.SetCursor(IDC_CURSOR1); // if( !m_List1.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,100) || !m_List2.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,101) || !m_List3.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,102) || !m_List4.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,103) || !m_List5.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,104) || !m_List6.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,105) || !m_List7.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,106) || !m_List8.Create(WS_CHILD | WS_CLIPCHILDREN | LVS_REPORT,CRect(0,0,0,0),&m_OutlookTabCtrl,107) ) return -1; // m_List1.InsertColumn(0,_T("Mail"),LVCFMT_LEFT,100); m_List2.InsertColumn(0,_T("Calendar"),LVCFMT_LEFT,100); m_List3.InsertColumn(0,_T("Contacts"),LVCFMT_LEFT,100); m_List4.InsertColumn(0,_T("Tasks"),LVCFMT_LEFT,100); m_List5.InsertColumn(0,_T("Business Affairs"),LVCFMT_LEFT,100); m_List6.InsertColumn(0,_T("Notes"),LVCFMT_LEFT,100); m_List7.InsertColumn(0,_T("Folder List"),LVCFMT_LEFT,100); m_List8.InsertColumn(0,_T("Shortcuts"),LVCFMT_LEFT,100); // m_List1.InsertItem(0,_T("11111111111")); m_List1.InsertItem(0,_T("22222222222")); m_List1.InsertItem(0,_T("33333333333")); // if( !m_OutlookTabCtrl.AddItem(m_List1,_T("Mail"),0,0) || !m_OutlookTabCtrl.AddItem(m_List2,_T("Calendar"),1,1) || !m_OutlookTabCtrl.AddItem(m_List3,_T("Contacts"),2,2) || !m_OutlookTabCtrl.AddItem(m_List4,_T("Tasks"),3,3) || !m_OutlookTabCtrl.AddItem(m_List5,_T("Business Affairs"),-1,-1) || !m_OutlookTabCtrl.AddItem(m_List6,_T("Notes"),4,4) || !m_OutlookTabCtrl.AddItem(m_List7,_T("Folder List"),5,5) || !m_OutlookTabCtrl.AddItem(m_List8,_T("Shortcuts"),6,6) ) return -1; // HANDLE itemContact = m_OutlookTabCtrl.GetItemHandleByIndex(2); // 'Contacts' item. m_OutlookTabCtrl.DisableItem(itemContact,true); // just for demonstration the disable item. // if( !m_OutlookTabCtrl.LoadState(AfxGetApp(),_T("OutlookTabCtrl"),_T("State")) ) { m_OutlookTabCtrl.PushVisibleItem(); m_OutlookTabCtrl.PushVisibleItem(); } m_OutlookTabCtrl.Update(); // return 0; } // void Dialog::OnDestroy() { m_OutlookTabCtrl.SaveState( AfxGetApp(), _T("OutlookTabCtrl"),_T("State")); // CDialog::OnDestroy(); } ///////////////////////////////////////////////////////////////////////////// // BOOL Dialog::OnInitDialog() { CDialog::OnInitDialog(); // SetOutlookTabCtrlPos(); GetDlgItem(IDC_OUTLOOKTABCTRL_BASE)->ShowWindow(SW_HIDE); // SetButtonCheck(IDC_RADIO12,true); SetButtonCheck(IDC_RADIO22,true); SetButtonCheck(IDC_RADIO31,true); SetButtonCheck(IDC_RADIO41,true); SetButtonCheck(IDC_CHECK11,true); SetButtonCheck(IDC_CHECK12,true); SetButtonCheck(IDC_CHECK21,true); SetButtonCheck(IDC_CHECK22,true); SetButtonCheck(IDC_CHECK23,true); m_OutlookTabCtrl.HideEmptyButtonsArea(true); EnableControl(IDC_CHECK24,false); SetButtonCheck(IDC_CHECK24,true); // return TRUE; } ///////////////////////////////////////////////////////////////////////////// // void Dialog::OnSize(UINT nType,int cx,int cy) { SetOutlookTabCtrlPos(); // CDialog::OnSize(nType,cx,cy); } ///////////////////////////////////////////////////////////////////////////// // LOGFONT const *Dialog::GetTahomaFont() const { static const LOGFONT lf = {-11/*8pt*/,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,VARIABLE_PITCH | FF_DONTCARE,_T("Tahoma")}; return &lf; } LOGFONT const *Dialog::GetTahomaBoldFont() const { static const LOGFONT lf = {-11/*8pt*/,0,0,0,FW_BOLD,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,VARIABLE_PITCH | FF_DONTCARE,_T("Tahoma")}; return &lf; } ///////////////////////////////////////////////////////////////////////////// // void Dialog::SetOutlookTabCtrlPos() { CWnd *baseWnd = GetDlgItem(IDC_OUTLOOKTABCTRL_BASE); // if(baseWnd) { CRect rcBase; baseWnd->GetWindowRect(&rcBase/*out*/); ScreenToClient(&rcBase); // CRect rc; GetClientRect(&rc/*out*/); rc.DeflateRect(rcBase.left,rcBase.top,rcBase.top,rcBase.top); m_OutlookTabCtrl.MoveWindow(&rc); } } ///////////////////////////////////////////////////////////////////////////// // void Dialog::SetButtonCheck(int id, bool check) const { reinterpret_cast<CButton*>( GetDlgItem(id) )->SetCheck(check ? BST_CHECKED : BST_UNCHECKED); } bool Dialog::GetButtonCheck(int id) const { return reinterpret_cast<CButton*>( GetDlgItem(id) )->GetCheck() == BST_CHECKED; } // void Dialog::EnableControl(int id, bool enable) const { CWnd *wnd = GetDlgItem(id); enable ? wnd->ModifyStyle(WS_DISABLED,0) : wnd->ModifyStyle(0,WS_DISABLED); wnd->Invalidate(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // bool Dialog::CanSelect(OutlookTabCtrl const *ctrl, HANDLE item) { const CString text = ctrl->GetItemText(item); if(text=="Calendar") // just for demonstration using of OutlookTabCtrl::Ability. { ::MessageBox(m_hWnd,_T("You can not select this item."),_T("OutlookTabCtrl::Ability"),MB_OK); return false; } return true; } ///////////////////////////////////////////////////////////////////////////// // void Dialog::OnSelectionChanged(OutlookTabCtrl *ctrl) { CString text = ctrl->GetItemText( ctrl->GetSelectedItem() ); if(text==_T("Tasks") || text==_T("Notes")) // just for demonstration using of OutlookTabCtrl::Notify. { text = _T("You selected item: \"") + text + _T('\"'); ::MessageBox(m_hWnd,text,_T("OutlookTabCtrl::Notify"),MB_OK); } } ///////////////////////////////////////////////////////////////////////////// // void Dialog::OnRightButtonReleased(OutlookTabCtrl *ctrl, CPoint pt) { CMenu menu; menu.LoadMenu(IDR_CONTEXT_MENU); CMenu *popup = menu.GetSubMenu(0); // if( !ctrl->CanVisibleItemPop() ) popup->EnableMenuItem(ID_CONTEXT_MENU_POP,MF_BYCOMMAND | MF_GRAYED); if( !ctrl->CanVisibleItemPush() ) popup->EnableMenuItem(ID_CONTEXT_MENU_PUSH,MF_BYCOMMAND | MF_GRAYED); // ctrl->ClientToScreen(&pt); popup->TrackPopupMenu(TPM_LEFTALIGN,pt.x,pt.y,this); } ///////////////////////////////////////////////////////////////////////////// // void Dialog::OnMenuButtonClicked(OutlookTabCtrl *ctrl, CRect const *rect) { OnRightButtonReleased(ctrl, CPoint(rect->right,rect->top) ); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // void Dialog::OnContextMenuPop() { m_OutlookTabCtrl.PopVisibleItem(); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // void Dialog::OnContextMenuPush() { m_OutlookTabCtrl.PushVisibleItem(); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // void Dialog::OnContextMenuManage() { if( ManageDialog(&m_OutlookTabCtrl).DoModal()==IDOK ) m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Style: style1. // void Dialog::OnBnClickedRadio11() { m_Style1.Install(&m_OutlookTabCtrl); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Style: style2. // void Dialog::OnBnClickedRadio12() { m_Style2.Install(&m_OutlookTabCtrl); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Style: style3. // void Dialog::OnBnClickedRadio13() { m_Style3.Install(&m_OutlookTabCtrl); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Style: style4. // void Dialog::OnBnClickedRadio14() { m_Style4.Install(&m_OutlookTabCtrl); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Caption: none. // void Dialog::OnBnClickedRadio21() { m_OutlookTabCtrl.ShowCaption(false); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Caption: top. // void Dialog::OnBnClickedRadio22() { if( !m_OutlookTabCtrl.IsCaptionVisible() ) m_OutlookTabCtrl.ShowCaption(true); m_OutlookTabCtrl.SetCaptionAlign(OutlookTabCtrl::CaptionAlignTop); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Caption: bottom. // void Dialog::OnBnClickedRadio23() { if( !m_OutlookTabCtrl.IsCaptionVisible() ) m_OutlookTabCtrl.ShowCaption(true); m_OutlookTabCtrl.SetCaptionAlign(OutlookTabCtrl::CaptionAlignBottom); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Layout: controls|splitter|tabs|buttons. // void Dialog::OnBnClickedRadio31() { m_OutlookTabCtrl.SetLayout(OutlookTabCtrl::Layout1); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Layout: controls|splitter|buttons|tabs. // void Dialog::OnBnClickedRadio32() { m_OutlookTabCtrl.SetLayout(OutlookTabCtrl::Layout2); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Layout: buttons|tabs|splitter|controls. // void Dialog::OnBnClickedRadio33() { m_OutlookTabCtrl.SetLayout(OutlookTabCtrl::Layout3); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Layout: tabs|buttons|splitter|controls. // void Dialog::OnBnClickedRadio34() { m_OutlookTabCtrl.SetLayout(OutlookTabCtrl::Layout4); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Buttons align: right. // void Dialog::OnBnClickedRadio41() { m_OutlookTabCtrl.SetButtonsAlign(OutlookTabCtrl::ButtonsAlignRight); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Buttons align: left. // void Dialog::OnBnClickedRadio42() { m_OutlookTabCtrl.SetButtonsAlign(OutlookTabCtrl::ButtonsAlignLeft); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Show border. // void Dialog::OnBnClickedCheck11() { m_OutlookTabCtrl.ShowBorder( GetButtonCheck(IDC_CHECK11) ); m_OutlookTabCtrl.Update(); m_OutlookTabCtrl.SetWindowPos(NULL, 0,0,0,0, SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED); // border update. } ///////////////////////////////////////////////////////////////////////////// // Active splitter. // void Dialog::OnBnClickedCheck12() { m_OutlookTabCtrl.ActivateSplitter( GetButtonCheck(IDC_CHECK12) ); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Show button text. // void Dialog::OnBnClickedCheck21() { m_OutlookTabCtrl.ShowButtonText( GetButtonCheck(IDC_CHECK21) ); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Show button separators. // void Dialog::OnBnClickedCheck22() { m_OutlookTabCtrl.ShowButtonSeparator( GetButtonCheck(IDC_CHECK22) ); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Show menu button. // void Dialog::OnBnClickedCheck23() { const bool show = GetButtonCheck(IDC_CHECK23); EnableControl(IDC_CHECK24,!show); m_OutlookTabCtrl.ShowMenuButton(show); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// // Hide empty button bar. // void Dialog::OnBnClickedCheck24() { m_OutlookTabCtrl.HideEmptyButtonsArea( GetButtonCheck(IDC_CHECK24) ); m_OutlookTabCtrl.Update(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#ifndef EX3OS_SEARCH_H #define EX3OS_SEARCH_H #include <iostream> #include "MapReduceFramework.h" #include "MapReduceClient.h" /* * File name key for the search task. */ class FileNameKey : public k1Base, public k2Base, public k3Base { private: std::string _name; public: FileNameKey(std::string name) : _name(name) {}; inline std::string getName() const { return _name; } inline bool operator<(const k1Base &other) const { return _name < ((FileNameKey*) &other)->getName(); } inline bool operator<(const k2Base &other) const { return _name < ((FileNameKey*) &other)->getName(); } inline bool operator<(const k3Base &other) const { return _name < ((FileNameKey*) &other)->getName(); } ~FileNameKey() {} }; /* * Integer value for the search task. */ class IntValue : public v2Base, public v3Base { private: int _value; public: IntValue(int value) : _value(value) {}; inline int getValue() { return _value; } ~IntValue() {} }; /* * MapReduce object for the search task. */ class SearchMapReduce : public MapReduceBase { private: std::string _strSearch; public: SearchMapReduce(std::string strSearch) : _strSearch(strSearch) {} inline std::string getStrSearch() const { return _strSearch; } void Map(const k1Base *const key, const v1Base *const val) const; void Reduce(const k2Base *const key, const V2_LIST &vals) const; }; #endif //EX3OS_SEARCH_H
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TESTCAUPDATERULES_HPP_ #define TESTCAUPDATERULES_HPP_ #include <cxxtest/TestSuite.h> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include "AbstractCaUpdateRule.hpp" #include "DiffusionCaUpdateRule.hpp" #include "AbstractCaSwitchingUpdateRule.hpp" #include "RandomCaSwitchingUpdateRule.hpp" #include "CellsGenerator.hpp" #include "FixedG1GenerationalCellCycleModel.hpp" #include "DifferentiatedCellProliferativeType.hpp" #include "CaBasedCellPopulation.hpp" #include "AbstractCellBasedTestSuite.hpp" #include "WildTypeCellMutationState.hpp" #include "CellLabel.hpp" #include "PottsMeshGenerator.hpp" #include "NodesOnlyMesh.hpp" #include "NodeBasedCellPopulation.hpp" #include "SmartPointers.hpp" #include "FileComparison.hpp" #include "PetscSetupAndFinalize.hpp" class TestCaUpdateRules : public AbstractCellBasedTestSuite { public: void TestDiffusionCaUpdateRuleIn2d() { // Set the timestep and size of domain to let us calculate the probabilities of movement double delta_t = 1; double delta_x = 1; double diffusion_parameter = 0.1; // Create an update law system DiffusionCaUpdateRule<2> diffusion_update_rule; // Test get/set methods TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 0.5, 1e-12); diffusion_update_rule.SetDiffusionParameter(1.0); TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 1.0, 1e-12); diffusion_update_rule.SetDiffusionParameter(diffusion_parameter); // Test EvaluateProbability() // Create a simple 2D PottsMesh PottsMeshGenerator<2> generator(5, 0, 0, 5, 0, 0); PottsMesh<2>* p_mesh = generator.GetMesh(); // Create cells std::vector<CellPtr> cells; MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, 1u, p_diff_type); // Specify where cells lie here we have one cell on the bottom left site std::vector<unsigned> location_indices; location_indices.push_back(0u); // Create cell population CaBasedCellPopulation<2u> cell_population(*p_mesh, cells, location_indices); // Note we just pass a pointer to the only cell as DiffusionUpdateRule is independent of cell type. CellPtr p_cell = cell_population.rGetCells().front(); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,5,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,10,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(6,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(7,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(10,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(12,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(15,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(16,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(17,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,19,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,18,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,23,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); } void TestDiffusionCaUpdateRuleIn2dWithMultipleCells() { // Set the timestep and size of domain to let us calculate the probabilities of movement double delta_t = 1; double delta_x = 1; double diffusion_parameter = 0.1; // Create an update law system DiffusionCaUpdateRule<2> diffusion_update_rule; // Test get/set methods TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 0.5, 1e-12); diffusion_update_rule.SetDiffusionParameter(1.0); TS_ASSERT_DELTA(diffusion_update_rule.GetDiffusionParameter(), 1.0, 1e-12); diffusion_update_rule.SetDiffusionParameter(diffusion_parameter); // Test EvaluateProbability() // Create a simple 2D PottsMesh PottsMeshGenerator<2> generator(5, 0, 0, 5, 0, 0); PottsMesh<2>* p_mesh = generator.GetMesh(); // Create cells std::vector<CellPtr> cells; MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, 10u, p_diff_type); // Specify where cells lie here we have one cell on the bottom left site std::vector<unsigned> location_indices; // Two cells will be added in locations 0 and 1 location_indices.push_back(0u); location_indices.push_back(0u); location_indices.push_back(1u); location_indices.push_back(1u); // Then other cells are added to the lattice to check if the probabilities are still the same for (unsigned i=4; i<10; i++) { location_indices.push_back(i); } // Create cell population CaBasedCellPopulation<2u> cell_population(*p_mesh, cells, location_indices, 2); // Note we just pass a pointer to the first cell as DiffusionUpdateRule is independent of cell type. CellPtr p_cell = cell_population.rGetCells().front(); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(0,5,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,1,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,6,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,10,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(5,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(6,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(7,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(10,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(12,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(15,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(16,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(17,11,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,19,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,18,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/4.0,1e-6); TS_ASSERT_DELTA(diffusion_update_rule.EvaluateProbability(24,23,cell_population, delta_t, delta_x, p_cell),diffusion_parameter*delta_t/delta_x/delta_x/2.0,1e-6); } void TestArchiveDiffusionCaUpdateRule() { OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "DiffusionCaUpdateRule.arch"; { DiffusionCaUpdateRule<2> update_rule; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables update_rule.SetDiffusionParameter(1.0); // Serialize via pointer to most abstract class possible AbstractCaUpdateRule<2>* const p_update_rule = &update_rule; output_arch << p_update_rule; } { AbstractCaUpdateRule<2>* p_update_rule; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_update_rule; // Test the member data TS_ASSERT_DELTA((static_cast<DiffusionCaUpdateRule<2>*>(p_update_rule))->GetDiffusionParameter(), 1.0, 1e-6); // Tidy up delete p_update_rule; } } void TestUpdateRuleOutputUpdateRuleInfo() { std::string output_directory = "TestCaUpdateRulesOutputParameters"; OutputFileHandler output_file_handler(output_directory, false); // Test with VolumeConstraintPottsUpdateRule DiffusionCaUpdateRule<2> diffusion_update_rule; diffusion_update_rule.SetDiffusionParameter(1.0); TS_ASSERT_EQUALS(diffusion_update_rule.GetIdentifier(), "DiffusionCaUpdateRule-2"); out_stream diffusion_update_rule_parameter_file = output_file_handler.OpenOutputFile("diffusion_update_rule_results.parameters"); diffusion_update_rule.OutputUpdateRuleInfo(diffusion_update_rule_parameter_file); diffusion_update_rule_parameter_file->close(); // Compare the generated file in test output with a reference copy in the source code. FileFinder generated = output_file_handler.FindFile("diffusion_update_rule_results.parameters"); FileFinder reference("cell_based/test/data/TestCaUpdateRules/diffusion_update_rule_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated, reference); TS_ASSERT(comparer.CompareFiles()); } /* * Now test the switching rules. */ void TestRandomCaSwitchingUpdateRuleIn2d() { // Set the timestep and size of domain to let us calculate the probabilities of movement double delta_t = 0.1; double delta_x = 1; double switching_parameter = 0.1; // Create an update law system RandomCaSwitchingUpdateRule<2> random_switching_update_rule; // Test get/set methods TS_ASSERT_DELTA(random_switching_update_rule.GetSwitchingParameter(), 0.5, 1e-12); random_switching_update_rule.SetSwitchingParameter(1.0); TS_ASSERT_DELTA(random_switching_update_rule.GetSwitchingParameter(), 1.0, 1e-12); random_switching_update_rule.SetSwitchingParameter(switching_parameter); // Test EvaluateProbability() // Create a simple 2D PottsMesh PottsMeshGenerator<2> generator(3, 0, 0, 3, 0, 0); PottsMesh<2>* p_mesh = generator.GetMesh(); // Create cells std::vector<CellPtr> cells; MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, 6u, p_diff_type); // Specify where cells lie here we have cells on the bottom two rows std::vector<unsigned> location_indices; for (unsigned i=0; i<6; i++) { location_indices.push_back(i); } // Create cell population CaBasedCellPopulation<2u> cell_population(*p_mesh, cells, location_indices); TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(0,1,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6); TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(0,6,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6); TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(0,5,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6); // Note this is independent of node index and population so even returns for nodes not in the mesh TS_ASSERT_DELTA(random_switching_update_rule.EvaluateSwitchingProbability(UNSIGNED_UNSET,UNSIGNED_UNSET,cell_population, delta_t, delta_x),switching_parameter*delta_t,1e-6); } void TestArchiveRandomCaSwitchingUpdateRule() { OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "RandomCaSwitchingUpdateRule.arch"; { RandomCaSwitchingUpdateRule<2> update_rule; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables update_rule.SetSwitchingParameter(1.0); // Serialize via pointer to most abstract class possible AbstractCaSwitchingUpdateRule<2>* const p_update_rule = &update_rule; output_arch << p_update_rule; } { AbstractCaSwitchingUpdateRule<2>* p_update_rule; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_update_rule; // Test the member data TS_ASSERT_DELTA((static_cast<RandomCaSwitchingUpdateRule<2>*>(p_update_rule))->GetSwitchingParameter(), 1.0, 1e-6); // Tidy up delete p_update_rule; } } void TestSwitchingUpdateRuleOutputUpdateRuleInfo() { std::string output_directory = "TestCaSwitchingUpdateRulesOutputParameters"; OutputFileHandler output_file_handler(output_directory, false); // Test with RandomCaSwitchingUpdateRule RandomCaSwitchingUpdateRule<2> random_switching_update_rule; random_switching_update_rule.SetSwitchingParameter(1.0); TS_ASSERT_EQUALS(random_switching_update_rule.GetIdentifier(), "RandomCaSwitchingUpdateRule-2"); out_stream random_switching_update_rule_parameter_file = output_file_handler.OpenOutputFile("random_switching_update_rule_results.parameters"); random_switching_update_rule.OutputUpdateRuleInfo(random_switching_update_rule_parameter_file); random_switching_update_rule_parameter_file->close(); // Compare the generated file in test output with a reference copy in the source code. FileFinder generated = output_file_handler.FindFile("random_switching_update_rule_results.parameters"); FileFinder reference("cell_based/test/data/TestCaUpdateRules/random_switching_update_rule_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated, reference); TS_ASSERT(comparer.CompareFiles()); } }; #endif /*TESTCAUPDATERULES_HPP_*/
#pragma once #include <fstream> #include "Square.hpp" static Color getClosestColor(glm::vec3 color); /* return the euchlidian distance between two colors */ static int getEuchlidianDistance(glm::vec3 color1, glm::vec3 color2); class BMPImage { private: size_t width, height; char header[54]; // file metadata 54 bytes long char* data; size_t dataSize; public: BMPImage(const char* const filepath); ~BMPImage(); size_t getWidth() const; size_t getHeight() const; void getPixels(Color output[]) const; };
#ifndef GDIPLUS_TEXTURE #define GDIPLUS_TEXTURE #include <windows.h> #include <gdiplus.h> // for rendering primitives to textures #include <tchar.h> #include <d3d9.h> // core direct3d #include <d3dx9.h> // aux libs #include "helperFunctions.h" using namespace Gdiplus ; class GDIPlusTexture { private: IDirect3DTexture9 *tex ; IDirect3DSurface9 *surface ; HDC texDC ; IDirect3DDevice9 *gpu ; // retain own reference obtained during construction int width, height ; public: Graphics *g ; // g is how you draw to the texture public: // Create a new texture that // you can draw to using GDI+ // smoothingMode will "blur the edges" // of the texture so it doesn't look so blocky. // "smoothingMode" is slower but looks much better. GDIPlusTexture( IDirect3DDevice9 *gpu, int width, int height, bool smoothingMode=true ) ; // Call this when you're DONE // drawing with g and you want // the texture back. You CAN // continue to draw after you // getTexture() IDirect3DTexture9* getTexture() ; int getWidth() ; int getHeight() ; // Uses the rect you specify to draw the text // and the background box. Text may get cut off void boxedText( TCHAR* text, Font *font, RECT padding, Color textColor, Color bkgColor, RectF limitingRect, StringAlignment alignment ) ; // Supports BMP, GIF, JPEG, PNG, TIFF, and EMF // D3DX supports .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga // So you can use this to load // .gif, .tiff, and .emf files while // the D3DX function cannot load them. static GDIPlusTexture* CreateFromFile( IDirect3DDevice9 *gpu, const char *filename ) ; ~GDIPlusTexture() ; } ; #endif
#include "stdafx.h" #include<sstream> #include<fstream> #include<iostream> #include<algorithm> #include<string> using namespace std; void printLastKlines(string filename){ const int k = 4; string L[k]; ifstream in(filename); int size = 0; if (in){ //Returns the next character in the input sequence, without extracting it: while (in.peek() != EOF){ //if the next line is not the End of file. getline(in, L[size%k]); //circular array. size++; } //case 1. size <= k . //k = 5, size = 3, there are only three lines in the file. //print L[0] to L[min(k,size)-1]. //case 2. size >k. //k = 3, size = 7, there are seven lines in the file. //0 1 2 //3 4 5 //6 //print out 4, 5, 6. Start at L[1] to L[0], which means L[(size % k + i) % k], i from 0 to k int start = size>k ? (size%k) : 0; int count = min(k, size); for (int i = 0; i<count; i++){ cout << L[(start + i) % k] << endl; } } } int main(){ string file1 = "12-1_test_case1.txt"; string file2 = "12-1_test_case2.txt"; cout << "File 1" << endl; printLastKlines(file1); cout << "File 2" << endl; printLastKlines(file1); system("pause"); return 0; }
#include <Adafruit_Sensor.h> //Compass stuff #include <Wire.h> //I2C Arduino Library #define address 0x1E //0011110b, I2C 7bit address of HMC5883 // Ultrasonic sensors use digital ports and needs a trigger to get an echo int rearUStrigger = 24; // rear Ultrasonic prox sensor trigger int rearUSecho = 22; // rear Ultrasonic prox sensor echo int frontUStrigger = 51; // front Ultrasonic prox sensor trigger int frontUSecho = 50; // front Ultrasonic prox sensor echo // Microphones use analog inputs int fR_MIC = 0; // front right microphone int fL_MIC = 1; // front left microphone int rR_MIC = 3; // rear right microphone int rL_MIC = 2; // rear left microphone // Compass uses digital ports int compData = 46; // Compass Data int compClock = 47; // Compass Clock // Remote controls use Pulse Wave Modulation digital outputs int rcLR = 12; // Remote Control L&R port FORWARD int rcFB = 11; // Remote Control F&B port FRONT STREERING int divider = 0; int check_fR_MIC = 1; int check_fL_MIC = 0; int check_rR_MIC = 0; int check_rL_MIC = 0; int check_compass = 1; int check_ultrasonicF = 0; int check_ultrasonicR = 0; void setup() { Serial.begin(9600); pinMode(rearUStrigger,OUTPUT); pinMode(rearUSecho,INPUT); pinMode(frontUStrigger,OUTPUT); pinMode(frontUSecho,INPUT); pinMode(rcLR,OUTPUT); pinMode(rcFB,OUTPUT); //Setting up Compass stuff Wire.begin(); //Put the HMC5883 IC into the correct operating mode Wire.beginTransmission(address); //open communication with HMC5883 Wire.write(0x02); //select mode register Wire.write(0x00); //continuous measurement mode Wire.endTransmission(); } void loop() { //#################MICROPHONE START################ /////////////////FRONT RIGHT/////////////////////// if(check_fR_MIC == 1){ for(int i = 0; i <=10; i++){ int sample = analogRead(fR_MIC); Serial.println(sample); } Serial.println(divider); } /////////////////FRONT LEFT/////////////////////// if(check_fL_MIC == 1){ for(int i = 0; i <=10; i++){ int sample = analogRead(fL_MIC); Serial.println(sample); } Serial.println(divider); } /////////////////REAR RIGHT/////////////////////// if(check_rR_MIC == 1){ for(int i = 0; i <=10; i++){ int sample = analogRead(rR_MIC); Serial.println(sample); } Serial.println(divider); } /////////////////REAR LEFT/////////////////////// if(check_rL_MIC == 1){ for(int i = 0; i <=10; i++){ int sample = analogRead(rL_MIC); Serial.println(sample); } Serial.println(divider); } //#################MICROPHONE END################# //#################ULTRA SONIC START################# /////////////////FRONT ULTRASONIC PROX///////////////// if(check_ultrasonicF == 1){ for(int i = 0; i <=10; i++){ digitalWrite(frontUStrigger, LOW); digitalWrite(frontUStrigger, HIGH); digitalWrite(frontUStrigger, LOW); int duration = pulseIn(frontUSecho, HIGH); Serial.println(duration); } Serial.println(divider); } /////////////////REAR ULTRASONIC PROX///////////////// if(check_ultrasonicR == 1){ for(int i = 0; i <=10; i++){ digitalWrite(rearUStrigger , LOW); digitalWrite(rearUStrigger , HIGH); digitalWrite(rearUStrigger , LOW); int duration = pulseIn(rearUSecho , HIGH); Serial.println(duration); } Serial.println(divider); } //#################ULTRA SONIC END################# /////////////////CHECK COMPASS///////////////// if(check_compass == 1){ for(int i = 0; i <=10; i++){ int x,y,z; //triple axis data //Tell the HMC5883L where to begin reading data Wire.beginTransmission(address); Wire.write(0x03); //select register 3, X MSB register Wire.endTransmission(); //Read data from each axis, 2 registers per axis Wire.requestFrom(address, 6); if(6<=Wire.available()){ x = Wire.read()<<8; //X msb x |= Wire.read(); //X lsb z = Wire.read()<<8; //Z msb z |= Wire.read(); //Z lsb y = Wire.read()<<8; //Y msb y |= Wire.read(); //Y lsb } //Print out values of each axis Serial.print("x: "); Serial.print(x); Serial.print(" y: "); Serial.print(y); Serial.print(" z: "); Serial.println(z); delay(250); } Serial.println(divider); } /////////////////MOTOR TEST///////////////// analogWrite(rcLR,50); }
// // GroupScene.cpp // XinzhouProject // // Created by YangLin on 2017/6/20. // // #include "GroupScene.h" GroupScene::GroupScene() { } GroupScene::~GroupScene() { } Scene * GroupScene::createScene() { auto scene = Scene::create(); auto layer = GroupScene::create(); scene->addChild(layer); return scene; } bool GroupScene::init() { if ( !Layer::init() ) { return false; } return true; } void GroupScene::onEnter() { Layer::onEnter(); initResource(); } void GroupScene::onEnterTransitionDidFinish() { Layer::onEnterTransitionDidFinish(); } void GroupScene::onExit() { Layer::onExit(); } void GroupScene::initResource() { }