text
stringlengths 8
6.88M
|
|---|
#pragma once
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <array>
#include <vector>
namespace oglml
{
class Texture2D;
class Shader;
class Particles
{
using ColorsData = std::array<float, 4>;
using OffsetsData = std::array<float, 2>;
public:
Particles();
~Particles() = default;
void SetNumber(std::size_t size);
void SetOrthoParams(float width, float height);
void SetTexture(Texture2D& texture);
void SetShader(Shader& shader);
void BufferColorsData(const std::vector<ColorsData>& colors);
void BufferOffsetsData(const std::vector<OffsetsData>& offsets);
void Draw();
protected:
void BindData();
private:
unsigned int m_colorsVBO;
unsigned int m_offsetsVBO;
unsigned int m_textureID = 0;
unsigned int m_shaderID = 0;
std::size_t m_particleNumber = 500;
glm::mat4 m_projection = glm::ortho(0.0f, 800.0f, 600.0f, 0.0f, -1.0f, 1.0f);
};
}
|
#include "m580_button.h"
M580_button::M580_button(QString text, QWidget *parent) : QPushButton(parent), m_text(text)
{
setText(m_text);
setStyleSheet("background-color: rgb(237, 187, 153);"
"color: rgb(255, 255, 255);");
}
void M580_button::setName(QString text)
{
m_text = text;
}
QString M580_button::getName()
{
return m_text;
}
M580_button::~M580_button()
{
}
|
#include <iostream>
#include "console.h"
#include<ctime>
using namespace std;
#define tuong_tren 2
#define tuong_duoi 23
#define tuong_trai 5
#define tuong_phai 69
struct ToaDo
{
int x,y;
};
ToaDo thanran[200];
enum TrangThai {UP,DOWN,RIGHT,LEFT};
struct snake
{
int n;//so đot cua ran
TrangThai tt;
};
void printSnake(snake snake,ToaDo dotcuoi)
{
setTextColor(22);
gotoXY(thanran[0].x, thanran[0].y);
cout<<(char)233;
for (int i=1 ; i<snake.n; i++)
{
setTextColor(2);
gotoXY(thanran[i].x, thanran[i].y);
cout<<(char)240;
}
gotoXY(dotcuoi.x,dotcuoi.y);
cout<<" ";
}
ToaDo dichuyen(snake&snake)
{
ToaDo dotcuoi=thanran[snake.n-1];
for(int i=snake.n-1; i>0; i--)
thanran[i]=thanran[i-1];
//input key(nhap bang ban phim)
int x=inputKey();
if (x=='A'||x=='a')
snake.tt=LEFT;
else if (x=='D'||x=='d')
snake.tt=RIGHT;
else if (x=='s'||x=='S')
snake.tt=DOWN;
else if (x=='w'||x=='W')
snake.tt=UP;
//di chuyen theo huong
if(snake.tt==UP)
thanran[0].y--;
else if (snake.tt==DOWN)
thanran[0].y++;
else if (snake.tt==RIGHT)
thanran[0].x++;
else if (snake.tt==LEFT)
thanran[0].x--;
return dotcuoi;
}
void themDotRan(snake &snake)
{
thanran[snake.n]=thanran[snake.n-1];
snake.n++;
}
void tuong()
{
for (int i=tuong_trai; i<=tuong_phai; i++)
{
setTextColor(19);
gotoXY(i,tuong_tren);
cout<<(char)220;
}
for (int i=tuong_trai; i<=tuong_phai; i++)
{
setTextColor(19);
gotoXY(i,tuong_duoi);
cout<<(char)220;
}
for (int x=tuong_tren+1; x<=tuong_duoi; x++)
{
setTextColor(19);
gotoXY(tuong_trai,x);
cout<<(char)219;
}
for (int i=tuong_tren+1; i<=tuong_duoi; i++)
{
setTextColor(19);
gotoXY(tuong_phai,i);
cout<<(char)219;
}
for (int i=tuong_tren+5; i<=tuong_duoi-5; i++)
{
setTextColor(11);
gotoXY(tuong_phai-15,i);
cout<<(char)219;
}
for (int i=tuong_tren+5; i<=tuong_duoi-5; i++)
{
setTextColor(11);
gotoXY(tuong_trai+15,i);
cout<<(char)219;
}
}
ToaDo bong()
{
setTextColor(12);
srand(time(NULL));
//bong di chuyen random tu trai qua phai tu tren xuong duoi
int x=tuong_trai+1+rand() % ((tuong_phai-1)-(tuong_trai+1)+1);
int y=tuong_tren+1+rand() % ((tuong_duoi-1)-(tuong_tren+1)+1);
gotoXY(x,y);
cout<<"0";
//return toa do cua bong
ToaDo temp;
temp.x=x;
temp.y=y;
return temp;
}
bool kiemtraanbong(ToaDo bong)
{
if (thanran[0].x==bong.x&& thanran[0].y==bong.y)
return true;
else
return false;
}
bool gameOver()
{
if (thanran[0].y == tuong_tren)
return true;
else if (thanran[0].y == tuong_duoi)
return true;
else if (thanran[0].x == tuong_trai)
return true;
else if (thanran[0].x == tuong_phai)
return true;
else if (thanran[0].x == tuong_phai-15&&thanran[0].y>=tuong_tren+5&&thanran[0].y<=tuong_duoi-5)
return true;
else if (thanran[0].x == tuong_trai+15&&thanran[0].y>=tuong_tren+5&&thanran[0].y<=tuong_duoi-5)
return true;
else
return false;
}
void GameOver()
{
if(gameOver()==true)
{
Sleep(500);
clrscr();
cout<<"Game Over. You Lose!!!";
}
}
int main()
{
//Khoi tao ran
snake snake;
snake.n=3;
thanran[0].x=tuong_trai+3;
thanran[0].y=tuong_tren+2;
thanran[1].x=tuong_trai+2;
thanran[1].y=tuong_tren+2;
thanran[1].x=tuong_trai+1;
thanran[1].y=tuong_tren+2;
snake.tt=RIGHT;
//
//diem
int diem=0;
//hien thi tuong
tuong();
//hien thi bong
ToaDo b=bong();
while (1)
{
//di chuyen
ToaDo dotcuoi=dichuyen(snake);
//in ran
printSnake(snake,dotcuoi);
if (kiemtraanbong(b)==true)
{
b=bong();
themDotRan(snake);
diem++;
gotoXY(tuong_phai+5,tuong_tren);
cout<<"Diem: "<<diem;
}
//toc do ran
if (gameOver()==true)
break;
Sleep(100);
}
GameOver();
cout<<endl<<"Your point is : "<<diem;
}
|
/* usb test with libusb-1.0 */
#include <iostream>
#include "libusb.h"
int main() {
libusb_device **devs;
libusb_device *dev;
libusb_device_descriptor desc;
libusb_device_handle *dh;
uint8_t path[8];
uint8_t sdat[255];
int r, cnt;
r = libusb_init(NULL); // initalize
if(r < 0) return r;
cnt = libusb_get_device_list(NULL, &devs);
if(cnt < 0) return cnt;
for(int i = 0; i < cnt; i++){
dev = devs[i];
r = libusb_get_device_descriptor(dev, &desc);
if(r < 0){
std::cout << "device get error..." << std::endl;
return r;
}
// show device description
printf("%04x/%04x (bus %d, device %d)", desc.idVendor, desc.idProduct,
libusb_get_bus_number(dev), libusb_get_device_address(dev));
r = libusb_get_port_numbers(dev, path, sizeof(path));
if(r < 0) return r;
printf(" path: %d", path[0]);
for(int j = 1; j < r; j++){
printf(".%d", path[j]);
}
// show spec string
libusb_open(dev, &dh);
// manufacturer, product, serialnumber
r = libusb_get_string_descriptor_ascii(dh, desc.iManufacturer,
(unsigned char *)sdat, sizeof(sdat));
if(r > -1) printf(" %s", sdat);
r = libusb_get_string_descriptor_ascii(dh, desc.iProduct,
(unsigned char *)sdat, sizeof(sdat));
if(r > -1) printf(" %s", sdat);
r = libusb_get_string_descriptor_ascii(dh, desc.iSerialNumber,
(unsigned char *)sdat, sizeof(sdat));
if(r > -1) printf(" %s", sdat);
libusb_release_interface(dh, 0);
libusb_close(dh);
printf("\n");
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL); // exit
return 0;
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 2003-2007 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Julien Picalausa
//
#ifndef OPERAINSTALLER_H
#define OPERAINSTALLER_H
#include "platforms/windows/win_handy.h"
#include "adjunct/autoupdate/country_checker.h"
#define REG_DEL_KEY (DWORD)-2
class OpTransaction;
class OperaInstallLog;
class OperaInstallerUI;
/*
The opera Installer class is used for two purposes:
-running the opera installer
-keeping track of which extensions and protocols are associated to opera
and changing those associations.
For running the installer, an installer object should be construced on the heap
and the RunWizard method should be called (or Run for non-interactive installation).
If no error is returned, control can be returned to the message loop and the installer
installer will manage itself and ultimately delete itself and exit.
When managing extension and protocol associations, the installer can be created on the
stack and the methods related to associations handling can be called
*/
class OperaInstaller
: private CountryCheckerListener
{
public:
/** The constructor will initialize the installer object depending on the options
* present on the command line.
*
* If the -install option is present, the installer settings to use are read from the
* command line and determines whether it is going to perform an upgrade.
*
* If the -install option isn't present, the object is initialized using the informations
* found in the log file created when installing the current opera instance.
*/
OperaInstaller();
~OperaInstaller();
/******** Installer run ********/
/** Starts the (un)installation in a non-interactive manner.
*
* @return OpStatus::OK if the installation process was successfully initialized.
* OpStatus::ERR if an error was encountered during initialization that would prevent any future call to run to succeed.
* Other error codes, except OOM indicate issues that can be fixed by changing the installation path or other settings.
*
*/
OP_STATUS Run();
/** Starts the (un)installation wizard
*/
OP_STATUS RunWizard();
/******** Associations handing ********/
/** List of files and protocols that Opera can be set to handle.
*/
enum AssociationsSupported
{
OEX = 0,
HTM,
HTML,
XHT,
XHTM,
XHTML,
MHT,
MHTML,
XML,
TORRENT,
BMP,
JPG,
JPEG,
PNG,
SVG,
GIF,
XBM,
OGA,
OGV,
OGM,
OGG,
WEBM,
HTTP,
HTTPS,
FTP,
MAILTO,
NNTP,
NEWS,
SNEWS,
LAST_ASSOC
};
/** Sets Opera as the default browser and handler for the most commonly supported files/protocols
*
* @param all_users If TRUE, the change is made system-wide (if possible).
* Otherwise, the change is made for the current user only.
*/
OP_STATUS SetDefaultBrowserAndAssociations(BOOL all_users = FALSE);
/** Sets Opera as the default mailer and handler for email related files/protocols
*
* @param all_users If TRUE, the change is made system-wide (if possible).
* Otherwise, the change is made for the current user only
*/
OP_STATUS SetDefaultMailerAndAssociations(BOOL all_users = FALSE);
/** Sets Opera as handler for news related files/protocols
*
* @param all_users If TRUE, the change is made system-wide (if possible).
* Otherwise, the change is made for the current user only
*/
OP_STATUS SetNewsAssociations(BOOL all_users = FALSE);
/** Rewrites the opera file handlers (Opera.HTML, Opera.Image, ...) to the registry.
*
* @param all_users If TRUE, the change is made system-wide (if possible).
* Otherwise, the change is made for the current user only
*/
OP_STATUS RestoreFileHandlers(BOOL all_users = FALSE);
/**
* Find out whether Opera is the handler for a given file type or protocol
*
* @param assoc The association to test for
*
* @return BOOL Whether Opera is set as handler for this extension/protocol
*/
BOOL HasAssociation(AssociationsSupported assoc);
/** Find out whether Opera is the default browser (on start menu)
*/
BOOL IsDefaultBrowser();
/**Find out whether Opera is the default mailer (on start menu)
*/
BOOL IsDefaultMailer();
/** Makes Opera the handler for a given file type or protocol
*
* @param assoc Specifies which file type/protocol to handle
*
* @param all_users If TRUE, the change is made system-wide (if possible).
* Otherwise, the change is made for the current user only
*/
OP_STATUS AssociateType(AssociationsSupported assoc, BOOL all_users = FALSE);
/** Sets Opera as the default browser (on start menu)
*
* @param all_users If TRUE, the change is made system-wide (if possible).
* Otherwise, the change is made for the current user only
*/
OP_STATUS BecomeDefaultBrowser(BOOL all_users = FALSE);
/** Sets Opera as the default mailer (on start menu)
*
* @param all_users If TRUE, the change is made system-wide (if possible).
* Otherwise, the change is made for the current user only
*/
OP_STATUS BecomeDefaultMailer(BOOL all_users = FALSE);
/** Returns whether Opera should use the system's default programs dialog or should
* use it's own file associations dialog.
*/
BOOL UseSystemDefaultProgramsDialog() {return IsSystemWin8() || IsSystemWinVista() && m_settings.all_users;}
/** Reports whether the installer object is in a state where it can reliably be used to examine
* or change file and protocol associations.
*
* This should only ever return FALSE if opera was started with the install or uninstall options
* or if the installer log file is not found in the opera directory. Even if FALSE is returned,
* all methods related to associations handling will still work, but the result will not be predictable
*/
BOOL AssociationsAPIReady() {return m_operation == OpNone && m_old_install_log != NULL; }
/******** Data structures used by the installer classes ********/
/** Structure defining the different settings the installer should respect when
* running
*/
typedef struct Settings
{
BOOL copy_only; //Installer should only copy the files to destination and nothing else
BOOL single_profile; //The installer should set up opera to use a single user profile instead of windows user profiles
BOOL launch_opera; //The installer will launch opera after completing installation
//All of the following should be FALSE if copy_only is true
BOOL all_users; //The installer should make system-wide change to install opera for all users (requires admin privileges)
BOOL set_default_browser; //The installer will make Opera the default browser for the current user (or for the system if all_users is true)
//Shortucts that the installer should create
BOOL desktop_shortcut;
BOOL start_menu_shortcut;
BOOL quick_launch_shortcut;
BOOL pinned_shortcut; //This option is applicable on Windows 7
//Whether the installer will actually delete or create these shortcuts when updating
BOOL update_desktop_shortcut;
BOOL update_start_menu_shortcut;
BOOL update_quick_launch_shortcut;
BOOL update_pinned_shortcut;
} Settings;
/** List of operations that the installer can perform. Used to know which
* mode the installer is in.
*/
typedef enum Operation
{
OpNone = 0,
OpInstall,
OpUpdate, // ToDo: Can we change this to upgrade. It's not a really good name when used in the wizard.
OpUninstall
} Operation;
/** Flags indicating which parts of the profile should be removed when
* uninstalling. Full provile is used when the entire profile folder
* should be removed.
*/
enum DeleteProfileParts
{
KEEP_PROFILE = 0x0000, //Don't remove anything
REMOVE_GENERATED = 0x0001, //History, cache, thumbnails, temporary downloads, etc...
REMOVE_PASSWORDS = 0x0002, //Wand and certificates
REMOVE_CUSTOMIZATION = 0x0004, //toolbars, keyboard shortcuts, skin,...
REMOVE_EMAIL = 0x0008, //mail folder
REMOVE_BOOKMARKS = 0x0010, //bookmarks
REMOVE_UNITE_APPS = 0x0020, //Unite apps
FULL_PROFILE = 0xFFFF, //Remove the fill profile directory
};
/** Used by RegistryOperation to express for which product an operation should be performed
*/
enum Product
{
PRODUCT_OPERA = 0x01,
PRODUCT_OPERA_NEXT = 0x02,
PRODUCT_OPERA_LABS = 0x04,
PRODUCT_ALL = 0xFF,
};
/** Structure used in to define lists of registry changes to perform.
*/
struct RegistryOperation
{
uni_char* key_path; //The key to change
uni_char* value_name; //The name of the value to change (NULL for default value)
DWORD value_type; //The value type. This can be either of the value type specified by the registry API when adding a value or REG_DELETE or REG_DEL_KEY
void* value_data; //The value data. The actual type to be casted to void* depends on value_type
// REG_NONE, REG_DELETE, REG_DELETE_KEY -> NULL
// REG_SZ, REG_EXPAND_SZ -> uni_char*
// REG_DWORD -> DWORD
// REG_BINARY -> char*
// Other types are not supported as of yet.
WinType min_os_version; //Minimum OS version required to perform operation. The operation will be ignored otherwise
HKEY root_key_limit; //Set to HKEY_CURRENT_USER if the operation should only be performed when installing for the current user
//or to HKEY_LOCAL_MACHINE if the operation should only be performed for installing for all users
//NULL if it can be performed in both cases.
UINT product_limit; //Indicate to only perform a registry operation if the correct product is being installed
UINT clean_parents; //How many ancestor levels of this key should be removed along with the value when uninstalling
};
/** List of errors that can occur during (un)installation.
*/
typedef enum ErrorCode
{
GET_USER_NAME_FAILED,
INSTALLER_INIT_FOLDER_FAILED,
INSTALLER_INIT_OPERATION_FAILED,
LAST_INSTALL_PATH_KEY_STRING_SET_FAILED,
INVALID_FOLDER,
CREATE_FOLDER_FAILED,
CANT_GET_FOLDER_WRITE_PERMISSIONS,
SHOW_PROGRESS_BAR_FAILED,
COPY_FILE_INIT_FAILED,
COPY_FILE_REPLACE_FAILED,
REGISTRY_INIT_UNINSTALL_KEY_FAILED,
REGISTRY_INIT_REGOP_KEY_FAILED,
SHORTCUT_INFO_INIT_FAILED,
BUILD_SHORTCUT_LIST_FAILED,
SHORTCUT_INIT_FAILED,
SHORTCUT_FILE_CONSTRUCT_FAILED,
SHORTCUT_REPLACE_FAILED,
SHORTCUT_DEPLOY_FAILED,
DEFAULT_PREFS_FILE_INIT_FAILED,
DEFAULT_PREFS_FILE_CREATE_FAILED,
DEFAULT_PREFS_FILE_CONSTRUCT_FAILED,
SET_MULTIUSER_PREF_FAILED,
INIT_LANG_PATH_FAILED,
SET_LANG_FILE_DIR_PREF_FAILED,
SET_LANG_FILE_PREF_FAILED,
DEFAULT_PREFS_FILE_COMMIT_FAILED,
INIT_DESKTOP_RESOURCES_FAILED,
GET_FIXED_PREFS_FOLDER_FAILED,
FIXED_PREFS_INIT_FAILED,
FIXED_PREFS_MAKE_COPY_FAILED,
FIXED_PREFS_COPY_CONTENT_FAILED,
SAVE_LOG_FAILED,
COMMIT_TRANSACTION_FAILED,
OLD_FILE_MATCHES_INIT_FAILED,
INIT_OLD_FILE_PATH_FAILED,
DELETE_OLD_FILE_FAILED,
INIT_OLD_SHORTCUT_FILE_FAILED,
DELETE_OLD_SHORTCUT_FAILED,
INIT_KEY_REPORTED_FAILED,
REGISTRY_OPERATION_FAILED,
DELETE_OLD_REG_VALUE_FAILED,
INIT_OLD_KEY_FAILED,
DELETE_OLD_KEY_FAILED,
DELETE_OLD_LOG_FAILED,
INIT_FILES_LIST_FAILED,
FILES_LIST_MISSING,
FILES_LIST_READ_FAILED,
INIT_RERUN_ARGS_FAILED,
WRONG_RERUN_OPERATION,
ELEVATION_SHELL_EXECUTE_FAILED,
ELEVATION_WAIT_FAILED,
ELEVATION_CREATE_EVENT_FAILED,
CANT_READ_MSI_UNINSTALL_KEY,
INIT_MSI_UNINSTALL_KEY_FAILED,
INIT_MSI_UNINSTALL_FOLDER_FAILED,
INIT_MSI_UNINSTALL_ARGS_FAILED,
MSI_UNINSTALL_SHELLEXECUTE_FAILED,
INIT_WISE_UNINSTALL_PATH_FAILED,
INIT_WISE_UNINSTALL_ARGS_FAILED,
WISE_UNINSTALL_SHELLEXECUTE_FAILED,
CANT_INSTALL_SINGLE_PROFILE_WITHOUT_WRITE_ACCESS,
SHORTCUT_INFO_SET_NEW_NAME_FAILED,
PARENT_PATH_INIT_FAILED,
INSTALLER_INIT_LOG_FAILED,
WRITE_FILE_TO_LOG_FAILED,
WRITE_REG_HIVE_TO_LOG_FAILED,
WRITE_SHORTCUT_TO_LOG_FAILED,
INIT_OLD_SHORTCUT_NAME,
FIND_OLD_SHORTCUT,
INIT_NEW_SHORTCUT_PATH,
INIT_NEW_SHORTCUT_FILE,
INIT_OLD_SHORTCUT_FILE,
MOVE_SHORTCUT_FAILED,
SET_SHORTCUT_NEW_PATH,
OTHER_USERS_ARE_LOGGED_ON,
CANT_ELEVATE_WITHOUT_UAC,
MSI_UNINSTALL_FAILED,
INIT_ELEVATION_ARGS_FAILED,
GET_INSTALLER_PATH_FOR_RUNONCE_FAILED,
INIT_RUNONCE_STRING,
WRITE_RUNONCE_FILE,
SET_RUNONCE_FAILED,
FIXED_PREFS_FILE_CREATE_FAILED,
FIXED_PREFS_FILE_CONSTRUCT_FAILED,
FIXED_PREFS_FILE_COMMIT_FAILED,
INIT_PREF_ENTRY_FAILED,
SET_PREF_FAILED,
COPY_FILE_WRITE_FAILED,
CANT_OBTAIN_WRITE_ACCESS,
ELEVATION_CANT_FIX_EVENT_ACL,
SET_OPERANEXT_PREF_FAILED,
MAKE_SHORTCUT_COMPARE_NAME_FAILED,
PIN_TO_TASKBAR_FAILED,
UNPIN_FROM_TASKBAR_FAILED,
PIN_OPERA_PATH_INIT_FAILED,
TEMP_OPERA_PATH_INIT_FAILED,
UNPIN_OPERA_PATH_INIT_FAILED,
TEMP_INIT_OLD_SHORTCUT_FILE_FAILED,
PIN_DELETE_OLD_SHORTCUT_FAILED,
TEMP_SHORTCUT_SET_NEW_NAME_FAILED,
TEMP_SHORTCUT_INIT_FAILED,
TEMP_SHORTCUT_DEPLOY_FAILED,
INIT_ERROR_LOG_PATH_FAILED,
INIT_ERROR_LOG_FAILED,
SET_COUNTRY_CODE_PREF_FAILED,
MAPI_LIBRARIES_INSTALLATION_FAILED,
MAPI_LIBRARIES_INST_INIT_FAILED,
MAPI_LIBRARIES_SRC_FILE_INIT_FAILED,
MAPI_LIBRARIES_DST_FILE_INIT_FAILED,
MAPI_LIBRARIES_REPLACE_FAILED,
MAPI_LIBRARIES_WRITE_FAILED,
MAPI_LIBRARIES_UNINSTALLATION_FAILED,
MAPI_LIBRARIES_UNINST_INIT_FAILED,
MAPI_LIBRARIES_DELETE_FAILED,
MAPI_LIBRARIES_RESET_DEFAULT_MAIL_CLIENT
} ErrorCode;
/******** Communication with the wizard ********/
/** Returns the operation the installer is performing or ready to perform
*/
OperaInstaller::Operation GetOperation() const {return m_operation;}
/** Returns the currently set install folder
*/
OP_STATUS GetInstallFolder(OpString &install_folder) const {return install_folder.Set(m_install_folder);}
/** Changes the installation folder. If an opera installation is found in the given folder,
* the installer will be set to update mode and all the installer settings and the installer
* language will be updated to reflect the settings used by that installation.
*/
OP_STATUS SetInstallFolder(const OpStringC& install_folder);
/** Returns the installation language
*/
OP_STATUS GetInstallLanguage(OpString &install_language) {return install_language.Set(m_install_language);};
/** Changes the installation language
*/
OP_STATUS SetInstallLanguage(OpStringC &install_language);
/** If this returns TRUE, the installer is performing (un)installation operations and its
* settings can no longer be affected.
*/
BOOL IsRunning() {return m_is_running;}
/** Checks whether installing in the currently set installation folder will require privilege elevation.
*/
OP_STATUS PathRequireElevation(BOOL &elevation_required);
/** Temporarily interrupts the installer.
*
* @param pause If true, the installation sequence will be suspended. If false, it is resumed.
*/
void Pause(BOOL pause);
/** Returns the settings the installer is using
*/
Settings GetSettings() {return m_settings;}
/** Specfies the settings to be used by the installer
*
* @param settings Settings to use
*
* @param preserve_multiuser Wether to keep any pre-existing single profile setting instead of overriding it
*
* @return FALSE if some settings given were incompatible
* with other settings given. In this case, the incompatible
* settings were corrected before getting applied. TRUE otherwise.
*/
BOOL SetSettings(Settings settings, BOOL preserve_multiuser = TRUE);
/* Informs the installer to run the Yandex script to set all default search engines
*
* @param run Whether to run the script
*/
void RunYandexScript(BOOL run) {m_run_yandex_script = run;}
/** Informs the installer of which part of the current user's profile
* should be removed when uninstalling.
*
* @param parts See DeleteProfileParts
*/
void SetDeleteProfile(UINT parts) {m_delete_profile = parts;}
/** Informs the installer that the installation was cancelled by
* the user when displaying the locked files dialog
*/
void WasCanceled(BOOL canceled) { m_was_canceled = canceled; };
/******** Other ********/
/** Performs the next installation step and reports any error
* that happened. The installer should be terminated when
* an error is returned. This is used by the OperaInstallerUI class.
*/
OP_STATUS DoStep();
/** Request the installer error log file in order to report an issue to it.
*/
OP_STATUS GetErrorLog(OpFile*& log);
/** Performs the actual deletion of the profile once the files aren't locked.
* This should ONLY be called right before opera stops.
*/
static void DeleteProfileEffective();
/** Called when Opera is started with the -give_folder_write_access command line
* option is given. used to make an elevated opera process temporarily
* give write access to a folder to an installer instance running as a non
* privileged user
*/
static void GiveFolderWriteAccess();
/** Called when country check is finished.
* Resumes installer if it is waiting for m_country_checker.
*/
virtual void CountryCheckFinished();
private:
/******** Initialization and preparation of installation ********/
/** Initializes the settings used for installation from command line options.
* The following options are recognized:
*
* Option | Sets the setting | Default, if option not specified
* ---------------------|-----------------------|-----------------------------------
* -copyonly | copy_only | FALSE
* -allusers | all_users | TRUE if user has an administrator account, FALSE otherwise.
* -singleprofile | single_profile | FALSE
* -setdefaultbrowser | set_default_browser | TRUE if VER_BETA isn't defined
* -startmenushortcut | start_menu_shortcut | TRUE
* -desktopshortcut | desktop_shortcut | TRUE
* -quicklaunchshortcut | quick_launch_shortcut | FALSE if running on Windows 7. TRUE otherwise.
* -pintotaskbar | pinned_shortcut | TRUE if running on Windows 7. FALSE otherwise.
* -launchopera | launch_opera | TRUE
*
* update_start_menu_shortcut is set to TRUE if -startmenushortcut is present. FALSE otherwise
* update_desktop_shortcut is set to TRUE if -desktopshortcut is present. FALSE otherwise
* update_quick_launch_shortcut is set to TRUE if -quicklaunchshortcut is present. FALSE otherwise
* update_pinned_shortcut is set to TRUE if -pintotaskbar is present and OS is Windows 7. FALSE otherwise
*
* if copy_only is set to TRUE:
* all_users, set_default_browser and the shortcut settings are always set to FALSE
* single_profile is always set to TRUE
*/
void SetSettingsFromCommandLine();
/** Initializes the installation folder from the -installfolder command line option if it is specified.
* Otherwise, attempts to use the folder used by the last installer run.
* Otherwise, uses the default installation folder.
*/
void SetInstallFolderFromCommandLine();
/** Initializes the installer language from the -language command line option
* if it is specified.
*/
void SetInstallLanguageFromCommandLine();
/** Called when the installation folder is set from the command line or changed by SetInstallFolder
*
* This method checks if a log file is present at a given folder and uses the information
* from it to decide what operation the installer will execute as well as initializing a
* few installer settings from the information found in the log file and in an eventual operaprefs_default.ini
*/
OP_STATUS CheckAndSetInstallFolder(const OpStringC& new_install_folder);
/******** (Un)Installation steps ********/
/** Attempts to remove installations made with the MSI or classic installer
*/
OP_STATUS Install_Remove_old();
/** Copies one file from the files list. This step is called once for each file
* to be copied.
*/
OP_STATUS Install_Copy_file();
/** Copies MAPI libraries.
*/
OP_STATUS Install_MAPI_Libraries();
/** Executes all the registry operations needed for installation. Those operations are
* specified by m_installer_regops
*/
OP_STATUS Install_Registry();
/** Notifies the system that some settings have changed
*/
OP_STATUS Install_Notify_system();
/** Writes shortcuts
*/
OP_STATUS Install_Create_shortcuts();
/** Does any change needed to operaprefs_default.ini and operaprefs_fixed.ini
* This also adds the preferences requested via the -setdefaultpref and -setfixedpref
* command line options.
*/
OP_STATUS Install_Default_prefs();
/** Writes the log, sets Opera as default browser if needed and starts Opera if needed.
*/
OP_STATUS Install_Finalize();
/** Removes files that were installed by the previous version but not needed in this version
* any longer
*/
OP_STATUS Update_Remove_old_files();
/** Add, remove or rename shortcuts depending on installer settings
*/
OP_STATUS Update_Shortcuts();
/** Remove all shortcuts that were installed
*/
OP_STATUS Uninstall_Remove_Shortcuts();
/** Cleans up the registry
*/
OP_STATUS Uninstall_Registry();
/** Removes MAPI libraries.
*/
OP_STATUS Uninstall_MAPI_Libraries();
/** Shows the survey and removes the installed files.
*/
OP_STATUS Uninstall_Finalize();
/******** Helper methods ********/
/** Finds an existing installation done with MSI in the installation folder and uninstalls it.
*
* @param found Returns whether an installation done with MSI was found.
*/
OP_STATUS FindAndRemoveMSIInstaller(BOOL &found);
/** Finds an existing installation done with Wise in the installation folder and uninstalls it.
*
* @param found Returns whether an installation done with Wise was found.
*/
OP_STATUS FindAndRemoveWiseInstaller(BOOL &found);
/** When trying to install with all_users set to FALSE, to a folder where the current user
* doesn't have write access, Run() calls this method to launch an elevated process
* that takes care to give write access to the user. See GiveFolderWriteAccess
*
* @param folder_path The fodler to which the current user should get access.
* @param permanent Whether to give access permanently. If this is FALSE, the elevated
* process will revert the permissions on the folder when the installer
* is done.
*/
OP_STATUS GetWritePermission(OpString &folder_path, BOOL permanent);
/** Launches an elevated non-interactive instance of the installer that takes care of the
* actual installation. If this method succeeds, it takes care of terminating this instance.
*/
OP_STATUS RunElevated();
/** Reads the files_list file that contains the list of files to install and initializes m_files_list
*/
OP_STATUS ReadFilesList();
/** Takes a RegistryOperation and executes it.
*
* @param root_key The key on which we are operating. Either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER
* @param operation See the definition of RegistryOperation
* @param key_path The key to write to. This overrides the key_path provided in RegistryOperation but is needed because
* the key path can contain placeholders to be replaced by the caller.
* @param transaction If provided, the action performed will be made part of this transaction.
* @param log If provided and the operation adds a value, it will be written to this log.
*/
OP_STATUS DoRegistryOperation(HKEY root_key, const RegistryOperation operation, OpStringC &key_path, OpTransaction *transaction, OperaInstallLog *log);
/** Helper function used by DoRegistryOperation. Replaces the different possible placeholder
* (keywords between {}) contained in a string by their actual value.
*/
OP_STATUS ExpandPlaceholders(OpString& string);
/** To be called when an operation on a file fails. This will attempt to see if the file is locked by another process and if
* it is, it will prompt the user to close the offending process.
*/
OP_STATUS CheckIfFileLocked(const uni_char* full_path);
/** This method attempts to determine whether there is an instance of Opera running that was started
* from the Opera executable present at a given path. The answer is not always reliable and it is
* possible that it doesn't detect a running instance when there is one, thus returning FALSE instead
* of TRUE in some cases.
*/
BOOL IsOperaRunningAt(const uni_char* full_path);
/** Modifies the ACL of an event obtained by CreateEvent, so that the Administrators group is
* allowed to access it using OpenEvent. This ensures that elevated processes can communicate
* with the non-elevated process that started them. This only appears to be an issue on XP so far.
*/
OP_STATUS FixEventACL(HANDLE evt);
/** Prepares a string containing the command line arguments needed to launch a non interactive
* installer process with the same settings as the current installer instance. This is used both
* for starting an elevated instance of the installer and for writing runonce registry entries
* sometimes needed in FindAndRemoveMSIInstaller
*/
OP_STATUS GetRerunArgs(OpString &args);
/** Actually write shortcut once the details of where they should be written have been collected
*
* @param destinations A list of DesktopShortcutInfo::Destinations indicating where shortcuts are needed
* @param use_opera_name Whether we should attempt to create shortcuts named "Opera.lnk" and only fallback to "Opera [version].lnk"
* if such shortcuts already exists. If false, shortcuts with name of type "Opera [version].lnk" will always be
* used.
*/
OP_STATUS AddShortcuts(OpINT32Vector &destinations, BOOL& use_opera_name);
/** Pin application to taskbar. Call to this function is valid for Windows 7 platform.
*
*/
OP_STATUS AddOperaToTaskbar();
/** Unpin application from taskbar. Call to this function is valid for Windows 7 platform.
*
*/
OP_STATUS RemoveOperaFromTaskbar();
/** Parses a list of string of the form [Section]Key=Value and uses them to write new preferences to a PrefsFile
*/
OP_STATUS AddPrefsFromStringsList(OpVector<OpString> &prefs_settings_list, PrefsFile &prefs_file);
/** Prepares the list of files to be removed from the profile just before the uninstaller terminates.
*/
OP_STATUS DeleteProfile(UINT parts);
/** Sends country code request to the autoupdate server if not sent already and
* if m_update_country_pref is true. Answer is added to default prefs if it is
* received before installer finishes default prefs step.
*/
OP_STATUS StartCountryCheckIfNeeded();
/**
*
*/
OP_STATUS ResetDefaultMailClient(bool all_users);
/******** Static installer data ********/
//List of registry operations done by Install()
static const RegistryOperation m_installer_regops[];
//List of registry operations done by RestoreFileHandlers
static const RegistryOperation m_file_handlers_regops[];
//Registry operation used by BecomeDefaultBrowser
static const RegistryOperation m_default_browser_start_menu_regop;
//Registry operation used by BecomeDefaultMailer
static const RegistryOperation m_default_mailer_start_menu_regop;
//Registry operation for setting the last install path
static const RegistryOperation m_set_last_install_path_regop;
//Registry operation for indicating that the uninstall survey has been answered at least once
static const RegistryOperation m_surveyed_regop;
//List of registry operations for each AssociationSupported
//describing how to make opera the handler
static const RegistryOperation* m_association_regops[LAST_ASSOC];
//Key name to check under HKEY_CLASSES_ROOT for each AssociationSupported
static const uni_char* m_check_assoc_keys[LAST_ASSOC];
/******** Installer settings ********/
OpString m_install_folder; //When installing/upgrading, this is the destination folder. Otherwise, this becomes the current Opera folder.
Settings m_settings; //Settings to use for installing or retreived from the current installation.
OpString m_install_language; //Language to be set as default and to use for the installer UI
UINT m_delete_profile; //Indicates which parts of the profile should be removed when uninstalling, if any.
int m_existing_multiuser_setting; //Whether an existing multiuser setting value was set in the default prefs file of the installation folder
int m_existing_product_setting; //Whether an existing Opera Product value was set in the default prefs file of the installation folder
/******** Installer state ********/
Operation m_operation; //The current mode of operation
BOOL m_is_running; //Whether Run() has been called
UINT m_step; // Indicates what group of operations we are currently doing (ie. copy files).
UINT m_step_index; // Indicates which operation within the current group we are doing (ie. copy file nr. 3).
UINT m_steps_count; //Keeps track of how many steps have been done. Useful for debugging
BOOL m_was_http_handler; // Indicates whether Opera was set as the default handler for the http protocol, before being uninstalled
BOOL m_was_canceled; // Indicates if the user has canceled the install by clicking cancel.
Product m_product_flag; //The product flag corresponding to the product currently being installed
OpStringC m_product_name; //The product name to append after "Opera"
OpString m_long_product_name; //The product name to append after "Opera", long version. This may be the same as m_product_name
UINT m_product_icon_nr; //The index of the icon to use in the dll for the current product.
OpString m_app_reg_name; //The name of the application used for the association API on Vista and higher
BOOL m_run_yandex_script; //Whether to run the Yandex script to change all default search engines
/******** Installer data ********/
OpAutoVector<OpString> m_files_list; //List of files that the installer should copy
static OpVector<OpFile>* s_delete_profile_files; //List of files that should be deleted when DeleteProfileEffective is called. Initialized by DeleteProfile
/******** Helper objects ********/
OperaInstallLog* m_old_install_log; // The log file found inside the old instalation on the users PC.
OpTransaction* m_installer_transaction; // The transaction on which all the (un)installation operations are done
OperaInstallLog* m_install_log; // The current log file for the installation we are currently doing.
OperaInstallerUI* m_opera_installer_ui; // The part of the installer that handles messages and the UI.
HANDLE m_get_write_permission_event; // Event used to communicate with the elevated process giving write permissions to the user.
OpFile* m_error_log; // File of unspecified format used to record information about errors.
CountryChecker* m_country_checker; // Retrieves IP-based country code from the autoupdate server.
OpString m_country; // Country code received from parent process or from the autoupdate server.
bool m_update_country_pref; // True if installer should update country code preference in default prefs file.
bool m_country_check_pause; // True if installer is paused waiting for country check.
static const unsigned long COUNTRY_CHECK_TIMEOUT = 5000; // Timeout for country check in ms.
};
#endif //OPERAINSTALLER_H
|
#include "ExpressionTree.h"
#include <fstream>
#include <iostream>
std::vector<ExpressionTree> fillFromFile(std::string);
int main()
{
std::vector<ExpressionTree> exprTrees = fillFromFile("expressions.txt");
for(auto& exprTree : exprTrees)
{
exprTree.printInfixExpr();
std::cout << '\n';
std::cout << '\n';
exprTree.printPostFixExpr();
std::cout << '\n';
std::cout << '\n';
std::cout << exprTree.getResult() << '\n';
std::cout << '\n';
std::cout << '\n';
std::cout << '\n';
}
return 0;
}
std::vector<ExpressionTree> fillFromFile(std::string fileName)
{
std::ifstream iFile(fileName);
std::vector<ExpressionTree> exprTrees;
if(iFile)
{
while(!iFile.eof())
{
std::string expr;
std::getline(iFile, expr);
ExpressionTree exprTree(expr);
exprTrees.push_back(exprTree);
}
}
return exprTrees;
}
|
#include <iostream>
#include <iomanip>
#include <cmath>
#include "Sphere.h"
Sphere::Sphere(){}
void Sphere::set(float radius, int sectors, int stacks)
{
this->radius = radius;
this->sectorCount = sectors;
if(sectors < MIN_SECTOR_COUNT)
this->sectorCount = MIN_SECTOR_COUNT;
this->stackCount = stacks;
if(sectors < MIN_STACK_COUNT)
this->sectorCount = MIN_STACK_COUNT;
buildVerticesSmooth();
}
std::vector<GLfloat> Sphere::getVertices(){
return vertices;
}
std::vector<unsigned int> Sphere::getIndices(){
return indices;
}
std::vector<GLfloat> Sphere::getNormals(){
return normals;
}
std::vector<GLfloat> Sphere::getTexCoords(){
return texCoords;
}
void Sphere::printSelf() const
{
auto getIndexCount = (unsigned int)indices.size();
auto getTriangleCount = getIndexCount / 3;
auto getVertexCount = (unsigned int)vertices.size() / 3;
auto getNormalCount = (unsigned int)normals.size() / 3;
auto getTexCoordCount = (unsigned int)texCoords.size() / 2;
std::cout << "===== Sphere =====\n"
<< " Radius: " << radius << "\n"
<< " Sector Count: " << sectorCount << "\n"
<< " Stack Count: " << stackCount << "\n"
<< "Smooth Shading: " << "true" << "\n"
<< "Triangle Count: " << getTriangleCount << "\n"
<< " Index Count: " << getIndexCount << "\n"
<< " Vertex Count: " << getVertexCount << "\n"
<< " Normal Count: " << getNormalCount << "\n"
<< "TexCoord Count: " << getTexCoordCount << std::endl;
}
void Sphere::clearArrays()
{
std::vector<GLfloat>().swap(vertices);
std::vector<GLfloat>().swap(normals);
std::vector<GLfloat>().swap(texCoords);
std::vector<unsigned int>().swap(indices);
}
void Sphere::buildVerticesSmooth()
{
// clear memory of prev arrays
clearArrays();
float x, y, z, xy; // vertex position
float nx, ny, nz, lengthInv = 1.0f / radius; // normal
float s, t; // texCoord
float sectorStep = 2 * M_PI / sectorCount;
float stackStep = M_PI / stackCount;
float sectorAngle, stackAngle;
for(int i = 0; i <= stackCount; ++i)
{
stackAngle = M_PI / 2 - i * stackStep; // starting from M_PI/2 to -M_PI/2
xy = radius * cosf(stackAngle); // r * cos(u)
z = radius * sinf(stackAngle); // r * sin(u)
// add (sectorCount+1) vertices per stack
// the first and last vertices have same position and normal, but different tex coords
for(int j = 0; j <= sectorCount; ++j)
{
sectorAngle = j * sectorStep; // starting from 0 to 2M_PI
// vertex position
x = xy * cosf(sectorAngle); // r * cos(u) * cos(v)
y = xy * sinf(sectorAngle); // r * cos(u) * sin(v)
addVertex(x, y, z);
// normalized vertex normal
nx = x * lengthInv;
ny = y * lengthInv;
nz = z * lengthInv;
addNormal(nx, ny, nz);
// vertex tex coord between [0, 1]
s = (float)j / sectorCount;
t = (float)i / stackCount;
addTexCoord(-s, -t);
}
}
// indices
// k1--k1+1
// | / |
// | / |
// k2--k2+1
unsigned int k1, k2;
for(int i = 0; i < stackCount; ++i)
{
k1 = i * (sectorCount + 1); // beginning of current stack
k2 = k1 + sectorCount + 1; // beginning of next stack
for(int j = 0; j < sectorCount; ++j, ++k1, ++k2)
{
// 2 triangles per sector excluding 1st and last stacks
if(i != 0)
{
addIndices(k1, k2, k1+1); // k1---k2---k1+1
}
if(i != (stackCount-1))
{
addIndices(k1+1, k2, k2+1); // k1+1---k2---k2+1
}
}
}
}
void Sphere::addVertex(float x, float y, float z)
{
vertices.push_back(x);
vertices.push_back(y);
vertices.push_back(z);
}
void Sphere::addNormal(float nx, float ny, float nz)
{
normals.push_back(nx);
normals.push_back(ny);
normals.push_back(nz);
}
void Sphere::addTexCoord(float s, float t)
{
texCoords.push_back(s);
texCoords.push_back(t);
}
void Sphere::addIndices(unsigned int i1, unsigned int i2, unsigned int i3)
{
indices.push_back(i1);
indices.push_back(i2);
indices.push_back(i3);
}
|
#include "stdafx.h"
#include "ReadyGO.h"
ReadyGO::~ReadyGO()
{
DeleteGO(m_ready);
DeleteGO(m_GO);
}
bool ReadyGO::Start()
{
m_ready = NewGO<SpriteRender>(30, "sp");
m_ready->Init(L"Assets/sprite/Ready2.dds", 980.f*0.8f, 388.414f*0.8f);
m_rpos = { -630,0,0 };
m_ready->SetPosition(m_rpos);
m_ready->SetScale({ m_rScale,m_rScale ,m_rScale });
m_ready->SetMulCol({ 1,1,1,m_rAlpha });
return true;
}
void ReadyGO::Update()
{
if (m_rAlpha < 1)
{
m_rAlpha *= 1.8f;
}
else
{
m_rAlpha = 1;
}
if (m_rpos.x >= -80 && m_rpos.x <= 0)
{
m_rScale += 0.18f/80.f;
m_rpos.x += 120.f/80.f;
}
else
{
m_rScale += 0.18f;
m_rpos.x += 120 * (m_rpos.x > -20 ? 1.5f:1);
}
if (m_rpos.x >= 20)
GO();
if (m_rpos.x >= 1700)
isEnd = true;
m_ready->SetPosition(m_rpos);
m_ready->SetScale({ m_rScale,m_rScale ,m_rScale });
m_ready->SetMulCol({ 1,1,1,m_rAlpha });
}
void ReadyGO::GO()
{
if (isFirstGO)
{
m_GO = NewGO<SpriteRender>(30, "sp");
m_GO->Init(L"Assets/sprite/r_go.dds", 1699.f*0.6f, 801.f*0.6f);
m_GO->SetScale({ m_gScale,m_gScale ,m_gScale });
isFirstGO = false;
}
if (m_gScale <= 1)
{
m_gScale *= 1.4f;
}
else
{
m_gScale *= 1.005f;
m_gAlpha -= 0.1f;
}
m_GO->SetScale({ m_gScale,m_gScale ,m_gScale });
m_GO->SetMulCol({ 1,1,1,m_gAlpha });
}
|
//Tran Nhan To - 58131391
#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
#include<iostream>
#include<fstream>
#define fo "output1.txt"
using namespace std;
int a[50][50],n,m;
int i,j;
//nhap ma tran kich thuot nxn
void nhapmang()
{
do{
cout<<"So dong va so cot phai bang nhau!"<<endl;
cout<<"Nhap so dong cua ma tran: ";
cin>>n;
cout<<"Nhap so cot cua ma tran: ";
cin>>m;
}while((m!=n) || ((m<3 || m>10) && (n<3 || n>10)));
for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
{
a[i][j]=rand()%21;
}
}
//xuat ma tran ra man hinh
void xuatmang()
{
for(i = 1; i <= n; i++)
{
for(j = 1; j <= m; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
//xoa dong thu i
void xoadong()
{
int dong;
do{
cout<<"\nNhap dong can xoa: ";
cin>>dong;
}while(dong < 0 && dong >= n);
for(i = dong; i <= n-1; i++){
for(j = 1; j <= m; j++)
a[i][j]=a[i+1][j];
}
n--;
xuatmang();
}
//xoa cot thu j
void xoacot()
{
int cot;
do{
cout<<"\nNhap cot can xoa: ";
cin>>cot;
}while(cot < 0 && cot >= n);
for(i = cot; i <= m-1; i++){
for(j = 1; j <= n; j++)
a[j][i]=a[j][i+1];
}
m--;
xuatmang();
}
//kiem tra ma tran co doi xung khong
int ktra(int a[50][50], int n)
{
for(i = 1; i < n; i++)
for(j = 1; j < n; j++)
{
if(a[i][j] != a[j][i])
return 0;
}
return 1;
}
//tim so hoang hau
bool maxduongcheo()
{
int k,h;
for (k = i, h = j; k >= 0 && h < n; k--, h++)
if (a[k][h] > a[i][j])
return false;
for (k = i+1, h = j-1; k < n && h >= 0; k++, h--)
if (a[k][h] > a[i][j])
return false;
for (k = i-1, h = j-1; k >= 0 && h >= 0; k--,h--)
if (a[k][h] > a[i][j])
return false;
for (k = i+1, h = j+1; k < n && h < n; k++, h++)
if (a[k][h] > a[i][j])
return false;
return true;
}
bool maxdongcot()
{
for (int k = 0; k < n; k++ )
if (a[k][j]>a[i][j])
return false;
for (int k = 0; k < n; k++ )
if (a[i][k]>a[i][j])
return false;
return true;
}
//ham main
int main()
{
nhapmang();
xuatmang();
xoadong();
xoacot();
if(ktra(a,n)==0)
cout<<"\nMa tran vua nhap k doi xung!";
else
cout<<"\nMa tran doi xung!";
cout<<"\nCac so hoang hau co trong ma tran la :"<<endl;
// timsohh();
getch();
}
|
/*!
* \file arrow.cpp
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Implementation of graphics arrow in stategraphs
*/
#include <QtGui>
#include <math.h>
#include "./arrow.h"
const qreal Pi = 3.14; /* definition of Pi */
/*!
* \brief Arrow constructor
* \param[in] startItem The tail graphics item
* \param[in] endItem The head graphics item
* \param[in] parent Not required, is automatically initalised
* \param[in] scene Not required, is automatically initalised
*
* This contructor takes starting and ending graphics items for an arrow to be drawn between them.
*/
Arrow::Arrow(GraphicsItem *startItem, GraphicsItem *endItem,
QGraphicsItem *parent, QGraphicsScene *scene)
: QGraphicsLineItem(parent, scene) {
myStartItem = startItem;
myEndItem = endItem;
setFlag(QGraphicsItem::ItemIsSelectable, true);
myColor = Qt::black;
setPen(QPen(myColor, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
offset = 0;
number = 1;
total = 1;
foreign = false;
showHead = true;
isCommunication = false;
myTransition = 0;
}
/*!
* \brief Set a new name
* \param[in] n The new name
*/
void Arrow::setName(QString n) {
name = n;
}
/*!
* \brief Set a new \c Mpre
* \param[in] m The new Mpre
*/
void Arrow::setMpre(Mpre m) {
mpre = m;
}
/*!
* \brief Set a new \c Mpost
* \param[in] mp The new Mpost
*/
void Arrow::setMpost(Mpost mp) {
mpost = mp;
}
QRectF Arrow::boundingRect() const {
// qreal extra = ((pen().width() + 20 + offset) / 2.0);
qreal extra = ((pen().width() + 20 + offset));
return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),
line().p2().y() - line().p1().y()))
.normalized()
.adjusted(-extra, -extra, extra, extra);
}
QPainterPath Arrow::shape() const {
QPainterPath path = QGraphicsLineItem::shape();
path.addPolygon(arrowHead);
return path;
}
void Arrow::updatePosition() {
QLineF line(mapFromItem(myStartItem, 0, 0), mapFromItem(myEndItem, 0, 0));
setLine(line);
}
void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
QWidget *) {
if (myStartItem->collidesWithItem(myEndItem))
return;
QPen myPen = pen();
myPen.setColor(myColor);
qreal arrowSize = 10;
painter->setPen(myPen);
if (foreign) painter->setPen(Qt::gray);
else
painter->setPen(isSelected() ? Qt::red : Qt::black);
if (isCommunication)
painter->setPen(isSelected() ? Qt::darkGreen : Qt::green);
painter->setRenderHint(QPainter::Antialiasing);
// new
QPainterPath endPath = myEndItem->shape();
float dif = 0.1;
QPointF intersectionPoint;
QPointF ip;
QLineF centerLine2(myStartItem->scenePos(), myEndItem->scenePos());
for (float i = 0; i < 1.0; i+=dif) {
float e = i+dif;
if (e > 0.99) e = 0;
QLineF myLine(endPath.pointAtPercent(i), endPath.pointAtPercent(e));
QLineF myLine2(myLine.x1()+centerLine2.x2(),
myLine.y1()+centerLine2.y2(),
myLine.x2()+centerLine2.x2(),
myLine.y2()+centerLine2.y2());
int rc = centerLine2.intersect(myLine2, &ip);
if (rc == QLineF::BoundedIntersection) {
intersectionPoint = ip;
break;
}
}
setLine(QLineF(intersectionPoint, myStartItem->pos()));
double angle = ::acos(line().dx() / line().length());
// double angle2 = angle;
if (line().dy() >= 0)
angle = (Pi * 2) - angle;
QPainterPath path;
QPointF half(line().x1() + (line().dx()/2), line().y1() + (line().dy()/2));
path.moveTo(line().p1());
// QPointF c2(line().x1()+(line().dx()/2.0)+(sin(angle2)*offset),
// line().y1()+(line().dy()/2.0)+(cos(angle2)*offset));
// offset = 20;
offset = (total-1)*-5+(number-1)*10;
QPointF c2 = half + QPointF(sin(angle + Pi) * offset,
cos(angle + Pi) * offset);
// QPointF c2 = half - QPointF(sin(angle + Pi) * offset,
// cos(angle + Pi) * offset);
path.quadTo(c2, line().p2());
// path.lineTo(c2);
// use path to work out angle
QLineF l(line().p1(), c2);
double angle3 = ::acos(l.dx() / l.length());
angle = angle3;
if (l.dy() >= 0)
angle = (Pi * 2) - angle;
QPointF arrowP1 = line().p1() + QPointF(sin(angle + Pi / 3) *
arrowSize, cos(angle + Pi / 3) * arrowSize);
QPointF arrowP2 = line().p1() + QPointF(sin(angle + Pi - Pi / 3) *
arrowSize, cos(angle + Pi - Pi / 3) * arrowSize);
/* The clear() function for QVector has a
* compile warning under Qt 4.5 */
#if QT_VERSION >= 0x040600 // If Qt version is 4.6 or higher
arrowHead.clear();
#else
arrowHead = QPolygonF();
#endif
arrowHead << line().p1();
if (showHead) arrowHead << arrowP1 << arrowP2;
// painter->drawLine(line());
painter->drawPath(path);
if (foreign) painter->setBrush(Qt::gray);
else
painter->setBrush(isSelected() ? Qt::red : Qt::black);
if (isCommunication)
painter->setBrush(isSelected() ? Qt::darkGreen : Qt::green);
painter->drawPolygon(arrowHead);
/*if(myTransition != 0)
{
if(myTransition->condition().enabled == true)
{
painter->drawText(half, myTransition->condition().toString());
}
}*/
}
|
#include <iostream>
#include <vector>
#include <map>
#include <ios>
#include <iomanip>
using namespace std;
vector< vector<int> > llenarMatriz( int , int ) ;
vector<int> soliNumeros( int ) ;
void mostrarMatriz( vector< vector<int> > ) ;
int valMaxMatriz( vector< vector<int> > ) ;
int valMaxVector( vector<int> ) ;
map< int , int > duplicados( int , vector< vector<int> > ) ;
void mostrarDuplicados( map< int , int > ) ;
int sumaDiagonalPrincipal( vector< vector<int> > ) ;
int promedioMatriz( vector< vector<int> > ) ;
int mayorPromedio( int , vector< vector<int> > ) ;
int main()
{
vector< vector<int> > matriz( 4 , vector<int>(4) ) ;
int valMax = 0 , // valor maximo de la matriz
sumaDiagonal = 0 , // suma de la diagonal principal
promedio = 0 , // promedio de la matriz
cantidad = 0 ; // cantidad de numeros mayores al promedio
map< int , int > posiciones ; // posiciones de los duplicados
cout << "Llenar matriz" << endl ;
matriz = llenarMatriz( matriz.size() , matriz.at(0).size() ) ;
cout << "Mostrar contenido de la matriz" << endl ;
mostrarMatriz( matriz ) ;
cout << endl ;
valMax = valMaxMatriz( matriz ) ;
cout << "El valor maximo de la matriz es: " << valMax << endl << endl ;
cout << "Buscar la cantidad de duplicados y sus posiciones" << endl ;
posiciones = duplicados( valMax , matriz ) ;
cout << "Cantidad de duplicados: " << posiciones.size() << endl ;
cout << "Mostrar las posiciones del los duplicados" << endl ;
mostrarDuplicados( posiciones ) ;
cout << endl ;
sumaDiagonal = sumaDiagonalPrincipal( matriz ) ;
cout << "La suma de la diagonal principal es: " << sumaDiagonal << endl ;
promedio = promedioMatriz( matriz ) ;
cout << "El promedio de la matriz es: " << promedio << endl ;
cantidad = mayorPromedio( promedio , matriz ) ;
cout << "Valores mayores al promedio es: " << cantidad << endl ;
return 0 ;
} // fin main
vector< vector<int> > llenarMatriz( int filas , int columnas )
{
vector< vector<int> > matriz( filas , vector<int>( columnas ) ) ;
int valor = 0 ;
for( int i = 0 ; i < filas ; i++ )
{
cout << "Valores de la fila " << i+1 << endl ;
matriz[i] = soliNumeros(4) ;
cout << endl ;
}
return matriz ;
} // fin llenarMatriz
vector<int> soliNumeros( int columnas )
{
vector<int> vector ;
int valor = 0 ;
for( int i = 0 ; i < columnas ; i++)
{
cout << "Ingrese valor: " ; cin >> valor ;
vector.push_back( valor ) ;
}
return vector ;
}
void mostrarMatriz( vector< vector<int> > matriz )
{
for( int i = 0 ; i < matriz.size() ; i++ )
{
for( int j = 0 ; j < matriz.at(0).size() ; j++ )
{
cout << setw( 5 ) ;
j == matriz.at(0).size() - 1 ? cout << matriz[i][j] << endl : cout << matriz[i][j] ;
}
}
} // mostrarMatriz
int valMaxMatriz( vector< vector<int> > matriz )
{
int max = 0 ,
aux = 0 ;
for( int i = 0 ; i < matriz.size() ; i++ )
{
aux = valMaxVector( matriz.at(i) ) ;
if( aux > max ) max = aux ;
}
return max ;
} // fin valMaxMatriz
int valMaxVector( vector<int> vector )
{
int max = 0 ;
for( int i = 0 ; i < vector.size() ; i++ )
{
if( max < vector.at(i) ) max = vector.at(i) ;
}
return max ;
} // fin valMaxVector
map< int , int > duplicados( int max , vector< vector<int> > matriz )
{
map< int , int > posiciones ; // posiciones X,Y
for( int i = 0 ; i < matriz.size() ; i++ )
{
for( int j = 0 ; j < matriz.at(0).size() ; j++ )
{
if( max == matriz[i][j] ) posiciones[i] = j ;
}
}
return posiciones ;
} // fin duplicados
void mostrarDuplicados( map< int , int > posiciones )
{
for( map< int , int >::iterator it = posiciones.begin() ; it != posiciones.end() ; ++it )
{
cout << "(" << it->first << "," << it->second << ")" << endl ;
}
} // fin mostrarDuplicados
int sumaDiagonalPrincipal( vector< vector<int> > matriz )
{
int suma = 0 ;
for( int i = 0 ; i < matriz.size() ; i++ )
{
suma += matriz[i][i] ;
}
return suma ;
} // fin sumaDiagonalPrincipal
int promedioMatriz( vector< vector<int> > matriz )
{
int promedio = 0 ;
for( int i = 0 ; i < matriz.size() ; i++ )
{
for( int j = 0 ; j < matriz.at(0).size() ; j++ )
{
promedio += matriz[i][j] ;
}
}
return promedio / ( matriz.size() * matriz.at(0).size() ) ;
} // fin promedioMatriz
int mayorPromedio( int promedio , vector< vector<int> > matriz )
{
int cantidad = 0 ;
for( int i = 0 ; i < matriz.size() ; i++ )
{
for( int j = 0 ; j < matriz.at(0).size() ; j++ )
{
if( matriz[i][j] > promedio ) cantidad++ ;
}
}
return cantidad ;
} // fin mayorPromedio
|
#include "stdafx.h"
#include "MyCompute.h"
#include "math.h"
CMyCompute::CMyCompute(void)
{
m_data = 0;
}
CMyCompute::CMyCompute(double data)
{
m_data = data;
}
CMyCompute::~CMyCompute(void)
{
}
double CMyCompute::MyCube(void)//立方运算
{
return m_data*m_data*m_data;
}
double CMyCompute::MyCube(double data)
{
return data*data*data;
}
double CMyCompute::MyLog(void)//取对数运算
{
if (m_data > 0)
return log(m_data);
else
{
char* szStr1 = "对数运算不能取负值!";
WCHAR wszClassName1[256];
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szStr1, strlen(szStr1) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
AfxMessageBox(wszClassName1);
return -1;
}
}
double CMyCompute::MyLog(double data)
{
if (data > 0)
return log(data);
else
{
char* szStr1 = "对数运算不能取负值!";
WCHAR wszClassName1[256];
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szStr1, strlen(szStr1) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
AfxMessageBox(wszClassName1);
return -1;
}
}
double CMyCompute::MySqrt(void)//开根号运算
{
if (m_data >= 0)
return sqrt(m_data);
else
{
char* szStr1 = "开根号运算不能取负值!";
WCHAR wszClassName1[256];
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szStr1, strlen(szStr1) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
AfxMessageBox(wszClassName1);
return -1;
}
}
double CMyCompute::MySqrt(double data)
{
if (data >= 0)
return sqrt(data);
else
{
char* szStr1 = "开根号运算不能取负值!";
WCHAR wszClassName1[256];
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szStr1, strlen(szStr1) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
AfxMessageBox(wszClassName1);
return -1;
}
}
double CMyCompute::MySquare(void)//平方运算
{
return m_data*m_data;
}
double CMyCompute::MySquare(double data)
{
return data*data;
}
|
/**************************
编(chao)写(xi)于2018-09-19日
抄袭自m0n0ph1/Process-Hollowing
用来Inject的进程必须是GUI进程
***************************/
#include <Windows.h>
#include <iostream>
using namespace std;
typedef struct _BASE_PROCESS_INFO
{
ULONG BaseAddress;
CONTEXT ThreadContext;
PROCESS_INFORMATION ProcessInfo;
}BASE_PROCESS_INFO, *PBASE_PROCESS_INFO;
typedef ULONG(WINAPI *NTUNMAPVIEWOFSECTION)(
__in HANDLE ProcessHandle,
__in PVOID BaseAddress
);
LONG TurnRvaIntoRaw(PIMAGE_NT_HEADERS temp, LONG Rva)
{
INT NumbersOfSections = temp->FileHeader.NumberOfSections;
PIMAGE_SECTION_HEADER SectionHeader = IMAGE_FIRST_SECTION(temp);
for (int i = 0; i < NumbersOfSections; ++i)
{
DWORD StartAddress = SectionHeader->VirtualAddress;
DWORD EndAddress = StartAddress + SectionHeader->Misc.VirtualSize;
if (Rva >= StartAddress && Rva <= EndAddress)
{
//cout << Rva - StartAddress + SectionHeader->PointerToRawData << endl;
return Rva - StartAddress + SectionHeader->PointerToRawData;
}
++SectionHeader;
}
return 0;
}
BOOL CreateInjectProcess(CHAR *ProcessImageName, PBASE_PROCESS_INFO BaseProcessInfo)
{
STARTUPINFOA StartInfo;
ZeroMemory(&StartInfo, sizeof(StartInfo));
StartInfo.cb = sizeof(StartInfo);
if (CreateProcessA(NULL, ProcessImageName, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &StartInfo, &BaseProcessInfo->ProcessInfo))
{
BaseProcessInfo->ThreadContext.ContextFlags = CONTEXT_FULL;
GetThreadContext(BaseProcessInfo->ProcessInfo.hThread, &BaseProcessInfo->ThreadContext);
ULONG Peb = BaseProcessInfo->ThreadContext.Ebx; //可以查看CreateProcess函数,最后的Context中EBX保存的实际上就是PEB
ULONG RetSize = 0;
ReadProcessMemory(BaseProcessInfo->ProcessInfo.hProcess, (PVOID)(Peb + 8), &BaseProcessInfo->BaseAddress, 4, &RetSize);
return TRUE;
}
return FALSE;
}
CHAR* GetProcessBuffer(CHAR *ProcessFilePath)
{
HANDLE FileHandle = CreateFileA(
ProcessFilePath,
GENERIC_READ,
0,
0,
OPEN_ALWAYS,
0,
0
);
if (FileHandle == NULL)
{
cout << "打开文件 " << ProcessFilePath << "失败!错误码是:" << GetLastError() << endl;
return NULL;
}
ULONG FileSize;
FileSize = GetFileSize(FileHandle, NULL);
CHAR *FileBuffer = new CHAR[FileSize];
if (FileBuffer == NULL)
{
cout << "分配内存失败!" << endl;
CloseHandle(FileHandle);
return NULL;
}
ULONG ReadBytes = 0;
if (!ReadFile(FileHandle, FileBuffer, FileSize, &ReadBytes, NULL) || ReadBytes != FileSize)
{
cout << "读取文件失败!错误码是:" << GetLastError() << endl;
CloseHandle(FileHandle);
return NULL;
}
return FileBuffer;
}
int main()
{
HANDLE hMutex = CreateMutexA(NULL, FALSE, "TY_MUTEX");
if (GetLastError() == ERROR_ALREADY_EXISTS) //如果当前进程已经存在那么打个招呼就退出
{
MessageBoxA(GetDesktopWindow(), "Hello Father!", "", MB_OK);
return 0;
}
BASE_PROCESS_INFO BaseProcessInfo;
ZeroMemory(&BaseProcessInfo, sizeof(BaseProcessInfo));
//CreateInjectProcess("C:\\Windows\\system32\\calc.exe", &BaseProcessInfo);
CHAR FilePath[MAX_PATH];
cin.getline(FilePath, MAX_PATH);
do
{
CreateInjectProcess(FilePath, &BaseProcessInfo);
if (BaseProcessInfo.BaseAddress == 0)
{
cout << "创建进程失败!" << endl;
break;
}
NTUNMAPVIEWOFSECTION NtUnmapViewofSection = NULL;
NtUnmapViewofSection = (NTUNMAPVIEWOFSECTION)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtUnmapViewOfSection");
if (NtUnmapViewofSection == NULL)
{
cout << "获取NtUnmapViewofSection函数失败!" << endl;
break;
}
NtUnmapViewofSection(BaseProcessInfo.ProcessInfo.hProcess, (PVOID)BaseProcessInfo.BaseAddress);
cin.getline(FilePath, MAX_PATH);
CHAR* ProcessBuffer = GetProcessBuffer(FilePath);
PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)ProcessBuffer;
if (DosHeader == NULL)
{
cout << "获取进程文件内容失败!" << endl;
break;
}
PIMAGE_NT_HEADERS NtHeader = (PIMAGE_NT_HEADERS)((ULONG)DosHeader + DosHeader->e_lfanew);
//其实这里可以偷懒,直接在ntheader内部制定的ImageBase分配内存,就不需要重定位了
LPVOID NewModuleBase = VirtualAllocEx(BaseProcessInfo.ProcessInfo.hProcess, (PVOID)BaseProcessInfo.BaseAddress, NtHeader->OptionalHeader.SizeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (NewModuleBase == NULL)
{
cout << "分配内存失败!错误码是:" << GetLastError() << endl;
break;
}
//这里保存下之前的NtHeader的ImageBase然后修改一下用以下文写入进去
ULONG OldImageBase = NtHeader->OptionalHeader.ImageBase;
NtHeader->OptionalHeader.ImageBase = (ULONG)NewModuleBase;
BOOL WriteMemoryFlag = 0;
WriteMemoryFlag = WriteProcessMemory(BaseProcessInfo.ProcessInfo.hProcess, NewModuleBase, (PVOID)ProcessBuffer, NtHeader->OptionalHeader.SizeOfHeaders, NULL);
if (WriteMemoryFlag == 0)
{
cout << "写入映像头失败!错误码是:" << GetLastError() << endl;
break;
}
IMAGE_SECTION_HEADER * SectionHeader = IMAGE_FIRST_SECTION(NtHeader);
for (int i = 0; i < NtHeader->FileHeader.NumberOfSections; ++i, ++SectionHeader)
{
WriteMemoryFlag = WriteProcessMemory(BaseProcessInfo.ProcessInfo.hProcess, (PVOID)((ULONG)NewModuleBase + SectionHeader->VirtualAddress), (PVOID)(ProcessBuffer + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, NULL);
if (WriteMemoryFlag == 0)
{
cout << "写入区块" << SectionHeader->Name << "失败!错误码是:" << GetLastError() << endl;
break;
}
}
if (WriteMemoryFlag == 0)
break;
//计算一下是否需要进行重定位运算,用当前模块地址减去NtHeader中要求的模块基址
ULONG RelctOffset = (ULONG)NewModuleBase - OldImageBase;
if (RelctOffset)
{
//虽然我特意在InjectedProcess的NtHeader->OptionalHeader.ImageBase的位置分配内存
//这样就不需要进行重定位了
//但是实际上并不是每次都能在那个位置分配成功
//因此这里重定位的操作还是要写
cout << "需要进行重定位!" << endl;
if (NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size > 0)
{
IMAGE_BASE_RELOCATION *RelocationImage = (IMAGE_BASE_RELOCATION *)(ProcessBuffer + TurnRvaIntoRaw(NtHeader, NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress));
for (; RelocationImage->VirtualAddress != 0;)
{
/*这里具体为什么写
#define CountRelocationEntries(dwBlockSize) \
(dwBlockSize - \
sizeof(BASE_RELOCATION_BLOCK)) / \
sizeof(BASE_RELOCATION_ENTRY)
就查看这个*/
ULONG NumberOfBlocks = (RelocationImage->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2;
USHORT * Block = (USHORT *)((CHAR*)RelocationImage + sizeof(IMAGE_BASE_RELOCATION));
for (ULONG i = 0; i < NumberOfBlocks; ++i, Block++)
{
USHORT addr = *Block & 0x0fff; //用低12位作为标志。
USHORT sign = *Block >> 12; //高四位作为标志来运算
if (sign == 3)
{
ULONG AddressOffset = RelocationImage->VirtualAddress + addr; //Block是当前页面内部的便宜地址,所以加上当前页面的位置即是总偏移地址。
ULONG OldValue = 0;
ReadProcessMemory(BaseProcessInfo .ProcessInfo.hProcess, (PVOID)((ULONG)NewModuleBase + AddressOffset), &OldValue, 4, NULL);
OldValue += RelctOffset;
WriteProcessMemory(BaseProcessInfo.ProcessInfo.hProcess, (PVOID)((ULONG)NewModuleBase + AddressOffset), &OldValue, 4, NULL);
}
else if (sign == 0)
{
//sign为0的模块仅仅是为了对齐内存。
}
}
RelocationImage = (IMAGE_BASE_RELOCATION *)((char*)RelocationImage + RelocationImage->SizeOfBlock);
}
}
}
WriteProcessMemory(BaseProcessInfo.ProcessInfo.hProcess, (PVOID)(BaseProcessInfo.ThreadContext.Ebx + 8), &NewModuleBase, 4, NULL);
BaseProcessInfo.ThreadContext.Eax = (ULONG)NewModuleBase + NtHeader->OptionalHeader.AddressOfEntryPoint;
BaseProcessInfo.ThreadContext.ContextFlags = CONTEXT_FULL;
SetThreadContext(BaseProcessInfo.ProcessInfo.hThread, &BaseProcessInfo.ThreadContext);
ResumeThread(BaseProcessInfo.ProcessInfo.hThread);
} while (FALSE);
system("pause");
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/img/src/imagemanagerimp.h"
#include "modules/img/imagedecoderfactory.h"
#include "modules/img/src/imagerep.h"
#include "modules/img/src/imagecontent.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/hardcore/cpuusagetracker/cpuusagetrackeractivator.h"
#ifdef IMG_TIME_LIMITED_CACHE
#include "modules/hardcore/mh/mh.h"
#endif // IMG_TIME_LIMITED_CACHE
#ifdef ASYNC_IMAGE_DECODERS_EMULATION
#include "modules/img/src/asyncemulationdecoder.h"
#endif // ASYNC_IMAGE_DECODERS_EMULATION
#ifdef CACHE_UNUSED_IMAGES
#include "modules/logdoc/urlimgcontprov.h"
#endif // CACHE_UNUSED_IMAGES
ImageManager* ImageManager::Create(ImageProgressListener* listener)
{
ImageManagerImp* img_man = OP_NEW(ImageManagerImp, (listener));
null_image_listener = OP_NEW(NullImageListener, ());
if (img_man == NULL || null_image_listener == NULL || (img_man->Create() == OpStatus::ERR_NO_MEMORY))
{
OP_DELETE(img_man);
OP_DELETE(null_image_listener);
null_image_listener = NULL;
return NULL;
}
return img_man;
}
ImageManagerImp::ImageManagerImp(ImageProgressListener* listener) : progress_listener(listener),
cache_size(0),
used_mem(0)
#ifdef IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
, anim_cache_size(0),
anim_used_mem(0)
#endif // IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
, cache_policy(IMAGE_CACHE_POLICY_SOFT)
#ifdef ASYNC_IMAGE_DECODERS
, async_factory(NULL)
#endif // ASYNC_IMAGE_DECODERS
, null_image_content(NULL)
#ifdef IMG_TIME_LIMITED_CACHE
, pending_cache_timeout(FALSE)
#endif // IMG_TIME_LIMITED_CACHE
#ifdef IMGMAN_USE_SCRATCH_BUFFER
, scratch_buffer(NULL)
, scratch_buffer_size(0)
#endif // IMGMAN_USE_SCRATCH_BUFFER
, m_lock_count(0)
, m_grace_lock_count(0)
, m_suppressed_free_memory(FALSE)
, m_current_grace_time(NULL)
#ifdef IMG_TOGGLE_CACHE_UNUSED_IMAGES
, is_caching_unused_images(
#ifdef IMG_CACHE_UNUSED_IMAGES
TRUE
#else // IMG_CACHE_UNUSED_IMAGES
FALSE
#endif // IMG_CACHE_UNUSED_IMAGES
)
#endif // IMG_TOGGLE_CACHE_UNUSED_IMAGES
{
}
ImageManagerImp::~ImageManagerImp()
{
#ifdef IMGMAN_USE_SCRATCH_BUFFER
OP_DELETEA(scratch_buffer);
#endif // IMGMAN_USE_SCRATCH_BUFFER
#ifdef IMG_TIME_LIMITED_CACHE
g_main_message_handler->UnsetCallBack(this, MSG_IMG_CLEAN_IMAGE_CACHE, (MH_PARAM_1)this);
#endif // IMG_TIME_LIMITED_CACHE
#ifdef ASYNC_IMAGE_DECODERS
OP_DELETE(async_factory);
#endif // ASYNC_IMAGE_DECODERS
#ifdef HAS_ATVEF_SUPPORT
OP_DELETE(atvef_image);
atvef_image = NULL;
#endif // HAS_ATVEF_SUPPORT
ClearImageList(&image_list);
ClearImageList(&visible_image_list);
ClearImageList(&free_image_list);
bitmap_image_list.Clear();
image_decoder_factory_list.Clear();
OP_DELETE(progress_listener);
OP_DELETE(null_image_content);
null_image_content = NULL;
OP_DELETE(null_image_listener);
null_image_listener = NULL;
}
void ImageManagerImp::LockImageCache()
{
if (!m_lock_count)
{
OP_ASSERT(!m_grace_lock_count);
// find first unused grace time
OP_ASSERT(!m_current_grace_time);
ImageGraceTimeSlot* gt = static_cast<ImageGraceTimeSlot*>(m_grace_times.First());
for (; gt; gt = static_cast<ImageGraceTimeSlot*>(gt->Suc()))
{
if (gt->Empty())
break;
}
// no unused grace time available - create new entry
if (!gt)
{
// on OOM this in effect will mean that images will have
// no grace time even if marked no longer visible between
// call to BeginGraceTime and EndGraceTime, which is
// probably not too bad
gt = OP_NEW(ImageGraceTimeSlot, ());
if (gt)
{
gt->Into(&m_grace_times);
}
}
OP_ASSERT(!gt || gt->Empty());
m_current_grace_time = gt;
m_suppressed_free_memory = FALSE;
}
++ m_lock_count;
}
void ImageManagerImp::UnlockImageCache()
{
OP_ASSERT(m_lock_count);
-- m_lock_count;
if (!m_lock_count)
{
OP_ASSERT(!m_grace_lock_count);
// set grace time - images made no longer visible between call
// to BeginGraceTime and EndGraceTime will not be purged until
// this time has passed
if (m_current_grace_time)
{
m_current_grace_time->m_time =
m_current_grace_time->Empty() ? 0 : g_op_time_info->GetRuntimeMS() + IMG_GRACE_TIME;
m_current_grace_time = NULL;
}
// image cache is no longer locked - purge now
if (m_suppressed_free_memory)
{
FreeMemory();
m_suppressed_free_memory = FALSE;
}
}
}
void ImageManagerImp::BeginGraceTime()
{
OP_ASSERT(m_lock_count);
++ m_grace_lock_count;
}
void ImageManagerImp::EndGraceTime()
{
OP_ASSERT(m_lock_count);
OP_ASSERT(m_grace_lock_count);
-- m_grace_lock_count;
}
BOOL ImageManagerImp::StateOfGrace(ImageRep* rep, double now) const
{
ImageGraceTimeSlot* gt = static_cast<ImageGraceTimeSlot*>(rep->GraceTimeSlot());
if (!gt)
return FALSE;
// this function may be called before the grace time has been set,
// in which case the image is in state of grace
if (m_lock_count && gt == m_current_grace_time)
return TRUE;
OP_ASSERT(gt->m_time);
return gt->m_time >= now;
}
#ifdef IMG_TOGGLE_CACHE_UNUSED_IMAGES
void ImageManagerImp::CacheUnusedImages(BOOL strategy)
{
if (is_caching_unused_images == strategy)
return;
is_caching_unused_images = strategy;
// ir->SetCacheUnusedImage(FALSE) may result in ir being
// deleted, so next will have to be fetched before calling
ImageRep* next;
for (ImageRep* ir = (ImageRep*)image_list.First(); ir; ir = next)
{
next = (ImageRep*)ir->Suc();
ir->SetCacheUnusedImage(is_caching_unused_images);
}
for (ImageRep* ir = (ImageRep*)visible_image_list.First(); ir; ir = next)
{
next = (ImageRep*)ir->Suc();
ir->SetCacheUnusedImage(is_caching_unused_images);
}
}
#endif // IMG_TOGGLE_CACHE_UNUSED_IMAGES
void ImageManagerImp::ClearImageList(Head* list)
{
#ifdef CACHE_UNUSED_IMAGES
const double now = g_op_time_info->GetRuntimeMS();
// Free all images first since they might be in the cache but not in a document,
// in which case they will be deleted by this and also delete their UrlImageContentProvider
ImageRep* nextir;
for (ImageRep* ir = (ImageRep*)list->First(); ir; ir = nextir)
{
nextir = (ImageRep*)ir->Suc();
if (!ir->IsFreed() && IsFreeable(ir, now))
ir->Clear();
}
#endif // CACHE_UNUSED_IMAGES
ImageRep* imageRep = (ImageRep*)list->First();
while (imageRep != NULL)
{
RemoveFromImageList(imageRep);
RemoveLoadedImage(imageRep);
#ifdef ASYNC_IMAGE_DECODERS
RemoveAsyncDestroyImage(imageRep);
#endif // ASYNC_IMAGE_DECODERS
OP_DELETE(imageRep);
imageRep = (ImageRep*)list->First();
}
}
OP_STATUS ImageManagerImp::Create()
{
#ifdef IMG_TIME_LIMITED_CACHE
RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_IMG_CLEAN_IMAGE_CACHE, (MH_PARAM_1)this));
#endif // IMG_TIME_LIMITED_CACHE
null_image_content = OP_NEW(NullImageContent, ());
if (null_image_content == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
#ifdef HAS_ATVEF_SUPPORT
atvef_image = OP_NEW(Image, ());
if (!atvef_image)
return OpStatus::ERR_NO_MEMORY;
ImageRep* rep = ImageRep::CreateAtvefImage(this);
if (!rep)
{
OP_DELETE(atvef_image);
atvef_image = NULL;
return OpStatus::ERR_NO_MEMORY;
}
atvef_image->SetImageRep(rep);
#endif
return OpStatus::OK;
}
OP_STATUS ImageManagerImp::AddImageDecoderFactory(ImageDecoderFactory* factory, INT32 type, BOOL check_header)
{
DecoderFactoryElm* elm = OP_NEW(DecoderFactoryElm, ());
if (elm == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
elm->factory = factory;
elm->type = type;
elm->check_header = check_header;
elm->Into(&image_decoder_factory_list);
return OpStatus::OK;
}
ImageDecoderFactory* ImageManagerImp::GetImageDecoderFactory(int type)
{
for (DecoderFactoryElm* elm = (DecoderFactoryElm*)image_decoder_factory_list.First(); elm != NULL; elm = (DecoderFactoryElm*)elm->Suc())
{
if (elm->type == type)
{
return elm->factory;
}
}
return NULL;
}
BOOL ImageManagerImp::IsFreeable(ImageRep* image_rep, double now)
{
if (cache_policy == IMAGE_CACHE_POLICY_SOFT)
{
return (!image_rep->IsLocked() && !image_rep->IsVisible() && !StateOfGrace(image_rep, now));
}
else if (cache_policy == IMAGE_CACHE_POLICY_STRICT)
{
return (!image_rep->IsLocked());
}
return FALSE;
}
#ifdef IMG_TIME_LIMITED_CACHE
void ImageManagerImp::ScheduleCacheTimeout()
{
if (pending_cache_timeout)
g_main_message_handler->RemoveDelayedMessage(MSG_IMG_CLEAN_IMAGE_CACHE, (MH_PARAM_1)this, 0);
pending_cache_timeout = FALSE;
// Find the time for the oldest image
ImageRep* image_rep = (ImageRep*)image_list.First();
const double now = g_op_time_info->GetRuntimeMS();
while (image_rep && !IsFreeable(image_rep, now))
{
// Make sure the current image is used more recently than the next
OP_ASSERT(!image_rep->Suc() || image_rep->GetLastUsed() <= ((ImageRep*)image_rep->Suc())->GetLastUsed());
image_rep = (ImageRep*)image_rep->Suc();
}
if (image_rep)
{
unsigned int tickdiff = g_op_time_info->GetRuntimeTickMS()-image_rep->GetLastUsed();
if (tickdiff > IMG_CACHE_TIME_LIMIT*1000)
tickdiff = 0;
else
tickdiff = IMG_CACHE_TIME_LIMIT*1000 - tickdiff;
// Add 10 seconds to group some messages together better
tickdiff += 10000;
g_main_message_handler->PostDelayedMessage(MSG_IMG_CLEAN_IMAGE_CACHE, (MH_PARAM_1)this, 0, tickdiff);
pending_cache_timeout = TRUE;
}
}
void ImageManagerImp::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
pending_cache_timeout = FALSE;
FreeMemory();
}
#endif // IMG_TIME_LIMITED_CACHE
void ImageManagerImp::FreeMemory()
{
if (m_lock_count)
{
m_suppressed_free_memory = TRUE;
return;
}
const double now = g_op_time_info->GetRuntimeMS();
// Free enough freeable images excluding predecoding images.
ImageRep* image_rep = (ImageRep*)image_list.First();
#ifdef IMG_TIME_LIMITED_CACHE
unsigned int nowTick = g_op_time_info->GetRuntimeTickMS();
BOOL deleted_oldest = FALSE;
#endif // IMG_TIME_LIMITED_CACHE
#ifdef IMAGE_TURBO_MODE
BOOL stop_predecoding_images = MoreToFree();
#endif // IMAGE_TURBO_MODE
while (image_rep != NULL && (MoreToFree()
#ifdef IMG_TIME_LIMITED_CACHE
|| nowTick-image_rep->GetLastUsed() > IMG_CACHE_TIME_LIMIT*1000
#endif // IMG_TIME_LIMITED_CACHE
))
{
ImageRep* next_image_rep = (ImageRep*)image_rep->Suc();
#ifdef IMG_TIME_LIMITED_CACHE
deleted_oldest = TRUE;
// Make sure the current image is used more recently than the next
OP_ASSERT(!next_image_rep || image_rep->GetLastUsed() <= next_image_rep->GetLastUsed());
#endif // IMG_TIME_LIMITED_CACHE
if (IsFreeable(image_rep, now))
{
image_rep->Clear();
}
image_rep = next_image_rep;
}
#ifdef IMAGE_TURBO_MODE
// Stop all ongoing predecoding images if the cacheend was reached.
if (stop_predecoding_images)
StopAllPredecodingImages();
#endif // IMAGE_TURBO_MODE
#ifdef IMG_TIME_LIMITED_CACHE
if (deleted_oldest || !pending_cache_timeout)
ScheduleCacheTimeout();
#endif // IMG_TIME_LIMITED_CACHE
// go through grace time slots and delete/clear the ones no longer relevant
UINT32 unused_grace_time_slots = 0;
ImageGraceTimeSlot* next;
for (ImageGraceTimeSlot* gt = static_cast<ImageGraceTimeSlot*>(m_grace_times.First()); gt; gt = next)
{
next = static_cast<ImageGraceTimeSlot*>(gt->Suc());
// slot no longer used
if (gt->m_time < now || gt->Empty())
{
gt->RemoveAll();
++ unused_grace_time_slots;
if (unused_grace_time_slots > IMG_GRACE_TIME_SLOT_COUNT)
{
gt->Out();
OP_DELETE(gt);
}
else
{
gt->m_time = 0;
}
}
}
}
void ImageManagerImp::SetCacheSize(INT32 cache_size, ImageCachePolicy cache_policy)
{
this->cache_size = cache_size;
this->cache_policy = cache_policy;
#ifdef IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
this->anim_cache_size = (1024 * 1024) + cache_size / 4;
#endif // IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
FreeMemory();
}
void ImageManagerImp::Touch(ImageRep* imageRep)
{
imageRep->Out();
ImageRepIntoImageList(imageRep);
}
#ifdef IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
void ImageManagerImp::TouchAnimated(AnimatedImageContent* animated_image_content)
{
animated_image_content->Out();
animated_image_content->Into(&animated_image_list);
}
#endif // IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
Image ImageManagerImp::GetImage(ImageContentProvider* content_provider)
{
ImageRep* imageRep = GetImageRep(content_provider);
if (imageRep == NULL)
{
imageRep = AddToImageList(content_provider);
if (imageRep == NULL)
{
// FIXME:OOM-KILSMO
return Image();
}
}
Image image;
image.SetImageRep(imageRep);
return image;
}
Image ImageManagerImp::GetImage(OpBitmap* bitmap)
{
ImageRep* imageRep = ImageRep::Create(bitmap);
if (imageRep == NULL)
{
// FIXME:OOM-KILSMO
return Image();
}
imageRep->Into(&bitmap_image_list);
Image image;
image.SetImageRep(imageRep);
return image;
}
void ImageManagerImp::ResetImage(ImageContentProvider* content_provider)
{
ImageRep* imageRep = GetImageRep(content_provider);
if (imageRep != NULL)
{
imageRep->Reset();
}
}
ImageRep* ImageManagerImp::GetImageRep(ImageContentProvider* content_provider)
{
void* image_rep = NULL;
OP_STATUS ret_val = image_hash_table.GetData(content_provider, &image_rep);
if (OpStatus::IsError(ret_val))
{
return NULL;
}
OP_ASSERT(image_rep);
return (ImageRep*)image_rep;
}
LoadedImageElm* ImageManagerImp::GetLoadedImageElm(ImageRep* image_rep)
{
for (LoadedImageElm* elm = (LoadedImageElm*)loaded_image_list.First(); elm != NULL; elm = (LoadedImageElm*)elm->Suc())
{
if (elm->image_rep == image_rep)
{
return elm;
}
}
return NULL;
}
OP_STATUS ImageManagerImp::AddLoadedImage(ImageRep* image_rep)
{
LoadedImageElm* elm = GetLoadedImageElm(image_rep);
if (elm != NULL)
{
return OpStatus::OK;
}
elm = OP_NEW(LoadedImageElm, ());
if (elm == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
elm->image_rep = image_rep;
if (loaded_image_list.Empty())
{
PostContinueLoading(); // FIXME:IMG
}
elm->Into(&loaded_image_list);
return OpStatus::OK;
}
void ImageManagerImp::RemoveLoadedImage(ImageRep* image_rep)
{
LoadedImageElm* elm = GetLoadedImageElm(image_rep);
if (elm)
{
elm->Out();
OP_DELETE(elm);
}
}
void ImageManagerImp::Progress()
{
LoadedImageElm* elm = (LoadedImageElm*)loaded_image_list.First();
#ifdef IMAGE_TURBO_MODE
// Skip invisible images so visible images get higher priority
while (elm && elm->Suc() && elm->image_rep->IsPredecoding())
elm = (LoadedImageElm*) elm->Suc();
#endif
if (elm != NULL)
{
ImageRep* image_rep = elm->image_rep;
OP_ASSERT(image_rep);
TRACK_CPU_PER_TAB(image_rep->GetContentProvider()->GetCPUUsageTracker());
elm->Out();
OP_DELETE(elm);
image_rep->OnMoreData(image_rep->GetContentProvider()); // FIXME:OOM-KILSMO
if (image_rep->IsFailed())
{
image_rep->ReportError();
}
if (!loaded_image_list.Empty())
{
PostContinueLoading();
}
}
}
int ImageManagerImp::CheckImageType(const unsigned char* data_buf, UINT32 buf_len)
{
OP_ASSERT(data_buf != 0 || buf_len == 0);
for (DecoderFactoryElm* elm = (DecoderFactoryElm*)image_decoder_factory_list.First(); elm != NULL; elm = (DecoderFactoryElm*)elm->Suc())
{
if (elm->check_header)
{
BOOL3 ret = elm->factory->CheckType(data_buf, buf_len);
if (ret == YES)
{
return elm->type;
}
if (ret == MAYBE)
{
return 0;
}
}
}
return -1;
}
BOOL ImageManagerImp::IsImage(int type)
{
ImageDecoderFactory* factory = GetImageDecoderFactory(type);
return factory != NULL;
}
#ifdef IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
void ImageManagerImp::FreeAnimMemory(AnimatedImageContent* animated_image_content)
{
if (anim_used_mem > anim_cache_size)
{
AnimatedImageContent* elm = (AnimatedImageContent*)animated_image_list.First();
while (elm)
{
AnimatedImageContent* next_elm = (AnimatedImageContent*)elm->Suc();
if (elm != animated_image_content)
{
elm->ClearBuffers();
elm->Out();
if (anim_cache_size >= anim_used_mem)
{
return;
}
}
elm = next_elm;
}
}
}
#endif // IMG_CACHE_MULTIPLE_ANIMATION_FRAMES
#ifdef ASYNC_IMAGE_DECODERS
void ImageManagerImp::SetAsyncImageDecoderFactory(AsyncImageDecoderFactory* factory)
{
async_factory = factory;
}
void ImageManagerImp::FreeUnusedAsyncDecoders()
{
AsyncImageElm* elm = (AsyncImageElm*)destroyed_async_decoders.First();
while (elm != NULL)
{
elm->Out();
elm->rep->FreeAsyncDecoder();
OP_DELETE(elm);
elm = (AsyncImageElm*)destroyed_async_decoders.First();
}
}
void ImageManagerImp::AddToAsyncDestroyList(ImageRep* image_rep)
{
AsyncImageElm* elm = OP_NEW(AsyncImageElm, ()); // FIXME:OOM
if (elm != NULL)
{
elm->rep = image_rep;
elm->Into(&destroyed_async_decoders);
}
}
void ImageManagerImp::RemoveAsyncDestroyImage(ImageRep* image_rep)
{
AsyncImageElm* elm = GetAsyncImageElm(image_rep);
if (elm)
{
elm->Out();
OP_DELETE(elm);
}
elm = GetAsyncDestroyElm(image_rep);
if (elm)
{
elm->Out();
elm->rep->FreeAsyncDecoder();
OP_DELETE(elm);
}
}
AsyncImageElm* ImageManagerImp::GetAsyncDestroyElm(ImageRep* image_rep)
{
for (AsyncImageElm* elm = (AsyncImageElm*)destroyed_async_decoders.First(); elm != NULL; elm = (AsyncImageElm*)elm->Suc())
{
if (elm->rep == image_rep)
{
return elm;
}
}
return NULL;
}
#endif // ASYNC_IMAGE_DECODERS
#ifdef HAS_ATVEF_SUPPORT
Image ImageManagerImp::GetAtvefImage()
{
return *atvef_image;
}
#endif
void ImageManagerImp::ImageRepIntoImageList(ImageRep* image_rep)
{
if (image_rep->IsVisible())
{
image_rep->Into(&visible_image_list);
}
else
{
if (image_rep->IsFreed())
{
image_rep->Into(&free_image_list);
}
else
{
image_rep->Into(&image_list);
#ifdef IMG_TIME_LIMITED_CACHE
image_rep->UpdateLastUsed(g_op_time_info->GetRuntimeTickMS());
if (!pending_cache_timeout)
ScheduleCacheTimeout();
#endif // IMG_TIME_LIMITED_CACHE
}
}
}
void ImageManagerImp::RemoveFromImageList(ImageRep* image_rep)
{
ImageContentProvider* content_provider = image_rep->GetImageContentProvider();
void* dummy;
OP_STATUS ret_val = image_hash_table.Remove(content_provider, &dummy);
OpStatus::Ignore(ret_val);
image_rep->Out();
}
void ImageManagerImp::ImageRepMoveToRightList(ImageRep* image_rep)
{
image_rep->Out();
ImageRepIntoImageList(image_rep);
}
#ifdef ASYNC_IMAGE_DECODERS_EMULATION
void ImageManagerImp::AddBufferedImageDecoder(AsyncEmulationDecoder* decoder)
{
BOOL post_continue = FALSE;
if (!decoder->InList())
{
post_continue = buffered_image_decoder_list.Empty();
decoder->Into(&buffered_image_decoder_list);
}
if (post_continue)
{
progress_listener->OnMoreBufferedData();
}
}
void ImageManagerImp::MoreBufferedData()
{
AsyncEmulationDecoder* decoder = (AsyncEmulationDecoder*)buffered_image_decoder_list.First();
if (decoder != NULL)
{
decoder->Out();
decoder->Decode();
if (!buffered_image_decoder_list.Empty())
{
progress_listener->OnMoreBufferedData();
}
}
}
void ImageManagerImp::MoreDeletedDecoders()
{
}
#endif // ASYNC_IMAGE_DECODERS_EMULATION
#ifdef CACHE_UNUSED_IMAGES
void ImageManagerImp::FreeImagesForContext(URL_CONTEXT_ID id)
{
ImageRep* image_rep = (ImageRep*)image_list.First();
while (image_rep != NULL)
{
ImageRep* next_image_rep = (ImageRep*)image_rep->Suc();
if (image_rep->GetCachedUnusedImage() &&
((UrlImageContentProvider*)image_rep->GetContentProvider())->GetUrl()->GetContextId() == id)
{
image_rep->Clear();
}
image_rep = next_image_rep;
}
}
#endif // CACHE_UNUSED_IMAGES
#ifdef IMGMAN_USE_SCRATCH_BUFFER
UINT32* ImageManagerImp::GetScratchBuffer(unsigned int width)
{
if (width <= scratch_buffer_size)
return scratch_buffer;
UINT32* pmb = OP_NEWA(UINT32, width);
if (!pmb)
return NULL;
OP_DELETEA(scratch_buffer);
scratch_buffer = pmb;
scratch_buffer_size = width;
return scratch_buffer;
}
#endif // IMGMAN_USE_SCRATCH_BUFFER
|
//
// Created by pierreantoine on 11/01/2020.
//
#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <cmath>
#include "fb3-2.h"
static unsigned symhash(const char *sym)
{
unsigned int hash = 0;
unsigned c;
while ((c = *(sym++)))
{
hash = hash * 9 ^ c;
}
return hash;
}
symbolptr symbol_lookup(symbolptr map, const unsigned map_size, char *name)
{
symbolptr sp = &map[symhash(name) % map_size];
int scount = map_size;
while (--scount >= 0)
{
if (sp->name && !strcmp(sp->name, name))
{
return sp;
}
if (!sp->name)
{
sp->name = strdup(name);
sp->value = 0;
sp->func = nullptr;
sp->syms = nullptr;
return sp;
}
if (++sp >= map + map_size)
{
sp = map;
}
}
yyerror("symbol table overflow");
abort();
}
struct symbol symtab[NHASH];
symbolptr lookup(char *name)
{
return symbol_lookup(symtab, NHASH, name);
}
void yyerror(const char *s, ...)
{
va_list ap;
va_start(ap, s);
fprintf(stderr, "%d: error: ", yylineno);
vfprintf(stderr, s, ap);
fprintf(stderr, "\n");
}
void assert_not_null(void *pointer)
{
if (!pointer)
{
yyerror("out of space");
exit(1);
}
}
astptr ast_malloc()
{
auto a = (astptr) malloc(sizeof(struct ast));
assert_not_null(a);
return a;
}
astptr newast(int nodetype, astptr l, astptr r)
{
astptr a = ast_malloc();
a->nodetype = nodetype;
a->l = l;
a->r = r;
return a;
}
astptr newnum(double d)
{
struct numval *a = (struct numval *) malloc(sizeof(struct numval));
assert_not_null(a);
a->nodetype = 'K';
a->number = d;
return (astptr) a;
}
astptr newcmp(int cmptype, astptr l, astptr r)
{
auto a = ast_malloc();
a->nodetype = '0' + cmptype;
a->l = l;
a->r = r;
return a;
}
astptr newfunc(enum bifs functype, astptr l)
{
auto a = (struct fncall *) malloc(sizeof(struct fncall *));
assert_not_null(a);
a->nodetype = 'F';
a->l = l;
a->functype = functype;
return (astptr) a;
}
astptr newcall(symbolptr s, astptr l)
{
auto a = (struct ufncall *) malloc(sizeof(struct ufncall));
assert_not_null(a);
a->nodetype = 'C';
a->l = l;
a->s = s;
return (astptr) a;
}
astptr newref(symbolptr s)
{
auto a = (struct symref *) malloc(sizeof(struct symref));
assert_not_null(a);
a->nodetype = 'N';
a->s = s;
return (astptr) a;
}
astptr newasgn(symbolptr s, astptr v)
{
auto a = (struct symasgn *) malloc(sizeof(struct symasgn));
a->nodetype = '=';
a->s = s;
a->v = v;
return (astptr) a;
}
astptr newflow(int nodetype, astptr cond, astptr tl, astptr el)
{
auto a = (struct flow *) malloc(sizeof(struct flow));
a->nodetype = nodetype;
a->cond = cond;
a->tl = tl;
a->el = el;
return (astptr) a;
}
void treefree(astptr a)
{
if (!a)
{
return;
}
switch (a->nodetype)
{
case '+':
case '-':
case '*':
case '/':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case 'L':
treefree(a->r);
[[fallthrough]];
case '|':
case 'M':
case 'C':
case 'F':
treefree(a->l);
[[fallthrough]];
case 'K':
case 'N':
break;
case '=':
treefree(((struct symasgn *) a)->v);
break;
case 'I' :
case 'W':
treefree(((struct flow *) a)->cond);
treefree(((struct flow *) a)->tl);
treefree(((struct flow *) a)->el);
break;
default:
printf("internal error: free bad node %c\n", a->nodetype);
}
free(a);
}
symlistptr newsymlist(symbolptr sym, symlistptr next)
{
auto sl = (struct symlist *) malloc(sizeof(struct symlist));
assert_not_null(sl);
sl->sym = sym;
sl->next = next;
return sl;
}
void symlistfree(symlistptr sl)
{
while (sl)
{
auto nsl = sl->next;
free(sl);
sl = nsl;
}
}
double eval_if(struct flow *ast);
double eval_while(struct flow *ast);
double callbuiltin(struct fncall *ast);
double calluser(struct ufncall *ast);
double read_number(struct numval *a);
void reset_old_values(unsigned int nargs, const double *oldval, symlistptr sl);
double eval(astptr a)
{
if (!a)
{
return 0.0;
}
switch (a->nodetype)
{
case 'K':
return read_number((struct numval *) a);
case 'N':
return ((struct symref *) a)->s->value;
case '=':
return ((struct symasgn *) a)->s->value = eval(((struct symasgn *) a)->v);
case '+':
return eval(a->l) + eval(a->r);
case '-':
return eval(a->l) - eval(a->r);
case '*':
return eval(a->l) * eval(a->r);
case '/':
return eval(a->l) / eval(a->r);
case '|':
return std::abs(eval(a->l));
case 'M':
return -eval(a->l);
case '1':
return eval(a->l) > eval(a->r);
case '2':
return eval(a->l) < eval(a->r);
case '3':
return eval(a->l) != eval(a->r);
case '4':
return eval(a->l) == eval(a->r);
case '5':
return eval(a->l) >= eval(a->r);
case '6':
return eval(a->l) <= eval(a->r);
case 'I':
return eval_if((struct flow *) a);
case 'W':
return eval_while((struct flow *) a);
case 'L':
eval(a->l);
return eval(a->r);
case 'F':
return callbuiltin((struct fncall *) a);
case 'C':
return calluser((struct ufncall *) a);
default:
printf("internal error: bad node %c\n", a->nodetype);
}
return 0;
}
double read_number(struct numval *a)
{
return a->number;
}
double eval_if(struct flow *ast)
{
if (eval(ast->cond) != 0)
{
return eval(ast->tl);
}
return eval(ast->el);
}
double eval_while(struct flow *ast)
{
if (!ast->tl)
{
return 0;
}
double v = 0;
while (eval(ast->cond) != 0)
{
v = eval(ast->tl);
}
return v;
}
double callbuiltin(struct fncall *ast)
{
double v = eval(ast->l);
switch (ast->functype)
{
case bifs::B_sqrt:
return std::sqrt(v);
case bifs::B_exp:
return std::exp(v);
case bifs::B_log:
return std::log(v);
case bifs::B_print:
printf("echo (%g)\n", v);
return v;
}
yyerror("unknown built-in call with key: %d", ast->functype);
return 0;
}
void dodef(symbolptr name, symlistptr syms, astptr func)
{
if (name->syms)
{
symlistfree(name->syms);
}
name->syms = syms;
if (name->func)
{
treefree(name->func);
}
name->func = func;
}
unsigned count_args(symlistptr list)
{
unsigned count;
for (count = 0; list; list = list->next)
{
count += 1;
}
return count;
}
double *double_malloc(unsigned size)
{
auto d = (double *) malloc(size * sizeof(double));
assert_not_null(d);
return d;
}
void save_and_update_values(symlistptr sl, unsigned int size, double *memory, const double *new_values);
void reset_old_values(symlistptr, unsigned int, const double *);
double calluser(struct ufncall *ast)
{
auto fn = ast->s;
if (!fn->func)
{
yyerror("call to undefined function %s\n", fn->name);
return 0;
}
auto args = ast->l;
unsigned nargs = count_args(fn->syms);
auto oldval = double_malloc(nargs);
auto newval = double_malloc(nargs);
for (unsigned i = 0; i < nargs; ++i)
{
if (!args)
{
yyerror("too few arguments in call to %s", fn->name);
free(oldval);
free(newval);
return 0;
}
if (args->nodetype == 'L')
{
newval[i] = eval(args->l);
args = args->r;
continue;
}
newval[i] = eval(args);
args = nullptr;
}
save_and_update_values(fn->syms, nargs, oldval, newval);
free(newval);
double v = eval(fn->func);
reset_old_values(fn->syms, nargs, oldval);
free(oldval);
return v;
}
void save_and_update_values(symlistptr sl, unsigned int size, double *memory, const double *new_values)
{
for (unsigned i = 0; i < size; ++i)
{
memory[i] = sl->sym->value;
sl->sym->value = new_values[i];
sl = sl->next;
}
}
void reset_old_values(symlistptr sl, unsigned int size, const double *old_values)
{
for (unsigned i = 0; i < size; ++i)
{
sl->sym->value = old_values[i];
sl = sl->next;
}
}
|
#include <iostream>
#include <vector>
//Metodo de burbuja.
int main()
{
//Se agrega una lista con valores aleatorios
std::vector<std::int32_t> l1 = {18,15,75,22,10,5,68,4};
int dam = 8;
std::cout << "Lista inicial: ";
for (int i = 0;i < dam;i++) {
std::cout << l1[i] << ",";
}
std::cout << "\n";
//aqui se ordena la lista
for (int i = 1;i < dam - 1; i++) {
for (int j = 0; j < dam - 1;j++) {
if (l1[j] > l1[j + 1]) {
int temp = l1[j];
l1[j] = l1[j + 1];
l1[j + 1] = temp;
}
}
}
//Se imprime la lista ordenada
std::cout << "Lista ordenada: ";
for (int i = 0;i < dam;i++) {
std::cout << l1[i]<<",";
}
}
|
// Created on: 1999-02-15
// Created by: Andrey BETENEV
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepGeom_SurfaceCurveAndBoundedCurve_HeaderFile
#define _StepGeom_SurfaceCurveAndBoundedCurve_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepGeom_SurfaceCurve.hxx>
class StepGeom_BoundedCurve;
class StepGeom_SurfaceCurveAndBoundedCurve;
DEFINE_STANDARD_HANDLE(StepGeom_SurfaceCurveAndBoundedCurve, StepGeom_SurfaceCurve)
//! complex type: bounded_curve + surface_curve
//! needed for curve_bounded_surfaces (S4132)
class StepGeom_SurfaceCurveAndBoundedCurve : public StepGeom_SurfaceCurve
{
public:
//! creates empty object
Standard_EXPORT StepGeom_SurfaceCurveAndBoundedCurve();
//! returns field BoundedCurve
Standard_EXPORT Handle(StepGeom_BoundedCurve)& BoundedCurve();
DEFINE_STANDARD_RTTIEXT(StepGeom_SurfaceCurveAndBoundedCurve,StepGeom_SurfaceCurve)
protected:
private:
Handle(StepGeom_BoundedCurve) myBoundedCurve;
};
#endif // _StepGeom_SurfaceCurveAndBoundedCurve_HeaderFile
|
#include<iostream>
#include<string>
using namespace std;
int convert_stoi(string s,auto it)
{
if(it==s.end())
return result;
else
return *it
}
int main()
{
string s;
cin>>s;
auto it=s.begin();
cout<<convert_stoi(s,it);
return 0;
}
|
#include "stdafx.h"
#include "QsoError.h"
QsoError::QsoError(QsoErrorType errorType)
:
m_error(),
m_errorType(errorType)
{
}
QsoError::~QsoError()
{
}
|
#pragma once
#include "sx/GlyphStyle.h"
#include <cu/cu_macro.h>
#include <vector>
namespace sx
{
class GlyphStyle;
class GlyphStyleID
{
public:
int Gen(const GlyphStyle& style);
private:
static size_t Hash(const GlyphStyle& style);
static void HashColor(size_t& seed, const pt2::GradientColor& color);
private:
static const int HASH_CAP = 197;
private:
int m_next_id;
std::vector<std::pair<GlyphStyle, int>> m_hash[HASH_CAP];
std::pair<GlyphStyle, int> m_last;
CU_SINGLETON_DECLARATION(GlyphStyleID)
}; // GlyphStyleID
}
|
/*
* convert.cpp
* Author: Claire Savard (claire.savard@colorado.edu)
*
* This file converts decimal values to ap_fixed and
* prints them in the proper format required here:
* https://www.xilinx.com/support/documentation/sw_manuals/xilinx11/cgn_r_coe_file_syntax.htm
*
* To run:
* $ make run
* $ ./convert
*
* Things to change before running script:
*
* in convert.cpp, input and output file names
*
* in convert.h, N (num of rows you want to convert), nbits
* (num tot bits in ap_fixed), ndec (num of bits assigned
* to decimal portion), nfeat (num of feats in each row)
*
* in Makefile: change path of vivado inputs dir to path
* found on your machine
*/
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <bits/stdc++.h>
#include <bitset>
#include "convert.h"
using namespace std;
// from https://www.geeksforgeeks.org/efficient-method-2s-complement-binary-string/
// Function to find two's complement
string findTwoscomplement(string str)
{
int n = str.length();
// Traverse the string to get first '1' from
// the last of string
int i;
for (i = n-1 ; i >= 0 ; i--)
if (str[i] == '1')
break;
// If there exists no '1' concatenate 1 at the
// starting of string
if (i == -1)
return '1' + str;
// Continue traversal after the position of
// first '1'
for (int k = i-1 ; k >= 0; k--)
{
//Just flip the values
if (str[k] == '1')
str[k] = '0';
else
str[k] = '1';
}
// return the modified string
return str;
}
// adapted from https://www.geeksforgeeks.org/convert-decimal-fraction-binary-number/
string decimalToBinary(float num){
bool sign = 0;
if (num<0) sign = 1;
num = abs(num);
string binary = "";
// Fetch the integral part of decimal number
int Integral = num;
// Fetch the fractional part decimal number
float fractional = num - Integral;
string int_bin = bitset<nint-1>(Integral).to_string();
binary = binary+int_bin;
// Conversion of fractional part to
// binary equivalent
int k_prec = nbits-nint;
while (k_prec--) {
// Find next bit in fraction
fractional *= 2;
int fract_bit = fractional;
if (fract_bit == 1){
fractional -= fract_bit;
binary.push_back(1 + '0');
} else binary.push_back(0 + '0');
}
if (sign){
binary = findTwoscomplement(binary);
binary = "1"+binary;
}else binary = "0"+binary;
return binary;
}
int main() {
struct tracks* trks[N];
ifstream input;
input.open("data/y_true.dat");
if (!input.is_open()) {
cout << "file not opened" << endl;
return 0;
}
ofstream output;
output.open("converted/y.coe");
output << "memory_initialization_radix=2;\n";
output << "memory_initialization_vector=";
input_t feat;
for (int i=0; i<N; i++){
string row = "";
for (int j=0; j<nfeat; j++){
input >> feat;
row = row + decimalToBinary(feat);
}
output << row;
if (i != N-1) output << ',' << endl;
}
output << ';';
output.close();
return 0;
}
|
#ifndef PI_SBUS
#define PI_SBUS
class PiSBus {
public:
PiSBus(std::string);
int Begin();
void Read();
void DisplayData();
private:
std::string _port;
int _file;
uint16_t _channel_values[18];
uint8_t _sbus_data[25];
};
#endif
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <stdio.h>
#include <string.h>
#define MAX 50000 // 5133
#define SIZE 10000
#define INF (1<<30)
using namespace std;
class ComparerInator {
public:
int
makeProgram(vector <int> A, vector <int> B, vector <int> wanted)
{
bool isA = true;
for (int i=0; i<A.size(); ++i) {
if (wanted[i] != A[i]) {
isA = false;
break;
}
}
bool isB = true;
for (int i=0; i<B.size(); ++i) {
if (wanted[i] != B[i]) {
isB = false;
break;
}
}
bool isAB = true;
for (int i=0; i<A.size(); ++i) {
int a = A[i]<B[i]?A[i]:B[i];
if (wanted[i] != a) {
isAB = false;
break;
}
}
bool isBA = true;
for (int i=0; i<B.size(); ++i) {
int a = A[i]<B[i]?B[i]:A[i];
if (wanted[i] != a) {
isBA = false;
break;
}
}
int ans = isBA||isAB?7:-1;
ans = isA||isB?1:ans;
return ans;
}
};
|
#pragma once
#include <cmath>
#include <ostream>
#include "ross.hpp"
namespace ross
{
/**
* Immutable type to represent colors by various channels, each of which is measured in intensity from 0.0 to 1.0
*/
template<uint8_t kChannels>
class color
{
public:
/**
* Each channel is a value from 0.0 (minimum intensity) to 1.0 (maximum intensity) inclusive.
*/
const real_t m_channels[kChannels];
/**
* Access channel
*/
constexpr real_t operator[](uint8_t channel) const
{
return m_channels[channel];
}
/**
* Get the number of channels in this color
*/
constexpr uint8_t size() const
{
return kChannels;
}
};
}
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */
#include "core/pch.h"
#include "modules/ecmascript/carakan/src/es_pch.h"
#include "modules/ecmascript/carakan/src/builtins/es_builtins.h"
#include "modules/ecmascript/carakan/src/builtins/es_date_builtins.h"
#include "modules/ecmascript/carakan/src/object/es_date_object.h"
#include "modules/stdlib/util/opdate.h"
/* The Date builtin methods consult OpDate and PI layer methods
* to sample and compute date/times. In the general case, these
* should be considered as not callable while on a thread stack.
*
* Switching stacks unnecessarily isn't desirable, so
* for OpDate, the following methods are considered as unsafe
* for thread stack usage:
*
* OpDate::UTC()
* OpDate::LocalTime()
* OpDate::GetCurrentUTCTime()
* OpDate::ParseDate()
*
* NOTE: should any of the other OpDate methods change to also
* require calling out to the platform, this needs to be
* reflected for ES_DateBuiltins. We do assume a higher level
* of stability for these methods in that regard, however.
*/
class ES_SuspendedParseDate
: public ES_SuspendedCall
{
public:
ES_SuspendedParseDate(ES_Execution_Context *context, const uni_char *date_string, BOOL with_localtime)
: utc(-1)
, local(-1)
, date_string(date_string)
, with_localtime(with_localtime)
{
context->SuspendedCall(this);
}
double utc;
double local;
private:
virtual void DoCall(ES_Execution_Context *context)
{
utc = OpDate::ParseDate(date_string, FALSE);
if (with_localtime)
local = OpDate::LocalTime(utc);
}
const uni_char *date_string;
BOOL with_localtime;
};
class ES_SuspendedUTC
: public ES_SuspendedCall
{
public:
ES_SuspendedUTC(ES_Execution_Context *context, double local)
: result(-1)
, local(local)
{
context->SuspendedCall(this);
}
double result;
private:
virtual void DoCall(ES_Execution_Context *context)
{
result = OpDate::UTC(local);
}
double local;
};
class ES_SuspendedGetCurrentTimeUTC
: public ES_SuspendedCall
{
public:
ES_SuspendedGetCurrentTimeUTC(ES_Execution_Context *context)
: result(-1)
{
context->SuspendedCall(this);
}
double result;
private:
virtual void DoCall(ES_Execution_Context *context)
{
result = OpDate::GetCurrentUTCTime();
}
};
static const char invalid_date[] = "Invalid Date";
static const int year_days[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
static const int leap_year_days[13] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
ST_HEADER_UNI(months)
ST_ENTRY(0,UNI_L("January"))
ST_ENTRY(1,UNI_L("February"))
ST_ENTRY(2,UNI_L("March"))
ST_ENTRY(3,UNI_L("April"))
ST_ENTRY(4,UNI_L("May"))
ST_ENTRY(5,UNI_L("June"))
ST_ENTRY(6,UNI_L("July"))
ST_ENTRY(7,UNI_L("August"))
ST_ENTRY(8,UNI_L("September"))
ST_ENTRY(9,UNI_L("October"))
ST_ENTRY(10,UNI_L("November"))
ST_ENTRY(11,UNI_L("December"))
ST_FOOTER_UNI
#define MONTHS(x) ST_REF(months,x)
ST_HEADER_UNI(days)
ST_ENTRY(0,UNI_L("Sunday"))
ST_ENTRY(1,UNI_L("Monday"))
ST_ENTRY(2,UNI_L("Tuesday"))
ST_ENTRY(3,UNI_L("Wednesday"))
ST_ENTRY(4,UNI_L("Thursday"))
ST_ENTRY(5,UNI_L("Friday"))
ST_ENTRY(6,UNI_L("Saturday"))
ST_FOOTER_UNI
#define DAYS(x) ST_REF(days,x)
/** TTS == TimeTo<some>String */
class ES_SuspendedTTS
: public ES_SuspendedCall
{
public:
typedef JString* (*TimeToXyzString)(ES_Context *context, double time);
ES_SuspendedTTS(TimeToXyzString fn, ES_Execution_Context *context, double time)
: result(NULL),
fn(fn),
time(time),
with_time(TRUE),
status(OpStatus::OK)
{
context->SuspendedCall(this);
if (OpStatus::IsMemoryError(status))
context->AbortOutOfMemory();
}
ES_SuspendedTTS(TimeToXyzString fn, ES_Execution_Context *context)
: result(NULL),
fn(fn),
time(0),
with_time(FALSE),
status(OpStatus::OK)
{
context->SuspendedCall(this);
if (OpStatus::IsMemoryError(status))
context->AbortOutOfMemory();
}
JString *result;
private:
virtual void DoCall(ES_Execution_Context *context)
{
TRAP(status, result = (*fn)(context, with_time ? time : OpDate::GetCurrentUTCTime()));
}
TimeToXyzString fn;
double time;
BOOL with_time;
OP_STATUS status;
};
/* static */ JString*
ES_DateBuiltins::TimeToString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2008-06-09 stanislavj
double localtime = OpDate::LocalTime(time);
int zoneoffset = DOUBLE2INT32((localtime - time) / msPerMinute);
zoneoffset = zoneoffset % 60 + (zoneoffset / 60 * 100);
if (uni_snprintf(string, ARRAY_SIZE(string) - 1,
// The .3 is highly desirable and some sites depend on it, see bug #54175
#ifdef ZONENAME_IN_DATESTRING // It breaks www.islam.org and is not compatible with MSIE, but with Mozilla
UNI_L("%.3s %.3s %02d %04d %02d:%02d:%02d GMT%+05d (%s)"),
#else
UNI_L("%.3s %.3s %02d %04d %02d:%02d:%02d GMT%+05d"),
#endif
DAYS(OpDate::WeekDay(localtime)),
MONTHS(OpDate::MonthFromTime(localtime)),
OpDate::DateFromTime(localtime),
OpDate::YearFromTime(localtime),
OpDate::HourFromTime(localtime),
OpDate::MinFromTime(localtime),
OpDate::SecFromTime(localtime),
zoneoffset
#ifdef ZONENAME_IN_DATESTRING
, uni_tzname(0)
#endif
) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
string[ARRAY_SIZE(string) - 1] = 0;
return JString::Make(context, string);
}
/* static */ JString*
ES_DateBuiltins::TimeToDateString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2008-06-09 stanislavj
double localtime = OpDate::LocalTime(time);
// The .3 is highly desirable and some sites depend on it, see bug #54175
if (uni_snprintf(string, ARRAY_SIZE(string) - 1, UNI_L("%.3s, %02d %.3s %04d"),
DAYS(OpDate::WeekDay(localtime)),
OpDate::DateFromTime(localtime),
MONTHS(OpDate::MonthFromTime(localtime)),
OpDate::YearFromTime(localtime)) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
string[ARRAY_SIZE(string) - 1] = 0;
return JString::Make(context, string);
}
/* static */ JString*
ES_DateBuiltins::TimeToTimeString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2008-06-09 stanislavj
double localtime = OpDate::LocalTime(time);
int zoneoffset = DOUBLE2INT32((localtime - time) / msPerMinute);
zoneoffset = zoneoffset % 60 + (zoneoffset / 60 * 100);
if (uni_snprintf(string, ARRAY_SIZE(string) - 1,
#ifdef ZONENAME_IN_DATESTRING
UNI_L("%02d:%02d:%02d GMT%+05d (%s)"),
#else
UNI_L("%02d:%02d:%02d GMT%+05d"),
#endif
OpDate::HourFromTime(localtime),
OpDate::MinFromTime(localtime),
OpDate::SecFromTime(localtime),
zoneoffset
#ifdef ZONENAME_IN_DATESTRING
, uni_tzname(0)
#endif
) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
string[ARRAY_SIZE(string) - 1] = 0;
return JString::Make(context, string);
}
static double
BreakdownLocalTime(ES_ImportedAPI::TimeElements* telts, double time)
{
double localtime = OpDate::LocalTime(time);
telts->year = OpDate::YearFromTime(localtime);
telts->month = OpDate::MonthFromTime(localtime);
telts->day_of_week = OpDate::WeekDay(localtime);
telts->day_of_month = OpDate::DateFromTime(localtime);
telts->hour = OpDate::HourFromTime(localtime);
telts->minute = OpDate::MinFromTime(localtime);
telts->second = OpDate::SecFromTime(localtime);
telts->millisecond = (int)OpDate::msFromTime(localtime);
return localtime;
}
/* static */ JString*
ES_DateBuiltins::TimeToLocaleString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2011-05-24 sof
ES_ImportedAPI::TimeElements telts;
double localtime = BreakdownLocalTime(&telts, time);
OP_STATUS r = ES_ImportedAPI::FormatLocalTime(ES_ImportedAPI::GET_DATE_AND_TIME, string, ARRAY_SIZE(string), &telts);
if (OpStatus::IsMemoryError(r))
LEAVE(r);
else if (OpStatus::IsError(r))
{
int zoneoffset = DOUBLE2INT32((localtime - time) / msPerMinute);
zoneoffset = zoneoffset % 60 + (zoneoffset / 60 * 100);
if (uni_snprintf(string, ARRAY_SIZE(string),
#ifdef ZONENAME_IN_DATESTRING
UNI_L("%s %s %02d, %02d:%02d:%02d GMT%+05d (%s) %04d"),
#else
UNI_L("%s %s %02d, %02d:%02d:%02d GMT%+05d %04d"),
#endif
DAYS(OpDate::WeekDay(localtime)),
MONTHS(OpDate::MonthFromTime(localtime)),
OpDate::DateFromTime(localtime),
OpDate::HourFromTime(localtime),
OpDate::MinFromTime(localtime),
OpDate::SecFromTime(localtime),
zoneoffset,
#ifdef ZONENAME_IN_DATESTRING
uni_tzname(0),
#endif
OpDate::YearFromTime(localtime)) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
}
return JString::Make(context, string);
}
/* static */ JString*
ES_DateBuiltins::TimeToLocaleDateString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2011-05-24 sof
ES_ImportedAPI::TimeElements telts;
double localtime = BreakdownLocalTime(&telts, time);
OP_STATUS r = ES_ImportedAPI::FormatLocalTime(ES_ImportedAPI::GET_DATE, string, ARRAY_SIZE(string), &telts);
if (OpStatus::IsMemoryError(r))
LEAVE(r);
else if (OpStatus::IsError(r))
{
if (uni_snprintf(string, ARRAY_SIZE(string), UNI_L("%3s %3s %02d, %04d"),
DAYS(OpDate::WeekDay(localtime)),
MONTHS(OpDate::MonthFromTime(localtime)),
OpDate::DateFromTime(localtime),
OpDate::YearFromTime(localtime)) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
}
return JString::Make(context, string);
}
/* static */ JString*
ES_DateBuiltins::TimeToLocaleTimeString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2011-05-24 sof
ES_ImportedAPI::TimeElements telts;
double localtime = BreakdownLocalTime(&telts, time);
OP_STATUS r = ES_ImportedAPI::FormatLocalTime(ES_ImportedAPI::GET_TIME, string, ARRAY_SIZE(string), &telts);
if (OpStatus::IsMemoryError(r))
LEAVE(r);
else if (OpStatus::IsError(r))
{
int zoneoffset = DOUBLE2INT32((localtime - time) / msPerMinute);
zoneoffset = zoneoffset % 60 + (zoneoffset / 60 * 100);
if (uni_snprintf(string, ARRAY_SIZE(string),
UNI_L("%02d:%02d:%02d"),
OpDate::HourFromTime(localtime),
OpDate::MinFromTime(localtime),
OpDate::SecFromTime(localtime)) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
}
return JString::Make(context, string);
}
/* static */ JString*
ES_DateBuiltins::TimeToUTCString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2008-06-09 stanislavj
// RFC 1123 format
// The .3 is highly desirable and some sites depend on it, see bug #54175
if (uni_snprintf(string, ARRAY_SIZE(string), UNI_L("%.3s, %02d %.3s %04d %02d:%02d:%02d GMT"),
DAYS(OpDate::WeekDay(time)),
OpDate::DateFromTime(time),
MONTHS(OpDate::MonthFromTime(time)),
OpDate::YearFromTime(time),
OpDate::HourFromTime(time),
OpDate::MinFromTime(time),
OpDate::SecFromTime(time)) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
return JString::Make(context, string);
}
/* static */ JString*
ES_DateBuiltins::TimeToISOString(ES_Context *context, double time)
{
if (op_isnan(time))
return JString::Make(context, invalid_date);
uni_char string[128]; // ARRAY OK 2008-06-09 stanislavj
int milliseconds = int(op_truncate(op_fmod(time, 1000)));
if (milliseconds < 0)
milliseconds = 1000 + milliseconds;
int year = OpDate::YearFromTime(time);
const uni_char *sign_prefix = UNI_L("");
BOOL extended_years;
if (year > 9999)
{
sign_prefix = UNI_L("+");
extended_years = TRUE;
}
else
{
extended_years = year < 0;
if (extended_years)
{
sign_prefix = UNI_L("-");
year = -year;
}
}
if (uni_snprintf(string, ARRAY_SIZE(string),
extended_years ? UNI_L("%s%06d-%02d-%02dT%02d:%02d:%02d.%03dZ") : UNI_L("%s%04d-%02d-%02dT%02d:%02d:%02d.%03dZ"),
sign_prefix,
year,
OpDate::MonthFromTime(time)+1,
OpDate::DateFromTime(time),
OpDate::HourFromTime(time),
OpDate::MinFromTime(time),
OpDate::SecFromTime(time),
milliseconds) < 0)
LEAVE(OpStatus::ERR_NO_MEMORY);
return JString::Make(context, string);
}
static BOOL
StrictProcessThis(double &this_number, const ES_Value_Internal &this_value)
{
if (this_value.IsObject() && this_value.GetObject()->IsDateObject())
{
ES_Date_Object *d = static_cast<ES_Date_Object *>(this_value.GetObject());
this_number = d->GetValue();
}
else
return FALSE;
return TRUE;
}
static BOOL
StrictProcessThis(ES_Execution_Context *context, double &this_number, const ES_Value_Internal &this_value, BOOL &is_nan, BOOL ltime = FALSE)
{
if (this_value.IsObject() && this_value.GetObject()->IsDateObject())
{
ES_Date_Object *d = static_cast<ES_Date_Object *>(this_value.GetObject());
is_nan = d->IsInvalid();
this_number = ltime ? d->GetLocalTime(context) : d->GetValue();
}
else
return FALSE;
return TRUE;
}
static BOOL
StrictCheckThis(const ES_Value_Internal &this_value)
{
return this_value.IsObject() && this_value.GetObject()->IsDateObject();
}
static void
SetThis(double v, const ES_Value_Internal &this_value)
{
static_cast<ES_Date_Object *>(this_value.GetObject())->SetValue(v);
}
static void
SetThisInvalid(const ES_Value_Internal &this_value, ES_Value_Internal *return_value)
{
static_cast<ES_Date_Object *>(this_value.GetObject())->SetInvalid();
return_value->SetNan();
}
/* static */ BOOL
ES_DateBuiltins::constructor_call(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
return_value->SetString(ES_SuspendedTTS(TimeToString, context).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::constructor_construct(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double utc;
if (argc == 0)
utc = ES_SuspendedGetCurrentTimeUTC(context).result;
else if (argc == 1)
{
if (argv[0].IsString())
{
double local;
if (!context->GetGlobalObject()->GetCachedParsedDate(argv[0].GetString(), utc, local))
{
ES_SuspendedParseDate parsed_date(context, StorageZ(context, argv[0].GetString()), TRUE);
utc = parsed_date.utc;
local = parsed_date.local;
context->GetGlobalObject()->SetCachedParsedDate(argv[0].GetString(), utc, local);
}
return_value->SetObject(ES_Date_Object::Make(context, ES_GET_GLOBAL_OBJECT(), utc, local));
return TRUE;
}
else
{
if (!argv[0].ToNumber(context))
return FALSE;
utc = OpDate::TimeClip(argv[0].GetNumAsDouble());
}
}
else
{
if (!argv[0].ToNumber(context) || !argv[1].ToNumber(context))
return FALSE;
double date = 1;
double hours = 0;
double minutes = 0;
double seconds = 0;
double ms = 0;
if (argc >= 3)
{
if (!argv[2].ToNumber(context))
return FALSE;
date = argv[2].GetNumAsDouble();
if (argc >= 4)
{
if (!argv[3].ToNumber(context))
return FALSE;
hours = argv[3].GetNumAsDouble();
if (argc >= 5)
{
if (!argv[4].ToNumber(context))
return FALSE;
minutes = argv[4].GetNumAsDouble();
if (argc >= 6)
{
if (!argv[5].ToNumber(context))
return FALSE;
seconds = argv[5].GetNumAsDouble();
if (argc >= 7)
{
if (!argv[6].ToNumber(context))
return FALSE;
ms = argv[6].GetNumAsDouble();
}
}
}
}
}
double year = argv[0].GetNumAsDouble();
if (!op_isnan(year))
{
year = argv[0].GetNumAsInteger();
if (year >= 0 && year <= 99)
year += 1900;
}
double month = argv[1].GetNumAsDouble();
double day = OpDate::MakeDay(year, month, date);
double t = OpDate::MakeTime(hours, minutes, seconds, ms);
utc = OpDate::TimeClip(ES_SuspendedUTC(context, OpDate::MakeDate(day, t)).result);
}
return_value->SetObject(ES_Date_Object::Make(context, ES_GET_GLOBAL_OBJECT(), utc));
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::valueOf(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.valueOf: this is not a Date object");
return FALSE;
}
return_value->SetNumber(t);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
return_value->SetString(ES_SuspendedTTS(TimeToString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toDateString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toDateString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
return_value->SetString(ES_SuspendedTTS(TimeToDateString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toTimeString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toTimeString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
return_value->SetString(ES_SuspendedTTS(TimeToTimeString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toLocaleString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toLocaleString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
return_value->SetString(ES_SuspendedTTS(TimeToLocaleString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toLocaleDateString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toLocaleDateString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
return_value->SetString(ES_SuspendedTTS(TimeToLocaleDateString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toLocaleTimeString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toLocaleTimeString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
return_value->SetString(ES_SuspendedTTS(TimeToLocaleTimeString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getTime(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.getTime: this is not a Date object");
return FALSE;
}
return_value->SetNumber(t);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getYear(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getYear: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int year = OpDate::YearFromTime(t) - 1900;
return_value->SetInt32(year);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getFullYear(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getFullYear: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int year = OpDate::YearFromTime(t);
return_value->SetInt32(year);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCFullYear(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCFullYear: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int year = OpDate::YearFromTime(t);
return_value->SetInt32(year);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getMonth(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getMonth: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int month = OpDate::MonthFromTime(t);
return_value->SetInt32(month);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCMonth(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCMonth: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int month = OpDate::MonthFromTime(t);
return_value->SetInt32(month);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getDate(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getDate: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int date = OpDate::DateFromTime(t);
return_value->SetInt32(date);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCDate(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCDate: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int date = OpDate::DateFromTime(t);
return_value->SetInt32(date);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getDay(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getDay: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int day = OpDate::WeekDay(t);
return_value->SetInt32(day);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCDay(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCDay: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int day = OpDate::WeekDay(t);
return_value->SetInt32(day);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getHours(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getHours: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int hours = OpDate::HourFromTime(t);
return_value->SetInt32(hours);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCHours(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCHours: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int hours = OpDate::HourFromTime(t);
return_value->SetInt32(hours);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getMinutes(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getMinutes: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int minutes = OpDate::MinFromTime(t);
return_value->SetInt32(minutes);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCMinutes(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCMinutes: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int minutes = OpDate::MinFromTime(t);
return_value->SetInt32(minutes);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getSeconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getSeconds: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int seconds = OpDate::SecFromTime(t);
return_value->SetInt32(seconds);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCSeconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCSeconds: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int seconds = OpDate::SecFromTime(t);
return_value->SetInt32(seconds);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getMilliseconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.getMilliseconds: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int ms = static_cast<int>(OpDate::msFromTime(t));
return_value->SetInt32(ms);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getUTCMilliseconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getUTCMilliseconds: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int ms = static_cast<int>(OpDate::msFromTime(t));
return_value->SetInt32(ms);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::getTimezoneOffset(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.getTimezoneOffset: this is not a Date object");
return FALSE;
}
if (is_nan)
return_value->SetNan();
else
{
int zoneoffset = static_cast<int>((t - static_cast<ES_Date_Object *>(argv[-2].GetObject())->GetLocalTime(context)) / msPerMinute);
return_value->SetInt32(zoneoffset);
}
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setTime(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
if (!StrictCheckThis(argv[-2]))
{
context->ThrowTypeError("Date.prototype.setTime: this is not a Date object");
return FALSE;
}
if (argc > 0 && !argv[0].ToNumber(context))
return FALSE;
if (argc >= 1)
{
double t = argv[0].GetNumAsDouble();
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setMilliseconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setMilliseconds: this is not a Date object");
return FALSE;
}
if (argc > 0 && !argv[0].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double t2 = OpDate::MakeTime(OpDate::HourFromTime(t), OpDate::MinFromTime(t),
OpDate::SecFromTime(t), argv[0].GetNumAsDouble());
t = ES_SuspendedUTC(context, OpDate::MakeDate(OpDate::Day(t), t2)).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setUTCMilliseconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.setUTCMilliseconds: this is not a Date object");
return FALSE;
}
if (argc > 0 && !argv[0].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double t2 = OpDate::MakeTime(OpDate::HourFromTime(t), OpDate::MinFromTime(t),
OpDate::SecFromTime(t), argv[0].GetNumAsDouble());
t = OpDate::MakeDate(OpDate::Day(t), t2);
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setSeconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setSeconds: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(2, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double ms = 0;
if (argc >= 2)
ms = argv[1].GetNumAsDouble();
else
ms = OpDate::msFromTime(t);
double t2 = OpDate::MakeTime(OpDate::HourFromTime(t), OpDate::MinFromTime(t),
argv[0].GetNumAsDouble(), ms);
t = ES_SuspendedUTC(context, OpDate::MakeDate(OpDate::Day(t), t2)).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setUTCSeconds(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.setUTCSeconds: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(2, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double ms = 0;
if (argc >= 2)
ms = argv[1].GetNumAsDouble();
else
ms = OpDate::msFromTime(t);
double t2 = OpDate::MakeTime(OpDate::HourFromTime(t), OpDate::MinFromTime(t),
argv[0].GetNumAsDouble(), ms);
t = OpDate::MakeDate(OpDate::Day(t), t2);
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setMinutes(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setMinutes: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(3, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double s = 0;
double ms = 0;
if (argc >= 2)
{
s = argv[1].GetNumAsDouble();
if (argc >= 3)
ms = argv[2].GetNumAsDouble();
else
ms = OpDate::msFromTime(t);
}
else
{
s = OpDate::SecFromTime(t);
ms = OpDate::msFromTime(t);
}
double t2 = OpDate::MakeTime(OpDate::HourFromTime(t), argv[0].GetNumAsDouble(), s, ms);
t = ES_SuspendedUTC(context, OpDate::MakeDate(OpDate::Day(t), t2)).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setUTCMinutes(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.setUTCMinutes: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(3, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !op_isnan(t))
{
double s = 0;
double ms = 0;
if (argc >= 2)
{
s = argv[1].GetNumAsDouble();
if (argc >= 3)
ms = argv[2].GetNumAsDouble();
else
ms = OpDate::msFromTime(t);
}
else
{
s = OpDate::SecFromTime(t);
ms = OpDate::msFromTime(t);
}
double t2 = OpDate::MakeTime(OpDate::HourFromTime(t), argv[0].GetNumAsDouble(),
s, ms);
t = OpDate::MakeDate(OpDate::Day(t), t2);
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setHours(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setHours: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(4, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double m = 0;
double s = 0;
double ms = 0;
if (argc >= 2)
{
m = argv[1].GetNumAsDouble();
if (argc >= 3)
{
s = argv[2].GetNumAsDouble();
if (argc >= 4)
ms = argv[3].GetNumAsDouble();
else
ms = OpDate::msFromTime(t);
}
else
{
s = OpDate::SecFromTime(t);
ms = OpDate::msFromTime(t);
}
}
else
{
m = OpDate::MinFromTime(t);
s = OpDate::SecFromTime(t);
ms = OpDate::msFromTime(t);
}
double t2 = OpDate::MakeTime(argv[0].GetNumAsDouble(), m, s, ms);
t = ES_SuspendedUTC(context, OpDate::MakeDate(OpDate::Day(t), t2)).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setUTCHours(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.setUTCHours: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(4, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double m = 0;
double s = 0;
double ms = 0;
if (argc >= 2)
{
m = argv[1].GetNumAsDouble();
if (argc >= 3)
{
s = argv[2].GetNumAsDouble();
if (argc >= 4)
ms = argv[3].GetNumAsDouble();
else
ms = OpDate::msFromTime(t);
}
else
{
s = OpDate::SecFromTime(t);
ms = OpDate::msFromTime(t);
}
}
else
{
m = OpDate::MinFromTime(t);
s = OpDate::SecFromTime(t);
ms = OpDate::msFromTime(t);
}
double t2 = OpDate::MakeTime(argv[0].GetNumAsDouble(), m, s, ms);
t = OpDate::MakeDate(OpDate::Day(t), t2);
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setDate(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setDate: this is not a Date object");
return FALSE;
}
if (argc > 0 && !argv[0].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double d = OpDate::MakeDay(OpDate::YearFromTime(t), OpDate::MonthFromTime(t), argv[0].GetNumAsDouble());
t = ES_SuspendedUTC(context, OpDate::MakeDate(d, OpDate::TimeWithinDay(t))).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setUTCDate(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.setUTCDate: this is not a Date object");
return FALSE;
}
if (argc > 0 && !argv[0].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double d = OpDate::MakeDay(OpDate::YearFromTime(t), OpDate::MonthFromTime(t),
argv[0].GetNumAsDouble());
t = OpDate::MakeDate(d, OpDate::TimeWithinDay(t));
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setMonth(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setMonth: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(2, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double date = 1;
if (argc >= 2)
date = argv[1].GetNumAsDouble();
else
date = OpDate::DateFromTime(t);
double d = OpDate::MakeDay(OpDate::YearFromTime(t), argv[0].GetNumAsDouble(), date);
t = ES_SuspendedUTC(context, OpDate::MakeDate(d, OpDate::TimeWithinDay(t))).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setUTCMonth(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.setUTCMonth: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(2, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1 && !is_nan)
{
double date = 1;
if (argc >= 2)
date = argv[1].GetNumAsDouble();
else
date = OpDate::DateFromTime(t);
double d = OpDate::MakeDay(OpDate::YearFromTime(t), argv[0].GetNumAsDouble(),
date);
t = OpDate::MakeDate(d, OpDate::TimeWithinDay(t));
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setYear(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setYear: this is not a Date object");
return FALSE;
}
if (argc > 0 && !argv[0].ToNumber(context))
return FALSE;
if (argc >= 1)
{
double month = 0;
double date = 1;
if (!is_nan)
{
month = OpDate::MonthFromTime(t);
date = OpDate::DateFromTime(t);
}
double year = argv[0].GetNumAsInteger();
if (0 <= year && year <= 99)
year += 1900;
else
year = argv[0].GetNumAsDouble();
double d = OpDate::MakeDay(year, month, date);
double time_within_day = is_nan ? 0 : OpDate::TimeWithinDay(t);
t = ES_SuspendedUTC(context, OpDate::MakeDate(d, time_within_day)).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setFullYear(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, TRUE))
{
context->ThrowTypeError("Date.prototype.setFullYear: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(3, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1)
{
double month = 0;
double date = 1;
if (argc >= 2)
{
month = argv[1].GetNumAsDouble();
if (argc >= 3)
date = argv[2].GetNumAsDouble();
else if (!is_nan)
date = OpDate::DateFromTime(t);
}
else
{
if (!is_nan)
{
date = OpDate::DateFromTime(t);
month = OpDate::MonthFromTime(t);
}
}
double d = OpDate::MakeDay(argv[0].GetNumAsDouble(), month, date);
double time_within_day = is_nan ? 0 : OpDate::TimeWithinDay(t);
t = ES_SuspendedUTC(context, OpDate::MakeDate(d, time_within_day)).result;
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::setUTCFullYear(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
BOOL is_nan;
if (!StrictProcessThis(context, t, argv[-2], is_nan, FALSE))
{
context->ThrowTypeError("Date.prototype.setUTCFullYear: this is not a Date object");
return FALSE;
}
for (unsigned i = 0; i < MIN(3, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 1)
{
double month = 0;
double date = 1;
if (argc >= 2)
{
month = argv[1].GetNumAsDouble();
if (argc >= 3)
date = argv[2].GetNumAsDouble();
else if (!is_nan)
date = OpDate::DateFromTime(t);
}
else
{
if (!is_nan)
{
date = OpDate::DateFromTime(t);
month = OpDate::MonthFromTime(t);
}
}
double d = OpDate::MakeDay(argv[0].GetNumAsDouble(), month, date);
double time_within_day = is_nan ? 0 : OpDate::TimeWithinDay(t);
t = OpDate::MakeDate(d, time_within_day);
t = OpDate::TimeClip(t);
SetThis(t, argv[-2]);
return_value->SetNumber(t);
}
else
SetThisInvalid(argv[-2], return_value);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toUTCString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toUTCString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
return_value->SetString(ES_SuspendedTTS(TimeToUTCString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toISOString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
double t;
if (!StrictProcessThis(t, argv[-2]))
{
context->ThrowTypeError("Date.prototype.toISOString: this is not a Date object");
return FALSE;
}
ES_CollectorLock gclock(context);
if (!op_isfinite(t))
{
context->ThrowRangeError("Date.prototype.toISOString: invalid time value");
return FALSE;
}
return_value->SetString(ES_SuspendedTTS(TimeToISOString, context, t).result);
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::toJSON(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
if (!argv[-2].ToObject(context, FALSE))
{
context->ThrowTypeError("Date.prototype.toJSON: this is not an object");
return FALSE;
}
ES_Value_Internal *value_registers = context->AllocateRegisters(1);
ES_Value_Internal &o_value = value_registers[0]; o_value = argv[-2];
if (!o_value.ToPrimitive(context, ES_Value_Internal::HintNumber))
{
context->FreeRegisters(1);
return FALSE;
}
BOOL is_nonfinite = o_value.IsNumber() && !op_isfinite(o_value.GetNumAsDouble());
context->FreeRegisters(1);
if (is_nonfinite)
{
return_value->SetNull();
return TRUE;
}
ES_Value_Internal toISOString_value;
GetResult result = argv[-2].GetObject(context)->GetL(context, context->rt_data->idents[ESID_toISOString], toISOString_value);
if (result == PROP_GET_FAILED)
return FALSE;
if (!GET_OK(result) || !toISOString_value.IsCallable(context))
{
context->ThrowTypeError("Date.prototype.toJSON: toISOString not callable");
return FALSE;
}
ES_Value_Internal *registers = context->SetupFunctionCall(toISOString_value.GetObject(context), 0);
registers[0] = argv[-2];
registers[1] = toISOString_value;
return context->CallFunction(registers, 0, return_value);
}
/* static */ BOOL
ES_DateBuiltins::parse(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
if (argc >= 1)
{
if (!argv[0].ToString(context))
return FALSE;
return_value->SetNumber(ES_SuspendedParseDate(context, StorageZ(context, argv[0].GetString()), FALSE).utc);
}
else
return_value->SetNull();
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::UTC(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
for (unsigned i = 0; i < MIN(7, argc); i++)
if (!argv[i].ToNumber(context))
return FALSE;
if (argc >= 2)
{
double date = 1;
double hours = 0;
double minutes = 0;
double seconds = 0;
double ms = 0;
if (argc >= 3)
{
date = argv[2].GetNumAsDouble();
if (argc >= 4)
{
hours = argv[3].GetNumAsDouble();
if (argc >= 5)
{
minutes = argv[4].GetNumAsDouble();
if (argc >= 6)
{
seconds = argv[5].GetNumAsDouble();
if (argc >= 7)
ms = argv[6].GetNumAsDouble();
}
}
}
}
double year = argv[0].GetNumAsDouble();
if (!op_isnan(year))
{
year = argv[0].GetNumAsInteger();
if (year >= 0 && year <= 99)
year += 1900;
}
double month = argv[1].GetNumAsDouble();
double day = OpDate::MakeDay(year, month, date);
double t = OpDate::MakeTime(hours, minutes, seconds, ms);
t = OpDate::TimeClip(OpDate::MakeDate(day, t));
return_value->SetNumber(t);
}
else
return_value->SetNan();
return TRUE;
}
/* static */ BOOL
ES_DateBuiltins::now(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
return_value->SetNumber(ES_SuspendedGetCurrentTimeUTC(context).result);
return TRUE;
}
/* static */ void
ES_DateBuiltins::PopulatePrototype(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype)
{
ES_Value_Internal undefined;
ASSERT_CLASS_SIZE(ES_DateBuiltinsCount);
APPEND_PROPERTY(ES_DateBuiltins, constructor, undefined);
APPEND_PROPERTY(ES_DateBuiltins, valueOf, MAKE_BUILTIN(0, valueOf));
APPEND_PROPERTY(ES_DateBuiltins, toString, MAKE_BUILTIN(0, toString));
APPEND_PROPERTY(ES_DateBuiltins, toDateString, MAKE_BUILTIN(0, toDateString));
APPEND_PROPERTY(ES_DateBuiltins, toTimeString, MAKE_BUILTIN(0, toTimeString));
APPEND_PROPERTY(ES_DateBuiltins, toLocaleString, MAKE_BUILTIN(0, toLocaleString));
APPEND_PROPERTY(ES_DateBuiltins, toLocaleDateString, MAKE_BUILTIN(0, toLocaleDateString));
APPEND_PROPERTY(ES_DateBuiltins, toLocaleTimeString, MAKE_BUILTIN(0, toLocaleTimeString));
APPEND_PROPERTY(ES_DateBuiltins, getTime, MAKE_BUILTIN(0, getTime));
APPEND_PROPERTY(ES_DateBuiltins, getYear, MAKE_BUILTIN(0, getYear));
APPEND_PROPERTY(ES_DateBuiltins, getFullYear, MAKE_BUILTIN(0, getFullYear));
APPEND_PROPERTY(ES_DateBuiltins, getUTCFullYear, MAKE_BUILTIN(0, getUTCFullYear));
APPEND_PROPERTY(ES_DateBuiltins, getMonth, MAKE_BUILTIN(0, getMonth));
APPEND_PROPERTY(ES_DateBuiltins, getUTCMonth, MAKE_BUILTIN(0, getUTCMonth));
APPEND_PROPERTY(ES_DateBuiltins, getDate, MAKE_BUILTIN(0, getDate));
APPEND_PROPERTY(ES_DateBuiltins, getUTCDate, MAKE_BUILTIN(0, getUTCDate));
APPEND_PROPERTY(ES_DateBuiltins, getDay, MAKE_BUILTIN(0, getDay));
APPEND_PROPERTY(ES_DateBuiltins, getUTCDay, MAKE_BUILTIN(0, getUTCDay));
APPEND_PROPERTY(ES_DateBuiltins, getHours, MAKE_BUILTIN(0, getHours));
APPEND_PROPERTY(ES_DateBuiltins, getUTCHours, MAKE_BUILTIN(0, getUTCHours));
APPEND_PROPERTY(ES_DateBuiltins, getMinutes, MAKE_BUILTIN(0, getMinutes));
APPEND_PROPERTY(ES_DateBuiltins, getUTCMinutes, MAKE_BUILTIN(0, getUTCMinutes));
APPEND_PROPERTY(ES_DateBuiltins, getSeconds, MAKE_BUILTIN(0, getSeconds));
APPEND_PROPERTY(ES_DateBuiltins, getUTCSeconds, MAKE_BUILTIN(0, getUTCSeconds));
APPEND_PROPERTY(ES_DateBuiltins, getMilliseconds, MAKE_BUILTIN(0, getMilliseconds));
APPEND_PROPERTY(ES_DateBuiltins, getUTCMilliseconds, MAKE_BUILTIN(0, getUTCMilliseconds));
APPEND_PROPERTY(ES_DateBuiltins, getTimezoneOffset, MAKE_BUILTIN(0, getTimezoneOffset));
APPEND_PROPERTY(ES_DateBuiltins, setTime, MAKE_BUILTIN(1, setTime));
APPEND_PROPERTY(ES_DateBuiltins, setMilliseconds, MAKE_BUILTIN(1, setMilliseconds));
APPEND_PROPERTY(ES_DateBuiltins, setUTCMilliseconds, MAKE_BUILTIN(1, setUTCMilliseconds));
APPEND_PROPERTY(ES_DateBuiltins, setSeconds, MAKE_BUILTIN(2, setSeconds));
APPEND_PROPERTY(ES_DateBuiltins, setUTCSeconds, MAKE_BUILTIN(2, setUTCSeconds));
APPEND_PROPERTY(ES_DateBuiltins, setMinutes, MAKE_BUILTIN(3, setMinutes));
APPEND_PROPERTY(ES_DateBuiltins, setUTCMinutes, MAKE_BUILTIN(3, setUTCMinutes));
APPEND_PROPERTY(ES_DateBuiltins, setHours, MAKE_BUILTIN(4, setHours));
APPEND_PROPERTY(ES_DateBuiltins, setUTCHours, MAKE_BUILTIN(4, setUTCHours));
APPEND_PROPERTY(ES_DateBuiltins, setDate, MAKE_BUILTIN(1, setDate));
APPEND_PROPERTY(ES_DateBuiltins, setUTCDate, MAKE_BUILTIN(1, setUTCDate));
APPEND_PROPERTY(ES_DateBuiltins, setMonth, MAKE_BUILTIN(2, setMonth));
APPEND_PROPERTY(ES_DateBuiltins, setUTCMonth, MAKE_BUILTIN(2, setUTCMonth));
APPEND_PROPERTY(ES_DateBuiltins, setYear, MAKE_BUILTIN(1, setYear));
APPEND_PROPERTY(ES_DateBuiltins, setFullYear, MAKE_BUILTIN(3, setFullYear));
APPEND_PROPERTY(ES_DateBuiltins, setUTCFullYear, MAKE_BUILTIN(3, setUTCFullYear));
APPEND_PROPERTY(ES_DateBuiltins, toUTCString, MAKE_BUILTIN(0, toUTCString));
APPEND_PROPERTY(ES_DateBuiltins, toGMTString, MAKE_BUILTIN_WITH_NAME(0, toUTCString, toGMTString)); // Alias for toUTCString
APPEND_PROPERTY(ES_DateBuiltins, toISOString, MAKE_BUILTIN(0, toISOString));
APPEND_PROPERTY(ES_DateBuiltins, toJSON, MAKE_BUILTIN(1, toJSON));
ASSERT_OBJECT_COUNT(ES_DateBuiltins);
}
/* static */ void
ES_DateBuiltins::PopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_class)
{
OP_ASSERT(prototype_class->GetPropertyTable()->Capacity() >= ES_DateBuiltinsCount);
JString **idents = context->rt_data->idents;
ES_Layout_Info layout;
DECLARE_PROPERTY(ES_DateBuiltins, constructor, DE, ES_STORAGE_WHATEVER);
DECLARE_PROPERTY(ES_DateBuiltins, valueOf, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toDateString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toTimeString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toLocaleString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toLocaleDateString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toLocaleTimeString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getTime, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getYear, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getFullYear, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCFullYear, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getMonth, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCMonth, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getDate, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCDate, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getDay, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCDay, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getHours, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCHours, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getMinutes, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCMinutes, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getSeconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCSeconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getMilliseconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getUTCMilliseconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, getTimezoneOffset, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setTime, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setMilliseconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setUTCMilliseconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setSeconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setUTCSeconds, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setMinutes, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setUTCMinutes, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setHours, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setUTCHours, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setDate, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setUTCDate, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setMonth, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setUTCMonth, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setYear, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setFullYear, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, setUTCFullYear, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toUTCString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toGMTString, DE, ES_STORAGE_OBJECT); // Alias for toUTCString
DECLARE_PROPERTY(ES_DateBuiltins, toISOString, DE, ES_STORAGE_OBJECT);
DECLARE_PROPERTY(ES_DateBuiltins, toJSON, DE, ES_STORAGE_OBJECT); // Alias for toUTCString
}
/* static */ void
ES_DateBuiltins::PopulateConstructor(ES_Context *context, ES_Global_Object *global_object, ES_Object *constructor)
{
JString **idents = context->rt_data->idents;
constructor->InitPropertyL(context, idents[ESID_parse], MAKE_BUILTIN(1, parse), DE);
constructor->InitPropertyL(context, idents[ESID_UTC], MAKE_BUILTIN(7, UTC), DE);
constructor->InitPropertyL(context, idents[ESID_now], MAKE_BUILTIN(0, now), DE);
}
|
#ifndef COMPUTETINITIAL_H
#define COMPUTETINITIAL_H
#include <vector>
#include <properties/properties.h>
/*!
\file
\brief This function computes the initial temperature distribution at all cells
*/
/**
Creates inittial temperature distribution
@param[in] grid - takes total number of nodes in X and Y directions
@param[in] settings - initial temperature at boundaries and in the center
@return initial temperature distribution
*/
std::vector<double> computeTInitial(const Grid &grid, const Settings &settings);
#endif
|
//---------------------------------------------------------
//
// Project: dada
// Module: gl
// File: Program.cpp
// Author: Viacheslav Pryshchepa
//
//---------------------------------------------------------
#include "dada/gl/GL.h"
#include "dada/core/Log.h"
#include "dada/gl/Program.h"
#include "dada/gl/Shader.h"
namespace dada
{
Program::Program() :
Object(),
m_id(0),
m_valid(false)
{
GLenum pre_err = glGetError();
m_id = glCreateProgram();
GLenum err = glGetError();
if (m_id == 0 || err != GL_NO_ERROR)
{
getLog() << "ERROR: Unable to create program" << endl;
}
}
Program::~Program()
{
glDeleteProgram(m_id);
}
bool Program::attach(Shader& sh)
{
m_valid = false;
glAttachShader(m_id, sh.getID());
GLenum err = glGetError();
m_valid = (err == GL_NO_ERROR);
return m_valid;
}
bool Program::link()
{
glLinkProgram(m_id);
GLint linked;
glGetProgramiv(m_id, GL_LINK_STATUS, &linked);
if (linked == 0)
{
GLint length = 0;
glGetProgramiv(m_id, GL_INFO_LOG_LENGTH, &length);
if (length > 1)
{
getLog() << "ERROR: While linking program " << m_id << endl;
char* buf = new char[length];
glGetProgramInfoLog(m_id, length, NULL, buf);
getLog() << buf << endl;
delete buf;
}
}
m_valid = (linked != 0);
return m_valid;
}
Program::index_t Program::findAttributeLocation(const char* name) const
{
return glGetAttribLocation(m_id, name);
}
Program::index_t Program::findUniformLocation(const char* name) const
{
return glGetUniformLocation(m_id, name);
}
bool Program::use()
{
bool res = false;
glUseProgram(m_id);
GLenum err = glGetError();
if (err == GL_NO_ERROR)
{
res = true;
}
else
{
getLog() << "ERROR: Unable to use program" << endl;
}
return res;
}
/*
bool Program::setUniform(index_t location, int val)
{
bool res = false;
glUniform1i(location, val);
GLenum err = glGetError();
if (err == GL_NO_ERROR)
{
res = true;
}
else
{
getLog() << "ERROR: Unable to set uniform of program" << endl;
}
return res;
}
bool Program::setUniform(index_t location, float val)
{
bool res = false;
glUniform1f(location, val);
GLenum err = glGetError();
if (err == GL_NO_ERROR)
{
res = true;
}
else
{
getLog() << "ERROR: Unable to set uniform of program" << endl;
}
return res;
}
bool Program::setUniform(index_t location, const Vector3f& val)
{
bool res = false;
glUniform3fv(location, 1, val.c_arr());
GLenum err = glGetError();
if (err == GL_NO_ERROR)
{
res = true;
}
else
{
getLog() << "ERROR: Unable to set uniform of program" << endl;
}
return res;
}
bool Program::setUniform(index_t location, const Vector4f& val)
{
bool res = false;
glUniform4fv(location, 1, val.c_arr());
GLenum err = glGetError();
if (err == GL_NO_ERROR)
{
res = true;
}
else
{
getLog() << "ERROR: Unable to set uniform of program" << endl;
}
return res;
}
bool Program::setUniform(index_t location, const Matrix4f& val)
{
bool res = false;
glUniformMatrix4fv(location, 1, GL_FALSE, val.c_arr());
GLenum err = glGetError();
if (err == GL_NO_ERROR)
{
res = true;
}
else
{
getLog() << "ERROR: Unable to set uniform of program" << endl;
}
return res;
}
*/
} // dada
|
#include<iostream>
#include "BBoard.hpp"
// #include "Ship.cpp"
#include<string>
using namespace std;
int main(){
Ship shipA("je", 4);
Ship shipB("Su", 2);
Ship shipC("Ta", 3);
BBoard boardA;
cout << shipA.getName() << endl;
//newBoard.getShipsArrayElement(2,4);
cout << boardA.placeShip(&shipA, 2, 4, 'C') << "shipA" <<endl;
cout << boardA.placeShip(&shipB, 1, 4, 'R') << "shipB" << endl;
cout << boardA.placeShip(&shipC, 8, 6, 'R') << "shipC" << endl;;
cout << boardA.attack(2, 4) << endl;
cout << boardA.attack(3, 4) << endl;
cout << boardA.attack(4, 4) << endl;
cout << boardA.attack(4, 4) << "edd" << endl;
cout << boardA.attack(5, 4) << endl;
cout << boardA.attack(1, 4) << endl;
cout << boardA.attack(3, 4) << endl;
cout << boardA.attack(8, 4) << "DE" << endl;
cout << boardA.attack(8, 6) << "SW" << endl;
cout << boardA.getShipsArrayElement(2,6) << endl;
cout << boardA.attack(3, 4) << endl;
cout << boardA.attack(1, 5) << endl;
cout << boardA.attack(8, 7) << endl;
cout << boardA.attack(7, 8) << endl;
cout << shipA.getDamage() << "a" << endl;
cout << shipB.getDamage() << "b" << endl;
cout << shipC.getDamage() << "c" << endl;
cout << boardA.getNumShipsRemaining() << endl;
cout << boardA.allShipsSunk() << endl;
// for(int row = 0; row < 10; row++){ //2 D array
// for(int col = 0; col < 10; col++){
// cout << boardA.getShipsArrayElement(row,col);
// }
// cout << endl;
// }
// Ship ship = *(shipBoard[row][col]);
// ship.takeHit();
// if(ship.getLength() == ship.getDamage())
// {
// std::cout << "They sank " << ship.getName() << "!" << std::endl;
// unSunkShip--;
return 0;
}
|
/////////////////////////////////////////////
/////////////////////////////////////////////
//
//
// APEX_Sieve
//
// small class used to get Sieve information:
// translates between hole number to column and row and vice vers
// (slighlty more complex arangement in APEX sieve)
//
// Also has function to return TCS (Target Co-ordinate System) coords
//
/////////////////////////////////////////////
#ifndef ROOT_APEX_Sieve
#define ROOT_APEX_Sieve
#include "file_def.h"
#include "InputAPEXL.h"
std::vector<int> Get_Col_Row(Int_t Hole);
const TVector3 GetSieveHoleTCS(Int_t Col, Int_t Row) /*const*/
{
// Double_t new_Z = ZPos;
// Double_t X_SH = SieveXbyRow[Row];
// cout << "Col = " << Col << endl;
// // Double_t Y_SH = SieveYbyCol[Col];
// cout << "X_SH = " << X_SH << " and Y_SH = " << 999 << " and new_Z = " << ZPos << endl;
// Double_t Y_SH = SieveYbyCol[Col];
// X_SH = SieveXbyRow[Row];
// Y_SH = SieveYbyCol[Col];
// cout << "X_SH = " << X_SH << " and Y_SH = " << Y_SH << endl;
// Double_t Sieve_Z = ZPos -
if(Col < 0 || Col > NSieveCol){
Col = 1;
}
if(Row < 0 || Row > NSieveRow){
Row = 1;
}
TVector3 SieveHoleTCS(SieveXbyRow[Row]+SieveOffX, SieveYbyCol[Col]+SieveOffY, ZPos);
return SieveHoleTCS;
}
// //_____________________________________________________________________________
const TVector3 GetSieveHoleTCS(UInt_t Hole) /*const*/
{
std::vector<int> x_y = {};
x_y = Get_Col_Row( Hole);
UInt_t Col = x_y[0];
UInt_t Row = x_y[1];
TVector3 SieveHoleTCS = {};
SieveHoleTCS = GetSieveHoleTCS(Col, Row);
return SieveHoleTCS;
}
// //_____________________________________________________________________________
std::vector<int> Get_Col_Row(Int_t Hole){
Int_t row_comp = 0;
Int_t no_col = 0;
Int_t col = 0;
Int_t row = 0;
for(Int_t i = 0; i<NSieveRow; i++){
row_comp += NoinEachRow[i];
if( (row_comp-1) >= Hole){
row = i;
no_col = Hole - ( row_comp - NoinEachRow[i]);
break;
}
}
if(row%2 == 0){
if(no_col==13){
col = 25;
}
else if (no_col==14){
col = 26;
}
else{
col = no_col *2;
}
}
if(row%2 == 1){
if(row > 1 && row < 15){
if(no_col >5){
col = (no_col*2)+3;
}
else{
col = (no_col*2) +1;
}
}
else{
col = (no_col*2) +1;
}
}
// cout << "For Hole " << Hole << ": row = " << row << " and col = " << col << endl;
// hole_no += Col;
std::vector<int> rowcol{col, row};
return rowcol;
}
// //____________________________________________________________________________
Int_t Get_Hole(Int_t Col, Int_t Row){
Int_t hole_no = 0;
for(Int_t i = 0; i<Row; i++){
hole_no += NoinEachRow[i];
}
// else if conditions here deal with columns at right edge of sieve slit (area odd rows do not have holes)
if(Row%2 == 0){
if(Col < 25){
hole_no += (Col/2);
}
else if(Col == 25){
hole_no += 13;
}
else if(Col == 26){
hole_no += 14;
}
}
if(Row%2 == 1){
if(Row > 1 && Row < 15){
if(Col < 13){
Col = ((Col+1)/2) - 1;
}
else if (Col >= 13){
Col = ((Col-3)/2);
}
}
else{
Col = ((Col+1)/2) -1;
}
hole_no += Col;
}
// hole_no += Col;
return hole_no;
}
#endif
|
#include "NutrientTableImpl.h"
#include <mylibs/io.hpp> // pl::printContainer
#include "Utils.h" // fa::utils::makeClassString
#include <functional> // std::plus, std::minus
#include <utility> // std::move
#include <mylibs/container.hpp> // pl::eraseIf
namespace fa {
using namespace literals;
NutrientTableImpl::NutrientPool::NutrientPool(std::initializer_list<value_type> initL) noexcept {
for (auto &&e : initL) {
container_.emplace(e.getNutrientType(),
e); // can not move e as evaluation order of function arguments is undefined
}
}
NutrientTableImpl::const_pointer NutrientTableImpl::NutrientPool::getNutrient(key_type nutrientType) const {
auto it = container_.find(nutrientType);
if (it == std::end(container_)) {
throw NoSuchNutrientException{ "Nutrient could not "
"be found in "
"NutrientTableImpl::NutrientPool::getNutrient" };
}
return &it->second;
}
OStream &operator<<(OStream &os, NutrientTableImpl::NutrientPool::this_type const &obj) {
OStringStream oStringStream{ };
pl::printContainer(obj.container_, oStringStream);
return os << utils::makeClassString(STR("NutrientTableIMpl::NutrientPool"),
STR("cont_"), oStringStream.str());
}
NutrientTableImpl::NutrientTableImpl() noexcept
: cont_{ } { }
//! Do not put more than one of each NutrientType in here!
NutrientTableImpl::NutrientTableImpl(std::initializer_list<std::pair<key_type, NutrientAmount>> initL)
: cont_{ } {
for (auto &&e : initL) {
auto pair = cont_.emplace(nutrientPool.getNutrient(e.first),
e.second);
if (!pair.second) { // if there already was an element with that key
throw std::logic_error{ "Error in "
"NutrientTableImpl::NutrientTableImpl"
"(std::initializer_list<std::pair<key_type, NutrientAmount>>): "
"there were duplicate Nutrients in the initializer_list." };
}
}
}
NutrientTableImpl::this_type operator+(NutrientTableImpl::this_type const &lhs,
NutrientTableImpl::this_type const &rhs) {
using BinaryOperator = std::plus<>;
return NutrientTableImpl::insertOrBinaryOpAssign(lhs, rhs, BinaryOperator{ });
}
NutrientTableImpl::this_type operator-(NutrientTableImpl::this_type const &lhs,
NutrientTableImpl::this_type const &rhs) {
auto res = lhs;
auto end = std::end(rhs.cont_);
for (auto &&e : res.cont_) {
auto it = rhs.cont_.find(e.first);
if (it != end) { // it was there
e.second -= it->second;
}
}
pl::eraseIf(res.cont_, [](auto &&e) { // if there is less than 0 of some Nutrient -> erase it
return e.second < 0.0_micg;
});
return res;
}
NutrientTableImpl::this_type operator*(NutrientTableImpl::this_type const &table,
Amount::value_type multiplier) {
return NutrientTableImpl::unaryOpTheAmounts(table, [multiplier] (auto &&amount) {
return amount * multiplier;
});
}
NutrientTableImpl::this_type operator/(NutrientTableImpl::this_type const &table,
Amount::value_type divisor) {
return NutrientTableImpl::unaryOpTheAmounts(table, [divisor] (auto &&amount) {
return amount / divisor;
});
}
NutrientTableImpl::this_type NutrientTableImpl::getMacroNutrients() const {
return createFilteredTable([](auto &&nutrient) {
return nutrient.isMacro();
});
}
NutrientTableImpl::this_type NutrientTableImpl::getMicroNutrients() const {
return createFilteredTable([](auto &&nutrient) {
return nutrient.isMicro();
});
}
NutrientTableImpl::pair NutrientTableImpl::getNutrient(key_type nutrientType) const {
auto pointer = nutrientPool.getNutrient(nutrientType);
auto it = cont_.find(pointer);
if (it == std::end(cont_)) { // it wasn't there
throw NoSuchNutrientException{ "Nutrient could "
"not be found in "
"NutrientTableImpl::"
"getNutrient(key_type) const" };
}
return *it;
}
// TODO: implement this function
pl::HashSet<NutrientTableImpl::key_type, NutrientTableImpl::const_pointer>
// ReSharper disable once CppMemberFunctionMayBeStatic
NutrientTableImpl::getPercentages() const {
throw NotYetImplementedException{ "NutrientTableImpl::getPercentages() const "
"has not yet been implemented" };
}
OStream &operator<<(OStream &os, NutrientTableImpl::this_type const &obj) {
static auto constexpr charsToRemoveAtTheEnd = 2;
OStringStream oStringStream{ }; /* style: [(5, "hi"), (7, "sup"), (9, "lol")] */
oStringStream << '[';
for (auto &&e : obj.cont_) {
oStringStream << '('
<< *e.first
<< ", "
<< e.second
<< "), ";
}
auto mapString = oStringStream.str();
mapString.erase(std::end(mapString) -
charsToRemoveAtTheEnd,
std::end(mapString)); // erase the superfluous ',' and ' ' characters at the end
mapString.push_back(']');
return os << utils::makeClassString(STR("NutrientTableImpl"),
STR("cont_"),
mapString);
} // END of function operator<<
bool operator==(NutrientTableImpl::this_type const &lhs,
NutrientTableImpl::this_type const &rhs) noexcept {
return lhs.cont_ == rhs.cont_;
}
bool operator!=(NutrientTableImpl::this_type const &lhs,
NutrientTableImpl::this_type const &rhs) noexcept {
return !(lhs == rhs);
}
/*
TODO: Add the correct overdose description, underdose...
Would be nicer, if this would be taken from a file or the db.
The amount to get an optiumdose was taken from:
https://www.dge.de/wissenschaft/referenzwerte/
(19+ years old, male). I assume it's not trivial to implement
different dosages for different ages, gender, or weights)
TODO: Some Nutrients are measured in IU or other measurements.
This has to be implemented correctly.
TODO: A synonym function that takes a string like thiamin and returns
vitamin b1.
*/
NutrientTableImpl::NutrientPool const NutrientTableImpl::nutrientPool = {
value_type{ pl::value_type<value_type>{
NutrientType::VitaminA, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_milg, // minimumDose
990.0_g, // maximumDose
1.0_milg, // optimumDose
0.0_micg, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminC, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
110.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminK, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
70.0_micg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminE, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
992.0_g, // maximumDose
0.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminD, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
20.0_micg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminB1, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
1.2_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminB2, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
1.4_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminB3, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
15.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminB6, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
1.5_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminB9, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
300.0_micg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::VitaminB12, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
3.0_micg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Calcium, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
1000.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Iron, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
10.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Selen, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
70.0_micg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Phosphorus, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
700.0_micg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Potassium, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
6.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Zinc, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
10.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Magnesium, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
400.0_milg, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Water, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
99990.0_g, // maximumDose
2500.0_g, // optimumDose - not from dge
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Protein, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
57.0_g, // optimumDose
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Fat, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
57.0_g, // optimumDose - magic number
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Carbohydrates, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
990.0_g, // maximumDose
150.0_g, // optimumDose - magic number
0.0_g, // storage
}
},
value_type{ pl::value_type<value_type>{
NutrientType::Kcal, // NutrientType
STR("not implemented"), // description
STR("not implemented"), // overdoseDescription
0.0_g, // minimumDose
900.0_g, // maximumDose
200.0_g, // optimumDose - magic number
0.0_g, // storage
}
},
}; // END of nutrientPool initialization
NutrientTableImpl::NutrientTableImpl(container_type &&container)
: cont_{ std::move(container) } { }
} // END of namespace fa
|
#ifndef VLEX_UTILS_H
#define VLEX_UTILS_H 1
#include <cassert>
#include <string>
//void *checked_malloc(int);
//std::string String(char *);
namespace vlex{
struct U_boolList{
bool head_;
U_boolList *tail_;
U_boolList(bool head, U_boolList *tail = nullptr):head_(head), tail_(tail){
}
};
}// namespace vlex
#endif
|
#include "processicon.h"
extern Game * game;
ProcessIcon::ProcessIcon(QGraphicsItem *parent): QGraphicsRectItem(parent){
setRect(0,0,100,100);
setBrush(Qt::green);
}
void ProcessIcon::mousePressEvent(QGraphicsSceneMouseEvent *event){
//when player clicks the process icon, creates a process
if (game->dragging == false){
game->dragging = true;
//change cursor when dragging it
game->setCursor();
}
}
|
//
// main.cpp
// 6. 面向对象
//
// Created by 赵志诚 on 2021/1/6.
// Copyright © 2021年 赵志诚. All rights reserved.
//
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
class vehicle
{
protected:
int wheels;
double weight;
public:
vehicle(int wh,double we)
{
wheels=wh;
weight=we;
}
vehicle(){}
void cout_vehicle()
{
cout<<"wheels:"<<wheels<<endl;
cout<<"weight: "<<weight<<endl;
}
};
class car :private vehicle
{
public:
int passenger_load;
car(int p,int wh,double we)
{
passenger_load=p;
wheels=wh;
weight=we;
}
void cout_car()
{
this->cout_vehicle();
cout<<"passenger: "<<this->passenger_load<<endl;
}
};
class truck :private vehicle
{
public:
int passenger_load;
double payload;
truck(int pa,double pay,int wh,double we)
{
passenger_load=pa;
payload=pay;
wheels=wh;
weight=we;
}
void cout_truck()
{
this->cout_vehicle();
cout<<"passenger:"<<this->passenger_load<<endl;
cout<<"payload: "<<this->payload<<endl;
}
};
int main()
{
vehicle v1(4,199.2);
v1.cout_vehicle();
cout<<endl;
car c1(5,150,12);
c1.cout_car();
cout<<endl;
truck t1(12,120.2,6,42.2);
t1.cout_truck();
cout<<endl;
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <ext/rope>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define M 1000000007
int n, a[2222], from[2222];
int C3 = 0;
int mem[2222][4444];
int calc(int x, int y, int c) {
if (c == C3) return 1;
int& ans = mem[c][x+y];
if (ans != -1) return ans;
int z = C3 - c - y;
ans = 0;
if (y > 0) {
if (x && y)
ans = (LL(x) * calc(x - 1, y - 1, c + 1)) % M;
if (z)
ans = (ans + LL(z) * calc(x, y, c + 1)) % M;
} else {
if (x)
ans = (LL(x) * calc(x, y, c + 1)) % M;
if (z > 1)
ans = (ans + LL(z - 1) * calc(x + 1, y + 1, c + 1)) % M;
}
return ans;
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
vector<int> v;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
if (a[i] != -1) {
from[a[i]] = i;
}
v.push_back(a[i]);
}
memset(mem, -1, sizeof(mem));
int c1 = 0, c2 = 0, c3 = 0;
for (int i = 1; i <= n; ++i) {
if (a[i] != -1 && from[i] == 0) ++c1;else
if (a[i] == -1) {
++c3;
if (from[i] != 0) ++c2;
}
}
C3 = c3;
cout << calc(c1, c2, 0) << endl;
return 0;
}
|
#include "Battery.h"
const double X0 = 512;
const double Y0 = 640;
Battery::Battery():
m_theta(0)
{
}
void Battery::Draw() {
Circle(X0, Y0, 60).draw(Color(100, 100, 100, 180));
Line(X0, Y0, X0 + R * cos(Theta()), Y0 + R * sin(Theta())).drawArrow(3, { 15, 15 }, Color(70, 70, 70, 180));
//font(Mouse::Pos()).draw();
}
double Battery::Theta() {
if (Input::MouseL.pressed == false) {
double mousex = Mouse::Pos().x;
double mousey = Mouse::Pos().y;
m_theta = atan2(mousey - Y0, mousex - X0);
}
return m_theta;
}
|
#ifndef BASE_SCHEDULING_TASK_LOOP_FOR_UI_H_
#define BASE_SCHEDULING_TASK_LOOP_FOR_UI_H_
// For now, TaskLoopForUI is just a pass-through to TaskLoopForWorker since we
// don't really support UI capabilities just yet. Once we implement a real UI
// thread along with UI event listening mechanics, then we can implement a real
// TaskLoopForUI, and swap out the implementation here.
#include "base/build_config.h"
#include "base/scheduling/task_loop_for_worker.h"
namespace base {
// TODO(domfarolino): Implement a real TaskLoopForUI and reference it here.
using TaskLoopForUI = TaskLoopForWorker;
} // namespace base
#endif // BASE_SCHEDULING_TASK_LOOP_FOR_UI_H_
|
#ifndef __SVR_CONFIG_H__
#define __SVR_CONFIG_H__
#include <string.h>
#include "Typedef.h"
#define MAX_SERVER_NODE_LIST (128)
class ServerNode
{
public:
ServerNode(int svid, const char* ip, short port)
{
this->svid = svid;
strcpy(this->ip,ip);
this->port = port;
}
char ip[64];
short port;
int svid;
char des[128];
};
class RobotSvrConfig
{
Singleton(RobotSvrConfig);
public:
void initServerConf();
int initServerConf(const char* content);
int getServerListSize(){return serversize;};
ServerNode* getServerNode(int i)
{
return serverlists[i];
}
private:
int parseServerXML(const char* path);
private:
ServerNode* serverlists[MAX_SERVER_NODE_LIST];
int serversize;
};
#endif
|
#pragma once
#include <stack>
#include <memory>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Window/Event.hpp>
#include "EntityManager.h"
#include "Output.h"
namespace FW
{
class Application;
class SceneManager
{
public:
class BaseScene // base scene in which all other scenes inherit from
: public sf::Drawable
{
public:
BaseScene(Application& app) : app(app), entities(app) {}
virtual void handleEvent(const sf::Event& event) { entities.handleEvent(event); } // default function hands event to entities
virtual void update(const float delta) { entities.update(delta); } // default function updates entities
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(entities); } // default function draws entities
void setAlive(const bool alive) { this->alive = alive; } // used to kill scene
bool getAlive() { return alive; }
protected:
Application & app; // stores reference to main application object
EntityManager entities; // and an entity manager
bool alive = true;
};
public:
SceneManager(Application& app);
void popScene();
BaseScene& getCurrentScene(); // gets current scene
void update() {
// remove all scenes that have died this frame
scenes.erase(std::remove_if(scenes.begin(), scenes.end(),
[](const std::unique_ptr<BaseScene>& scene) { return !scene->getAlive(); }
), scenes.end());
}
template <typename SceneType>
void addScene()
{
// add a new scene to the vector, must inherit from BaseScene
static_assert(std::is_base_of<BaseScene, SceneType>::value, "'SceneType' must inherit 'BaseScene'.");
scenes.push_back(std::make_unique<SceneType>(app)); // uses a smart pointer to the scene
}
private:
Application & app; // stores reference to main application object
std::vector<std::unique_ptr<BaseScene>> scenes; // vector of scenes
};
}
|
//: C03:Menu.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Prosty program menu, ilustrujacy
// uzycie instrukcji "break" i "continue"
#include <iostream>
using namespace std;
int main() {
char c; // Do przechowywania odpowiedzi
while(true) {
cout << "GLOWNE MENU:" << endl;
cout << "l: lewe, p: prawe, w: wyjscie -> ";
cin >> c;
if(c == 'w')
break; // Wyjscie z "while(1)"
if(c == 'l') {
cout << "LEWE MENU:" << endl;
cout << "wybierz a lub b: ";
cin >> c;
if(c == 'a') {
cout << "wybrales 'a'" << endl;
continue; // Powrot do glownego menu
}
if(c == 'b') {
cout << "wybrales 'b'" << endl;
continue; // Powrot do glownego menu
}
else {
cout << "nie wybrales a ani b!"
<< endl;
continue; // Powrot do glownego menu
}
}
if(c == 'p') {
cout << "PRAWE MENU:" << endl;
cout << "wybierz c lub d: ";
cin >> c;
if(c == 'c') {
cout << "wybrales 'c'" << endl;
continue; // Powrot do glownego menu
}
if(c == 'd') {
cout << "wybrales 'd'" << endl;
continue; // Powrot do glownego menu
}
else {
cout << "nie wybrales c ani d!"
<< endl;
continue; // Powrot do glownego menu
}
}
cout << "musisz wpisac l, p albo w!" << endl;
}
cout << "wyjscie z menu..." << endl;
} ///:~
|
#pragma once
#include <set>
#include "../system.hpp"
namespace sbg {
struct PhysicEngine : Engine {
void add(std::shared_ptr<Entity> entity);
void remove(std::weak_ptr<Entity> entity);
void execute(Time time) override;
private:
std::set<std::weak_ptr<Entity>, std::owner_less<std::weak_ptr<Entity>>> _objects;
};
}
|
/*
ID: andonov921
TASK: comehome
LANG: C++
*/
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <algorithm>
#include <sstream>
#include <climits>
#include <fstream>
#include <cmath>
using namespace std;
/// ********* debug template by Bidhan Roy *********
template < typename F, typename S >
ostream& operator << ( ostream& os, const pair< F, S > & p ) {
return os << "(" << p.first << ", " << p.second << ")";
}
template < typename T >
ostream &operator << ( ostream & os, const vector< T > &v ) {
os << "{";
typename vector< T > :: const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "}";
}
template < typename T >
ostream &operator << ( ostream & os, const set< T > &v ) {
os << "[";
typename set< T > :: const_iterator it;
for ( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "]";
}
template < typename T >
ostream &operator << ( ostream & os, const unordered_set< T > &v ) {
os << "[";
typename unordered_set< T > :: const_iterator it;
for ( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "]";
}
template < typename F, typename S >
ostream &operator << ( ostream & os, const map< F, S > &v ) {
os << "[";
typename map< F , S >::const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << it -> first << ": " << it -> second ;
}
return os << "]";
}
template < typename F, typename S >
ostream &operator << ( ostream & os, const unordered_map< F, S > &v ) {
os << "[";
typename unordered_map< F , S >::const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << it -> first << ": " << it -> second ;
}
return os << "]";
}
#define debug(x) cerr << #x << " = " << x << endl;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef pair<double, double> PDD;
typedef vector<bool> VB;
typedef vector<int> VI;
typedef vector<char> VC;
typedef vector<LL> VLL;
typedef vector<double> VD;
typedef vector<string> VS;
typedef vector<VB> VVB;
typedef vector<VI> VVI;
typedef vector<VC> VVC;
typedef vector<VLL> VVLL;
typedef vector<VD> VVD;
typedef vector<VS> VVS;
ifstream fin("comehome.in");
ofstream fout("comehome.out");
#define cin fin
#define cout fout
int n, weight;
string from, to;
unordered_map<string, int> s2i;
unordered_map<int, string> i2s;
vector<vector<PII>> g;
VI distances;
VB visited;
void read_input(){
cin >> n; // 1 <= n <= 10000
string newline;
getline(cin, newline);
int curr = 0;
for(int i=0;i<n;i++){
cin >> from >> to >> weight;
if(!s2i.count(from)){
s2i[from] = curr;
i2s[curr] = from;
curr++;
g.push_back(vector<PII>());
}
if(!s2i.count(to)){
s2i[to] = curr;
i2s[curr] = to;
curr++;
g.push_back(vector<PII>());
}
g[s2i[from]].push_back({s2i[to], weight});
g[s2i[to]].push_back({s2i[from], weight});
}
}
void dijkstra(){
priority_queue<PII, vector<PII>, greater<PII>> pq;
int curr = s2i["Z"];
int curr_dist = 0;
pq.push({curr_dist, curr});
while(!pq.empty()){
tie(curr_dist, curr) = pq.top(); pq.pop();
if(visited[curr]) continue;
visited[curr] = true;
distances[curr] = curr_dist;
for(auto neighbor : g[curr]){
int to = neighbor.first;
int weight = neighbor.second;
if(!visited[to] && distances[to] > distances[curr] + weight){
distances[to] = distances[curr] + weight;
pq.push({distances[to], to});
}
}
}
}
void solve(){
int p = g.size();
distances.resize(p, INT_MAX);
visited.resize(p, false);
dijkstra();
int min_dist = INT_MAX;
int min_idx = -1;
for(int i=0;i<p;i++){
if(i2s[i][0] >= 'Z') continue;
if(distances[i] < min_dist){
min_dist = distances[i];
min_idx = i;
}
}
cout << i2s[min_idx] << " " << min_dist << "\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
read_input();
solve();
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define MAX 100
#define MOD 1000000007
#define pb push_back
/* add vars here */
int xa, ya, xb, yb;
/* add your algorithm here */
int main() {
cin >> xa >> ya >> xb >> yb;
int xd ,yd;
xd = abs(xa - xb);
yd = abs(ya - yb);
int xc= xb + yd;
int yc= yb + xd;
int xdd= xa + yd;
int ydd= ya + xd;
if (xb >= xa && yb >= ya) {
xc = xb - yd;
yc = yb + xd;
xdd = xa - yd;
ydd = ya + xd;
} else if (xa >= xb && yb >= ya) {
xc = xb - yd;
yc = yb - xd;
xdd = xa - yd;
ydd = ya - xd;
} else if (xb >= xa && ya >= yb){
xc = xb + yd;
yc = yb + xd;
xdd = xa + yd;
ydd = ya + xd;
} else {
xc = xb + yd;
yc = yb - xd;
xdd = xa + yd;
ydd = ya - xd;
}
cout << xc << " " << yc << " " << xdd << " " << ydd << endl;
}
|
#pragma once
#include "Unit.h"
#include "Inventory.h"
class Player2 : public Unit, public Inventory
{
public:
Player2();
~Player2();
void InputPlayer();
void ShowStatus();
};
|
#include "Command.h"
Command::Command(std::string commandName, std::string(*Execute)(std::vector<std::string> &arguments, unsigned short originID, unsigned short targetID), bool requiresTarget, int numParams, int minLevel)
{
// lets assume good data;
this->commandName = commandName;
this->executeFnc = Execute;
this->requiresTarget = requiresTarget;
this->numRequiredParams = numParams;
this->minLevel = minLevel;
}
bool Command::Execute(unsigned short origin)
{
std::vector<std::string> satisfy;
return this->Execute(satisfy, origin, 0);
}
bool Command::Execute(std::vector<std::string> &arguments, unsigned short origin)
{
return this->Execute(arguments, origin, 0);
}
bool Command::Execute(std::vector<std::string> &arguments, unsigned short origin, unsigned short target)
{
if (requiresTarget && !target)
{
commandResult = "This commmand requires a target client.";
return false;
}
else if (arguments.size() < numRequiredParams)
{
commandResult = "This commmand requires at least " + std::to_string(numRequiredParams) + " parameters";
return false;
}
try
{
commandResult = this->executeFnc(arguments, origin, target);
}
catch (std::exception &e)
{
printf("Command generated an exception-> %s\n", e.what());
return false;
}
return true;
}
std::string Command::getName()
{
return commandName;
}
std::string Command::getResult()
{
return commandResult;
}
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
typedef long long LL;
bool ans;
int num[5];
void DFS(int k,int now){
if( ans ) return;
if( k == 5 ){
if( now == 23 )
ans = true;
return;
}
DFS(k+1,now+num[k]);
DFS(k+1,now-num[k]);
DFS(k+1,now*num[k]);
}
int main(int argc, char const *argv[])
{
while( scanf("%d %d %d %d %d",&num[0],&num[1],&num[2],&num[3],&num[4]) && (num[0]|num[1]|num[2]|num[3]|num[4]) ){
ans = false;
sort(num,num+5);
do{
DFS(1,num[0]);
}while( next_permutation(num,num+5) );
if( ans ) printf("Possible\n");
else printf("Impossible\n");
}
return 0;
}
|
//
// ofxTwistedRibbon.cpp
// example
//
// Created by Atsushi Tadokoro on 8/14/14.
//
//
#include "ofxTwistedRibbon.h"
ofxTwistedRibbon::ofxTwistedRibbon(int _length, ofColor _color, float _thickness){
length = _length;
color = _color;
thickness = _thickness;
}
void ofxTwistedRibbon::update(ofVec3f position){
points.push_back(position);
colors.push_back(color);
if (points.size() > length) {
points.pop_front();
colors.pop_front();
}
}
void ofxTwistedRibbon::update(ofVec3f position, ofColor _color){
points.push_back(position);
colors.push_back(_color);
if (points.size() > length) {
points.pop_front();
colors.pop_front();
}
}
void ofxTwistedRibbon::draw(){
ofEnableDepthTest();
ofSetColor(255);
ofVboMesh mesh;
mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
for(unsigned int i = 1; i < points.size(); i++){
ofVec3f thisPoint = points[i-1];
ofVec3f nextPoint = points[i];
ofVec3f direction = (nextPoint - thisPoint);
float distance = direction.length();
ofVec3f unitDirection = direction.normalized();
ofVec3f toTheLeft = unitDirection.getRotated(90, ofVec3f(0, 1, 1));
ofVec3f toTheRight = unitDirection.getRotated(-90, ofVec3f(0, 1, 1));
ofVec3f leftPoint = thisPoint+toTheLeft * thickness;
ofVec3f rightPoint = thisPoint+toTheRight * thickness;
ofFloatColor fcolor = ofFloatColor(colors[i].r / 255.0,
colors[i].g / 255.0,
colors[i].b / 255.0);
mesh.addColor(fcolor);
mesh.addVertex(ofVec3f(leftPoint.x, leftPoint.y, leftPoint.z));
mesh.addColor(fcolor);
mesh.addVertex(ofVec3f(rightPoint.x, rightPoint.y, rightPoint.z));
int n = mesh.getNumColors();
}
mesh.draw();
}
|
#include <stdio.h>
#include <assert.h>
#include "exeq.h"
/////////////////////////////////////////////////////////////
// Init function initializes the EXEQ
/////////////////////////////////////////////////////////////
EXEQ* EXEQ_init(void){
int ii;
EXEQ *t = (EXEQ *) calloc (1, sizeof (EXEQ));
for(ii=0; ii<MAX_EXEQ_ENTRIES; ii++){
t->EXEQ_Entries[ii].valid=false;
}
return t;
}
/////////////////////////////////////////////////////////////
// Print State
/////////////////////////////////////////////////////////////
void EXEQ_print_state(EXEQ *t){
int ii = 0;
printf("Printing EXEQ \n");
printf("Entry Valid inst Wait Cycles\n");
for(ii = 0; ii < MAX_EXEQ_ENTRIES; ii++) {
printf("%5d :: %d ", ii, t->EXEQ_Entries[ii].valid);
printf("%5d \t", (int)t->EXEQ_Entries[ii].inst.inst_num);
printf("%5d \n", t->EXEQ_Entries[ii].inst.exe_wait_cycles);
}
printf("\n");
}
/////////////////////////////////////////////////////////////
// Every cycle, all valid EXEQ entries undergo exe_wait--
/////////////////////////////////////////////////////////////
void EXEQ_cycle(EXEQ *t){
int ii;
for(ii=0; ii<MAX_EXEQ_ENTRIES; ii++){
if(t->EXEQ_Entries[ii].valid){
t->EXEQ_Entries[ii].inst.exe_wait_cycles--;
}
}
}
/////////////////////////////////////////////////////////////
// insert entry in EXEQ, exit if no space!
/////////////////////////////////////////////////////////////
void EXEQ_insert(EXEQ *t, Inst_Info inst){
int ii;
for(ii=0; ii<MAX_EXEQ_ENTRIES; ii++){
if(!t->EXEQ_Entries[ii].valid){
t->EXEQ_Entries[ii].valid=true;
t->EXEQ_Entries[ii].inst=inst;
t->EXEQ_Entries[ii].inst.exe_wait_cycles=1;
// override wait time for LOAD (or any multicycle op)
if(t->EXEQ_Entries[ii].inst.op_type == OP_LD){
t->EXEQ_Entries[ii].inst.exe_wait_cycles=LOAD_EXE_CYCLES;
}
return;
}
}
printf("ERROR: Trying to install in full EXEQ. Dying...\n");
exit(-1);
}
/////////////////////////////////////////////////////////////
// If any EXEQ entry has zero wait time return true, else false
/////////////////////////////////////////////////////////////
bool EXEQ_check_done(EXEQ *t){
int ii;
for(ii=0; ii<MAX_EXEQ_ENTRIES; ii++){
if(t->EXEQ_Entries[ii].valid){
if(t->EXEQ_Entries[ii].inst.exe_wait_cycles==0){
return true;
}
}
}
return false;
}
/////////////////////////////////////////////////////////////
// Remove an finshed entry from the EXEQ (call after check_done)
/////////////////////////////////////////////////////////////
Inst_Info EXEQ_remove(EXEQ *t){
Inst_Info retval;
int ii;
for(ii=0; ii<MAX_EXEQ_ENTRIES; ii++){
if(t->EXEQ_Entries[ii].valid){
if(t->EXEQ_Entries[ii].inst.exe_wait_cycles==0){
t->EXEQ_Entries[ii].valid=false;
return t->EXEQ_Entries[ii].inst;
}
}
}
printf("ERROR: Trying to remove entry from empty EXEQ. Dying...\n");
exit(-1);
return retval;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
|
#include<bits/stdc++.h>
using namespace std;
main()
{
long long int a, b, count, extra, sum;
while(scanf("%lld %lld",&a,&b)==2)
{
if(a==0 && b==0)
break;
while(a!=0 ||b!=0)
{
sum = (a%10+b%10);
if(sum + extra>9)
{
count++;
extra=1;
}
else
{
extra=0;
}
a/=10;
b/=10;
}
if(count==0)
{
printf("No carry operation.\n");
}
else if(count==1)
{
printf("%lld carry operation.\n",count);
}
else
{
printf("%lld carry operations.\n",count);
}
count=0;
extra=0;
}
return 0;
}
|
#include "../DetectMemoryLeak.h"
#include "Minimap.h"
#include "GraphicsManager.h"
#include "RenderHelper.h"
#include "../EntityManager.h"
#include "GL\glew.h"
#include "../PlayerInfo/PlayerInfo.h"
#include "../Application.h"
#include "MouseController.h"
#include "KeyboardController.h"
#include "MeshList.h"
CMinimap::CMinimap(void)
: m_cMinimap_Background(NULL)
, m_cMinimap_Border(NULL)
, m_cMinimap_Avatar(NULL)
, m_cMinimap_Target(NULL)
, m_cMinimap_Stencil(NULL)
, m_iAngle(-90)
, mode(MODE_2D)
{
//Init();
}
CMinimap::~CMinimap(void)
{
//if (m_cMinimap_Background)
//{
// delete m_cMinimap_Background;
// m_cMinimap_Background = NULL;
//}
//if (m_cMinimap_Border)
//{
// delete m_cMinimap_Border;
// m_cMinimap_Border = NULL;
//}
//if (m_cMinimap_Avatar)
//{
// delete m_cMinimap_Avatar;
// m_cMinimap_Avatar = NULL;
//}
//if (m_cMinimap_Target)
//{
// delete m_cMinimap_Target;
// m_cMinimap_Target = NULL;
//}
}
// Initialise this class instance
bool CMinimap::Init(void)
{
minimapList.clear();
mmRoomList.clear();
roomPosMapList.clear();
roomScaleMapList.clear();
teleporterMapPos.clear();
teleporterMapScale.clear();
teleporterActPos.clear();
for (std::list<EntityBase*>::iterator it = EntityManager::GetInstance()->getCollisionList().begin();
it != EntityManager::GetInstance()->getCollisionList().end(); ++it)
{
if (dynamic_cast<GenericEntity*>(*it)->type != GenericEntity::TELEPORTER)
continue;
this->addToMinimapList(*it);
}
// Setup the 2D entities
float halfWindowWidth = Application::GetInstance().GetWindowWidth() / 2.0f;
float halfWindowHeight = Application::GetInstance().GetWindowHeight() / 2.0f;
m_iAngle = 0;
//position.Set(halfWindowWidth, halfWindowHeight, 0.0f);
//magical numbers here
position.Set(halfWindowWidth - 65.f, halfWindowHeight - 65.f, 0.0f);
scale.Set(100.0f, 100.0f, 100.0f);
//playerMapScale = Player::GetInstance()->GetScale() * (0.1);
playerMapScale = Vector3(10,10,10) * (1 / scale.x);
m_iNumWall = 0;
m_iNumTele = 0;
m_bEnlarged = false;
m_fRange = scale.x * 0.1;
mapState = NORMAL;
//map id
//mapID[0] = "wallpos";
//mapID[1] = "wallscale";
//mapID[2] = "telepos";
//mapID[3] = "telescale";
mmRoomList = Level::GetInstance()->getRooms();
for (size_t i = 0; i < Level::GetInstance()->getRooms().size(); ++i)
{
Vector3 tScale(Level::GetInstance()->getRooms()[i].width, Level::GetInstance()->getRooms()[i].height, 1);
tScale = tScale * (1.0f / (scale.x * 0.1));
roomScaleMapList.push_back(tScale);
roomPosMapList.push_back(tScale); //temp pushback
}
for (std::list<EntityBase*>::iterator it = minimapList.begin(); it != minimapList.end(); ++it)
{
if (dynamic_cast<GenericEntity*>((*it))->type == GenericEntity::TELEPORTER)
{
teleporterMapPos.push_back((*it)->GetPosition());
teleporterActPos.push_back((*it)->GetPosition());
teleporterMapScale.push_back((*it)->GetScale() * (1.0f / (scale.x * 0.1)));
}
}
playerMapScale = Vector3(10, 10, 10) * (1 / scale.x);
return true;
}
bool CMinimap::SetTarget(Mesh* aTarget)
{
if(aTarget != NULL)
{
m_cMinimap_Target = aTarget;
return true;
}
return false;
}
Mesh* CMinimap::GetTarget(void) const
{
return m_cMinimap_Target;
}
// Set the background mesh to this class
bool CMinimap::SetBackground(Mesh* aBackground)
{
if (aBackground != NULL)
{
m_cMinimap_Background = aBackground;
return true;
}
return false;
}
// Get the background mesh to this class
Mesh* CMinimap::GetBackground(void) const
{
return m_cMinimap_Background;
}
// Set the Border mesh to this class
bool CMinimap::SetBorder(Mesh* aBorder)
{
if (aBorder != NULL)
{
m_cMinimap_Border = aBorder;
return true;
}
return false;
}
// Get the Border mesh to this class
Mesh* CMinimap::GetBorder(void) const
{
return m_cMinimap_Border;
}
// Set the Avatar mesh to this class
bool CMinimap::SetAvatar(Mesh* anAvatar)
{
if (anAvatar != NULL)
{
m_cMinimap_Avatar = anAvatar;
return true;
}
return false;
}
// Get the Avatar mesh to this class
Mesh* CMinimap::GetAvatar(void) const
{
return m_cMinimap_Avatar;
}
// Set m_iAngle of avatar
bool CMinimap::SetAngle(const int m_iAngle)
{
this->m_iAngle = m_iAngle;
return true;
}
// Get m_iAngle
int CMinimap::GetAngle(void) const
{
return m_iAngle;
}
// Set the Stencil mesh to this class
bool CMinimap::SetStencil(Mesh* aStencil)
{
if (aStencil != NULL)
{
m_cMinimap_Stencil = aStencil;
return true;
}
return false;
}
// Get the Stencil mesh to this class
Mesh* CMinimap::GetStencil(void) const
{
return m_cMinimap_Stencil;
}
//void CMinimap::setObjectPos(std::string _type, Vector3 _pos)
//{
// minimapData[_type].push_back(_pos);
//}
// Set the Enemy mesh to this class
bool CMinimap::SetObjectMesh(Mesh* _mesh)
{
if (_mesh == NULL)
return false;
m_cMinimap_Object = _mesh;
return true;
}
// Get the Enemy mesh to this class
Mesh* CMinimap::GetObjectMesh(void) const
{
return m_cMinimap_Object;
}
void CMinimap::setObject(Vector3 _pos ,Vector3 _scale)
{
objPos = _pos;
objScale = _scale;
}
//std::map<std::string, std::vector<Vector3>> CMinimap::getMinimapData()
//{
// return minimapData;
//}
//// set minimap map scale
//void CMinimap::setObjectScale(std::string _type, Vector3 _scale)
//{
// minimapData[_type].push_back(_scale);
//}
// get player map scale
Vector3 CMinimap::getPlayerMapScale()
{
return playerMapScale;
}
// set player map scale
void CMinimap::setPlayerMapScale(Vector3 _scale)
{
playerMapScale = _scale;
}
// get bool enlarged
bool CMinimap::getIsEnlarged()
{
return m_bEnlarged;
}
// set bool enlarged
void CMinimap::setIsEnlarged(bool _isEnlarged)
{
m_bEnlarged = _isEnlarged;
}
// enlarge minimap
void CMinimap::EnlargeMap(bool _isEnlarged)
{
float halfWindowWidth = Application::GetInstance().GetWindowWidth() / 2.0f;
float halfWindowHeight = Application::GetInstance().GetWindowHeight() / 2.0f;
if (_isEnlarged)
{
scale.Set(500, 500, 1);
position.Set(0, 0, 9.f);
//rescale
roomScaleMapList.clear();
for (size_t i = 0; i < Level::GetInstance()->getRooms().size(); ++i)
{
Vector3 tScale(Level::GetInstance()->getRooms()[i].width, Level::GetInstance()->getRooms()[i].height, 1);
tScale *= 1.0f / (scale.x * 0.05);
roomScaleMapList.push_back(tScale);
}
playerMapScale = Vector3(10, 10, 10) * (1 / scale.x);
m_fRange = scale.x * 0.1f;
mapState = ENLARGED;
}
else
{
scale.Set(100, 100, 1);
//position.Set(335.f, 235.f, 0.0f);
position.Set(halfWindowWidth - 65.f, halfWindowHeight - 65.f, -1000.0f);
//rescale
roomScaleMapList.clear();
for (size_t i = 0; i < Level::GetInstance()->getRooms().size(); ++i)
{
Vector3 tScale(Level::GetInstance()->getRooms()[i].width, Level::GetInstance()->getRooms()[i].height, 1);
tScale *= 1.0f / (scale.x * 0.05);
roomScaleMapList.push_back(tScale);
}
playerMapScale = Vector3(10, 10, 10) * (1 / scale.x);
m_fRange = scale.x * 0.1f;
mapState = NORMAL;
}
}
void CMinimap::addTeleporterPos(Vector3 _pos)
{
teleporterActPos.push_back(_pos);
}
void CMinimap::addToMinimapList(EntityBase * _entity)
{
minimapList.push_back(_entity);
}
std::list<EntityBase*>& CMinimap::getMinimapList(void)
{
return minimapList;
}
std::vector<Level::Rectangle> CMinimap::getMiniMapRooomList()
{
return mmRoomList;
}
void CMinimap::setMiniMapRoomList(std::vector<Level::Rectangle> _mmRoom)
{
mmRoomList = _mmRoom;
}
//update minimap
void CMinimap::Update(double dt)
{ //temp storing method to be changed for storing the individual walls to instead the room only
float halfWindowWidth = Application::GetInstance().GetWindowWidth() / 2.0f; //400
float halfWindowHeight = Application::GetInstance().GetWindowHeight() / 2.0f; //300
//for the rooms
for (size_t i = 0; i < Level::GetInstance()->getRooms().size(); ++i)
{
Vector3 roomPos(Level::GetInstance()->getRooms()[i].getMidPoint().x, Level::GetInstance()->getRooms()[i].getMidPoint().y, 0);
mmRoomList[i].m_bInRange = false;
if ((roomPos - Player::GetInstance()->GetPos()).LengthSquared() < m_fRange * m_fRange)
{
Vector3 tPos = roomPos - Player::GetInstance()->GetPos();
tPos = tPos * (1.0f / (scale.x * 0.1));
roomPosMapList[i] = tPos;
mmRoomList[i].m_bInRange = true;
//CMinimap::GetInstance()->setObjectPos("wallpos", tPos);
}
}
int counter = 0;
//other entity e.g teleporter and stuff if we adding
for (std::list<EntityBase*>::iterator it = minimapList.begin(); it != minimapList.end(); ++it)
{
(*it)->SetInRange(false);
if (((*it)->GetPosition() - Player::GetInstance()->GetPos()).LengthSquared() < m_fRange * m_fRange)
{
teleporterMapScale[counter] = ((*it)->GetScale() * (1.0f / (scale.x * 0.1)));
teleporterMapPos[counter] = ((*it)->GetPosition() - Player::GetInstance()->GetPos()) * (1.0f / (scale.x * 0.1));
(*it)->SetInRange(true);
}
++counter;
}
if (mapState == NORMAL)
{
position.Set(halfWindowWidth - 65.f, halfWindowHeight - 65.f, 0.0f);
}
else if (mapState == ENLARGED)
{
if (MouseController::GetInstance()->IsButtonReleased(MouseController::LMB))
{
double x, y;
MouseController::GetInstance()->GetMousePosition(x, y);
int w = Application::GetInstance().GetWindowWidth();
int h = Application::GetInstance().GetWindowHeight();
x = x + Player::GetInstance()->GetPos().x - (w * 0.5f);
y = y - Player::GetInstance()->GetPos().y + (h * 0.5f);
float posX = static_cast<float>(x);
float posY = (h - static_cast<float>(y));
Vector3 temp(posX, posY, 0);
//std::cout << "mousePos: " << temp << "\n";
for (int i = 0; i < teleporterMapPos.size(); ++i)
{
if ((teleporterMapPos[i] - playerMapPos).LengthSquared() > m_fRange * m_fRange)
continue;
//std::cout << "mmPos: " << teleporterMapPos[i] << "\n";
if (temp < teleporterMapPos[i] * scale.x + teleporterMapScale[i] * scale.x * 2 &&
temp > teleporterMapPos[i] * scale.x - teleporterMapScale[i] * scale.x * 2)
{
//std::cout << "can teleport\n";
Player::GetInstance()->SetPos(teleporterActPos[i]);
EnlargeMap(false);
m_bEnlarged = false;
break;
//std::cout << "index: " << i << " <in range to tele> \n\n";
}
}
}
}
playerMapPos = Player::GetInstance()->GetPos() * (1.0f / (scale.x * 0.1));
}
void CMinimap::RenderUI()
{
if (mode == MODE_3D)
return;
//objPos = objPos * (1.0f / scale.x);
//objScale = objScale * (1.0f / 50.f);
//std::cout << map_ePos << std::endl;
MS& modelStack = GraphicsManager::GetInstance()->GetModelStack();
// Push the current transformation into the modelStack
modelStack.PushMatrix();
// Translate the current transformation
modelStack.Translate(position.x, position.y, position.z);
// Scale the current transformation
modelStack.Scale(scale.x, scale.y, scale.z);
// Push the current transformation into the modelStack
modelStack.PushMatrix();
// Enable stencil mode
glEnable(GL_STENCIL_TEST);
// Configure stencil mode
glStencilFunc(GL_ALWAYS, 1, 0xFF); // Set any stencil to 1
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glStencilMask(0xFF); // Write to stencil buffer
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Don't write to colour buffer
glDepthMask(GL_FALSE); // Don't write to depth buffer
glClear(GL_STENCIL_BUFFER_BIT); // Clear stencil buffer (0 by default)
if (m_cMinimap_Stencil)
RenderHelper::RenderMesh(m_cMinimap_Stencil);
// Switch off stencil function
glStencilFunc(GL_EQUAL, 1, 0xFF); // Pass test if stencil value is 1
glStencilMask(0x00); // Don't write anything to stencil buffer
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // Write to colour buffer
glDepthMask(GL_TRUE); // Write to depth buffer
modelStack.PushMatrix();
// Rotate the current transformation
modelStack.Rotate(m_iAngle, 0.0f, 0.0f, -1.0f);
if (m_cMinimap_Background)
RenderHelper::RenderMesh(m_cMinimap_Background);
// Render walls
glDisable(GL_DEPTH_TEST);
for (size_t i = 0; i < roomPosMapList.size(); ++i)
{
//if (playerMapPos.LengthSquared() > minimapData["wallpos"][i].LengthSquared())
//if ((roomPosMapList[i] - playerMapPos).LengthSquared() < m_fRange)
if(mmRoomList[i].m_bInRange)
{
//std::cout << minimapData["wallpos"][i] << " render\n";
modelStack.PushMatrix();
modelStack.Translate(roomPosMapList[i].x, roomPosMapList[i].y, 0);
modelStack.Scale(roomScaleMapList[i].x, roomScaleMapList[i].y, roomScaleMapList[i].z);
// Render an object
RenderHelper::RenderMesh(m_cMinimap_Object);
modelStack.PopMatrix();
}
}
int counter = 0;
for (std::list<EntityBase*>::iterator it = minimapList.begin();
it != minimapList.end(); ++it)
{
if ((*it)->IsInRange())
{
//std::cout << minimapData["wallpos"][i] << " render\n";
modelStack.PushMatrix();
modelStack.Translate(teleporterMapPos[counter].x, teleporterMapPos[counter].y, 0);
modelStack.Scale(teleporterMapScale[counter].x, teleporterMapScale[counter].y, 1);
// Render an object
RenderHelper::RenderMesh(MeshList::GetInstance()->GetMesh("greenCube"));
modelStack.PopMatrix();
}
++counter;
}
//for (int i = 0; i < m_iNumWall; ++i)
//{
// //if (playerMapPos.LengthSquared() > minimapData["wallpos"][i].LengthSquared())
// if((minimapData["wallpos"][i] - playerMapPos).LengthSquared() < m_fRange)
// {
// //std::cout << minimapData["wallpos"][i] << " render\n";
// modelStack.PushMatrix();
// modelStack.Translate(minimapData["wallpos"][i].x, minimapData["wallpos"][i].y, 0);
// // Rotate the current transformation
// modelStack.Rotate(m_iAngle, 0.0f, 0.0f, -1.0f);
// modelStack.Scale(minimapData["wallscale"][i].x, minimapData["wallscale"][i].y, minimapData["wallscale"][i].z);
// // Render an object
// RenderHelper::RenderMesh(m_cMinimap_Object);
// modelStack.PopMatrix();
// }
//}
glEnable(GL_DEPTH_TEST);
modelStack.PopMatrix();
// Disable depth test
glDisable(GL_DEPTH_TEST);
// Display the Avatar
if (m_cMinimap_Avatar)
{
modelStack.PushMatrix();
//modelStack.Translate(Player::GetInstance()->GetPos().x * (1 / scale.x), Player::GetInstance()->GetPos().y * (1 / scale.x), Player::GetInstance()->GetPos().z);
modelStack.Rotate(Math::RadianToDegree(atan2(Player::GetInstance()->GetView().y, Player::GetInstance()->GetView().x)) - 90, 0, 0, 1);
modelStack.Scale(playerMapScale.x, playerMapScale.y, playerMapScale.z);
RenderHelper::RenderMesh(m_cMinimap_Avatar);
modelStack.PopMatrix();
}
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Disable stencil test
glDisable(GL_STENCIL_TEST);
modelStack.PopMatrix();
if (m_cMinimap_Border)
RenderHelper::RenderMesh(m_cMinimap_Border);
modelStack.PopMatrix();
//clear all pos
//minimapData["wallpos"].clear();
//minimapData["wallscale"].clear();
//minimapData["telepos"].clear();
//minimapData["telescale"].clear();
//teleporterActPos.clear();
}
CMinimap* Create::Minimap(const bool m_bAddToLibrary)
{
CMinimap* result = CMinimap::GetInstance();
if (m_bAddToLibrary)
EntityManager::GetInstance()->AddEntity(result, false);
return result;
}
|
//
// Created by heyhey on 20/03/2018.
//
#include "Structure.h"
Structure::Structure() {
}
Structure::Structure(Condition *condition) : condition(condition) {}
Condition *Structure::getCondition() const {
return condition;
}
void Structure::setCondition(Condition *condition) {
Structure::condition = condition;
}
ostream &operator<<(ostream &os, const Structure &structure) {
os << static_cast<const Instruction &>(structure) << " condition: " << structure.condition;
return os;
}
Structure::~Structure() {
}
|
#include <iostream>
#include <vector>
/************************************
* Some Experimentation with vectors*
************************************/
using namespace std;
int main (int argc, char **argv) {
vector<int> v;
vector<int> *v_ptr = &v;
v.push_back(11);
v.push_back(22);
cout << "Size of v is " << v.size() << endl; /* Answer is 2 */
v_ptr->push_back(33);
v.push_back(44);
cout << "Size of v is " << v_ptr->size() << endl; /* Answer is 4 */
v[5] = 55; /* This is wrong because this vector does not have a 5th element yet.
but it works */
for (size_t i = 0; i < v.size(); i++) cout << v[i] << " "; /* Vector knows its own size */
cout << endl;
cout << "Trying to access 10th element: " << v[10] << endl; /* This shows 0, don't know what is going on */
vector<int>::iterator i = v.begin() + 2;
sort(v.begin(), v.end());
for (vector<int>::iterator i = v.begin(); i != v.end(); ++i) {
cout << *i << endl;
}
return (0);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
* Author: Petter Nilsen
*/
#include "core/pch.h"
#ifdef WIC_PERMISSION_LISTENER
#include "adjunct/quick/permissions/DesktopPermissionCallback.h"
DesktopPermissionCallback::DesktopPermissionCallback(OpPermissionListener::PermissionCallback *callback, OpString& hostname):m_permission_callback(callback)
{
m_accessing_hostname.Set(hostname);
}
OP_STATUS DesktopPermissionCallback::AddWebHandlerRequest(const OpStringC& request)
{
OpString* s = OP_NEW(OpString,());
if(!s || OpStatus::IsError(s->Set(request)) || OpStatus::IsError(m_web_handler_request.Add(s)))
{
OP_DELETE(s);
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
void DesktopPermissionCallbackQueue::RemoveItem(DesktopPermissionCallback* item)
{
OP_ASSERT(HasLink(item));
if(HasLink(item))
{
item->Out();
}
}
void DesktopPermissionCallbackQueue::DeleteItem(DesktopPermissionCallback* item)
{
RemoveItem(item);
OP_DELETE(item);
}
BOOL DesktopPermissionCallbackQueue::HasType(OpPermissionListener::PermissionCallback::PermissionType type)
{
DesktopPermissionCallback *item = First();
while(item)
{
if(item->GetPermissionCallback() && item->GetPermissionCallback()->Type() == type)
{
return TRUE;
}
item = static_cast<DesktopPermissionCallback*>(item->Suc());
}
return FALSE;
}
#endif // WIC_PERMISSION_LISTENER
|
//include header
#include "main.hpp"
//prototypes
void Main_Testing();
void ConnectFour_Testing();
void Gomoku_Testing();
void TicTacToe_Testing();
void TicTacToe_Implementation_Test1();
void Hex_Testing();
void Go_Testing();
void Benchmark();
void DiffSim_Testing(Game_Engine* diffSim, Player_Engine* players[], string testFileName);
void Lotka_Testing();
void EEG_Testing();
void FileRead_Test();
void AMAF_Testing();
void Param_Impact_Testing_v06();
void AMAF_Testing_Extensive(Game_Engine* game, Player_Engine** players, int simulations, int repeats, int games, const bool disable_sim_set = false);
void FuncApp_test();
void LRP_test_basic();
void LRP_test_linearDW();
void LRP_test_exponentDW();
void LRP_test_linAB_exponentDW(double* score_avg, double* score_avg_last10, double* output_param);
void LRP_test_linAB_exponentDW_FunApp(double* score_avg = NULL, double* score_avg_last10 = NULL, double* last_param_val = NULL, bool force_setting_output = false);
void LRP_test_linAB_exponentDW_FunApp_MulParams(double* score_avg = NULL, double* score_avg_last10 = NULL, double** last_param_val = NULL, bool force_setting_output = false, int num_output_params = 0);
void Tom_Sample_Storage_Test();
void LRP_test_wrapper();
void LRP_test_wrapperMultiPar();
void LRP_improved_v1(double* score_avg = NULL, double* score_avg_last10 = NULL, double** last_param_val = NULL, bool force_setting_output = false, const int set_final_evaluations = 750, double* avg_num_games = NULL, double* final_eval_score = NULL);
void Fixed_Play_Testing(double input_param1 = 0.0, double input_param2 = 0.0);
void Tom_Paper1_tests();
//---- WRITE OWN CODE IN THIS PROCEDURE ----
void Main_Testing()
{
#if(!TOM_DEBUG)
srand((unsigned int)time(NULL));
#endif
//Benchmark();
//TicTacToe_Testing();
//Gomoku_Testing();
//ConnectFour_Testing();
//FileRead_Test();
//Lotka_Testing();
//EEG_Testing();
//AMAF_Testing();
//Hex_Testing();
//FuncApp_test();
//LRP_test_basic();
//LRP_test_linearDW();
//LRP_test_exponentDW();
//LRP_test_linAB_exponentDW();
//LRP_test_wrapper();
//LRP_test_linAB_exponentDW_FunApp();
//LRP_test_linAB_exponentDW_FunApp_MulParams();
//Param_Impact_Testing_v06();
//TicTacToe_Implementation_Test1();
//Go_Testing();
Fixed_Play_Testing(); //evaluate fixed settings (no LRP)
//LRP_improved_v1(); //single LRP run
//LRP_test_wrapperMultiPar(); //multiple LRP repeats
//Tom_Paper1_tests();
}
//-----------------------------------------
//Improved LRP search v1 - restart from kNN best average score after a batch of iterations
//kNN is weighted according to the number of repeated evaluations (num_repeats), evaluated sample can be set to a higher weight
void LRP_improved_v1(double* score_avg, double* score_avg_last10, double** last_param_val, bool force_setting_output, const int set_final_evaluations, double* avg_num_games, double* final_eval_score)
{
//konfiguracija tom
const int num_iterations_self = 100; //number MCTS simulations per move: evaluated player
const int num_iterations_opponent = 100; //number MCTS simulation per move: opponent
const int num_games_start = 10; //number of games per score output at LRP start
const int num_games_end = num_games_start; //number of games per score output at LRP end
const double min_increase_num_games_fact = 1.0; //minimal increase factor of games per evaluation if confidence below threshold (is ignored if max_increase_num_games_fact <= 1.0)
const double max_increase_num_games_fact = 1.0; //maximal increase factor of games per evaluation requested by LRP confidence statistical test (disable by setting <= 1.0)
const double start_Cp_self = 0.2; //initial Cp: evaluated player
const double start_RAVE_V_self = 35.0; //initial RAVE parameter V: evaluated player
const double fixed_CP_opponent = 0.2; //initial Cp: opponent
const double funcApp_init_weights = 0.0; //initial function approximator weights (to be optimized by LRP)
const int num_LRP_iterations = 500; //number of LRP iterations (must be > 1 otherwise invalid values appear)
const double dw_start = 0.2000; //LRP delta weight (change in Cp value): at start
const double dw_limit = 0.0010; //LRP delta weight (change in Cp value): at end
const double lrp_ab_max = 0.75; //LRP learning parameter alpha: maximal value
const double lrp_ab_min = 0.02; //LRP learning parameter alpha: minmal value
const double lrp_ab_dscore_min = 1.0 / (double)((num_games_start+num_games_end)/2.0); //LRP minimum delta score (to change probabilites with minimum alpha value)
const double lrp_ab_dscore_max = lrp_ab_dscore_min * 10.0; //MUST BE HIGHER OR EQUAL TO lrp_ab_dscore_min
const double lrp_b_koef = 1; //LRP learning parameter beta koeficient [0,1] of alpha value
const bool exp_dw_decrease = 0; //use exponential weight decrease (instead of linear)
const int eval_player_position = 1; //which player to optimize and evaluate 0 or 1, currently works only for two-player games
const bool LRP_output_best_kNN = true; //if true final param values will be set according to kNN best avg, otherwise final param values are left from the last LRP iteration (true is default setting)
const bool KNN_weight_repeats = true; //LRP best neighbour by kNN weight by number of repeats per sample (true is default setting)
const double LRP_best_neighbour_weight_central = 1.1; //scalar factor of central (observed) sample weight when averaging with kNN (1.1 is default setting, 1.0 means equal weight to other samples)
//number of games to evaluate final combination of parameters
//const int final_evaluation_num_games = 5000;
const int final_evaluation_num_games = set_final_evaluations;
//20000, 95% confidence that true value deviates less by 1%
//5000, 95% confidence that true value deviates less by 2%
//1200, 95% confidence that true value deviates less by 4%
//750, 95% confidence that true value deviates less by 5% (default setting)
//200, 95% confidence that true value deviates less by 10%
const int final_evaluation_num_iterations_self = num_iterations_self;
const int final_evaluation_num_iterations_opponent = num_iterations_opponent;
const int final_eval_player_position = eval_player_position;
//number of LRP_iterations between restarts from best position in parameter space (disable by setting to num_LRP_iterations or 0)
//const int LRP_restart_condition_iterations = 0; //never restart
const int LRP_restart_condition_iterations = (int)(sqrt(num_LRP_iterations) + 0.5); //sqare root of LRP iterations (default setting)
//const int LRP_restart_condition_iterations = (int)(num_LRP_iterations/10.0 + 0.5); //linear to numer of LRP iterations
//user-defined equations for LRP_best_neighbours_num: number of nearest neighbours when searching combination of parameters with best average score
const int LRP_best_neighbours_num = (int)(min( (sqrt(num_LRP_iterations/10.0 * 1000.0/((num_games_start+num_games_end)/2.0)))*0.5 , num_LRP_iterations*0.1*LRP_best_neighbour_weight_central) + 0.5); //sqare root of num LRP iterations and games (default setting)
//const int LRP_best_neighbours_num = (int)(min( (sqrt(num_LRP_iterations/20.0 * 1000.0/((num_games_start+num_games_end)/2.0)))*0.5 , num_LRP_iterations*0.1*LRP_best_neighbour_weight_central) + 0.5); //less KNN, sqare root of num LRP iterations and games
//const int LRP_best_neighbours_num = (int)(min( (sqrt(num_LRP_iterations/10.0)*(100.0/((num_games_start+num_games_end)/2.0))) , num_LRP_iterations*0.1*0.5*LRP_best_neighbour_weight_central) + 0.5); //sqare root of num LRP iterations, linear in games
//restart from best only if current score differs from best by more than this factor, if (1-current/best >= factor) then restart) (0.0 restarts always, also if last is best), is ignored if LRP_restart_condition_iterations == 0
//const double LRP_restart_condition_score_rel_diff = 0.0; //always restart
const double LRP_restart_condition_score_rel_diff = 0.1 * 1/sqrt(LRP_best_neighbours_num) * LRP_best_neighbour_weight_central; //(default setting)
const double LRP_restart_condition_score_rel_diff_end = 0.2 * LRP_restart_condition_score_rel_diff; //the factor decreases linearly by the number of iterations down to this value
//confidence interval factor for assessing if two scores belong to different distributions
const bool LRP_change_AB_by_confidence = true; //change LRP alpha-beta parameters proportionally to confidence between scores (true, default setting) or to absolute difference (false)
const bool LRP_change_DW_by_confidence = false; //NOT YET IMPLEMENTED: change LRP delta weight proportionally to confidence between scores (true) or linearly/exponentially between dw_start and dw_limit (false, default setting)
const double lrp_score_diff_conf_factor = 1.44; //(1.44 <- 85% is default setting)
//99% -> 2.58
//95% -> 1.96
//90% -> 1.645
//85% -> 1.44
//80% -> 1.28
//75% -> 1.15
//70% -> 1.04
//THE NUMBER OF Func_App_UCT_Params must be set in Player_AI_UCT_TomTest.hpp with the constant TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_PARAMS
//TODO1: da ce je slabši rezultat, da razveljaviš in daš na prejšnje stanje, parameter pa ni treba dat celo pot nazaj ampak samo do določene mere
//TODO2 (več dela): preizkusi če bi dva ločena LRPja delovala boljše za iskanje 2 parametrov, 2 varianti:
// *oba LRPja istočasno izvedeta akcijo in opazujeta izhod
// *LRPja izmenično izvajata akcije (to pomeni, da je na razpolago pol manj korakov za posamezen LRP)
const bool show_full_output = true; //runtime setting
//Game_Engine* game = new Game_ConnectFour();
Game_Engine* game = new Game_Gomoku();
//Game_Engine* game = new Game_TicTacToe();
//Game_Engine* game = new Game_Hex();
Player_AI_UCT_TomTest* optimizingPlayer = new Player_AI_UCT_TomTest();
Player_AI_UCT* opponent = new Player_AI_UCT(game);
Tom_Function_Approximator* funcApp1 = new Tom_Function_Approximator();
funcApp1->Initialize();
funcApp1->num_results = optimizingPlayer->Func_App_UCT_num_params;
funcApp1->Settings_Apply_New();
for(int i = 0; i < funcApp1->num_params; i++)
funcApp1->parameter_weights[i] = funcApp_init_weights;
optimizingPlayer->Func_App_UCT_Params = funcApp1;
optimizingPlayer->game = game;
optimizingPlayer->Initialize();
optimizingPlayer->Output_Log_Level_Create_Headers();
optimizingPlayer->UCT_param_C = start_Cp_self;
optimizingPlayer->RAVE_param_V = start_RAVE_V_self;
////2014_01 Q-Values test: best 11 param LRP search settings ... and ... _2014_02_12 Gomo SARSA+RAVE search 7 par
////setting TOMPLAYER_AI_UCT_TOMTEST_QVALUE_TRACE_GAMMA_TV = 1
//GOMOKU
//optimizingPlayer->UCT_param_C = 0.079;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.395;
//optimizingPlayer->QVALUE_param_alpha = 1.229;
//optimizingPlayer->QVALUE_param_gamma = 1.739;
//optimizingPlayer->QVALUE_param_lambda = 0.125;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.843;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0.132;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 2.023;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = -1.266;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1.540;
//optimizingPlayer->QVALUE_param_initVal = 0.407;
////2014_02 Q-Values test fixed leaf node val
//optimizingPlayer->UCT_param_C = 0.08;
//2014_02_24 Conn4 SARSA+AMAF search 3 par
//connect 4
//optimizingPlayer->UCT_param_C = 0.122;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.141;
//optimizingPlayer->QVALUE_param_alpha = 0.744;
//optimizingPlayer->QVALUE_param_gamma = 1.229;
//optimizingPlayer->QVALUE_param_lambda = 0.466;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.815;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 2.136;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1.099;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = -0.561;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 3.875;
//optimizingPlayer->QVALUE_param_initVal = 1.366;
//-- 2014_03_01 Gomo SARSA+AMAF_EQ3 dimnish params
//set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 3, set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 2, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_ALGORITHM = 3
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
// //search 7
//optimizingPlayer->UCT_param_C = -5.3042;
//optimizingPlayer->AMAF_param_alpha = 0.9169;
//optimizingPlayer->QVALUE_param_scoreWeight = 2.9037;
//optimizingPlayer->QVALUE_param_alpha = 1.229;
//optimizingPlayer->QVALUE_param_gamma = 1.739;
//optimizingPlayer->QVALUE_param_lambda = 0.125;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.843;
// //search 6 - lambda_playOut=1
////optimizingPlayer->QVALUE_param_lambda_playOut = 1.0; //2014_03_01 Gomo SARSA+AMAF_EQ3 dimnish params - search 6
// //search 3
////optimizingPlayer->QVALUE_param_alpha = 0.2;
////optimizingPlayer->QVALUE_param_gamma = 0.99;
////optimizingPlayer->QVALUE_param_lambda = 0.25;
//-- end - 2014_03_01 Gomo SARSA+AMAF_EQ3 dimnish params
//-- 2014_03_01 Conn4 SARSA+AMAF_EQ3 dimnish params
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
// //search 7
//optimizingPlayer->UCT_param_C = 0.150;
//optimizingPlayer->AMAF_param_alpha = -0.792;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.120;
//optimizingPlayer->QVALUE_param_alpha = 0.744;
//optimizingPlayer->QVALUE_param_gamma = 1.229;
//optimizingPlayer->QVALUE_param_lambda = 0.466;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.815;
//-- end - 2014_03_01 Conn4 SARSA+AMAF_EQ3 dimnish params
//-- 2014_03_03 SARSA+AMAF_EQ3 direct search 12 par - configuration
//-- 2014_03_07 SARSA+AMAF_EQ3 single NN by sum_iter - configuration
// //gomoku
//optimizingPlayer->UCT_param_C = -5.7522;
//optimizingPlayer->AMAF_param_alpha = 0.8997;
//optimizingPlayer->QVALUE_param_scoreWeight = 3.5116;
//optimizingPlayer->QVALUE_param_alpha = 0.3124;
//optimizingPlayer->QVALUE_param_gamma = 1.0004;
//optimizingPlayer->QVALUE_param_lambda = 0.6664;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.9129;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
// //connect4
//optimizingPlayer->UCT_param_C = 0.1747;
//optimizingPlayer->AMAF_param_alpha = -0.7338;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.3131;
//optimizingPlayer->QVALUE_param_alpha = 0.7833;
//optimizingPlayer->QVALUE_param_gamma = 1.0839;
//optimizingPlayer->QVALUE_param_lambda = 0.397;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.8754;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//-- end - 2014_03_03 SARSA+AMAF_EQ3 direct search 12 par - configuration
////-- 2014_03_05 SARSA+AMAF_EQ3 TicTacToe search 7 par - configuration
////-- 2014_03_06 MCTSiter op_X self_X direct search par
//optimizingPlayer->UCT_param_C = 0;
//optimizingPlayer->AMAF_param_alpha = 0;
//optimizingPlayer->RAVE_param_V = 0;
//optimizingPlayer->QVALUE_param_scoreWeight = 0;
//optimizingPlayer->QVALUE_param_alpha = 0;
//optimizingPlayer->QVALUE_param_gamma = 0;
//optimizingPlayer->QVALUE_param_lambda = 0;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////-- 2014_03_06 MCTSiter op_X self_X gomo SARSA+AMAF_EQ3 RUN3 direct search par 3 and 3-6
//optimizingPlayer->UCT_param_C = 0.2859;
//optimizingPlayer->AMAF_param_alpha = -1.0040;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.8373;
//optimizingPlayer->QVALUE_param_alpha = 0.3124;
//optimizingPlayer->QVALUE_param_gamma = 1.0004;
//optimizingPlayer->QVALUE_param_lambda = 0.6664;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.9129;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//-- 2014_02_06 SARSA (without AMAF) and fixed leaf and init - search 5 par
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//optimizingPlayer->UCT_param_C = 0.08;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.6203;
//optimizingPlayer->QVALUE_param_alpha = 0.2954;
//optimizingPlayer->QVALUE_param_gamma = 2.3039;
//optimizingPlayer->QVALUE_param_lambda = 0.3282;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.899;
//-- 2014_03_07 SARSA+AMAF_EQ3 single NN by sum_iter Gomo iter1000-1000 RUN2
//funcApp1->parameter_weights[0] = -2.8608;
//funcApp1->parameter_weights[1] = -0.4007;
//funcApp1->parameter_weights[2] = 0.1647;
//funcApp1->parameter_weights[3] = -0.9058;
//funcApp1->parameter_weights[4] = 1.3514;
//funcApp1->parameter_weights[5] = 0.9685;
//funcApp1->parameter_weights[6] = -0.7590;
//funcApp1->parameter_weights[7] = -0.7765;
//funcApp1->parameter_weights[8] = -0.0926;
//-- 2014_03_17 paper table1
////SARSA1+RAVE
//optimizingPlayer->UCT_param_C = 0.0544;
//optimizingPlayer->RAVE_param_V = 35.0;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.7036;
//optimizingPlayer->QVALUE_param_alpha = 0.7209;
//optimizingPlayer->QVALUE_param_gamma = 0.9072;
//optimizingPlayer->QVALUE_param_lambda = 0.6071;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85812;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA2+RAVE
//optimizingPlayer->UCT_param_C = -2.0;
//optimizingPlayer->RAVE_param_V = 35.0;
//optimizingPlayer->QVALUE_param_scoreWeight = 2.0;
//optimizingPlayer->QVALUE_param_alpha = 0.3124;
//optimizingPlayer->QVALUE_param_gamma = 1.0004;
//optimizingPlayer->QVALUE_param_lambda = 0.6664;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.9129;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//funcApp1->parameter_weights[0] = 0.0;
//funcApp1->parameter_weights[1] = 1.5;
//funcApp1->parameter_weights[2] = 3;
////UCT+AMAF_EQ3
//optimizingPlayer->UCT_param_C = 0.10;
//optimizingPlayer->AMAF_param_alpha = 0.80;
////SARSA gamma 0
////set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_TRACE_GAMMA_TV 0
//optimizingPlayer->UCT_param_C = 0.0544;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.7036;
//optimizingPlayer->QVALUE_param_alpha = 0.7209;
//optimizingPlayer->QVALUE_param_gamma = 0.0;
//optimizingPlayer->QVALUE_param_lambda = 0.55;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85812;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT gamma 1 (and QleafVal)
////set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_TRACE_GAMMA_TV 1
//optimizingPlayer->UCT_param_C = 0.04234;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 1.0;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.7329;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT gamma 1 run2 (and variants)
//optimizingPlayer->UCT_param_C = 0.0227;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.6206;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85856;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//funcApp1->parameter_weights[0] = 0.1761;
//funcApp1->parameter_weights[1] = -0.0136;
//funcApp1->parameter_weights[2] = 0.1234;
////SARSA-CORRECT + AMAF_EQ3
//optimizingPlayer->UCT_param_C = -2.0;
//optimizingPlayer->AMAF_param_alpha = 0.8997;
//optimizingPlayer->QVALUE_param_scoreWeight = 2.0;
////optimizingPlayer->QVALUE_param_alpha = 1.0; //search 5 params
//optimizingPlayer->QVALUE_param_alpha = 0.3124; //search 6 params
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.6206;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85856;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT run3 (and same-lambda)
//optimizingPlayer->UCT_param_C = 0.025;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.62;
////optimizingPlayer->QVALUE_param_lambda = 0.90; //version: SAME LAMBDA
////optimizingPlayer->QVALUE_param_lambda = 1.0; //version: LAM=1
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.90;
////optimizingPlayer->QVALUE_param_lambda_playOut = 1.00; //version: LAMply=1
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT run4 - individual parameters
//optimizingPlayer->UCT_param_C = 0.03584;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.88836;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.88836;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT run5 - individual parameters
//optimizingPlayer->UCT_param_C = 0.04944;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.7943;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.8853;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.8853;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////funcApp1->parameter_weights[0] = -0.1694;
////funcApp1->parameter_weights[1] = -0.0433;
////funcApp1->parameter_weights[3] = -0.9036;
////funcApp1->parameter_weights[4] = -0.9036;
////SARSA-CORRECT run5-1 - variant1
//optimizingPlayer->UCT_param_C = 0.01556;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.78564;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.70458;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.70458;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//////SARSA-CORRECT run5+AMAF_EQ3 - individual parameters
//optimizingPlayer->UCT_param_C = -2.0;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.5;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.8853;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.8853;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//optimizingPlayer->AMAF_param_alpha = 0.80;
//optimizingPlayer->RAVE_param_V = 35.0;
//funcApp1->parameter_weights[0] = -4.0;
//SARSA-CORRECT run5 - individual parameters
//optimizingPlayer->UCT_param_C = 0.04944;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.7943;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.8853;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.8853;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////funcApp1->parameter_weights[0] = -2.0;
////funcApp1->parameter_weights[1] = 0.25;
////optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT run6
//optimizingPlayer->UCT_param_C = 0.04944;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.7943;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.62392;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.8764;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT run7+AMAF3 (or RAVE)
//optimizingPlayer->UCT_param_C = -5.0;
//optimizingPlayer->QVALUE_param_scoreWeight = 2.0;
//optimizingPlayer->QVALUE_param_alpha = 0.5;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.58;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//optimizingPlayer->AMAF_param_alpha = 0.90;
//optimizingPlayer->RAVE_param_V = 35.0;
////optimizingPlayer->QVALUE_param_initVal = 0.0; //RUN 7-1 translated0.5
////funcApp1->parameter_weights[0] = 0.5;
////funcApp1->parameter_weights[1] = 0.15;
////funcApp1->parameter_weights[2] = 0.5;
////funcApp1->parameter_weights[3] = -0.25;
////TDfourth run1 QleafVal
//optimizingPlayer->UCT_param_C = 0.0191;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
//optimizingPlayer->QVALUE_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_gamma = 0.854;
//optimizingPlayer->QVALUE_param_lambda = 1.0;
////optimizingPlayer->QVALUE_param_lambda = 0.584;
//optimizingPlayer->QVALUE_param_initVal = 0.0;
//funcApp1->parameter_weights[0] = 0.15;
//funcApp1->parameter_weights[1] = 0.06;
////TDfourth - TDmin (WR) + AMAF3 (2014_04_28 paper T1 TDfourth TD-UCT WR + aAMAF2)
//double TD_leaf_state_value = currentNode->Q_value;;
//MC_value = set_QVALUE_param_scoreWeight*(child->Q_value+0.5) + set_MC_weight*(MC_value); //TDfourth
optimizingPlayer->UCT_param_C = 0.052;
optimizingPlayer->AMAF_param_alpha = 0.90;
optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
optimizingPlayer->QVALUE_param_alpha = 1.0;
optimizingPlayer->QVALUE_param_gamma = 0.877;
optimizingPlayer->QVALUE_param_lambda = 1.0;
optimizingPlayer->QVALUE_param_initVal = 0.0;
//-- 2014_03_11 paper optimizations F3, F4 and T2 (different games)
//////UCB, RAVE
//optimizingPlayer->UCT_param_C = 0.0;
//optimizingPlayer->RAVE_param_V = 0.0;
//funcApp1->parameter_weights[0] = -0.16;
//funcApp1->parameter_weights[1] = 0.13;
//////SARSA
//optimizingPlayer->UCT_param_C = 0.0544;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.7036;
//optimizingPlayer->QVALUE_param_alpha = 0.7209;
//optimizingPlayer->QVALUE_param_gamma = 0.9072;
//optimizingPlayer->QVALUE_param_lambda = 0.6071;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85812;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//funcApp1->parameter_weights[0] = 0.07;
//funcApp1->parameter_weights[1] = 0.25;
//funcApp1->parameter_weights[2] = 0.23;
//funcApp1->parameter_weights[3] = 0.35;
//funcApp1->parameter_weights[4] = -0.1;
////////SARSA gomoku19x19 8000-2000 (run2)
//optimizingPlayer->UCT_param_C = 0.7043;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.9658;
//optimizingPlayer->QVALUE_param_alpha = 0.7209;
//optimizingPlayer->QVALUE_param_gamma = 0.9072;
//optimizingPlayer->QVALUE_param_lambda = 0.6071;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85812;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////funcApp1->parameter_weights[0] = 0.07;
////funcApp1->parameter_weights[1] = 0.25;
////funcApp1->parameter_weights[2] = 0.23;
////funcApp1->parameter_weights[3] = 0.35;
////funcApp1->parameter_weights[4] = -0.1;
//////SARSA+AMAF
//optimizingPlayer->UCT_param_C = -2.0;
//optimizingPlayer->AMAF_param_alpha = 0.8997;
////optimizingPlayer->AMAF_param_alpha = 1.0;
//optimizingPlayer->QVALUE_param_scoreWeight = 2.0;
//optimizingPlayer->QVALUE_param_alpha = 0.3124;
//optimizingPlayer->QVALUE_param_gamma = 1.000;
//optimizingPlayer->QVALUE_param_lambda = 0.6664;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.9129;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//funcApp1->parameter_weights[0] = -3.309;
//funcApp1->parameter_weights[1] = -2;
//funcApp1->parameter_weights[2] = -1.7102;
//funcApp1->parameter_weights[3] = 0.0;
//funcApp1->parameter_weights[4] = 0.0;
//funcApp1->parameter_weights[5] = 0.0;
////////SARSA (Hex7x7 run2)
//optimizingPlayer->UCT_param_C = 0.13;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.3242;
//optimizingPlayer->QVALUE_param_alpha = 0.1563;
//optimizingPlayer->QVALUE_param_gamma = 1.000;
//optimizingPlayer->QVALUE_param_lambda = 0.63945;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.91768;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//////SARSA+AMAF (Hex7x7 run2)
//optimizingPlayer->UCT_param_C = -2.8378;
//optimizingPlayer->AMAF_param_alpha = 0.8253;
//optimizingPlayer->QVALUE_param_scoreWeight = 0.9124;
//optimizingPlayer->QVALUE_param_alpha = 0.2401;
//optimizingPlayer->QVALUE_param_gamma = 1.000;
//optimizingPlayer->QVALUE_param_lambda = 0.7627;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.9465;
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//-- end- 2014_03_11 paper optimizations F3, F4 and T2 (different games)
////SARSA-third test1
//optimizingPlayer->UCT_param_C = 0.05;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
//optimizingPlayer->QVALUE_param_alpha = 0.2;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 1.0;
//optimizingPlayer->QVALUE_param_initVal = 0.0;
//// SARSA(lambda) two + AMAF
//optimizingPlayer->QVALUE_param_leaf_node_val0 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val1 = 1;
//optimizingPlayer->QVALUE_param_leaf_node_val2 = 0;
//optimizingPlayer->QVALUE_param_leaf_node_val3 = 1;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
//optimizingPlayer->UCT_param_C = -5.75;
//optimizingPlayer->AMAF_param_alpha = 0.90;
//optimizingPlayer->QVALUE_param_scoreWeight = 3.51;
//optimizingPlayer->QVALUE_param_alpha = 0.3124;
//optimizingPlayer->QVALUE_param_gamma = 0.9129;
//optimizingPlayer->QVALUE_param_lambda = 0.730;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.9129;
//-------- end of settings -------- //
bool silence_output = ((score_avg != NULL)||(score_avg_last10 != NULL)||(last_param_val != NULL));
//apply settings and initialize structurs
optimizingPlayer->UCT_param_IterNum = num_iterations_self;
opponent->UCT_param_IterNum = num_iterations_opponent;
opponent->UCT_param_C = fixed_CP_opponent;
Player_Engine* players[2];
players[eval_player_position] = optimizingPlayer;
players[1-eval_player_position] = opponent;
Tom_Lrp* Lrp = new Tom_Lrp();
Lrp->Initialize();
Lrp->num_actions = funcApp1->num_actions;
Lrp->Settings_Apply_New();
Lrp->Evaluations_History_Allocate(num_LRP_iterations+1, funcApp1->num_params);
//results storage
Tom_Sample_Storage<double>* score_history = new Tom_Sample_Storage<double>(num_LRP_iterations+1);
srand((unsigned int)time(NULL));
double cpu_time = getCPUTime();
double cpu_time1;
//calculate exponential time constant
double dw_tau = (double) num_LRP_iterations / (log(dw_start/dw_limit));
//output test settings
if((!silence_output)||(force_setting_output)){
gmp->Print("LRP_improved_v1()\n");
gmp->Print("%s %dx%d\n",game->game_name.c_str(),game->board_length,game->board_height);
gmp->Print("Players: "); for(int i = 0; i < 2; i++) gmp->Print("%s \t",players[i]->player_name.c_str()); gmp->Print("\n");
gmp->Print("Evaluated_player %d sim %d start_Cp %1.3f par_w_init %1.3f\n",eval_player_position+1, num_iterations_self, start_Cp_self, funcApp_init_weights);
gmp->Print("Opponent_player %d sim %d fixed_Cp %3.3f\n",2-eval_player_position, num_iterations_opponent, fixed_CP_opponent);
gmp->Print("LRP_steps %5d games %d %d\n",num_LRP_iterations, num_games_start, num_games_end);
gmp->Print("LRP_restart %4d restart_threshold %5.3f %5.3f\n",LRP_restart_condition_iterations, LRP_restart_condition_score_rel_diff, LRP_restart_condition_score_rel_diff_end);
gmp->Print("kNN %2d central_weight %3.1f weight_repeats %d\n",LRP_best_neighbours_num,LRP_best_neighbour_weight_central, (int)KNN_weight_repeats);
gmp->Print("enable_output_best_kNN %d final_eval_games %d\n", (int)LRP_output_best_kNN, final_evaluation_num_games);
gmp->Print("Score_conf_test %4.2f\n",lrp_score_diff_conf_factor);
gmp->Print("Games_by_conf_fact %3.1f %3.1f\n",min_increase_num_games_fact,max_increase_num_games_fact);
gmp->Print("LRP_ab_by_conf %d LRP_dw_by_conf %d\n",(int)LRP_change_AB_by_confidence,(int)LRP_change_DW_by_confidence);
gmp->Print("LRP_ab_min %1.3f LRP_ab_max %1.3f LRP_b_koef %1.3f\n", lrp_ab_min, lrp_ab_max, lrp_b_koef);
gmp->Print("lrp_ab_dscore_min %1.3f lrp_ab_dscore_max %1.3f\n", lrp_ab_dscore_min, lrp_ab_dscore_max);
gmp->Print("Use_linear_dw_decrease %d dw %1.5f %1.5f dw_tau %1.5f\n", (int)(!exp_dw_decrease), dw_start, dw_limit, dw_tau);
gmp->Print("Evaluated_player: RAVE_scheme %d start_RAVE_V %4.1f\n", TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME, start_RAVE_V_self);
gmp->Print("AMAF_EQUATION_TYPE %d PARAM_FUNC_APP_TYPE %d Nnet I %d O %d H %d F %d\n", TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE, TOMPLAYER_AI_UCT_TOMTEST_PARAM_FUNC_APP_TYPE, TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_INPUTS, TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_OUTPUTS, TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_HIDD_LAYER, TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NEURAL_FUNC);
gmp->Print("QVALUE_EQUATION_TYPE %d QVALUE_ALGORITHM %d TRACE_GAMMA S%d T%d\n", TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_ALGORITHM, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_TRACE_GAMMA_SV, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_TRACE_GAMMA_TV);
gmp->Print("\n");
}
//--- LRP algorithm ---//
double score, previous_score, score_tmp, final_score;
int num_LRP_batch_iterations, num_games_tmp;
int selected_action;
int index_best_setting;
int count_restarts, count_restart_checks;
double confidence_normal_dist1;
double confidence_normal_dist2;
double confidence_num_games1, confidence_num_games2;
int total_games_count;
double dw = dw_start;
double lrp_ab = 0.0;
int num_games = num_games_start;
//evaluate starting setting
score = game->Evaluate_Players(1,num_games,-1,players,false,eval_player_position) / num_games;
score_history->Add_Sample(score);
Lrp->Evaluations_History_Add_Sample(-1, num_games, score, 0.0, funcApp1->parameter_weights);
total_games_count = num_games;
//int best_iteration = -1;
//double best_score = score;
//double best_paramC = start_c1;
if(!silence_output){
if(show_full_output){
gmp->Print(" \t \t Parameters");
}
gmp->Print("\ni \t score");
for(int p = 0; p < funcApp1->num_params; p++)
gmp->Print("\t P%d",p);
if(show_full_output){
gmp->Print(" \t\t action");
for(int a = 0; a < Lrp->num_actions; a++)
gmp->Print("\t A%d[%%]",a);
gmp->Print("\t dw \t\t lrp_ab");
gmp->Print("\t Games");
gmp->Print("\t NormDistConf");
}
gmp->Print("\n%d \t%5.1f%",0,score*100);
for(int p = 0; p < funcApp1->num_params; p++)
gmp->Print("\t%6.3f",funcApp1->parameter_weights[p]);
if(show_full_output){
gmp->Print(" \t\t ");
gmp->Print("//");
Lrp->Debug_Display_Probabilites(0);
gmp->Print(" \t %1.5f \t %1.3f",dw, lrp_ab);
gmp->Print(" \t %4d",num_games);
}
gmp->Print("\n");
}
//debug
//double debug_scores[num_LRP_iterations] = {0.1 , 0.2 , 0.3 , 0.4 , 0.5};
//srand(0);
//Lrp iterations
num_LRP_batch_iterations = 0;
count_restarts = 0;
count_restart_checks = 0;
for(int i = 0; i < num_LRP_iterations; i++){
if(exp_dw_decrease){
//exponential iterative decrease of weight change step
dw = dw_start * exp(-i/dw_tau);
}else{
//linear iterative decrease of weight change step
dw = dw_limit + (dw_start - dw_limit) * (1.0 - (double)i/(num_LRP_iterations-1));
}
//increase number of games per evalation
num_games = (int)((num_games_start + (num_games_end - num_games_start) * ((double)(i+1)/num_LRP_iterations)) + 0.5);
//Lrp select action
selected_action = Lrp->Select_Action(TOM_LRP_SELECT_ACTION_CHECK_SUM);
//apply action
//if(selected_action == Lrp->num_actions-1){
// funcApp1->parameter_weights[0] = 0.2;
//}else{
// funcApp1->parameter_weights[0] = -0.5;
//}
funcApp1->Action_Update_Weights(selected_action, dw);
//optimizingPlayer->UCT_param_C = funcApp1->parameter_weights[0];
//evaluate new setting and save scores
previous_score = score; //save previous score
score = game->Evaluate_Players(1,num_games,-1,players,false,eval_player_position) / num_games;
//-- statistical difference test --//
int stat_run_once = 0;
while(stat_run_once < 2){
//calculate the confidence, that the last two scores belong to different normal distributions
confidence_normal_dist1 =
sqrt(
(Lrp->evaluations_history[Lrp->evaluations_history_num_samples-1].num_repeats)
* (score - previous_score) * (score - previous_score)
/ (previous_score * (1-previous_score) + 0.00001) // + 0.00001 only to avoid division by 0
/ 2.0 //optional
);
//calculate the confidence, that the last two scores belong to different normal distributions
confidence_normal_dist2 =
sqrt(
(num_games)
* (score - previous_score) * (score - previous_score)
/ (score * (1-score) + 0.00001) // + 0.00001 only to avoid division by 0
/ 2.0 //optional
);
confidence_num_games1 = lrp_score_diff_conf_factor*lrp_score_diff_conf_factor*(previous_score * (1-previous_score)) * 2.0 / ((score - previous_score) * (score - previous_score) + 0.00001);
confidence_num_games2 = lrp_score_diff_conf_factor*lrp_score_diff_conf_factor*(score * (1-score)) * 2.0 / ((score - previous_score) * (score - previous_score) + 0.00001);
//re-evaluate with higher number of games if confidence below threshold (lrp_score_diff_conf_factor)
num_games_tmp = (int)(((max_increase_num_games_fact-1.0)*num_games) * (1.0 - min(1.0, max(confidence_normal_dist1, confidence_normal_dist2) / lrp_score_diff_conf_factor)));
if((num_games_tmp > 0) && (stat_run_once == 0)){ //if confidence below threshold, then repeat player evaluation with higher number of games
num_games_tmp = (int)max(num_games_tmp, num_games*(min_increase_num_games_fact - 1.0)); //set number of additional games minimum to increase_num_games_thr
score_tmp = game->Evaluate_Players(1,num_games_tmp,-1,players,false,eval_player_position) / num_games_tmp; //perform additional evaluations
score = (score_tmp*num_games_tmp + score*num_games) / (num_games_tmp + num_games); //update score
num_games += num_games_tmp; //update number of evaluation games
stat_run_once = 1; //repeat statistical test
}else{
stat_run_once = 2; //do not repeat statistical test
}
}
//-- END - statistical difference test --//
score_history->Add_Sample(score);
Lrp->Evaluations_History_Add_Sample(selected_action, num_games, score, 0.0, funcApp1->parameter_weights);
total_games_count += num_games;
//score = debug_scores[i]; //DEBUG
if(!silence_output){
gmp->Print("%d \t%5.1f%",i+1,score*100);
for(int p = 0; p < funcApp1->num_params; p++)
gmp->Print("\t%6.3f",funcApp1->parameter_weights[p]);
gmp->Print(" \t\t ");
}
//-- adaptively change LRP learning parameter alpha (and beta) --//
//proportional to confidence between scores
if(LRP_change_AB_by_confidence){
lrp_ab = max(lrp_ab_min, lrp_ab_max * min(1.0 , max(confidence_normal_dist1, confidence_normal_dist2) / lrp_score_diff_conf_factor));
//inverse, for testing only - should perform worse //lrp_ab = lrp_ab_min + lrp_ab_max - max(lrp_ab_min, lrp_ab_max * min(1.0 , max(confidence_normal_dist1, confidence_normal_dist2) / 1.96));
//linearly proportional lrp learning parameter
}else{
lrp_ab =
lrp_ab_min + (lrp_ab_max - lrp_ab_min) * max(0.0 , min(1.0 ,
(abs(score-previous_score) - lrp_ab_dscore_min) / (lrp_ab_dscore_max - lrp_ab_dscore_min)
));
}
Lrp->learn_param_a = lrp_ab;
Lrp->learn_param_b = lrp_ab * lrp_b_koef;
//-- END - adaptively change LRP learning parameter alpha (and beta) --//
//Lrp correct probabilites based on previous and current score
if(score > previous_score){
Lrp->Update_Probabilites_Reward(selected_action,Lrp->learn_param_a);
if(!silence_output) if(show_full_output) gmp->Print("+");
}else{
Lrp->Update_Probabilites_Penalty(selected_action,Lrp->learn_param_b);
if(!silence_output) if(show_full_output) gmp->Print("-");
}
//output
if(!silence_output){
if(show_full_output){
gmp->Print("%d",selected_action);
Lrp->Debug_Display_Probabilites(0);
gmp->Print(" \t %1.5f \t %1.3f",dw, lrp_ab);
gmp->Print(" \t %4d",num_games);
gmp->Print(" \t %5.2f %5.2f %4.0f %4.0f",confidence_normal_dist1, confidence_normal_dist2, confidence_num_games1, confidence_num_games2);
}
}
//remember best
//if(score >= best_score){
// best_iteration = i;
// best_score = score;
// best_paramC = playerUCT1->UCT_param_C;
//}
//Restart from best position periodically after LRP_restart_condition_iterations iterations
num_LRP_batch_iterations++;
if( (LRP_restart_condition_iterations > 0) && (num_LRP_batch_iterations >= LRP_restart_condition_iterations) ){
//calculate kNN scores and find best parameter setting
index_best_setting = Lrp->Evaluations_History_Best_KNN_Average_Slow(LRP_best_neighbours_num, KNN_weight_repeats, LRP_best_neighbour_weight_central, false, 0);
//check difference between scores of last sample (current state) and best score, threshold decreases linearly (by increasing number of iterations, it is more likely to restart from best position)
double last_sample_score = Lrp->evaluations_history[(Lrp->evaluations_history_num_samples)-1].kNN_score;
double best_sample_score = Lrp->evaluations_history[index_best_setting].kNN_score;
double current_score_ratio;
if(best_sample_score != 0.0) //division safety
current_score_ratio = 1.0 - last_sample_score/best_sample_score;
else
current_score_ratio = 0.0;
double restart_threshold = LRP_restart_condition_score_rel_diff_end + (LRP_restart_condition_score_rel_diff-LRP_restart_condition_score_rel_diff_end) * (1.0 - (double)i/(num_LRP_iterations-1));
//DEBUG
//gmp->Print("\n"); Lrp->Debug_Display_Evaluations_History();
//gmp->Print("\t %d %f %d %f\t",index_best_setting, best_sample_score, (Lrp->evaluations_history_num_samples)-1, last_sample_score);
if( current_score_ratio >= restart_threshold ){
if(!silence_output){
gmp->Print(" \t RESTART %3.3f", current_score_ratio );
}
//--do execute restart from best position--
//reset LRP probabilites
Lrp->State_Reset();
//set parameter values to best combination found so far
for(int p = 0; p < funcApp1->num_params; p++)
funcApp1->parameter_weights[p] = Lrp->evaluations_history[index_best_setting].param_values[p];
//set appropriate score to compare in next iteration
score = Lrp->evaluations_history[index_best_setting].score;
//increase counter of restarts
count_restarts++;
}else{
if(!silence_output){
gmp->Print(" \t CHECK %3.3f", current_score_ratio );
}
}
num_LRP_batch_iterations = 0;
count_restart_checks++;
}
if(!silence_output){
gmp->Print("\n");
}
}
//output best parameter combination from history instead of values in last iteration
if(LRP_output_best_kNN){
index_best_setting = Lrp->Evaluations_History_Best_KNN_Average_Slow(LRP_best_neighbours_num, KNN_weight_repeats, LRP_best_neighbour_weight_central, false, 0);
for(int p = 0; p < funcApp1->num_params; p++)
funcApp1->parameter_weights[p] = Lrp->evaluations_history[index_best_setting].param_values[p];
}
//--- LRP algorithm END---//
cpu_time = getCPUTime()-cpu_time;
//evaluation of final parameters
optimizingPlayer->UCT_param_IterNum = final_evaluation_num_iterations_self;
opponent->UCT_param_IterNum = final_evaluation_num_iterations_opponent;
players[final_eval_player_position] = optimizingPlayer;
players[1-final_eval_player_position] = opponent;
cpu_time1 = getCPUTime();
final_score = game->Evaluate_Players(1,final_evaluation_num_games,-1,players,false,eval_player_position) / final_evaluation_num_games;
cpu_time1 = getCPUTime()-cpu_time;
//output best
//gmp->Print("\nBest score: %5.1f% \t P1->Cp %5.3f \t i %d\n", best_score*100, best_paramC, best_iteration+1);
//output values
score_history->Calc_AvgDev();
double score10 = score_history->Calc_Avg_On_Interval((int)(num_LRP_iterations*0.9), num_LRP_iterations);
if(!silence_output){
double final_eval_dev = sqrt(1.96*1.96*final_score*(1-final_score)*2.0 / final_evaluation_num_games);
//Lrp output (best parameters value)
gmp->Print("\n");
//Lrp->Debug_Display_Evaluations_History(); //output LRP evaluations history
Lrp->Evaluations_History_Best_Single();
Lrp->Evaluations_History_Best_KNN_Average_Slow(LRP_best_neighbours_num, true, LRP_best_neighbour_weight_central, false);
//Statistics and final evaluation
gmp->Print("\navgGam \t avg100\t avg10 \t fEval",final_evaluation_num_games);
for(int p = 0; p < funcApp1->num_params; p++)
gmp->Print("\t FinP%d",p);
gmp->Print("\t fEvaConf95");
gmp->Print("\n%6.1f \t %5.2f \t %5.2f \t %5.2f", (double)total_games_count / (num_LRP_iterations+1), score_history->avg*100, score10*100, final_score*100);
for(int p = 0; p < funcApp1->num_params; p++)
gmp->Print("\t%7.4f",funcApp1->parameter_weights[p]);
gmp->Print("\t %5.2f",final_eval_dev*100);
//runtime
gmp->Print("\n\nRuntime [s]:\n Lrp\t%9.3f\n Eval\t%9.3f (%d games)\n Total\t%9.3f\n", cpu_time, cpu_time1, final_evaluation_num_games, cpu_time+cpu_time1);
}
//DEBUG
//gmp->Print("RR: %5.2f%% \t ",(double)count_restarts/count_restart_checks*100.0); //output restart rate
//gmp->Print("ratio p0: %3.3f\n",optimizingPlayer->debug_dbl_cnt1 / optimizingPlayer->debug_dbl_cnt2 *100.0); //2-interval C search ratio of use p0 to (p0+p1)
//return values
if(score_avg != NULL)
(*score_avg) = score_history->Calc_Avg();
if(last_param_val != NULL)
for(int i = 0; i < funcApp1->num_params; i++)
(*last_param_val)[i] = funcApp1->parameter_weights[i];
if(score_avg_last10 != NULL)
(*score_avg_last10) = score_history->Calc_Avg_On_Interval((int)(num_LRP_iterations*0.9), num_LRP_iterations);
if(avg_num_games != NULL)
(*avg_num_games) = (double)total_games_count / (num_LRP_iterations + 1);
if(final_eval_score != NULL)
(*final_eval_score) = final_score;
gmp->Flush();
//free memory
delete(score_history);
delete(Lrp);
delete(optimizingPlayer);
delete(opponent);
delete(game);
}
void LRP_test_wrapperMultiPar()
{
const int num_repeats = 100; //number of LRP repeats (not STEPS!)
const int num_LRP_params = TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_PARAMS; //the number of weights set by LRP
const int num_final_evaluations = 20000; //number of games to evaluate final combination of parameters (default 750)
//20000, 95% confidence that true value deviates less by 1%
//5000, 95% confidence that true value deviates less by 2%
//1200, 95% confidence that true value deviates less by 4%
//750, 95% confidence that true value deviates less by 5%
//200, 95% confidence that true value deviates less by 10%
// --- settings end --- //
double score_avg;
double score_avg_last10;
double* last_param_val = new double[num_LRP_params];
double avg_num_games;
double final_eval_score;
bool output_settings_once = true;
double cpu_time = getCPUTime();
Tom_Sample_Storage<double>* avg_score = new Tom_Sample_Storage<double>(num_repeats);
Tom_Sample_Storage<double>* avg_score10 = new Tom_Sample_Storage<double>(num_repeats);
Tom_Sample_Storage<double>* last_param[num_LRP_params];
for(int p = 0; p < num_LRP_params; p++)
last_param[p] = new Tom_Sample_Storage<double>(num_repeats);
Tom_Sample_Storage<double>* final_score = new Tom_Sample_Storage<double>(num_repeats);
Tom_Sample_Storage<double>* num_games_per_step = new Tom_Sample_Storage<double>(num_repeats);
gmp->Print("LRP_test_wrapperMultiPar(), %d repeats %d params\n\n", num_repeats, num_LRP_params);
for(int r = 0; r < num_repeats; r++){
//LRP_test_linAB_exponentDW_FunApp_MulParams(&score_avg,&score_avg_last10,&last_param_val,output_settings_once,num_LRP_params);
LRP_improved_v1(&score_avg,&score_avg_last10,&last_param_val,output_settings_once,num_final_evaluations,&avg_num_games,&final_eval_score);
if(output_settings_once){
gmp->Print("\nRun avg [%%] [%%] [%%] Final_params\n");
gmp->Print(" games scr100 scr10 final "); for(int p = 0; p < num_LRP_params; p++) gmp->Print("P%d ",p); gmp->Print("\n");
}
gmp->Print("%3d %6.1f %6.2f %6.2f %6.2f ",r,avg_num_games,score_avg*100,score_avg_last10*100,final_eval_score*100); for(int p = 0; p < num_LRP_params; p++) gmp->Print("%7.4f ",last_param_val[p]); gmp->Print("\n");
avg_score->Add_Sample(score_avg);
avg_score10->Add_Sample(score_avg_last10);
for(int p = 0; p < num_LRP_params; p++)
last_param[p]->Add_Sample(last_param_val[p]);
final_score->Add_Sample(final_eval_score);
num_games_per_step->Add_Sample(avg_num_games);
output_settings_once = false;
gmp->Flush();
}
avg_score->Calc_AllExceptSum();
avg_score10->Calc_AllExceptSum();
for(int p = 0; p < num_LRP_params; p++){
last_param[p]->Calc_AllExceptSum();
}
final_score->Calc_AllExceptSum();
num_games_per_step->Calc_AllExceptSum();
gmp->Print("\n\n");
gmp->Print("Summary avg [%%] [%%] [%%] Final_params\n");
gmp->Print(" games scr100 scr10 final "); for(int p = 0; p < num_LRP_params; p++) gmp->Print("P%d ",p); gmp->Print("\n");
gmp->Print("avg %6.1f %6.2f %6.2f %6.2f ", num_games_per_step->avg, avg_score->avg*100, avg_score10->avg*100, final_score->avg*100); for(int p = 0; p < num_LRP_params; p++) gmp->Print("%7.4f ", last_param[p]->avg); gmp->Print("\n");
gmp->Print("dev %6.1f %6.2f %6.2f %6.2f ", num_games_per_step->dev, avg_score->dev*100, avg_score10->dev*100, final_score->dev*100); for(int p = 0; p < num_LRP_params; p++) gmp->Print("%7.4f ", last_param[p]->dev); gmp->Print("\n");
gmp->Print("conf %6.1f %6.2f %6.2f %6.2f ", num_games_per_step->conf, avg_score->conf*100, avg_score10->conf*100, final_score->conf*100); for(int p = 0; p < num_LRP_params; p++) gmp->Print("%7.4f ", last_param[p]->conf); gmp->Print("\n");
gmp->Print("median %6.1f %6.2f %6.2f %6.2f ", num_games_per_step->median, avg_score->median*100, avg_score10->median*100, final_score->median*100); for(int p = 0; p < num_LRP_params; p++) gmp->Print("%7.4f ", last_param[p]->median); gmp->Print("\n");
cpu_time = getCPUTime()-cpu_time;
gmp->Print("\n\nTotalRuntime: %9.3f s\n", cpu_time);
gmp->Flush();
delete[] last_param_val;
delete(avg_score);
delete(avg_score10);
for(int p = 0; p < num_LRP_params; p++)
delete(last_param[p]);
}
void Fixed_Play_Testing(double input_param1, double input_param2)
{
//--- SET GAME AND PLAYERS HERE ---//
//Game_Engine* game = new Game_ConnectFour();
Game_Engine* game = new Game_Gomoku();
//Game_Engine* game = new Game_TicTacToe();
//Game_Engine* game = new Game_Hex();
////variable board size
//if(input_param1 > 0){
// game->board_length = (int)input_param1;
// game->board_height = (int)input_param1;
// game->board_size = game->board_length * game->board_height;
// game->maximum_allowed_moves = game->board_size;
// game->maximum_plys = game->board_size;
// game->Settings_Apply_Changes();
//}
Player_Engine* players[2];
Player_AI_UCT* opponent = new Player_AI_UCT(game);
//Player_AI_UCT_RAVE* opponent = new Player_AI_UCT_RAVE(game);
Player_AI_UCT* benchmarkOpponent = new Player_AI_UCT(game);
Player_AI_UCT_TomTest* evaluated = new Player_AI_UCT_TomTest();
Player_AI_UCT_TomTest* benchmarkEvaluated = new Player_AI_UCT_TomTest();
//--- pre-init (no need to change this) ---//
Tom_Function_Approximator* funcApp1 = new Tom_Function_Approximator();
funcApp1->Initialize();
funcApp1->num_results = TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_PARAMS;
funcApp1->Settings_Apply_New();
evaluated->Func_App_UCT_Params = funcApp1;
evaluated->game = game;
benchmarkEvaluated->Func_App_UCT_Params = funcApp1;
benchmarkEvaluated->game = game;
evaluated->Initialize();
benchmarkEvaluated->Initialize();
evaluated->Output_Log_Level_Create_Headers();
//--- SET BENCHMARK PARAMETERS HERE ---//
int repeats = 5000;
//1000000, 95% confidence that true value deviates less by 0.1%
//200000, 95% confidence that true value deviates less by 0.3%
//20000, 95% confidence that true value deviates less by 1%
//5000, 95% confidence that true value deviates less by 2%
//1200, 95% confidence that true value deviates less by 4%
int eval_player_position = 1; //which player to test: 0 or 1; works only for two-player games
int benchmark_same_player = 0;
//0 - disabled (default)
//1 - benchmark "opponent" vs "opponent"
//2 - benchmark "evaluated" vs "evaluated"
int human_opponent_override = 0;
//0 - disabled (default)
//1 - replace opponent AI player with human input and output game state after every move
int display_output_game = 0; //display single output game regardless of human or AI opponent
int measure_time_per_move = 0; //output time per move for each player at end of evaluation procedure
int output_interval_repeats = (int)(sqrt(repeats)); //output interval of average values from evaluation function (0 = disabled)
//int output_interval_repeats = 0;
//--- SET PLAYERS PARAMETERS HERE ---//
//opponent->UCT_param_IterNum = (int)input_param1;
opponent->UCT_param_IterNum = 100;
opponent->UCT_param_C = 0.2;//0.5/sqrt(2);
//opponent->UCT_param_C = -0.08;
//opponent->RAVE_param_V = 37;
//evaluated->UCT_param_IterNum = (int)input_param1;
//evaluated->UCT_param_IterNum = (int)input_param2;
evaluated->UCT_param_IterNum = 100;
evaluated->UCT_param_C = 0.2;//0.5/sqrt(2);
evaluated->AMAF_param_alpha = 1.0;
//evaluated->RAVE_param_V = 35;
//evaluated->UCT_param_C = -5.7522;
//2014_01 Q-Values test: best 11 param LRP search settings (TOMPLAYER_AI_UCT_TOMTEST_QVALUE_TRACE_GAMMA_TV = 1)
//GOMOKU
//evaluated->UCT_param_C = 0.079;
//evaluated->QVALUE_param_scoreWeight = 0.395;
//evaluated->QVALUE_param_alpha = 1.229;
//evaluated->QVALUE_param_gamma = 1.739;
//evaluated->QVALUE_param_lambda = 0.125;
//evaluated->QVALUE_param_lambda_playOut = 0.843;
//evaluated->QVALUE_param_leaf_node_val0 = 0.132;
//evaluated->QVALUE_param_leaf_node_val1 = 2.023;
//evaluated->QVALUE_param_leaf_node_val2 = -1.266;
//evaluated->QVALUE_param_leaf_node_val3 = 1.540;
//evaluated->QVALUE_param_initVal = 0.407;
//-- 2014_02_19 eval 1M Gomoku comparison best --//
//-- 2014_03_11 paper -//
//evaluated->UCT_param_C = 0.04; //TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 0, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 0
////
//evaluated->UCT_param_C = -0.08;
//evaluated->RAVE_param_V = 37.0; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 1, TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME = 1, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 0
//evaluated->UCT_param_C = 0.07;
//evaluated->AMAF_param_alpha = 0.43; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 3, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 0
//evaluated->AMAF_param_alpha = -1.5; //set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 2, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_ALGORITHM = 3
//evaluated->QVALUE_param_scoreWeight = 0.6;
//evaluated->AMAF_param_alpha = -1.75; //set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 2, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_ALGORITHM = 3
//evaluated->UCT_param_C = -5.3042; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 3, set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 2, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_ALGORITHM = 3
//evaluated->QVALUE_param_scoreWeight = 2.9037;
//evaluated->AMAF_param_alpha = 0.9169;
//CONNECT4
//evaluated->UCT_param_C = 0.122;
//evaluated->QVALUE_param_scoreWeight = 0.141;
//evaluated->QVALUE_param_alpha = 0.744;
//evaluated->QVALUE_param_gamma = 1.229;
//evaluated->QVALUE_param_lambda = 0.466;
//evaluated->QVALUE_param_lambda_playOut = 0.815;
//evaluated->QVALUE_param_leaf_node_val0 = 2.136;
//evaluated->QVALUE_param_leaf_node_val1 = 1.099;
//evaluated->QVALUE_param_leaf_node_val2 = -0.561;
//evaluated->QVALUE_param_leaf_node_val3 = 3.875;
//evaluated->QVALUE_param_initVal = 1.366;
//-- 2014_02_19 end --//
//-- 2014_02_24 eval 1M Conn4 comparison best --//
//evaluated->UCT_param_C = 0.177;
//evaluated->UCT_param_C = 0.170;
//evaluated->AMAF_param_alpha =-0.986; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 1, TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME = 0, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 0
//evaluated->UCT_param_C = 0.190;
//evaluated->RAVE_param_V = -85.550; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 1, TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME = 1, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 0
//evaluated->UCT_param_C = 0.150;
//evaluated->AMAF_param_alpha =-0.930; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 3, TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME = 0, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 0
//evaluated->UCT_param_C = 0.150; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 1, TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME = 0, set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 2, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_ALGORITHM = 3
//evaluated->QVALUE_param_scoreWeight = 0.120;
//evaluated->AMAF_param_alpha = -0.792;
//evaluated->UCT_param_C = 0.147; //set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 3, TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME = 0, set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 2, TOMPLAYER_AI_UCT_TOMTEST_QVALUE_ALGORITHM = 3
//evaluated->QVALUE_param_scoreWeight = 0.133;
//evaluated->AMAF_param_alpha = -0.699;
////benchmark 2014_02_24 Conn4 comparison best - 5
////set TOMPLAYER_AI_UCT_TOMTEST_AMAF_EQUATION_TYPE = 1, TOMPLAYER_AI_UCT_TOMTEST_AMAF_ENABLE_RAVE_SCHEME = 1, set TOMPLAYER_AI_UCT_TOMTEST_QVALUE_EQUATION_TYPE = 0
////set TOMPLAYER_AI_UCT_TOMTEST_PARAM_FUNC_APP_TYPE = 3, TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_INPUTS 3, TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_OUTPUTS 2, TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_HIDD_LAYER 3
//evaluated->UCT_param_C = 0.2;
//evaluated->RAVE_param_V = 0.0;
//funcApp1->parameter_weights[0] = 0.0050;
//funcApp1->parameter_weights[1] = -2.2469;
//funcApp1->parameter_weights[2] = -0.9316;
//funcApp1->parameter_weights[3] = 1.2891;
//funcApp1->parameter_weights[4] = -0.2774;
//funcApp1->parameter_weights[5] = -1.5939;
//funcApp1->parameter_weights[6] = 0.3289;
//funcApp1->parameter_weights[7] = 1.3833;
//funcApp1->parameter_weights[8] = -1.8694;
//funcApp1->parameter_weights[9] = 2.4987;
//funcApp1->parameter_weights[10] = 0.5779;
//funcApp1->parameter_weights[11] = -0.3715;
//funcApp1->parameter_weights[12] = 0.5555;
//funcApp1->parameter_weights[13] = 0.9744;
//funcApp1->parameter_weights[14] = 1.0207;
//funcApp1->parameter_weights[15] = 0.3399;
//funcApp1->parameter_weights[16] = -0.5799;
//funcApp1->parameter_weights[17] = -0.0008;
//funcApp1->parameter_weights[18] = 1.4078;
//funcApp1->parameter_weights[19] = 0.3903;
//-- 2014_03_03 SARSA+AMAF_EQ3 direct search 12 par - configuration
// //gomoku
//evaluated->UCT_param_C = -11.7952;
//evaluated->AMAF_param_alpha = 0.82822;
//evaluated->QVALUE_param_scoreWeight = 2.2312;
//evaluated->QVALUE_param_alpha = 0.3124;
//evaluated->QVALUE_param_gamma = 1.0004;
//evaluated->QVALUE_param_lambda = 0.6664;
//evaluated->QVALUE_param_lambda_playOut = 0.9129;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//// //connect4
//evaluated->UCT_param_C = 0.1747;
//evaluated->AMAF_param_alpha = -0.7338;
//evaluated->QVALUE_param_scoreWeight = 0.3131;
//evaluated->QVALUE_param_alpha = 0.7833;
//evaluated->QVALUE_param_gamma = 1.0839;
//evaluated->QVALUE_param_lambda = 0.397;
//evaluated->QVALUE_param_lambda_playOut = 0.8754;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
////-- 2014_03_11 paper T1 SARSA (no AMAF)
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//evaluated->UCT_param_C = 0.0544;
//evaluated->QVALUE_param_scoreWeight = 0.7036;
//evaluated->QVALUE_param_alpha = 0.7209;
//evaluated->QVALUE_param_gamma = 0.9072;
//evaluated->QVALUE_param_lambda = 0.6071;
//evaluated->QVALUE_param_lambda_playOut = 0.85812;
//-- 2014_03_11 paper T1 SARSA no MC (and no AMAF)
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//evaluated->UCT_param_C = 0.1703;
//evaluated->QVALUE_param_scoreWeight = 1.0;
//evaluated->QVALUE_param_alpha = 0.2218;
//evaluated->QVALUE_param_gamma = 0.708;
//evaluated->QVALUE_param_lambda = 1.6706;
//evaluated->QVALUE_param_lambda_playOut = 0.9141;
//// SARSA+AMAF
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//evaluated->UCT_param_C = -5.75;
//evaluated->AMAF_param_alpha = 0.90;
//evaluated->QVALUE_param_scoreWeight = 3.51;
//evaluated->QVALUE_param_alpha = 0.3124;
//evaluated->QVALUE_param_gamma = 1.0004;
//evaluated->QVALUE_param_lambda = 0.6664;
//evaluated->QVALUE_param_lambda_playOut = 0.9129;
////SARSA-CORRECT gamma 1 run2 alpha 1 Wq 1
//evaluated->UCT_param_C = 0.045;
//evaluated->QVALUE_param_scoreWeight = 1.0;
//evaluated->QVALUE_param_alpha = 1.0;
//evaluated->QVALUE_param_gamma = 1.0;
//evaluated->QVALUE_param_lambda = 0.5276;
//evaluated->QVALUE_param_lambda_playOut = 0.92086;
//evaluated->QVALUE_param_initVal = 0.5;
//SARSA-CORRECT gamma 1 run2 (and variants)
//optimizingPlayer->UCT_param_C = 0.0227;
//optimizingPlayer->QVALUE_param_scoreWeight = 1.0;
//optimizingPlayer->QVALUE_param_alpha = 0.9912;
//optimizingPlayer->QVALUE_param_gamma = 1.0;
//optimizingPlayer->QVALUE_param_lambda = 0.6206;
//optimizingPlayer->QVALUE_param_lambda_playOut = 0.85856;
//optimizingPlayer->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT run 2 + AMAF_EQ3
//evaluated->UCT_param_C = -2.6226;
//evaluated->AMAF_param_alpha = 0.88664;
//evaluated->QVALUE_param_scoreWeight = 1.3173;
//evaluated->QVALUE_param_alpha = 1.0;
//evaluated->QVALUE_param_gamma = 1.0;
//evaluated->QVALUE_param_lambda = 0.8118;
//evaluated->QVALUE_param_lambda_playOut = 0.8662;
//evaluated->QVALUE_param_initVal = 0.5;
////SARSA-CORRECT run5 - individual parameters
//evaluated->UCT_param_C = 0.04944;
//evaluated->QVALUE_param_scoreWeight = 0.7943;
//evaluated->QVALUE_param_alpha = 1.111;
//evaluated->QVALUE_param_gamma = 1.0;
//evaluated->QVALUE_param_lambda = 0.69502;
//evaluated->QVALUE_param_lambda_playOut = 0.8853;
//evaluated->QVALUE_param_initVal = 0.5;
////SARSA-third test1
//evaluated->UCT_param_C = 0.05;
//evaluated->QVALUE_param_scoreWeight = 1.0;
//evaluated->QVALUE_param_alpha = 1.0;
//evaluated->QVALUE_param_gamma = 1.0;
//evaluated->QVALUE_param_lambda = 1.0;
//evaluated->QVALUE_param_initVal = 0.0;
////SARSAcorrect variant0
//evaluated->UCT_param_C = 0.049;
//evaluated->QVALUE_param_scoreWeight = 0.794;
//evaluated->QVALUE_param_alpha = 1.0;
//evaluated->QVALUE_param_gamma = 1.0;
//evaluated->QVALUE_param_lambda = 0.885;
//evaluated->QVALUE_param_lambda_playOut = 0.885;
//evaluated->QVALUE_param_initVal = 0.5;
////TDfourth - TDleaf
////double TD_leaf_state_value = currentNode->Q_value;;
////MC_value = set_QVALUE_param_scoreWeight*(child->Q_value+0.5) + set_MC_weight*(MC_value); //TDfourth
//evaluated->UCT_param_C = 0.022;
//evaluated->QVALUE_param_scoreWeight = 0.863;
//evaluated->QVALUE_param_alpha = 0.670;
//evaluated->QVALUE_param_gamma = 0.845;
//evaluated->QVALUE_param_lambda = 0.663;
//evaluated->QVALUE_param_initVal = 0.0;
////TDfourth - TD0
////double TD_leaf_state_value = QVALUE_param_initVal;
////MC_value = set_QVALUE_param_scoreWeight*(child->Q_value+0.5) + set_MC_weight*(MC_value); //TDfourth
//evaluated->UCT_param_C = 0.049;
//evaluated->QVALUE_param_scoreWeight = 0.794;
//evaluated->QVALUE_param_alpha = 1.111;
//evaluated->QVALUE_param_gamma = 0.885;
//evaluated->QVALUE_param_lambda = 0.785;
//evaluated->QVALUE_param_initVal = 0.0;
////TDfourth - TDmin
////double TD_leaf_state_value = currentNode->Q_value;;
////MC_value = set_QVALUE_param_scoreWeight*(child->Q_value+0.5) + set_MC_weight*(MC_value); //TDfourth
//evaluated->UCT_param_C = 0.052;
//evaluated->QVALUE_param_scoreWeight = 1.0;
//evaluated->QVALUE_param_alpha = 1.0;
//evaluated->QVALUE_param_gamma = 0.877;
//evaluated->QVALUE_param_lambda = 1.0;
//evaluated->QVALUE_param_initVal = 0.0;
////TDfourth - remake SARSA first version
//evaluated->UCT_param_C = -5.75;
//evaluated->AMAF_param_alpha = 0.90;
//evaluated->QVALUE_param_scoreWeight = 3.51;
//evaluated->QVALUE_param_alpha = 0.3124;
//evaluated->QVALUE_param_gamma = 0.9129;
//evaluated->QVALUE_param_lambda = 0.6664;
//evaluated->QVALUE_param_lambda_playOut = 0.9129;
//evaluated->QVALUE_param_initVal = 0.0;
//// SARSA(lambda) two + AMAF
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//evaluated->UCT_param_C = -5.75;
//evaluated->AMAF_param_alpha = 0.90;
//evaluated->QVALUE_param_scoreWeight = 3.51;
//evaluated->QVALUE_param_alpha = 0.3124;
//evaluated->QVALUE_param_gamma = 0.9129;
//evaluated->QVALUE_param_lambda = 0.730;
//evaluated->QVALUE_param_lambda_playOut = 0.9129;
//-- 2014_03_11-17 paper F4o2 1000 iterations Gomo7x7 best params at 1-3 param search
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//// UCB
//evaluated->UCT_param_C = 0.1022;
//// RAVE
//evaluated->UCT_param_C = 0.1382;
//evaluated->RAVE_param_V = -149.77;
// SARSA
//evaluated->UCT_param_C = 0.1024;
//evaluated->QVALUE_param_scoreWeight = 0.2152;
//evaluated->QVALUE_param_alpha = 0.7209;
//evaluated->QVALUE_param_gamma = 0.9072;
//evaluated->QVALUE_param_lambda = 0.6071;
//evaluated->QVALUE_param_lambda_playOut = 0.85812;
//// SARSA+AMAF
//evaluated->UCT_param_C = -13.931;
//evaluated->AMAF_param_alpha = 0.97942;
//evaluated->QVALUE_param_scoreWeight = 0.9208;
//evaluated->QVALUE_param_alpha = 0.3124;
//evaluated->QVALUE_param_gamma = 1.0004;
//evaluated->QVALUE_param_lambda = 0.6664;
//evaluated->QVALUE_param_lambda_playOut = 0.9129;
//-- end - 2014_03_11 paper T11000 iterations Gomo7x7 best params
//-- 2014_04_01 paper F4 optimized values at 1000 iterations Gomo 7x7 to 19x19
////-- Gomoku 9x9 iterations 1000-1000 --//
////Plain UCT
//evaluated->UCT_param_C = 0.052;
////RAVE
//evaluated->UCT_param_C = -0.149;
//evaluated->RAVE_param_V = 332;
////SARSA
//evaluated->UCT_param_C = 0.086;
//evaluated->QVALUE_param_scoreWeight = 0.520;
//evaluated->QVALUE_param_alpha = 0.7209;
//evaluated->QVALUE_param_gamma = 0.9072;
//evaluated->QVALUE_param_lambda = 0.6071;
//evaluated->QVALUE_param_lambda_playOut = 0.85812;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
////SARSA+AMAF
//evaluated->UCT_param_C = -8.948;
//evaluated->AMAF_param_alpha = 1.137;
//evaluated->QVALUE_param_scoreWeight = 0.776;
//evaluated->QVALUE_param_alpha = 0.3124;
//evaluated->QVALUE_param_gamma = 1.0004;
//evaluated->QVALUE_param_lambda = 0.6664;
//evaluated->QVALUE_param_lambda_playOut = 0.9129;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
////-- Gomoku 19x19 iterations 1000-1000 --//
////Plain UCT
//evaluated->UCT_param_C = 0.046;
////Plain UCT optimized 4000-1000
//evaluated->UCT_param_C = 0.037;
////RAVE
//evaluated->UCT_param_C = 0.997;
//evaluated->RAVE_param_V = 111;
////RAVE optimized 4000-1000
//evaluated->UCT_param_C = -0.083;
//evaluated->RAVE_param_V = 195;
////RAVE optimized 8000-2000
//evaluated->UCT_param_C = 3.452;
//evaluated->RAVE_param_V = 46.9;
////SARSA
//evaluated->UCT_param_C = 1.158;
//evaluated->QVALUE_param_scoreWeight = 0.915;
//evaluated->QVALUE_param_alpha = 0.7209;
//evaluated->QVALUE_param_gamma = 0.9072;
//evaluated->QVALUE_param_lambda = 0.6071;
//evaluated->QVALUE_param_lambda_playOut = 0.85812;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
////SARSA+AMAF
//evaluated->UCT_param_C = -3.802;
//evaluated->AMAF_param_alpha = 0.863;
//evaluated->QVALUE_param_scoreWeight = 2.851;
//evaluated->QVALUE_param_alpha = 0.3124;
//evaluated->QVALUE_param_gamma = 1.0004;
//evaluated->QVALUE_param_lambda = 0.6664;
//evaluated->QVALUE_param_lambda_playOut = 0.9129;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//-- TicTacToe 100 iterations --//
////SARSA+AMAF
//evaluated->UCT_param_C = 0.1705;
//evaluated->AMAF_param_alpha = 0.22765;
//evaluated->QVALUE_param_scoreWeight = 0.2966;
//evaluated->QVALUE_param_alpha = 0.3685;
//evaluated->QVALUE_param_gamma = 1.000;
//evaluated->QVALUE_param_lambda = 0.36015;
//evaluated->QVALUE_param_lambda_playOut = 0.84016;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
// -- Hex 7x7 iterations 100-100 --//
////Plain UCT
////RAVE
//evaluated->UCT_param_C = -0.12;
//evaluated->RAVE_param_V = 158;
////SARSA
////SARSA+AMAF
//evaluated->UCT_param_C = -2.5641;
//evaluated->AMAF_param_alpha = 0.70345;
//evaluated->QVALUE_param_scoreWeight = 1.265;
//evaluated->QVALUE_param_alpha = 0.085;
//evaluated->QVALUE_param_gamma = 1.000;
//evaluated->QVALUE_param_lambda = 1.1717;
//evaluated->QVALUE_param_lambda_playOut = 0.90422;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
// -- Hex 7x7 iterations 1000-1000 --//
////SARSA+AMAF
//evaluated->UCT_param_C = -6.6244;
//evaluated->AMAF_param_alpha = 0.7883;
//evaluated->QVALUE_param_scoreWeight = 0.3242;
//evaluated->QVALUE_param_alpha = 0.1563;
//evaluated->QVALUE_param_gamma = 1.000;
//evaluated->QVALUE_param_lambda = 0.63945;
//evaluated->QVALUE_param_lambda_playOut = 0.91768;
//evaluated->QVALUE_param_leaf_node_val0 = 0;
//evaluated->QVALUE_param_leaf_node_val1 = 1;
//evaluated->QVALUE_param_leaf_node_val2 = 0;
//evaluated->QVALUE_param_leaf_node_val3 = 1;
//evaluated->QVALUE_param_initVal = 0.5;
//-- 2014_02_21 Gomo Qval NN search
////2014_02_21 Gomo Qval single_NN search - initQ
//funcApp1->parameter_weights[0] = -0.95;
//funcApp1->parameter_weights[1] = 1.9;
//funcApp1->parameter_weights[2] = 0.17;
//funcApp1->parameter_weights[3] = -0.03;
////2014_02_21 Gomo Qval single_NN search - leaf_val - 1 - long
//funcApp1->parameter_weights[0] = -0.77;
//funcApp1->parameter_weights[1] = 3.84;
//funcApp1->parameter_weights[2] = -2.24;
//funcApp1->parameter_weights[3] = -0.08;
//-- end: 2014_02_21 Gomo Qval NN search
//2014_01_08 RAVE LRP direct search + single NN - first experiments
//Conn4 singleN RAVE0 bias + test8.1 + test1.1
//single-layer NN score and weights
//best solution
//46.9200 0.0019 0.4079 -0.1863 -0.5264 -0.2975 -1.1809
//funcApp1->parameter_weights[0] = 0.0019;
//funcApp1->parameter_weights[1] = 0.4079;
//funcApp1->parameter_weights[2] = -0.1863;
//funcApp1->parameter_weights[3] = -0.5264;
//funcApp1->parameter_weights[4] = -0.2975;
//funcApp1->parameter_weights[5] = -1.1809;
//2014_01_10 RAVE LRP dual layer NN - first exp, week run
//Conn4 - merged
//dual-layer NN score and weights
//best solution
//48.3800 0.0667 -0.8963 -1.2155 -3.7149 -3.5235 -0.8082 -4.7469 3.1732
//-1.5695 -2.4915 -0.6675 1.6720 0.8763 1.1854 1.8081 -0.4054 -2.1228 -0.6290 1.2969 1.0485
//1M evaluations score: 48.83 +-0.1
//funcApp1->parameter_weights[0] = 0.0667;
//funcApp1->parameter_weights[1] = -0.8963;
//funcApp1->parameter_weights[2] = -1.2155;
//funcApp1->parameter_weights[3] = -3.7149;
//funcApp1->parameter_weights[4] = -3.5235;
//funcApp1->parameter_weights[5] = -0.8082;
//funcApp1->parameter_weights[6] = -4.7469;
//funcApp1->parameter_weights[7] = 3.1732;
//funcApp1->parameter_weights[8] = -1.5695;
//funcApp1->parameter_weights[9] = -2.4915;
//funcApp1->parameter_weights[10] = -0.6675;
//funcApp1->parameter_weights[11] = 1.6720;
//funcApp1->parameter_weights[12] = 0.8763;
//funcApp1->parameter_weights[13] = 1.1854;
//funcApp1->parameter_weights[14] = 1.8081;
//funcApp1->parameter_weights[15] = -0.4054;
//funcApp1->parameter_weights[16] = -2.1228;
//funcApp1->parameter_weights[17] = -0.6290;
//funcApp1->parameter_weights[18] = 1.2969;
//funcApp1->parameter_weights[19] = 1.0485;
//2014_01 Q-Values test: analyzed best param values for SARSA(lambda)
//see weights settings in "2014_01 Q-Values test\sarsa-lambda 11 weight mapping to parameters.txt"
//funcApp1->parameter_weights[0] = 2.5;
//funcApp1->parameter_weights[1] = 1.0;
//funcApp1->parameter_weights[2] = -0.5;
//funcApp1->parameter_weights[3] = 2.5;
//funcApp1->parameter_weights[4] = 0.0;
//funcApp1->parameter_weights[5] = 0.0;
//funcApp1->parameter_weights[6] = 0.0;
//funcApp1->parameter_weights[7] = 0.0;
//funcApp1->parameter_weights[8] = 0.0;
//funcApp1->parameter_weights[9] = 0.0;
//funcApp1->parameter_weights[10] = 0.0;
//funcApp1->parameter_weights[0] = 0;
//funcApp1->parameter_weights[1] = 1;
//funcApp1->parameter_weights[2] = 0;
//funcApp1->parameter_weights[3] = 1;
////2014_03_07 SARSA+AMAF_EQ3 single NN by sum_iter
//funcApp1->parameter_weights[0] = -0.8054;
//funcApp1->parameter_weights[1] = 0.7459;
//funcApp1->parameter_weights[2] = -1.3799;
//funcApp1->parameter_weights[3] = -0.2492;
//funcApp1->parameter_weights[4] = 0.9302;
//funcApp1->parameter_weights[5] = 0.2021;
//funcApp1->parameter_weights[6] = 0.2007;
//funcApp1->parameter_weights[7] = 0.303;
//funcApp1->parameter_weights[8] = 0.0062;
//---execute testing---//
benchmarkOpponent->UCT_param_IterNum = opponent->UCT_param_IterNum;
benchmarkOpponent->UCT_param_C = opponent->UCT_param_C;
benchmarkEvaluated->UCT_param_IterNum = evaluated->UCT_param_IterNum;
benchmarkEvaluated->UCT_param_C = evaluated->UCT_param_C;
benchmarkEvaluated->AMAF_param_alpha = evaluated->AMAF_param_alpha;
benchmarkEvaluated->RAVE_param_V = evaluated->RAVE_param_V;
//TODO copy all new Qval params to benchmarkEvaluated
players[1-eval_player_position] = opponent;
players[eval_player_position] = evaluated;
//setup result storage
Tom_Sample_Storage<double>* score[2];
gmp->Print("Fixed_Play_Testing()\n");
gmp->Print("%s repeats %d (input params %3.3lf %3.3lf)\n",(game->game_name).c_str(), repeats, input_param1, input_param2);
gmp->Print("Evaluated player %d sim %d\n",eval_player_position+1, evaluated->UCT_param_IterNum);
if((display_output_game == 0)&&(human_opponent_override == 0)){
gmp->Print("Opponent C %3.3f, sim %d\n",opponent->UCT_param_C,opponent->UCT_param_IterNum);
gmp->Print("\n");
gmp->Print(" Score[%%]\n");
gmp->Print(" Repeats Avg Conf95 Dev Runtime[s]\n");
score[0] = new Tom_Sample_Storage<double>(repeats);
score[1] = new Tom_Sample_Storage<double>(repeats);
double cpu_time = getCPUTime();
if(benchmark_same_player == 0){
game->Evaluate_Players(1,repeats,-1,players,false,eval_player_position,score,output_interval_repeats,measure_time_per_move);
}else if(benchmark_same_player == 1){
gmp->Print("! benchmark_same_player = opponent vs opponent !\n");
players[eval_player_position] = benchmarkOpponent;
game->Evaluate_Players(1,repeats,-1,players,false,eval_player_position,score,output_interval_repeats,measure_time_per_move);
}else if(benchmark_same_player == 2){
gmp->Print("! benchmark_same_player = evaluated vs evaluated !\n");
players[1-eval_player_position] = benchmarkEvaluated;
game->Evaluate_Players(1,repeats,-1,players,false,eval_player_position,score,output_interval_repeats,measure_time_per_move);
}
cpu_time = getCPUTime()-cpu_time;
gmp->Print("%8d %6.2f %6.2f %6.2f %9.3f\n",
repeats,
score[eval_player_position]->avg*100,
score[eval_player_position]->Calc_Confidence()*100,
score[eval_player_position]->dev*100,
cpu_time
);
delete(score[0]);
delete(score[1]);
}else{
gmp->Print("! HUMAN Opponent !\n");
gmp->Print("\n");
if(human_opponent_override == 1)
players[1-eval_player_position] = new Player_Human(game);
game->Simulate_Output_Game(players);
if(human_opponent_override == 1)
delete(players[1-eval_player_position]);
}
gmp->Flush();
//gmp->Print("\n\nFixed_Play_Testing(): TotalRuntime: %9.3f s\n", cpu_time);
delete(game);
delete(opponent);
delete(benchmarkOpponent);
delete(evaluated);
delete(benchmarkEvaluated);
}
void Tom_Paper1_tests()
{
////F1,F23
//Fixed_Play_Testing(10);
//Fixed_Play_Testing(20);
//Fixed_Play_Testing(50);
//Fixed_Play_Testing(200);
//Fixed_Play_Testing(500);
//Fixed_Play_Testing(1000);
////F4
//Fixed_Play_Testing(7);
//Fixed_Play_Testing(9);
//Fixed_Play_Testing(11);
//Fixed_Play_Testing(13);
//Fixed_Play_Testing(15);
//Fixed_Play_Testing(17);
//Fixed_Play_Testing(19);
////Hex/TTT test
//Fixed_Play_Testing(10,10);
//Fixed_Play_Testing(20,20);
//Fixed_Play_Testing(30,30);
//Fixed_Play_Testing(40,40);
//Fixed_Play_Testing(10,20);
//Fixed_Play_Testing(10,30);
//Fixed_Play_Testing(10,40);
//Fixed_Play_Testing(10,50);
//Fixed_Play_Testing(20,10);
//Fixed_Play_Testing(30,10);
//Fixed_Play_Testing(40,10);
//Fixed_Play_Testing(50,10);
//Fixed_Play_Testing(50,50);
//Fixed_Play_Testing(50,60);
//Fixed_Play_Testing(50,70);
//Fixed_Play_Testing(50,80);
//Fixed_Play_Testing(50,90);
//Fixed_Play_Testing(60,50);
//Fixed_Play_Testing(70,50);
//Fixed_Play_Testing(80,50);
//Fixed_Play_Testing(90,50);
//Fixed_Play_Testing(100,100);
////Hex test
//Fixed_Play_Testing(50,50);
//Fixed_Play_Testing(50,100);
//Fixed_Play_Testing(100,50);
//Fixed_Play_Testing(100,100);
//Fixed_Play_Testing(200,200);
//Fixed_Play_Testing(200,500);
//Fixed_Play_Testing(500,200);
//Fixed_Play_Testing(500,500);
//Fixed_Play_Testing(500,1000);
//Fixed_Play_Testing(1000,500);
//Fixed_Play_Testing(1000,1000);
}
void Hex_Testing()
{
Game_Engine* hex = new Game_Hex();
Player_Human* playerHuman = new Player_Human(hex);
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(hex);
Player_AI_UCT* playerUCT2 = new Player_AI_UCT(hex);
//Player_Engine* players[] = {playerHuman,playerUCT1};
Player_Engine* players[] = {playerUCT1,playerUCT2};
hex->players = players;
//players settings
playerUCT1->UCT_param_IterNum = 50;
playerUCT1->UCT_param_C = 1.0 / (2*sqrt(2));
playerUCT2->UCT_param_IterNum = 5000;
playerUCT2->UCT_param_C = 0.7 / (2*sqrt(2));
//testing
unsigned int tmpr = (unsigned int)time(NULL);
srand(tmpr);
//srand(1362238250);
double cpu_time = getCPUTime();
//gomoku->Simulate_Output_Game();
hex->Game_Reset();
playerUCT1->Reset();
playerUCT2->Reset();
hex->Game_Reset();
hex->Simulate_Output_Game();
//gomoku->Simulate_Human_Game();
cpu_time = getCPUTime()-cpu_time;
printf("Runtime: %9.3f s\n",cpu_time);
printf("%d\n",tmpr);
}
void Param_Impact_Testing_v06()
{
//game
Game_Engine* ticTac = new Game_ConnectFour();
//Game_Engine* ticTac = new Game_Gomoku();
//Game_Engine* ticTac = new Game_TicTacToe();
Player_Engine* players[2];
// Player_AI_UCT* pUCT;
//opponent
//Player_Random* opponent = new Player_Random(ticTac);
Player_AI_UCT* opponent = new Player_AI_UCT(ticTac);
//choose test learning algorithms
Player_Engine* pUCTlist[] = {
//new Player_AI_UCT(ticTac)
new Player_AI_UCT_TomTest(ticTac)
//new Player_AI_UCT(ticTac)//,
//new Player_AI_UCT_AMAF(ticTac)
};
Tom_Function_Approximator* funcApp1 = new Tom_Function_Approximator();
funcApp1->Initialize();
funcApp1->num_results = TOMPLAYER_AI_UCT_TOMTEST_FUNC_APPROX_NUM_PARAMS;
funcApp1->Settings_Apply_New();
//funcApp1->parameter_weights[0] = -0.06;
//funcApp1->parameter_weights[1] = 0.32;
//funcApp1->parameter_weights[2] = 0.166;
int test_num_algorithms = sizeof(pUCTlist) / sizeof(Player_AI_UCT*);
//set multiple test configuration
int test_base_val_iterNum = 100;
int test_base_val_maxPlys = 0;
double test_base_val_paramC = 0.2;// TOMPLAYER_AI_UCT_PARAM_C;
int test_comb_num_SimNum = 1;
int test_comb_num_maxPlys = 1;
int test_comb_num_paramC = 1;
double test_fact_SimNum = 1.0;
double test_fact_maxPlys = 1.0;
double test_fact_paramC = 1.0;
int runs = 1;
int base_repeats = test_base_val_iterNum*1000; //10*1000*1000; //MUST BE AT LEAST EQUAL TO test_base_val_iterNum
opponent->UCT_param_IterNum = 100;
opponent->UCT_param_C = 0.2;//0.5/sqrt(2);
int eval_player_position = 1; //which player to test: 0 or 1; works only for two-player games
//---execute testing---
players[1-eval_player_position] = opponent;
//run tests
if(base_repeats < test_base_val_iterNum){
base_repeats = test_base_val_iterNum;
}
double cpu_time = getCPUTime();
//setup result storage
Tom_Sample_Storage<double>* score[2];
//printf("Param_Impact_Testing()\n");
printf("%s repeats %d\n",(ticTac->game_name).c_str(), base_repeats / test_base_val_iterNum);
printf("Evaluated player %d sim %d\n",eval_player_position+1, test_base_val_iterNum);
printf("Opponent C %3.3f, sim %d\n",opponent->UCT_param_C,opponent->UCT_param_IterNum);
printf("\n");
printf("Par \t Score[%%]\n");
printf("Cp \t Avg \t Dev \t Conf95\n");
for(int i = 0; i < test_comb_num_SimNum*test_comb_num_maxPlys*test_comb_num_paramC; i++){
//int tIterNum = (int)(test_base_val_iterNum * pow(test_fact_SimNum , i % test_comb_num_SimNum));
//int tmaxply = (int)(test_base_val_maxPlys * pow(test_fact_maxPlys , (int)(i/test_comb_num_SimNum) % test_comb_num_maxPlys));
//double tparamc = test_base_val_paramC * pow(test_fact_paramC , (int)((int)(i/test_comb_num_SimNum)/test_comb_num_maxPlys) % test_comb_num_paramC);
int tIterNum = test_base_val_iterNum;
double tparamc = test_base_val_paramC;
//printf("\nnSim %d nPly %d parC %1.3f",tIterNum,tmaxply,tparamc);
//printf("\n\nProcedure AMAF_param_Testing(): nSim %d ParC %1.3f\n\n",tIterNum,tparamc);
for(int ac = 0; ac < test_num_algorithms; ac++){
((Player_AI_UCT*)pUCTlist[ac])->UCT_param_IterNum = tIterNum;
((Player_AI_UCT*)pUCTlist[ac])->UCT_param_C = tparamc;
//((Player_AI_UCT*)players[1-eval_player_position])->UCT_param_C = tparamc;
players[eval_player_position] = pUCTlist[ac];
((Player_AI_UCT_TomTest*)(players[eval_player_position]))->Func_App_UCT_Params = funcApp1;
//AMAF_Testing_Extensive(ticTac, players, tIterNum, runs, base_repeats / tIterNum);
score[0] = new Tom_Sample_Storage<double>(runs*(base_repeats / tIterNum));
score[1] = new Tom_Sample_Storage<double>(runs*(base_repeats / tIterNum));
ticTac->Evaluate_Players(runs,(base_repeats / tIterNum),-1,players,false,eval_player_position,score);
printf("%3.3f \t %5.2f \t %5.2f \t %5.2f\n",tparamc,score[eval_player_position]->avg*100,score[eval_player_position]->dev*100,score[eval_player_position]->Calc_Confidence()*100);
delete(score[0]);
delete(score[1]);
}
test_base_val_paramC += test_fact_paramC;
}
cpu_time = getCPUTime()-cpu_time;
printf("\n\nProcedure Param_Impact_Testing_v06(): TotalRuntime: %9.3f s\n", cpu_time);
}
void Tom_Sample_Storage_Test()
{
Tom_Sample_Storage<double>* tmp = new Tom_Sample_Storage<double>(100);
for(int i = 0; i < 100; i++)
tmp->Add_Sample(i,true,false);
printf("s %3.3f\n",tmp->sum);
printf("a %3.3f\n",tmp->avg);
printf("d %3.3f\n",tmp->dev);
printf("c %3.3f\n",tmp->conf);
printf("\n");
tmp->Calc_Dev();
printf("d %3.3f\n",tmp->dev);
printf("\n");
tmp->Calc_All();
printf("s %3.3f\n",tmp->sum);
printf("a %3.3f\n",tmp->avg);
printf("d %3.3f\n",tmp->dev);
printf("c %3.3f\n",tmp->conf);
printf("\n");
printf("c %3.3f\n",tmp->Calc_Confidence());
}
void FuncApp_test()
{
//Tom_Function_Approximator* evalC = new Tom_Function_Approximator();
//evalC->Initialize();
//evalC->Debug_Display_Weights(2);
//evalC->num_parameters = 3;
//evalC->Settings_Apply_New();
//evalC->Debug_Display_Weights(2);
//Tom_Lrp* Lrp = new Tom_Lrp();
//Lrp->Initialize();
//Lrp->Debug_Display_Probabilites();
//Lrp->num_actions = 5;
//Lrp->Settings_Apply_New();
//Lrp->Debug_Display_Probabilites(0);
}
void LRP_test_wrapper()
{
int num_repeats = 100;
// --- settings end --- //
double score_avg;
double score_avg_last10;
double last_param_val;
bool output_settings_once = true;
double cpu_time = getCPUTime();
Tom_Sample_Storage<double>* avg_score = new Tom_Sample_Storage<double>(num_repeats);
Tom_Sample_Storage<double>* avg_score10 = new Tom_Sample_Storage<double>(num_repeats);
Tom_Sample_Storage<double>* last_param = new Tom_Sample_Storage<double>(num_repeats);
printf("LRP_test_wrapper(), %d repeats\n\n", num_repeats);
for(int r = 0; r < num_repeats; r++){
//LRP_test_linAB_exponentDW(&score_avg,&score_avg_last10,&last_param_val);
LRP_test_linAB_exponentDW_FunApp(&score_avg,&score_avg_last10,&last_param_val,output_settings_once);
if(output_settings_once){
printf("\nRun \t [%%] \t [%%] \t Final_params\n");
printf(" \t scr100\t scr10 \t P1\n");
}
printf("%d \t %5.2f \t %5.2f \t %6.4f\n",r,score_avg*100,score_avg_last10*100,last_param_val);
avg_score->Add_Sample(score_avg);
avg_score10->Add_Sample(score_avg_last10);
last_param->Add_Sample(last_param_val);
output_settings_once = false;
}
avg_score->Calc_AvgDev(); avg_score->Calc_Confidence();
avg_score10->Calc_AvgDev(); avg_score10->Calc_Confidence();
last_param->Calc_AvgDev(); last_param->Calc_Confidence();
printf("\n\n");
printf("Summary [%%] \t [%%] \t Final_params\n");
printf(" \t scr100\t scr10 \t P1\n");
printf("avg \t %5.2f\t %5.2f\t %6.4f\n", avg_score->avg*100, avg_score10->avg*100, last_param->avg);
printf("dev \t %5.2f\t %5.2f\t %6.4f\n", avg_score->dev*100, avg_score10->dev*100, last_param->dev);
printf("conf \t %5.2f\t %5.2f\t %6.4f\n", avg_score->conf*100, avg_score10->conf*100, last_param->conf);
cpu_time = getCPUTime()-cpu_time;
printf("\n\nTotalRuntime: %9.3f s\n", cpu_time);
}
//LRP learning with Tom_Function_Approximator object
// with proportionally linearly changing learning parameters a and b
// with exponentialy decreasing weight change step
void LRP_test_linAB_exponentDW_FunApp_MulParams(double* score_avg, double* score_avg_last10, double** last_param_val, bool force_setting_output, int num_output_params)
{
//konfiguracija brane
//const int num_iterations_self = 30; //number MCTS simulations per move: evaluated player
//const int num_iterations_opponent = num_iterations_self; //number MCTS simulation per move: opponent
//const int num_games = 1000; //number of games per score output
//const double start_Cp_self = 0.0; //initial Cp: evaluated player
//const double fixed_CP_opponent = 0.0; //initial Cp: opponent
//const int num_LRP_iterations = 100; //number of LRP iterations
//const double dw_start = 0.05; //LRP delta weight (change in Cp value): at start
//const double dw_limit = 0.05/20; //LRP delta weight (change in Cp value): at end
//const double lrp_ab_max = 0.20; //LRP learning parameter alpha: maximum value
//const double lrp_ab_min = 0.20; //LRP learning parameter alpha: minmum value
//const double lrp_ab_dscore_min = 1.0 / (double)num_games; //LRP minimum delta score (to change probabilites with minimum alpha alpha value)
//const double lrp_ab_dscore_max = lrp_ab_dscore_min * 10.0; //MUST BE HIGHER OR EQUAL TO lrp_ab_dscore_min
//const double lrp_b_koef = 1.0; //LRP learning parameter beta koeficient [0,1] of alpha value
//const bool exp_dw_decrease = 1; //use exponential weight decrease (instead of linear)
//const int eval_player_position = 1; //which player to optimize and evaluate 0 or 1, currently works only for two-player games
//konfiguracija tom
const int num_iterations_self = 100; //number MCTS simulations per move: evaluated player
const int num_iterations_opponent = num_iterations_self; //number MCTS simulation per move: opponent
const int num_games = 100; //number of games per score output
const double start_Cp_self = 1.0; //initial Cp: evaluated player
const double fixed_CP_opponent = 0.0; //initial Cp: opponent
const int num_LRP_iterations = 1000; //number of LRP iterations
const double dw_start = 0.050; //LRP delta weight (change in Cp value): at start
const double dw_limit = 0.002; //LRP delta weight (change in Cp value): at end
const double lrp_ab_max = 0.40; //LRP learning parameter alpha: maximum value
const double lrp_ab_min = 0.02; //LRP learning parameter alpha: minmum value
const double lrp_ab_dscore_min = 1.0 / (double)num_games; //LRP minimum delta score (to change probabilites with minimum alpha alpha value)
const double lrp_ab_dscore_max = lrp_ab_dscore_min * 10.0; //MUST BE HIGHER OR EQUAL TO lrp_ab_dscore_min
const double lrp_b_koef = 1; //LRP learning parameter beta koeficient [0,1] of alpha value
const bool exp_dw_decrease = 0; //use exponential weight decrease (instead of linear)
const int eval_player_position = 1; //which player to optimize and evaluate 0 or 1, currently works only for two-player games
//TODO1: da ce je slabši rezultat, da razveljaviš in daš na prejšnje stanje, parameter pa ni treba dat celo pot nazaj ampak samo do določene mere
//TODO2: preizkusi če bi dva ločena LRPja delovala boljše za iskanje 2 parametrov, 2 varianti:
// *oba LRPja istočasno izvedeta akcijo in opazujeta izhod
// *LRPja izmenično izvajata akcije (to pomeni, da je na razpolago pol manj korakov za posamezen LRP)
const bool show_full_output = true; //runtime setting
//Game_Engine* game = new Game_Gomoku();
Game_Engine* game = new Game_ConnectFour();
//Game_Engine* game = new Game_TicTacToe();
Player_AI_UCT_TomTest* optimizingPlayer = new Player_AI_UCT_TomTest(game);
Player_AI_UCT* opponent = new Player_AI_UCT(game);
Tom_Function_Approximator* funcApp1 = new Tom_Function_Approximator();
funcApp1->Initialize();
if(num_output_params == 0){
funcApp1->num_results = 2;
}else{
funcApp1->num_results = num_output_params;
}
funcApp1->Settings_Apply_New();
optimizingPlayer->Func_App_UCT_Params = funcApp1;
//optimizingPlayer->UCT_param_C = start_Cp_self;
optimizingPlayer->UCT_param_C = 1.0;
//-------- end of settings -------- //
bool silence_output = ((score_avg != NULL)||(score_avg_last10 != NULL)||(last_param_val != NULL));
//apply settings and initialize structurs
optimizingPlayer->UCT_param_IterNum = num_iterations_self;
opponent->UCT_param_IterNum = num_iterations_opponent;
opponent->UCT_param_C = fixed_CP_opponent;
for(int i = 0; i < funcApp1->num_params; i++)
funcApp1->parameter_weights[i] = start_Cp_self;
Player_Engine* players[2];
players[eval_player_position] = optimizingPlayer;
players[1-eval_player_position] = opponent;
Tom_Lrp* Lrp = new Tom_Lrp();
Lrp->Initialize();
Lrp->num_actions = funcApp1->num_actions;
Lrp->Settings_Apply_New();
//results storage
Tom_Sample_Storage<double>* score_history = new Tom_Sample_Storage<double>(num_LRP_iterations);
srand((unsigned int)time(NULL));
double cpu_time = getCPUTime();
//calculate exponential time constant
double dw_tau = (double) num_LRP_iterations / (log(dw_start/dw_limit));
//output test settings
if((!silence_output)||(force_setting_output)){
printf("LRP_test_linAB_exponentDW_FunApp_MulParams()\n");
printf("%s\n",game->game_name.c_str());
printf("Evaluated player %d sim %d start Cp %1.3f\n",eval_player_position+1, num_iterations_self, start_Cp_self);
printf("Opponent C %3.3f, sim %d\n",fixed_CP_opponent,num_iterations_opponent);
printf("Games %d LRP_iter %5d\n", num_games, num_LRP_iterations);
printf("\n");
printf("LRP_ab_min %1.3f LRP_ab_max %1.3f dScoreMin %1.3f dScoreMax %1.3f\n", lrp_ab_min, lrp_ab_max, lrp_ab_dscore_min, lrp_ab_dscore_max);
printf("LRP_b_koef %1.3f\n", lrp_b_koef);
printf("dw_start %1.5f dw_limit %1.5f dw_tau %1.5f\n", dw_start, dw_limit, dw_tau);
printf("Use linear dw decrease: %d\n", (int)(!exp_dw_decrease));
printf("\n");
}
//--- LRP algorithm ---//
double score, previous_score;
int selected_action;
double dw = dw_start;
double lrp_ab = 0.0;
//evaluate starting setting
score = game->Evaluate_Players(1,num_games,-1,players,false,eval_player_position) / num_games;
//int best_iteration = -1;
//double best_score = score;
//double best_paramC = start_c1;
if(!silence_output){
if(show_full_output){
printf(" \t \t Parameters");
}
printf("\ni \t score");
for(int p = 0; p < funcApp1->num_params; p++)
printf("\t P%d",p);
if(show_full_output){
printf(" \t\t action");
for(int a = 0; a < Lrp->num_actions; a++)
printf("\t A%d[%%]",a);
printf("\t dw \t\t lrp_ab");
}
printf("\n%d \t%5.1f%%",0,score*100);
for(int p = 0; p < funcApp1->num_params; p++)
printf("\t %5.3f",funcApp1->parameter_weights[p]);
if(show_full_output){
printf(" \t\t ");
printf("//");
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f \t %1.3f",dw, lrp_ab);
}
printf("\n");
}
//debug
//double debug_scores[num_LRP_iterations] = {0.1 , 0.2 , 0.3 , 0.4 , 0.5};
//srand(0);
//Lrp iterations
for(int i = 0; i < num_LRP_iterations; i++){
if(exp_dw_decrease){
//exponential iterative decrease of weight change step
dw = dw_start * exp(-i/dw_tau);
}else{
//linear iterative decrease of weight change step
dw = dw_limit + (dw_start - dw_limit) * (1.0 - (double)i/(num_LRP_iterations-1));
}
//Lrp select action
selected_action = Lrp->Select_Action(TOM_LRP_SELECT_ACTION_CHECK_SUM);
//apply action
//if(selected_action == Lrp->num_actions-1){
// funcApp1->parameter_weights[0] = 0.2;
//}else{
// funcApp1->parameter_weights[0] = -0.5;
//}
funcApp1->Action_Update_Weights(selected_action, dw);
//optimizingPlayer->UCT_param_C = funcApp1->parameter_weights[0];
//evaluate new setting
previous_score = score; //save previous score
score = game->Evaluate_Players(1,num_games,-1,players,false,eval_player_position) / num_games;
//score = debug_scores[i]; //DEBUG
if(!silence_output){
printf("%d \t%5.1f%%",i+1,score*100);
for(int p = 0; p < funcApp1->num_params; p++)
printf("\t %5.3f",funcApp1->parameter_weights[p]);
printf(" \t\t ");
}
//linearly proportional lrp learning parameter
lrp_ab =
lrp_ab_min + (lrp_ab_max - lrp_ab_min) * max(0.0 , min(1.0 ,
(abs(score-previous_score) - lrp_ab_dscore_min) / (lrp_ab_dscore_max - lrp_ab_dscore_min)
));
Lrp->learn_param_a = lrp_ab;
Lrp->learn_param_b = lrp_ab * lrp_b_koef;
//Lrp correct probabilites based on previous and current score
if(score > previous_score){
Lrp->Update_Probabilites_Reward(selected_action,Lrp->learn_param_a);
if(!silence_output) if(show_full_output) printf("+");
}else{
Lrp->Update_Probabilites_Penalty(selected_action,Lrp->learn_param_b);
if(!silence_output) if(show_full_output) printf("-");
}
if(!silence_output){
if(show_full_output){
printf("%d",selected_action);
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f \t %1.3f",dw, lrp_ab);
}
printf("\n");
}
//remember best
//if(score >= best_score){
// best_iteration = i;
// best_score = score;
// best_paramC = playerUCT1->UCT_param_C;
//}
//update score
score_history->Add_Sample(score);
}
//--- LRP algorithm END---//
cpu_time = getCPUTime()-cpu_time;
//output best
//printf("\nBest score: %5.1f%% \t P1->Cp %5.3f \t i %d\n", best_score*100, best_paramC, best_iteration+1);
//output values
score_history->Calc_AvgDev();
double score10 = score_history->Calc_Avg_On_Interval((int)(num_LRP_iterations*0.9), num_LRP_iterations);
if(!silence_output){
printf("\navg100 dev100 \t avg10");
for(int p = 0; p < funcApp1->num_params; p++)
printf(" \t FinP%d",p);
printf("\n");
printf("%3.2f %3.2f \t %3.2f",score_history->avg*100, score_history->dev*100, score10*100);
for(int p = 0; p < funcApp1->num_params; p++)
printf("\t %3.4f",funcApp1->parameter_weights[p]);
printf("\n");
printf("\n\nTotalRuntime: %9.3f s\n", cpu_time);
}
//return values
if(score_avg != NULL)
(*score_avg) = score_history->Calc_Avg();
if(last_param_val != NULL)
for(int i = 0; i < funcApp1->num_params; i++)
(*last_param_val)[i] = funcApp1->parameter_weights[i];
if(score_avg_last10 != NULL)
(*score_avg_last10) = score_history->Calc_Avg_On_Interval((int)(num_LRP_iterations*0.9), num_LRP_iterations);
//free memory
delete(score_history);
delete(Lrp);
delete(optimizingPlayer);
delete(opponent);
delete(game);
}
//LRP learning with Tom_Function_Approximator object
// with proportionally linearly changing learning parameters a and b
// with exponentialy decreasing weight change step
void LRP_test_linAB_exponentDW_FunApp(double* score_avg, double* score_avg_last10, double* output_param, bool force_setting_output)
{
const int num_iterations_self = 100;
const int num_games = 200;
const int num_LRP_iterations = 200;
const double dw_start = 0.020;
const double dw_limit = 0.001;
const double lrp_ab_min = 0.02;
const double lrp_ab_max = 0.20;
const double lrp_ab_dscore_min = 1.0 / (double)num_games;
const double lrp_ab_dscore_max = lrp_ab_dscore_min * 10.0; //MUST BE HIGHER OR EQUAL TO lrp_ab_dscore_min
const double start_Cp_self = 0.0;
const double fixed_CP_opponent = 0.0;
const int num_iterations_opponent = num_iterations_self;
const int eval_player_position = 1; //which player to optimize and evaluate 0 or 1, currently works only for two-player games
const bool show_full_output = true; //runtime setting
//Game_Engine* game = new Game_Gomoku();
Game_Engine* game = new Game_ConnectFour();
//Game_Engine* game = new Game_TicTacToe();
Player_AI_UCT_TomTest* optimizingPlayer = new Player_AI_UCT_TomTest(game);
Player_AI_UCT* opponent = new Player_AI_UCT(game);
Tom_Function_Approximator* funcApp1 = new Tom_Function_Approximator();
optimizingPlayer->Func_App_UCT_Params = funcApp1;
//optimizingPlayer->UCT_param_C = start_Cp_self;
optimizingPlayer->UCT_param_C = 1.0; //this is the
//-------- end of settings -------- //
bool silence_output = ((score_avg != NULL)||(score_avg_last10 != NULL)||(output_param != NULL));
//apply settings and initialize structurs
optimizingPlayer->UCT_param_IterNum = num_iterations_self;
opponent->UCT_param_IterNum = num_iterations_opponent;
opponent->UCT_param_C = fixed_CP_opponent;
funcApp1->Initialize();
for(int i = 0; i < funcApp1->num_params; i++)
funcApp1->parameter_weights[i] = start_Cp_self;
Player_Engine* players[2];
players[eval_player_position] = optimizingPlayer;
players[1-eval_player_position] = opponent;
Tom_Lrp* Lrp = new Tom_Lrp();
Lrp->Initialize();
//results storage
Tom_Sample_Storage<double>* score_history = new Tom_Sample_Storage<double>(num_LRP_iterations);
srand((unsigned int)time(NULL));
double cpu_time = getCPUTime();
//calculate exponential time constant
double dw_tau = (double) num_LRP_iterations / (log(dw_start/dw_limit));
//output test settings
if((!silence_output)||(force_setting_output)){
printf("LRP_test_linAB_exponentDW_FunApp()\n");
printf("%s\n",game->game_name.c_str());
printf("Evaluated player %d sim %d start Cp %1.3f\n",eval_player_position+1, num_iterations_self, start_Cp_self);
printf("Opponent C %3.3f, sim %d\n",fixed_CP_opponent,num_iterations_opponent);
printf("Games %d LRP_iter %5d\n", num_games, num_LRP_iterations);
printf("\n");
printf("LRP_ab_min %1.3f LRP_ab_max %1.3f dScoreMin %1.3f dScoreMax %1.3f\n", lrp_ab_min, lrp_ab_max, lrp_ab_dscore_min, lrp_ab_dscore_max);
printf("dw_start %1.5f dw_limit %1.5f dw_tau %1.5f\n", dw_start, dw_limit, dw_tau);
printf("\n");
}
//--- LRP algorithm ---//
double score, previous_score;
int selected_action;
double dw = dw_start;
double lrp_ab = 0.0;
//evaluate starting setting
score = game->Evaluate_Players(1,num_games,-1,players,false,eval_player_position) / num_games;
//int best_iteration = -1;
//double best_score = score;
//double best_paramC = start_c1;
if(!silence_output){
if(show_full_output)
printf(" \t \t pr[%%] pr[%%]");
printf("\ni \t score Cp");
if(show_full_output){
printf(" \t\t action A0 A1 \t\t dw \t\t lrp_ab");
}
printf("\n%d \t%5.1f%% %5.3f \t ",0,score*100,funcApp1->parameter_weights[0]);
if(show_full_output){
printf("// \t ");
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f \t %1.3f",dw, lrp_ab);
}
printf("\n");
}
//Lrp iterations
for(int i = 0; i < num_LRP_iterations; i++){
//exponential iterative decrease of weight change step
dw = dw_start * exp(-i/dw_tau);
//Lrp select action
selected_action = Lrp->Select_Action(TOM_LRP_SELECT_ACTION_CHECK_SUM);
//apply action
funcApp1->Action_Update_Weights(selected_action, dw);
//optimizingPlayer->UCT_param_C = funcApp1->parameter_weights[0];
//evaluate new setting
previous_score = score; //save previous score
score = game->Evaluate_Players(1,num_games,-1,players,false,eval_player_position) / num_games;
if(!silence_output) printf("%d \t%5.1f%% %5.3f \t ",i+1,score*100,funcApp1->parameter_weights[0]);
//linearly proportional lrp learning parameter
lrp_ab =
lrp_ab_min + (lrp_ab_max - lrp_ab_min) * max(0.0 , min(1.0 ,
(abs(score-previous_score) - lrp_ab_dscore_min) / (lrp_ab_dscore_max - lrp_ab_dscore_min)
));
Lrp->learn_param_a = lrp_ab;
Lrp->learn_param_b = lrp_ab;
//Lrp correct probabilites based on previous and current score
if(score > previous_score){
Lrp->Update_Probabilites_Reward(selected_action,Lrp->learn_param_a);
if(!silence_output) if(show_full_output) printf("+");
}else{
Lrp->Update_Probabilites_Penalty(selected_action,Lrp->learn_param_b);
if(!silence_output) if(show_full_output) printf("-");
}
if(!silence_output){
if(show_full_output){
printf("%d \t ",selected_action);
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f \t %1.3f",dw, lrp_ab);
}
printf("\n");
}
//remember best
//if(score >= best_score){
// best_iteration = i;
// best_score = score;
// best_paramC = playerUCT1->UCT_param_C;
//}
//update score
score_history->Add_Sample(score);
}
//--- LRP algorithm END---//
cpu_time = getCPUTime()-cpu_time;
//output best
//printf("\nBest score: %5.1f%% \t P1->Cp %5.3f \t i %d\n", best_score*100, best_paramC, best_iteration+1);
//output values
score_history->Calc_AvgDev();
double score10 = score_history->Calc_Avg_On_Interval((int)(num_LRP_iterations*0.9), num_LRP_iterations);
if(!silence_output){
printf("\navg100 dev100 \t avg10 \t FinPar\n");
printf("%3.2f %3.2f \t %3.2f \t %3.4f\n",score_history->avg*100, score_history->dev*100, score10*100, funcApp1->parameter_weights[0]);
printf("\n\nTotalRuntime: %9.3f s\n", cpu_time);
}
//return values
if(score_avg != NULL)
(*score_avg) = score_history->Calc_Avg();
if(output_param != NULL)
(*output_param) = funcApp1->parameter_weights[0];
if(score_avg_last10 != NULL)
(*score_avg_last10) = score_history->Calc_Avg_On_Interval((int)(num_LRP_iterations*0.9), num_LRP_iterations);
//free memory
delete(score_history);
delete(Lrp);
delete(optimizingPlayer);
delete(opponent);
delete(game);
}
//LRP learning
// with proportionally linearly changing learning parameters a and b
// with exponentialy decreasing weight change step
void LRP_test_linAB_exponentDW(double* score_avg, double* score_avg_last10, double* output_param)
{
const int num_simulations = 100;
const int num_games = 200;
const int num_LRP_iterations = 100;
const double dw_start = 0.020;
const double dw_limit = 0.001;
const double lrp_ab_min = 0.02;
const double lrp_ab_max = 0.20;
const double lrp_ab_dscore_min = 1.0 / (double)num_games;
const double lrp_ab_dscore_max = lrp_ab_dscore_min * 10.0; //MUST BE HIGHER OR EQUAL TO lrp_ab_dscore_min
const double start_c1 = 1.0;
const double start_c2 = 0.0;
//Game_Engine* game = new Game_Gomoku();
Game_Engine* game = new Game_ConnectFour();
Tom_Lrp* Lrp = new Tom_Lrp();
Lrp->Initialize();
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(game);
Player_AI_UCT* playerUCT2 = new Player_AI_UCT(game);
Player_Engine* players[] = {playerUCT1,playerUCT2};
((Player_AI_UCT*) players[0])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[1])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[0])->UCT_param_C = start_c1;
((Player_AI_UCT*) players[1])->UCT_param_C = start_c2;
//results storage
Tom_Sample_Storage<double>* score_history = new Tom_Sample_Storage<double>(num_LRP_iterations);
srand((unsigned int)time(NULL));
double cpu_time = getCPUTime();
//calculate exponential time constant
double dw_tau = (double) num_LRP_iterations / (log(dw_start/dw_limit));
//output test settings
//printf("LRP_test_linAB_exponentDW()\n");
//printf("Test setup:\n");
//printf(" game %s sim %4d games %4d\n",game->game_name.c_str(), num_simulations, num_games);
//printf(" LRP_iter %5d\n", num_LRP_iterations);
//printf(" LRP_ab_min %1.3f LRP_ab_max %1.3f dScoreMin %1.3f dScoreMax %1.3f\n", lrp_ab_min, lrp_ab_max, lrp_ab_dscore_min, lrp_ab_dscore_max);
//printf(" dw_start %1.5f dw_limit %1.5f dw_tau %1.5f\n", dw_start, dw_limit, dw_tau);
//printf(" c1 %1.3f c2 %1.3f\n\n", start_c1, start_c2);
//--- LRP algorithm ---//
double score, previous_score;
int selected_action;
double dw = dw_start;
double lrp_ab = 0.0;
//evaluate starting setting
score = game->Evaluate_Players(1,num_games,-1,players,false,0) / num_games;
int best_iteration = -1;
double best_score = score;
double best_paramC = start_c1;
//printf(" \t \t pr[%%] pr[%%]\n");
//printf("i \t score P1->Cp \t action A0 A1 \t\t dw \t\t lrp_ab\n");
//printf("%d \t%5.1f%% ",0,score*100);
//printf(" %5.3f \t ", playerUCT1->UCT_param_C);
//printf("// \t ");
//Lrp->Debug_Display_Probabilites(0);
//printf(" \t %1.5f \t %1.3f",dw, lrp_ab);
//printf("\n");
//Lrp iterations
for(int i = 0; i < num_LRP_iterations; i++){
//exponential iterative decrease of weight change step
dw = dw_start * exp(-i/dw_tau);
//Lrp select action
selected_action = Lrp->Select_Action(TOM_LRP_SELECT_ACTION_CHECK_SUM);
//apply action
if(selected_action == 0)
playerUCT1->UCT_param_C += dw;
else
playerUCT1->UCT_param_C -= dw;
//evaluate new setting
previous_score = score; //save previous score
score = game->Evaluate_Players(1,num_games,-1,players,false,0) / num_games;
//printf("%d \t%5.1f%% ",i+1,score*100);
//printf(" %5.3f \t ", playerUCT1->UCT_param_C);
//linearly proportional lrp learning parameter
lrp_ab =
lrp_ab_min + (lrp_ab_max - lrp_ab_min) * max(0.0 , min(1.0 ,
(abs(score-previous_score) - lrp_ab_dscore_min) / (lrp_ab_dscore_max - lrp_ab_dscore_min)
));
Lrp->learn_param_a = lrp_ab;
Lrp->learn_param_b = lrp_ab;
//Lrp correct probabilites based on previous and current score
if(score > previous_score){
Lrp->Update_Probabilites_Reward(selected_action,Lrp->learn_param_a);
//printf("+");
}else{
Lrp->Update_Probabilites_Penalty(selected_action,Lrp->learn_param_b);
//printf("-");
}
//printf("%d \t ",selected_action);
//Lrp->Debug_Display_Probabilites(0);
//
//printf(" \t %1.5f \t %1.3f",dw, lrp_ab);
//printf("\n");
//remember best
//if(score >= best_score){
// best_iteration = i;
// best_score = score;
// best_paramC = playerUCT1->UCT_param_C;
//}
//update score
score_history->Add_Sample(score);
}
//--- LRP algorithm END---//
//output best
//printf("\nBest score: %5.1f%% \t P1->Cp %5.3f \t i %d\n", best_score*100, best_paramC, best_iteration+1);
cpu_time = getCPUTime()-cpu_time;
//printf("\n\nTotalRuntime: %9.3f s\n", cpu_time);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Reward(0,Lrp->learn_param_a);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Penalty(1,Lrp->learn_param_b);
//Lrp->Debug_Display_Probabilites();
//Lrp->State_Reset();
//Lrp->Debug_Display_Probabilites();
//delete(Lrp);
//output values
(*score_avg) = score_history->Calc_Avg();
(*output_param) = playerUCT1->UCT_param_C;
(*score_avg_last10) = score_history->Calc_Avg_On_Interval((int)(num_LRP_iterations*0.9), num_LRP_iterations);
//free memory
delete(score_history);
delete(Lrp);
delete(playerUCT1);
delete(playerUCT2);
delete(game);
}
//LRP learning with exponentially decreasing weight change step
void LRP_test_exponentDW()
{
int num_simulations = 100;
int num_games = 200;
int num_LRP_iterations = 100;
double dw_start = 0.05;
double dw_limit = 0.001;
double lrp_ab = 0.1;
double start_c1 = 1.0;
double start_c2 = 0.0;
//Game_Engine* game = new Game_Gomoku();
Game_Engine* game = new Game_ConnectFour();
Tom_Lrp* Lrp = new Tom_Lrp();
Lrp->Initialize();
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(game);
Player_AI_UCT* playerUCT2 = new Player_AI_UCT(game);
Player_Engine* players[] = {playerUCT1,playerUCT2};
((Player_AI_UCT*) players[0])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[1])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[0])->UCT_param_C = start_c1;
((Player_AI_UCT*) players[1])->UCT_param_C = start_c2;
srand((unsigned int)time(NULL));
double cpu_time = getCPUTime();
//calculate exponential time constant
double dw_tau = (double) num_LRP_iterations / (log(dw_start/dw_limit));
//output test settings
printf("LRP_test_exponentDW()\n");
printf("Test setup:\n");
printf(" game %s sim %4d games %4d\n",game->game_name.c_str(), num_simulations, num_games);
printf(" LRP_iter %5d LRP_ab %1.3f\n", num_LRP_iterations, lrp_ab);
printf(" dw_start %1.5f dw_limit %1.5f dw_tau %1.5f\n", dw_start, dw_limit, dw_tau);
printf(" c1 %1.3f c2 %1.3f\n\n", start_c1, start_c2);
Lrp->learn_param_a = lrp_ab;
Lrp->learn_param_b = lrp_ab;
//--- LRP algorithm ---//
double score, previous_score;
int selected_action;
double dw = dw_start;
//evaluate starting setting
score = game->Evaluate_Players(1,num_games,-1,players) / num_games;
int best_iteration = -1;
double best_score = score;
double best_paramC = start_c1;
printf(" \t \t pr[%%] pr[%%]\n");
printf("i \t score P1->Cp \t action A0 A1 \t \t dw\n");
printf("%d \t%5.1f%% ",0,score*100);
printf(" %5.3f \t ", playerUCT1->UCT_param_C);
printf("// \t ");
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f",dw);
printf("\n");
//Lrp iterations
for(int i = 0; i < num_LRP_iterations; i++){
//exponential iterative decrease of weight change step
dw = dw_start * exp(-i/dw_tau);
//Lrp select action
selected_action = Lrp->Select_Action(TOM_LRP_SELECT_ACTION_CHECK_SUM);
//apply action
if(selected_action == 0)
playerUCT1->UCT_param_C += dw;
else
playerUCT1->UCT_param_C -= dw;
//evaluate new setting
previous_score = score; //save previous score
score = game->Evaluate_Players(1,num_games,-1,players) / num_games;
printf("%d \t%5.1f%% ",i+1,score*100);
printf(" %5.3f \t ", playerUCT1->UCT_param_C);
//Lrp correct probabilites based on previous and current score
if(score > previous_score){
Lrp->Update_Probabilites_Reward(selected_action,Lrp->learn_param_a);
printf("+");
}else{
Lrp->Update_Probabilites_Penalty(selected_action,Lrp->learn_param_b);
printf("-");
}
printf("%d \t ",selected_action);
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f",dw);
printf("\n");
//remember best
if(score >= best_score){
best_iteration = i;
best_score = score;
best_paramC = playerUCT1->UCT_param_C;
}
}
//--- LRP algorithm END---//
//output best
printf("\nBest score: %5.1f%% \t P1->Cp %5.3f \t i %d\n", best_score*100, best_paramC, best_iteration+1);
cpu_time = getCPUTime()-cpu_time;
printf("\n\nTotalRuntime: %9.3f s\n", cpu_time);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Reward(0,Lrp->learn_param_a);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Penalty(1,Lrp->learn_param_b);
//Lrp->Debug_Display_Probabilites();
//Lrp->State_Reset();
//Lrp->Debug_Display_Probabilites();
//delete(Lrp);
}
//LRP learning with linearly decreasing weight change step
void LRP_test_linearDW()
{
int num_simulations = 100;
int num_games = 200;
int num_LRP_iterations = 100;
double dw_max = 0.2;
double dw_min = 0.001;
double lrp_ab = 0.1;
double start_c1 = 1.0;
double start_c2 = 0.0;
//Game_Engine* game = new Game_Gomoku();
Game_Engine* game = new Game_ConnectFour();
Tom_Lrp* Lrp = new Tom_Lrp();
Lrp->Initialize();
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(game);
Player_AI_UCT* playerUCT2 = new Player_AI_UCT(game);
Player_Engine* players[] = {playerUCT1,playerUCT2};
((Player_AI_UCT*) players[0])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[1])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[0])->UCT_param_C = start_c1;
((Player_AI_UCT*) players[1])->UCT_param_C = start_c2;
srand((unsigned int)time(NULL));
double cpu_time = getCPUTime();
printf("LRP_test_linearDW()\n");
printf("Test setup:\n");
printf(" game %s sim %4d games %4d\n",game->game_name.c_str(), num_simulations, num_games);
printf(" LRP_iter %5d LRP_ab %1.3f\n", num_LRP_iterations, lrp_ab);
printf(" dw_max %1.5f dw_min %1.5f\n", dw_max, dw_min);
printf(" c1 %1.3f c2 %1.3f\n\n", start_c1, start_c2);
Lrp->learn_param_a = lrp_ab;
Lrp->learn_param_b = lrp_ab;
//--- LRP algorithm ---//
double score, previous_score;
int selected_action;
double dw = dw_max;
//evaluate starting setting
score = game->Evaluate_Players(1,num_games,-1,players) / num_games;
int best_iteration = -1;
double best_score = score;
double best_paramC = start_c1;
printf(" \t \t pr[%%] pr[%%]\n");
printf("i \t score P1->Cp \t action A0 A1 \t \t dw\n");
printf("%d \t%5.1f%% ",0,score*100);
printf(" %5.3f \t ", playerUCT1->UCT_param_C);
printf("// \t ");
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f",dw);
printf("\n");
//Lrp iterations
for(int i = 0; i < num_LRP_iterations; i++){
//linear decrease of weight change step
dw = dw_min + (dw_max - dw_min) * (1.0 - (double)i/(num_LRP_iterations-1));
//Lrp select action
selected_action = Lrp->Select_Action(TOM_LRP_SELECT_ACTION_CHECK_SUM);
//apply action
if(selected_action == 0)
playerUCT1->UCT_param_C += dw;
else
playerUCT1->UCT_param_C -= dw;
//evaluate new setting
previous_score = score; //save previous score
score = game->Evaluate_Players(1,num_games,-1,players) / num_games;
printf("%d \t%5.1f%% ",i+1,score*100);
printf(" %5.3f \t ", playerUCT1->UCT_param_C);
//Lrp correct probabilites based on previous and current score
if(score > previous_score){
Lrp->Update_Probabilites_Reward(selected_action,Lrp->learn_param_a);
printf("+");
}else{
Lrp->Update_Probabilites_Penalty(selected_action,Lrp->learn_param_b);
printf("-");
}
printf("%d \t ",selected_action);
Lrp->Debug_Display_Probabilites(0);
printf(" \t %1.5f",dw);
printf("\n");
//remember best
if(score >= best_score){
best_iteration = i;
best_score = score;
best_paramC = playerUCT1->UCT_param_C;
}
}
//--- LRP algorithm END---//
//output best
printf("\nBest score: %5.1f%% \t P1->Cp %5.3f \t i %d\n", best_score*100, best_paramC, best_iteration+1);
cpu_time = getCPUTime()-cpu_time;
printf("\n\nTotalRuntime: %9.3f s\n", cpu_time);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Reward(0,Lrp->learn_param_a);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Penalty(1,Lrp->learn_param_b);
//Lrp->Debug_Display_Probabilites();
//Lrp->State_Reset();
//Lrp->Debug_Display_Probabilites();
//delete(Lrp);
}
//BASIC LRP learning with fixed parameters
void LRP_test_basic()
{
int num_simulations = 100;
int num_games = 200;
int num_LRP_iterations = 5;
double dw = 0.01;
double lrp_ab = 0.1;
double start_c1 = 0.0;
double start_c2 = 0.0;
//Game_Engine* game = new Game_Gomoku();
Game_Engine* game = new Game_ConnectFour();
Tom_Lrp* Lrp = new Tom_Lrp();
Lrp->Initialize();
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(game);
Player_AI_UCT* playerUCT2 = new Player_AI_UCT(game);
Player_Engine* players[] = {playerUCT1,playerUCT2};
((Player_AI_UCT*) players[0])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[1])->UCT_param_IterNum = num_simulations;
((Player_AI_UCT*) players[0])->UCT_param_C = start_c1;
((Player_AI_UCT*) players[1])->UCT_param_C = start_c2;
srand((unsigned int)time(NULL));
double cpu_time = getCPUTime();
printf("LRP_test_basic()\n");
printf("Test setup:\n");
printf(" game %s sim %4d games %4d\n",game->game_name.c_str(), num_simulations, num_games);
printf(" LRP_iter %5d LRP_ab %1.3f dw %1.3f\n", num_LRP_iterations, lrp_ab, dw);
printf(" c1 %1.3f c2 %1.3f\n\n", start_c1, start_c2);
Lrp->learn_param_a = lrp_ab;
Lrp->learn_param_b = lrp_ab;
//--- LRP algorithm ---//
double score, previous_score;
int selected_action;
//evaluate starting setting
score = game->Evaluate_Players(1,num_games,-1,players) / num_games;
int best_iteration = -1;
double best_score = score;
double best_paramC = start_c1;
printf(" \t \t pr[%%] pr[%%]\n");
printf("i \t score P1->Cp \t action A0 A1\n",score*100);
printf("%d \t%5.1f%% ",0,score*100);
printf(" %5.3f \t ", playerUCT1->UCT_param_C);
printf("// \t ");
Lrp->Debug_Display_Probabilites(0);
printf("\n");
//Lrp iterations
for(int i = 0; i < num_LRP_iterations; i++){
//Lrp select action
selected_action = Lrp->Select_Action(TOM_LRP_SELECT_ACTION_CHECK_SUM);
//apply action
if(selected_action == 0)
playerUCT1->UCT_param_C += dw;
else
playerUCT1->UCT_param_C -= dw;
//evaluate new setting
previous_score = score; //save previous score
score = game->Evaluate_Players(1,num_games,-1,players) / num_games;
printf("%d \t%5.1f%% ",i+1,score*100);
printf(" %5.3f \t ", playerUCT1->UCT_param_C);
//Lrp correct probabilites based on previous and current score
if(score > previous_score){
Lrp->Update_Probabilites_Reward(selected_action,Lrp->learn_param_a);
printf("+");
}else{
Lrp->Update_Probabilites_Penalty(selected_action,Lrp->learn_param_b);
printf("-");
}
printf("%d \t ",selected_action);
Lrp->Debug_Display_Probabilites(0);
printf("\n");
//remember best
if(score >= best_score){
best_iteration = i;
best_score = score;
best_paramC = playerUCT1->UCT_param_C;
}
}
//--- LRP algorithm END---//
//output best
printf("\nBest score: %5.1f%% \t P1->Cp %5.3f \t i %d\n", best_score*100, best_paramC, best_iteration+1);
cpu_time = getCPUTime()-cpu_time;
printf("\n\nTotalRuntime: %9.3f s\n", cpu_time);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Reward(0,Lrp->learn_param_a);
//Lrp->Debug_Display_Probabilites();
//Lrp->Update_Probabilites_Penalty(1,Lrp->learn_param_b);
//Lrp->Debug_Display_Probabilites();
//Lrp->State_Reset();
//Lrp->Debug_Display_Probabilites();
//delete(Lrp);
}
void AMAF_Testing()
{
Game_Engine* ticTac = new Game_ConnectFour();
//Game_Engine* ticTac = new Game_Gomoku();
//Game_Engine* ticTac = new Game_TicTacToe();
Player_Human* playerHuman = new Player_Human(ticTac);
Player_AI_UCT* playerUCT = new Player_AI_UCT(ticTac);
Player_AI_UCT_AMAF* playerUCT_AMAF = new Player_AI_UCT_AMAF(ticTac);
Player_AI_UCT_RAVE* playerUCT_RAVE = new Player_AI_UCT_RAVE(ticTac);
Player_Random* playerRandom = new Player_Random(ticTac);
Player_AI_UCT_TomTest* UCTtest = new Player_AI_UCT_TomTest(ticTac);
//Player_Engine* players[] = {playerUCT_AMAF,playerUCT_RAVE};
Player_Engine* players[] = {UCTtest,playerUCT};
ticTac->players = players;
playerUCT->UCT_param_IterNum = 100;
playerUCT_RAVE->UCT_param_IterNum = playerUCT_AMAF->UCT_param_IterNum = playerUCT->UCT_param_IterNum;
//playerUCT->UCT_param_C = 1.0 / (2*sqrt(2));
playerUCT_RAVE->RAVE_param_V = 15.0;
srand((unsigned int)time(NULL));
//Player_Engine* tmpPlayer;
//for(int i = 0; i < 10; i++){
//ticTac->Evaluate_Players(1,1000,TOMGAME_OUTPUT_DEPTH0,players);
//tmpPlayer = players[0]; players[0] = players[1]; players[1] = tmpPlayer;
//ticTac->Evaluate_Players(1,1000,TOMGAME_OUTPUT_DEPTH0,players);
//tmpPlayer = players[0]; players[0] = players[1]; players[1] = tmpPlayer;
//
//playerUCT_RAVE->RAVE_param_V += 2.0;
//playerUCT->UCT_param_IterNum += 50;
//playerUCT_AMAF->UCT_param_IterNum = playerUCT1->UCT_param_IterNum;
//}
//ticTac->Simulate_Output_Game();
double approx_worse_C = 0.0;
double approx_optimal_C = 0.175; //ticTac 0.1 ; conn4 0.175 ; gomoku ??
int sim1 = 100;
int sim2 = 200;
UCTtest->UCT_param_IterNum = sim1;
playerUCT->UCT_param_IterNum = sim1;
//test1
UCTtest->UCT_param_C = approx_worse_C;
playerUCT->UCT_param_C = approx_worse_C;
printf("\n\n%d %d %3.3f %3.3f",UCTtest->UCT_param_IterNum,playerUCT->UCT_param_IterNum,UCTtest->UCT_param_C,playerUCT->UCT_param_C);
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
UCTtest->UCT_param_C = approx_optimal_C;
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
//test2
UCTtest->UCT_param_C = approx_worse_C;
playerUCT->UCT_param_C = approx_optimal_C;
printf("\n\n%d %d %3.3f %3.3f",UCTtest->UCT_param_IterNum,playerUCT->UCT_param_IterNum,UCTtest->UCT_param_C,playerUCT->UCT_param_C);
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
UCTtest->UCT_param_C = approx_optimal_C;
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
//test3
UCTtest->UCT_param_IterNum = sim2;
playerUCT->UCT_param_IterNum = sim2;
UCTtest->UCT_param_C = approx_worse_C;
playerUCT->UCT_param_C = approx_worse_C;
printf("\n\n%d %d %3.3f %3.3f",UCTtest->UCT_param_IterNum,playerUCT->UCT_param_IterNum,UCTtest->UCT_param_C,playerUCT->UCT_param_C);
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
UCTtest->UCT_param_C = approx_optimal_C;
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
//test4
UCTtest->UCT_param_C = approx_worse_C;
playerUCT->UCT_param_C = approx_optimal_C;
printf("\n\n%d %d %3.3f %3.3f",UCTtest->UCT_param_IterNum,playerUCT->UCT_param_IterNum,UCTtest->UCT_param_C,playerUCT->UCT_param_C);
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
UCTtest->UCT_param_C = approx_optimal_C;
AMAF_Testing_Extensive(ticTac, players, 0, 2, 1000, true);
}
void AMAF_Testing_Extensive(Game_Engine* game, Player_Engine** players, int simulations, int repeats, int games, const bool disable_sim_set)
{
Player_Engine* tmpPlayer;
if(!disable_sim_set){
((Player_AI_UCT_AMAF*) players[0])->UCT_param_IterNum = simulations;
((Player_AI_UCT*) players[1])->UCT_param_IterNum = simulations;
}
//printf("\nProcedure AMAF_Testing_Extensive()\n");
//printf("\nAMAF variant: %d", TOMPLAYER_AI_UCT_AMAF_VARIANT);
//printf("\nAMAF ignore unexpanded: %d", TOMPLAYER_AI_UCT_AMAF_IGNORE_UNTIL_EXPANDED);
//printf("\nMCTS simulations: %d\n", simulations);
game->Evaluate_Players(repeats,games,TOMGAME_OUTPUT_DEPTH0,players);
//printf("\n\nPlayer swap\n");
tmpPlayer = players[0]; players[0] = players[1]; players[1] = tmpPlayer;
game->Evaluate_Players(repeats,games,TOMGAME_OUTPUT_DEPTH0,players);
//reswap players
tmpPlayer = players[0]; players[0] = players[1]; players[1] = tmpPlayer;
}
void FileRead_Test()
{
fprintf(stderr,"Test error output channel\n");
double** inputData;
int nRows, nColumns;
Read_Input_File_Double(&inputData,&nRows,&nColumns,"testInput.txt");
printf("File successfully read: num samples %d, num atributes %d\n",nRows,nColumns);
for(int i = 0; i < nRows; i++)
delete(inputData[i]);
delete(inputData);
}
void EEG_Testing()
{
//DEBUG TESTING
//Game_Engine *diffSim = new Game_EEG();
//Player_Passive *player = new Player_Passive(diffSim);
////Player_SameMove *player= new Player_SameMove(diffSim); player->move = 3;
//Player_Engine* players[] = {player};
//diffSim->players = players;
//diffSim->Simulate_Output_Game();
////diffSim->Debug_Random_Move_Output();
////diffSim->Debug_Random_Move_Output(10);
////diffSim->Debug_Test_Sequence();
//-END DEBUG
string testFileName;
Game_Engine *diffSim = new Game_EEG(); extern_call_command = ".\\Source\\matlab_code\\call_command_EEG.bat";
//testFileName = "testInput_1.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str(),0,1/20);
//testFileName = "testInput_2.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str(),0,1/20);
//testFileName = "testInput_3.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str(),0.0,0.05);
//testFileName = "testInput_4.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str(),0,1/20);
//testFileName = "testInput_5.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str(),0,1/20);
//testFileName = "testInput_6.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str(),0,1/20);
//testFileName = "testInput_Simple.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str(),0,1/20);
//!!! WARNING!!! WHEN CHANGING INPUT FILE you must change the value of TOMGAME_EEG_MOVING_AVG_SAMPLES in Game_EEG.hpp !!!
//testFileName = "EEG_input1.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str());
//testFileName = "EEG_input2.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str());
testFileName = "EEG_input3.txt"; ((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str());
//Player_Human *player = new Player_Human(diffSim);
Player_Passive *player= new Player_Passive(diffSim);
//Player_Random *player = new Player_Random(diffSim);
//Player_SameMove *player= new Player_SameMove(diffSim); player->move = 3;
//Player_AI_Simple *player= new Player_AI_Simple(diffSim);
Player_AI_UCT *pUCT;
//pUCT = new Player_AI_UCT(diffSim);
pUCT = new Player_AI_UCT_Reinforce(diffSim);
//pUCT = new Player_AI_UCT_Reinforce_DPrepeat(diffSim);
//pUCT = new Player_AI_UCT_Reinforce_DPpassive(diffSim);
pUCT->UCT_param_IterNum = 9;
pUCT->UCT_param_defaultPolicy_maxPlys = 1;
//pUCT->UCT_param_C = 0.0;
//pUCT->UCT_param_C = 0.08;
//pUCT->UCT_param_C = 100;
Player_Engine* players[] = {pUCT};
//Player_Engine* players[] = {player};
DiffSim_Testing(diffSim, players, testFileName);
}
void Lotka_Testing(){
string testFileName;
Game_Engine *diffSim = new Game_DiffSim(); extern_call_command = ".\\Source\\matlab_code\\call_command.bat";
testFileName = "testInput_1.txt";
//testFileName = "testInput_2.txt";
//testFileName = "testInput_3.txt";
//testFileName = "testInput_4.txt";
//testFileName = "testInput_5.txt"; //WARNING: TOMGAME_DIFFSIM_TMP_TARGET_MAX_DIFF in Game_DiffSim.hpp must be set to 100.0 (otherwise score is always 0.0)
//testFileName = "testInput_6.txt";
//testFileName = "testInput_Simple.txt";
((Game_DiffSim*)diffSim)->Set_Target_Trajectory_From_File(testFileName.c_str());
//Player_Human *player = new Player_Human(diffSim);
Player_Passive *player= new Player_Passive(diffSim);
//Player_Random *player = new Player_Random(diffSim);
//Player_SameMove *player= new Player_SameMove(diffSim); player->move = 3;
//Player_AI_Simple *player= new Player_AI_Simple(diffSim);
Player_AI_UCT *pUCT;
pUCT = new Player_AI_UCT(diffSim);
//pUCT = new Player_AI_UCT_Reinforce(diffSim);
//pUCT = new Player_AI_UCT_Reinforce_DPrepeat(diffSim);
//pUCT = new Player_AI_UCT_Reinforce_DPpassive(diffSim);
pUCT->UCT_param_IterNum = 100;
pUCT->UCT_param_defaultPolicy_maxPlys = 1;
//pUCT->UCT_param_C = 0.0;
//pUCT->UCT_param_C = 0.08;
//pUCT->UCT_param_C = 100;
Player_Engine* players[] = {pUCT};
//Player_Engine* players[] = {player};
DiffSim_Testing(diffSim, players, testFileName);
}
void DiffSim_Testing(Game_Engine* diffSim, Player_Engine* players[], string testFileName)
{
diffSim->players = players;
double cpu_time = getCPUTime();
#if(!TOM_OUTPUT_TO_MATLAB)
#if(!TOM_EXTENSIVE_TEST)
diffSim->Simulate_Output_Game();
#else
Player_AI_UCT* pUCT = (Player_AI_UCT*)(players[0]);
//choose test learning algorithms
Player_AI_UCT* pUCTlist[] = {
new Player_AI_UCT(diffSim),
new Player_AI_UCT_Reinforce(diffSim),
new Player_AI_UCT_Reinforce_DPrepeat(diffSim),
new Player_AI_UCT_Reinforce_DPpassive(diffSim)
};
int test_num_algorithms = sizeof(pUCTlist) / sizeof(Player_AI_UCT*);
//set multiple test configuration
int test_base_val_SimNum = 9;
int test_base_val_maxPlys = 1;
double test_base_val_paramC = pUCT->UCT_param_C;
int test_comb_num_SimNum = 3;
int test_comb_num_maxPlys = 3;
int test_comb_num_paramC = 2;
double test_fact_SimNum = 9.0;
double test_fact_maxPlys = 5.0;
double test_fact_paramC = 0.0000001;
int runs = 1;
int repeats = 100;
//---execute testing---
printf("\n");
printf("%s\n",(diffSim->game_name).c_str());
printf("%s\n",testFileName.c_str());
//run tests
for(int i = 0; i < test_comb_num_SimNum*test_comb_num_maxPlys*test_comb_num_paramC; i++){
int tsimnum = (int)(test_base_val_SimNum * pow(test_fact_SimNum , i % test_comb_num_SimNum));
int tmaxply = (int)(test_base_val_maxPlys * pow(test_fact_maxPlys , (int)(i/test_comb_num_SimNum) % test_comb_num_maxPlys));
double tparamc = pUCT->UCT_param_C = test_base_val_paramC * pow(test_fact_paramC , (int)((int)(i/test_comb_num_SimNum)/test_comb_num_maxPlys) % test_comb_num_paramC);
printf("\nnSim %d nPly %d parC %1.3f",tsimnum,tmaxply,tparamc);
for(int ac = 0; ac < test_num_algorithms; ac++){
pUCT = pUCTlist[ac];
pUCT->UCT_param_IterNum = tsimnum;
pUCT->UCT_param_defaultPolicy_maxPlys = tmaxply;
pUCT->UCT_param_C = tparamc;
players[0] = pUCT;
diffSim->Evaluate_Players(runs,repeats,TOMGAME_OUTPUT_DEPTH0,players);
}
}
#endif
#else
//traning games for simple AI
if(dynamic_cast<Player_AI_Simple*>(players[0]) != NULL){
diffSim->Learn_Players(1000,0);
diffSim->Game_Reset();
}
//single output game
diffSim->Simulate_Output_Game();
#endif
cpu_time = getCPUTime()-cpu_time;
//------------------------------------------------
//WRITE CONFIGURATION
#if(TOM_OUTPUT_TO_MATLAB)
FILE* outputConfStream;
//create directory (if not already) and open file ".\Runtime_Output\output_conf.txt"
if (CreateDirectoryA(".\\Runtime_Output", NULL) || ERROR_ALREADY_EXISTS == GetLastError()){
fopen(&outputConfStream, (TOM_OUTPUT_FOLDER + output_conf_filename).c_str() ,"w");
}else{ // Failed to create directory.
printf("WARNING: unable to create 'Runtime_Output' directory, output stream will not be created!");
}
//write configuration data
fprintf(outputConfStream,"%s\n",(diffSim->game_name).c_str());
fprintf(outputConfStream,"%s\n",testFileName.c_str());
fprintf(outputConfStream,"\n");
diffSim->Calculate_Score();
fprintf(outputConfStream,"Score: %8.6f\n",diffSim->score[0]);
fprintf(outputConfStream,"\n");
fprintf(outputConfStream,"%s\n",(players[0]->player_name).c_str());
if(dynamic_cast<Player_AI_UCT*>(players[0]) != NULL){
fprintf(outputConfStream," num Sim: %d\n",((Player_AI_UCT*)players[0])->UCT_param_IterNum);
fprintf(outputConfStream," ply Lim: %d\n",((Player_AI_UCT*)players[0])->UCT_param_defaultPolicy_maxPlys);
fprintf(outputConfStream," par C: %6.3f\n",((Player_AI_UCT*)players[0])->UCT_param_C);
}
fprintf(outputConfStream,"\n");
fprintf(outputConfStream,"Runtime: %9.3f s", cpu_time);
//close file
fclose(outputConfStream);
#endif
//diffSim->Game_Reset();
//diffSim->Debug_Random_Move_Output();
//diffSim->Debug_Test_Sequence();
}
void Benchmark()
{
//-------------- set up benchmark test here --------------
//choose benchmark game/problem
Game_Engine *game1 = new Game_TicTacToe();
//Game_Engine *game1 = new Game_ConnectFour();
//Game_Engine *game1 = new Game_Gomoku();
//player allocation
Player_AI_UCT *pUCT1 = new Player_AI_UCT();
Player_AI_UCT *pUCT2 = new Player_AI_UCT(game1);
Player_AI_Simple *pSim1 = new Player_AI_Simple(game1);
Player_AI_Simple *pSim2 = new Player_AI_Simple(game1);
Player_Random *pRan1 = new Player_Random(game1);
Player_Random *pRan2 = new Player_Random(game1);
Player_Human *pHuman = new Player_Human(game1);
//benchmark visualization and runtime settings
int learn_out_depth = 0;
int eval_out_depth = 1;
//game settings
int num_repeats = 10;
int num_games = 1000;
//player/learning settings
int UCT_simulations = 1000;
int learning_games = 100000; //= UCT_simulations*num_games*num_repeats
double UCT_C = 1.0 / (2*sqrt(2));
pUCT1->Reset_Settings();
pUCT1->Reset_Settings(game1);
pUCT1->UCT_param_IterNum = UCT_simulations;
pUCT2->UCT_param_IterNum = UCT_simulations;
pUCT1->UCT_param_C = UCT_C;
pUCT2->UCT_param_C = UCT_C;
pSim1->player_number = 0;
pSim2->player_number = 1;
pSim1->external_reset_enabled = 0;
pSim2->external_reset_enabled = 0;
//----------------- execute experiments -----------------------
//pre-learning
game1->Learn_Two_Players(learning_games,learn_out_depth, pSim1, pSim2);
game1->Learn_Two_Players(learning_games,learn_out_depth, pSim1, pRan2);
game1->Learn_Two_Players(learning_games,learn_out_depth, pRan1, pSim2);
//evaulation
game1->Evaluate_Two_Players(num_repeats,num_games,eval_out_depth, pUCT1, pUCT1);
game1->Evaluate_Two_Players(num_repeats,num_games,eval_out_depth, pUCT1, pUCT2);
game1->Evaluate_Two_Players(num_repeats,num_games,eval_out_depth, pUCT1, pRan1);
game1->Evaluate_Two_Players(num_repeats,num_games,eval_out_depth, pUCT1, pSim2);
game1->Evaluate_Two_Players(num_repeats,num_games,eval_out_depth, pSim1, pUCT1);
//----------------- clear -----------------------
delete(pUCT1);
delete(pUCT2);
delete(pSim1);
delete(pSim2);
delete(pRan1);
delete(pRan2);
delete(pHuman);
delete(game1);
}
void ConnectFour_Testing()
{
Game_Engine* ticTac = new Game_ConnectFour();
//ticTac->Debug_Test_Sequence();
Player_Human* playerHuman = new Player_Human(ticTac);
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(ticTac);
Player_Engine* players[] = {playerUCT1,playerUCT1};
ticTac->players = players;
playerUCT1->UCT_param_IterNum = 100;
//playerUCT1->UCT_param_C = 1.0 / (2*sqrt(2));
srand((unsigned int)time(NULL));
ticTac->Simulate_Output_Game();
}
void Gomoku_Testing()
{
Game_Engine* gomoku = new Game_Gomoku();
Player_Human* playerHuman = new Player_Human(gomoku);
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(gomoku);
Player_AI_UCT* playerUCT2 = new Player_AI_UCT(gomoku);
//Player_Engine* players[] = {playerHuman,playerUCT1};
Player_Engine* players[] = {playerUCT1,playerUCT1};
gomoku->players = players;
//players settings
playerUCT1->UCT_param_IterNum = 5000;
playerUCT1->UCT_param_C = 1.0 / (2*sqrt(2));
playerUCT2->UCT_param_IterNum = 10;
playerUCT2->UCT_param_C = 1.0 / (2*sqrt(2));
//testing
unsigned int tmpr = (unsigned int)time(NULL);
srand(tmpr);
//srand(1362238250);
//gomoku->Simulate_Output_Game();
gomoku->Game_Reset();
playerUCT1->Reset();
//playerUCT2->Reset();
gomoku->Game_Reset();
gomoku->Simulate_Output_Game(); //UGOTOVI ZAKAJ GA TUKAJ SESUJE ČE DAM 2x ZAPOREDOMA SIMULATE OUTPUT GAME
gomoku->Simulate_Output_Game();
//gomoku->Simulate_Human_Game();
printf("%d\n",tmpr);
}
void TicTacToe_Testing()
{
//Game_Engine* ticTac = new Game_ConnectFour();
Game_Engine* ticTac = new Game_TicTacToe();
//Game_Engine* ticTac = new Game_Gomoku();
//ticTac->Debug_Test_Sequence();
//players
Player_Human* playerHuman = new Player_Human(ticTac);
Player_AI_UCT* playerUCT1 = new Player_AI_UCT(ticTac);
Player_AI_UCT* playerUCT2 = new Player_AI_UCT(ticTac);
//binding objects and structures
Player_Engine* players[] = {playerUCT1,playerHuman};
ticTac->players = players;
//players settings
playerUCT1->UCT_param_IterNum = 1000;
//playerUCT1->UCT_param_C = 1.0 / (2*sqrt(2));
playerUCT2->UCT_param_IterNum = 50;
//playerUCT2->UCT_param_C = 1.0 / (2*sqrt(2));
//testing
srand((unsigned int)time(NULL));
//srand(3);
double cpu_time = getCPUTime();
//ticTac->Simulate_Output_Game();
//ticTac->Evaluate_Players(10,100);
//ticTac->Play_Move(0);
//ticTac->Play_Move(playerUCT1->Get_Move());
//ticTac->Play_Move(playerUCT1->Get_Move());
//ticTac->Play_Move(playerUCT1->Get_Move());
//playerUCT1->Output_UCT_Tree();
cpu_time = getCPUTime()-cpu_time;
printf("Runtime: %9.3f s\n",cpu_time);
ticTac->Simulate_Output_Game();
//ticTac->Debug_Test_Sequence();
//ticTac->Simulate_Human_Game();
//tt1->Debug_Test_Sequence();
//Player_AI_Simple* player1 = new Player_AI_Simple(ticTac);
//Player_AI_Simple* player2 = new Player_AI_Simple(ticTac);
//player2->player_number = 1;
//Player_Engine* players[] = {player1, player2};
////ticTac->Simulate_Output_Game(players);
//ticTac->Evaluate_Players(players,10,100);
//players[0] = new Player_Human(ticTac);
//player2->selectMoveType = TOMPlayer_AI_Simple_MOVE_TYPE_BEST;
//ticTac->Game_Reset();
//ticTac->Simulate_Output_Game(players);
}
void TicTacToe_Implementation_Test1(){
Game_TicTacToe* ticTac = new Game_TicTacToe();
Game_TicTacToe* tt1 = ticTac;
Game_Engine* tt2 = new Game_TicTacToe();
Game_Engine* tt3;
//srand((unsigned int)time(NULL));
tt1->Debug_Random_Move_Output(3);
tt1->Output_Moves_History();
tt3 = tt1->Create_Duplicate_Game();
tt3->Debug_Random_Move_Output(3);
tt3->Output_Moves_History();
tt2->Copy_Game_State_From(tt1);
tt2->Output_Moves_History();
ticTac->Debug_Test_Sequence();
tt1->Debug_Test_Sequence();
ticTac->Simulate_Human_Game();
}
//main procedure
int main(int argc, char* argv[])
{
//save program start time to global variable
#if ((_WIN32 || _WIN64) && _MSC_VER)
__time64_t long_time;
_time64( &long_time ); // Get time as 64-bit integer.
program_start_time = new struct tm();
_localtime64_s( program_start_time, &long_time ); // Convert to local time.
#else
time_t long_time;
time( &long_time );
program_start_time = localtime( &long_time); // Convert to local time.
#endif
char tmpString[256];
sprintf_s(tmpString, "__%4d-%d%d-%d%d-%d%d-%d%d-%d%d",
program_start_time->tm_year+1900,
(int)(program_start_time->tm_mon+1) / 10,
(int)(program_start_time->tm_mon+1) % 10,
(int)(program_start_time->tm_mday) / 10,
(int)(program_start_time->tm_mday) % 10,
(int)(program_start_time->tm_hour) / 10,
(int)(program_start_time->tm_hour) % 10,
(int)(program_start_time->tm_min) / 10,
(int)(program_start_time->tm_min) % 10,
(int)(program_start_time->tm_sec) / 10,
(int)(program_start_time->tm_sec) % 10
);
program_start_time_output_str = string(tmpString);
//set output filenames
output_data_filename = (string)TOM_OUTPUT_DATA_FILE_TEXT_TAG + program_start_time_output_str + ".txt";
output_conf_filename = (string)TOM_OUTPUT_CONF_FILE_TEXT_TAG + program_start_time_output_str + ".txt";
//------------------------------------------------
//PROGRAM EXECUTION settings
#if(TOM_OUTPUT_TO_MATLAB)
//generate filename
FILE* tmpStream;
//create directory (if not already) and redirect standard output to ".\Runtime_Output\output.txt"
if (CreateDirectoryA(".\\Runtime_Output", NULL) || ERROR_ALREADY_EXISTS == GetLastError()){
tmpStream = freopen((TOM_OUTPUT_FOLDER + output_data_filename).c_str() ,"w",stdout);
}else{ // Failed to create directory.
printf("WARNING: unable to create 'Runtime_Output' directory, stdout will not be redirected!");
}
#endif
//init global (multi) printer object
#if(TOM_GLOBAL_ENABLE_MCTS_OUTPUT_LEVEL)
gmp = new MultiPrinter(TOM_GLOBAL_MCTS_OUTPUT_NUM_LEVELS+1, true, "");
for(int i = 0; i < TOM_GLOBAL_MCTS_OUTPUT_NUM_LEVELS; i++){
stringstream tmpStr1;
if((i < 10)&&(TOM_GLOBAL_MCTS_OUTPUT_NUM_LEVELS > 9))
tmpStr1 << "__MCTSlvl0" << i;
else
tmpStr1 << "__MCTSlvl" << i;
gmp->filenames[i] = (string(argv[0]) + string(tmpString) + tmpStr1.str() + ".txt");
}
gmp->filenames[TOM_GLOBAL_MCTS_OUTPUT_NUM_LEVELS] = (string(argv[0]) + string(tmpString) + "__main.txt");
gmp->selected_file = TOM_GLOBAL_MCTS_OUTPUT_NUM_LEVELS; //set default duplicate output to file "__main.txt"
if( gmp->Create_Output_Files() != 0 ){
fprintf(stdout, "Program abort by Create_Output_Files()\n");
fflush(stdout);
cout << endl << "Press any key to exit.";
cin.get();
exit(EXIT_FAILURE);
}
#else
#if(!TOM_GLOBAL_DUPLICATE_OUTPUT_TO_FILE)
gmp = new MultiPrinter(1, false, string(argv[0]) + string(tmpString));
#else
gmp = new MultiPrinter(1, true, string(argv[0]) + string(tmpString));
//gmp->filenames[0] = (string(argv[0]) + string(tmpString) + ".txt");
if( gmp->Create_Output_Files() != 0 ){
fprintf(stdout, "Program abort by Create_Output_Files()\n");
fflush(stdout);
cout << endl << "Press any key to exit.";
cin.get();
exit(EXIT_FAILURE);
}
//if(argc > 0)
// gmp->Print("%s\n\n",gmp->filenames[0].c_str());
// printf("%s\n\n",gmp->filenames[0].c_str());
#endif
#endif
//------------------------------------------------
//USER CODE
Main_Testing();
//------------------------------------------------
//MAIN EXIT PROCEDURE
printf("\n\n");
//gmp->Close_Output_Files();
delete(gmp);
#if(TOM_OUTPUT_TO_MATLAB)
fclose(stdout);
tmpStream = freopen("CONOUT$", "w", stdout); //redirect standard output back to console
//call Matlab script for results visualization
system((extern_call_command + " " + output_data_filename + " " + output_conf_filename + " " + program_start_time_output_str).c_str());
#else
if((argc > 1)&&(argv[1][0] == '1')){
//do not prompt for key-press
}else{
fflush(stdout);
cout << endl << "Press any key to exit.";
cin.get();
}
#endif
}
//
//void Go_Testing()
//{
// //GoGameEngine::humanGame(2,1,0.0);
//
// //GoGameEngine::debugTestSequence();
//
// //GoGameEngine::benchmarkSeries();
//
//
// //--------------
//
// srand((unsigned int)time(NULL));
//
// //input parameters
// bool playersResetAfterRepeat[] = {0, 0};
// double playersExploreFact[] = {0.1, 0.1};
// int board_width = 2;
// int num_games_learn = 10000;
// int num_games_evaluate = 100;
// int num_repeats = 1;
// int num_UCTsimulation = 100;
//
//
// //instantiate game
// GoGameEngine* game = new GoGameEngine(board_width);
// game->komi = 0.0;
//
// //instantiate players
// PlayerGoAI_basic* player1 = new PlayerGoAI_basic(game,0,playersExploreFact[0]);
// PlayerGoAI_basic* player2 = new PlayerGoAI_basic(game,1,playersExploreFact[1]);
// player1->selectMoveType = 1;
// player2->selectMoveType = 1;
// player1->resetAfterSeries = playersResetAfterRepeat[0];
// player2->resetAfterSeries = playersResetAfterRepeat[1];
//
// PlayerGoHuman* playerHuman1 = new PlayerGoHuman(game);
//
// PlayerGoAI_UCT* playerUCT1 = new PlayerGoAI_UCT(game,0.1,num_UCTsimulation);
// PlayerGoAI_UCT* playerUCT2 = new PlayerGoAI_UCT(game,0.1,num_UCTsimulation);
// playerUCT1->UCT_defaultPolicy_maxPlys = game->board_size;
// playerUCT2->UCT_defaultPolicy_maxPlys = game->board_size;
//
// //PlayerGo* players[] = {player1human, player2};
// //PlayerGo* players[] = {player1, player2};
// //PlayerGo* players[] = {playerHuman1, playerUCT1};
// //PlayerGo* players[] = {playerUCT1, playerHuman1};
// PlayerGo* players[] = {player1, player2};
//// PlayerGo* players1[] = {player1, playerUCT1};
//// PlayerGo* players2[] = {playerUCT2, player2};
// PlayerGo* players1[] = {playerUCT1, player2};
// PlayerGo* players2[] = {player1, playerUCT2};
//
// //execute games
// //game->komi = 1.0;
// //game->playOutputGame(players);
// game->evaluatePlayersPerformance(players, 1, num_games_learn, 0.0, 0, 1.0); //learning phase for player1 and player2
// game->evaluatePlayersPerformance(players1, num_repeats, num_games_evaluate, 0.0, 1, 1.0); //basic AI players are equal with komi 1.0 and exploration 0.1
// game->evaluatePlayersPerformance(players2, num_repeats, num_games_evaluate, 0.0, 1, 1.0); //basic AI players are equal with komi 1.0 and exploration 0.1
// //game->evaluatePlayersPerformance(players, 100, 100000, 1.0, 1); //basic AI players are equal with komi 1.0 and exploration 0.1
//
// //clean up
// delete player1;
// delete player2;
// delete playerUCT1;
// delete playerUCT2;
// //delete *players; //not sure if needed
// delete game;
//
//}
|
#ifndef HOSTMANAGERWIDGET_H
#define HOSTMANAGERWIDGET_H
#include <QDialog>
class HostManager ;
class QTableView ;
class QToolBar ;
class QTextEdit ;
class QStandardItemModel ;
class HostManagerDialog : public QDialog
{
Q_OBJECT
public:
explicit HostManagerDialog(QWidget * parent = 0);
~HostManagerDialog();
private slots:
void loadHostFile();
void addItem();
void removeItem();
void accept();
void reload();
//void accept();
private:
void setup();
void initializeTableView();
void createToolButtons();
void loadDataFromFile();
private:
QTextEdit * m_fileView ;
HostManager * m_manager ;
QStandardItemModel * m_model ;
QTableView * m_tableview ;
QToolBar * m_toolBar ;
};
#endif // HOSTMANAGERWIDGET_H
|
#pragma once
#ifndef __MACROS_H_
#define __MACROS_H_
#include <map>
#include <vector>
#include <string>
#define __MY_A(V) #V
#define __MY_W(V) L##V
#define STRING std::string
#define WSTRING std::wstring
#if !defined(_UNICODE) && !defined(UNICODE)
#define TSTRING std::string
#define __MY_T(V) #V
#define __MY__TEXT(quote) quote
#else
#define TSTRING std::wstring
#define __MY_T(V) L###V
#define __MY__TEXT(quote) L##quote
#endif
#define _MY_TEXT(x) __MY__TEXT(x)
#define _MY_T(x) __MY__TEXT(x)
#define _tstring TSTRING
#define tstring TSTRING
typedef std::vector<std::string> STRINGVECTOR;
typedef std::vector<std::wstring> WSTRINGVECTOR;
typedef std::vector<STRINGVECTOR> STRINGVECTORVECTOR;
typedef std::vector<WSTRINGVECTOR> WSTRINGVECTORVECTOR;
typedef std::map<std::string, STRINGVECTOR> STRINGVECTORMAP;
typedef std::map<std::wstring, WSTRINGVECTOR> WSTRINGVECTORMAP;
typedef std::map<std::string, std::string> STRINGSTRINGMAP;
typedef std::map<std::wstring, std::wstring> WSTRINGWSTRINGMAP;
typedef std::map<std::string, STRINGSTRINGMAP> STRINGSTRINGMAPMAP;
typedef std::map<std::wstring, WSTRINGWSTRINGMAP> WSTRINGWSTRINGMAPMAP;
#define __MY_A(V) #V
#define __MY_W(V) L##V
#if !defined(_UNICODE) && !defined(UNICODE)
#define TSTRINGVECTOR STRINGVECTOR
#define TSTRINGVECTORVECTOR STRINGVECTORVECTOR
#define TSTRINGTSTRINGMAP STRINGSTRINGMAP
#define TSTRINGTSTRINGMAPMAP STRINGSTRINGMAPMAP
#define TSTRINGVECTORMAP STRINGVECTORMAP
#else
#define TSTRINGVECTOR WSTRINGVECTOR
#define TSTRINGVECTORVECTOR WSTRINGVECTORVECTOR
#define TSTRINGTSTRINGMAP WSTRINGWSTRINGMAP
#define TSTRINGTSTRINGMAPMAP WSTRINGWSTRINGMAPMAP
#define TSTRINGVECTORMAP WSTRINGVECTORMAP
#endif // !defined(_UNICODE) && !defined(UNICODE)
//传入应用程序文件名称、参数、启动类型及等待时间启动程序
typedef enum LaunchType {
LTYPE_0 = 0, //立即
LTYPE_1 = 1, //直等
LTYPE_2 = 2, //延迟(设定等待时间)
}LAUNCHTYPE;
#endif //__MACROS_H_
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef LOGDOC_H
#define LOGDOC_H
#include "modules/logdoc/markup.h"
class H5Element;
class HTML5Parser;
typedef int OP_PARSING_STATUS;
class ParsingStatus : public OpStatus
{
public:
enum
{
NEED_MORE_DATA = USER_SUCCESS + 1,
EXECUTE_SCRIPT = USER_SUCCESS + 2
};
};
class LogicalDocument
{
public:
class Script
{
public:
Script() : m_parsing_ready(TRUE) {}
BOOL IsReadyForParsing() { return m_parsing_ready; }
private:
BOOL m_parsing_ready;
};
LogicalDocument()
: m_root(NULL)
, m_parser(NULL)
, m_blocking_script(NULL)
, m_strict_mode(FALSE)
, m_quirks_line_height_mode(FALSE)
, m_doctype_name(NULL)
, m_doctype_public_id(NULL)
, m_doctype_system_id(NULL)
#ifdef HTML5_STANDALONE
, m_tokenize_only(FALSE)
#endif // HTML5_STANDALONE
{}
~LogicalDocument();
H5Element* GetRoot() { return m_root; }
OP_PARSING_STATUS Parse(Markup::Type context_elm_type, const uni_char *buffer, unsigned buffer_length, BOOL end_of_data);
OP_PARSING_STATUS ParseFragment(H5Element *context_elm, const uni_char *buffer, unsigned buffer_length);
OP_STATUS AddParsingData(const uni_char* data, unsigned data_length);
OP_PARSING_STATUS ContinueParsing();
OP_STATUS SetDoctype(const uni_char *name, const uni_char *pub_id, const uni_char *sys_id);
const uni_char* GetDoctypeName() { return m_doctype_name; }
const uni_char* GetDoctypePubId() { return m_doctype_public_id; }
const uni_char* GetDoctypeSysId() { return m_doctype_system_id; }
void CheckQuirksMode();
Script* GetBlockingScript() { return m_blocking_script; }
#ifdef HTML5_STANDALONE
void SetTokenizeOnly() { m_tokenize_only = TRUE; }
HTML5Parser* GetParser() { return m_parser; }
#endif // HTML5_STANDALONE
private:
H5Element* m_root;
HTML5Parser* m_parser;
Script* m_blocking_script;
BOOL m_strict_mode;
BOOL m_quirks_line_height_mode;
uni_char* m_doctype_name;
uni_char* m_doctype_public_id;
uni_char* m_doctype_system_id;
#ifdef HTML5_STANDALONE
BOOL m_tokenize_only;
#endif // HTML5_STANDALONE
};
#endif // LOGDOC_H
|
#ifndef note_h
#define note_h
#include <QString>
#include <QDate>
#include <QXmlStreamWriter>
#include "noteediteur.h"
#include "ui_mainwindow.h"
class NoteEditeur;
class ArticleEditeur;
class TaskEditeur;
class ImageEditeur;
class VideoEditeur;
class AudioEditeur;
class MultimediaEditeur;
/*********************************************************************
*** Execption ***
**********************************************************************/
/*! \class NoteExeption
* \brief classe permettant de lancer des exeptions en cas d'erreur
*/
class NotesException{
public:
NotesException(const QString& message):info(message) {}
QString getInfo() const {
return info;
}
private:
QString info;
};
/*********************************************************************/
/*********************************************************************
*** Note Abstract Class ***
**********************************************************************/
/*! \class Note
* \brief Abstraite dont hérite toutes les autres notes
*
* Cette classe ne peut pas être instanciée
*/
class Note {
protected:
int id ;
QString title ;
QDate dateC;
QDate dateM;
bool archive;
unsigned int nbMemento;
unsigned int nbMax;
public:
static int idIterator;
/**
* @brief Note
* constructeur sans argument pour la creation automatique qui sera ensuite éditée
*/
Note(): id(), title(""), dateC(QDate::currentDate()), dateM(QDate::currentDate()), archive(false),nbMemento(0),nbMax(5) {}
virtual ~Note() {}
/**
* @brief Note
* @param i
* @param t
* @param d_c
* @param d_lm
* @param a
* constructeur avec argument que l'on utilise lors de la reconstruction après le chargement du fichier XML
*/
Note(int i, const QString t=(QString)"", QDate d_c=QDate::currentDate(),
QDate d_lm=QDate::currentDate(), bool a=false): id(i), title(t), dateC(d_c), dateM(d_lm), archive(a), nbMemento(0),nbMax(5){}
/**
* @brief clone
* @return un pointeur sur note
* methode virtuelle pure qui retourne un noubel object de
* la classe de l'objet appelant (article, tâche ou multimédia...)
* elle sera redéfinie pour TOUTES les classes filles
*/
virtual Note* clone() =0;
///ACCESSEURS
/**
* @brief getId
* @return unsigned int
* retourne l'id de la note
*/
unsigned int getId() const {return id;}
/**
* @brief getTitle
* @return le titre
*/
const QString& getTitle() const {return title;}
/**
* @brief getDateC
* @return la date de creation de la note
*/
const QDate& getDateC() const {return dateC;}
/**
* @brief getDateM
* @return la date de dernière modification
*/
const QDate& getDateM() const {return dateM;}
/**
* @brief GetArchive
* @return retourne le booleen archive
* permet de savoir si la note est archivée ou non
*/
bool GetArchive() const {return archive;}
/**
* @brief getNbmemento
* @return le nombre de version précédente
*/
unsigned int getNbmemento() const {return nbMemento;}
/**
* @brief getType
* @return le type de la fonction
* nous avions implémenter cette fonction lorsque nous étions tenter d'utiliser des DownCast
* nous avons finalement privilégié les methodes virtuelles
*/
virtual const QString getType() const =0;
///SET
/**
* @brief setTitle
* @param newTitle
* permet de modifier le titre d'une note
*/
virtual void setTitle(const QString& newTitle) {title=newTitle ;}
/**
* @brief setDateLastModification
* permet de modifier la date d'une note avec la date du jour
*/
virtual void setDateLastModification() {dateM=QDate::currentDate();}
/**
* @brief setDateLastModification
* @param newDate
* permet de modifier la date d'une note avec une date donné (lorsqu'on récupère une version précédente)
*/
virtual void setDateLastModification(QDate& newDate) {dateM=newDate;}
/**
* @brief setArchive
* permet de rendre une note archivé ou non.
*/
virtual void setArchive() {archive=!archive ;}
/**
* @brief setArchive
* @param a
* on utilise ici un paramètre pour modifier la valeur d'archive lors de la mise a jour d'une version précédente
*/
virtual void setArchive(bool a) {archive=a ;}
/**
* @brief setId
* met la valeur de l'id de la note avec la valeur incrémentée du dernier id
*/
virtual void setId() {id = idIterator++;}
/**
* @brief setNotesListNote
* @return retourne le titre de la note que l'on va mettre dans la liste des notes (affichage)
* on utilise une methode virtuelle car lorsqu'on manipule les notes du tableau de note de NoteManager
* on ne connait pas le type de la note
* on avait donc besoin de gérer la génération du titre a afficher au niveau des methodes de note
*/
virtual QString setNotesListNote();
///SAVE
/**
* @brief saveNote
* @param stream
* on utilise une methode virtuelle car lorsqu'on manipule les notes du tableau de note de NoteManager
* on ne connait pas le type de la note
* on save les notes differements au niveau de leur type
* la methode doit donc être redefinie et est donc virtuelle pure
*/
virtual void saveNote(QXmlStreamWriter &stream) const = 0;
///MEMENTO
/**
* @brief addMemento
* @return une reference sur la note
* ajoute la version de la note avant les modifications au tableau careTaker
*
*/
virtual Note& addMemento()=0;
/**
* @brief editNote
* genère l'éditeur adéquat en fonction du type de la note
* cette methode doit donc être redefini pour chaque type de note
*/
virtual void editNote() =0;
};
/*********************************************************************/
/*********************************************************************
*** Note Abstract Memento ***
**********************************************************************/
/**
* @brief The MementoN class
* classe abstraite de base dont vont hériter les autres memento
*/
class MementoN {
protected :
friend class Note;
int id ;
QString title ;
QDate dateC;
QDate dateM;
bool archive;
public :
/**
* @brief MementoN
* @param i
* @param t
* @param d_c
* @param d_lm
* @param a
* constructeur de la classe
*/
MementoN(int i, const QString t, QDate d_c,
QDate d_lm, bool a): id(i), title(t), dateC(d_c), dateM(d_lm), archive(a){}
};
/*********************************************************************
*** Memento Article ***
**********************************************************************/
/*! \class MementoA
* \brief Classe qui hérite de MementoN
*
* Elle regroupe les même attributs qu'un Article avec des methodes différentes
*
*/
class MementoA : public MementoN {
private :
friend class Article;
QString text;
public:
/**
* @brief MementoA
* @param i
* @param t
* @param d_c
* @param d_lm
* @param a
* @param txt
* constructeur de la classe
*/
MementoA(int i, const QString t, QDate d_c, QDate d_lm, bool a, const QString txt): MementoN(i,t,d_c,d_lm,a), text(txt) {}
};
/*********************************************************************
*** Article **
*********************************************************************/
/*! \class Article
* \brief Classe qui hérite de Note
*
* Note avec un tableau des attributs en plus :
* Un tableau (+taille max et taille actuelle) de MementoA pour sauvegarder ses versions précédentes
* Du texte
*/
class Article : public Note {
private:
QString text;
MementoA** careTaker;
public :
/**
* @brief Article
* constructeur sans argument
*/
Article() : Note(), text(""), careTaker(new MementoA*[5]) {}
/**
* @brief Article
* @param i
* @param t
* @param d_c
* @param d_lm
* @param a
* @param txt
* constructeur avec argument pour la reconstruction à partir du fichier xml
*/
Article(int i, const QString t=(QString)"", QDate d_c=QDate::currentDate(),
QDate d_lm=QDate::currentDate(), bool a=false, const QString txt=(QString)""):
Note(i,t,d_c,d_lm,a), text(txt), careTaker(new MementoA*[5]){}
/**
* @brief clone
* @return un pointeur sur article
* permet de cloner un patron de base de la classe
*/
virtual Article* clone();
///ACCESSEURS
/**
* @brief getText
* @return le texte de l'article
*/
const QString& getText() const {return text ;}
/**
* @brief getDateC
* @return la date de creation
*/
const QDate& getDateC() const {return dateC;}
/**
* @brief getType
* @return le type
*/
const QString getType() const {return "Article";}
///SET
/**
* @brief setText
* @param t
* permet de modifier le text
*/
void setText(const QString& t) {text=t ;}
///DESCTRUCTEUR
~Article() {}
/**
* @brief saveNote
* @param stream
* permet de d'adopter la syntaxe adequat a l'artivle pour le save
*/
void saveNote(QXmlStreamWriter &stream) const;
///MEMENTO
/**
* @brief createMemento
* @return un pointeur sur une version antèrieur
*/
MementoA* createMemento() {
return new MementoA(getId(),getTitle(),getDateC(),getDateM(),GetArchive(),text) ;
}
/**
* @brief addMemento
* @return une ref sur l'article
* permet d'ajouter le memento au tableau des versions précédentes
*/
Article& addMemento();
/**
* @brief getPreviousMemento
* @return un pointeur sur l'article
* modifie la note avec l'état de la version précédente
*/
Article *getPreviousMemento();
/**
* @brief editNote
* voir Note
*/
void editNote();
};
/********************************************************************/
enum state {Waiting,Ongoing,Done};
///METHODES PERMETTANT LE PASSSAGE D'UN TYPE QSTRING A UN TYPE STATE ET INVERSEMENT
/*! \enum state
* \brief
* Différents états que peut prendre une Tâche
*/
inline QString toString(state s){
switch (s){
case Waiting: return "Waiting";
case Ongoing: return "Ongoing";
case Done: return "Done";
default: return "[Unknown status]";
}
}
/*! \enum state
* \brief
* Différents états que peut prendre une Tâche
*/
inline state toState(const QString& s){
if (s == "Waiting") return Waiting;
if (s == "Ongoing") return Ongoing;
if (s == "Done") return Done;
else throw NotesException("ERROR");
}
/*********************************************************************
*** Memento Task ***
**********************************************************************/
/**********************************************************************/
/*! \class MementoT
* \brief Classe qui hérite de MementoN
*
* Elle regroupe les même attributs qu'une Tache avec des methodes différentes
*
*/
class MementoT : public MementoN {
private :
friend class Task;
QString action;
unsigned int priority;
QDate deadline;
state status;
public :
/**
* @brief MementoT
* @param i
* @param t
* @param d_c
* @param d_lm
* @param a
* @param act
* @param p
* @param dl
* @param s
* constructeur
*/
MementoT(int i, const QString t, QDate d_c, QDate d_lm, bool a, const QString act, unsigned int p, QDate dl, state s):
MementoN(i,t,d_c,d_lm,a), action(act), priority(p), deadline(dl) ,status(s) {}
};
/********************************************************************
*** Task ***
*********************************************************************/
/*! \class Task
* \brief Classe qui hérite de Note
*
* Note avec un tableau et des attributs en plus :
* Un tableau (+taille max et taille actuelle) de MementoA pour sauvegarder ses versions précédentes
* une action
* une valeur de priorité
* une date d'échéance
* un etat (en cours, en attente, fait)
* un tableau des états précédents
*/
class Task : public Note {
private:
QString action;
unsigned int priority;
QDate deadline;
state status;
MementoT** careTaker;
public :
///CONSTRUCTEURS
/**
* @brief Task
* @param i
* @param t
* @param d_c
* @param d_lm
* @param a
* @param act
* @param p
* @param dl
* @param s
* constructeur avec argument
*/
Task(int i, const QString t, QDate d_c, QDate d_lm, bool a, const QString act, unsigned int p=0,
QDate dl=QDate(0000,00,00), state s=Waiting):
Note(i,t,d_c,d_lm,a), action(act), priority(p), deadline(dl), status(s), careTaker(new MementoT*[5]) {}
/**
* @brief Task
* constructeur sans argument
*/
Task() : Note(), action(""), priority(0), deadline(QDate::currentDate()), status(Waiting),careTaker(new MementoT*[5]) {}
/**
* @brief clone
* @return un pointeur sur Task
* voir Note
*/
virtual Task* clone();
///ACCESSEURS
/**
* @brief getAction
* @return l'action
*/
const QString& getAction() const {return action ;}
/**
* @brief getPriority
* @return la valeur de la priorité
*/
const unsigned int& getPriority() const {return priority ;}
/**
* @brief getDeadline
* @return la date d'échéance
*/
const QDate& getDeadline() const {return deadline ;}
/**
* @brief getState
* @return l'état parmis les états possible
*/
const state& getState() const {return status ;}
/**
* @brief getType
* @return le type
*/
const QString getType() const {return "Task";}
///SET
/**
* @brief setAction
* @param newAction
* permet de modifier l'action
*/
void setAction(const QString& newAction) {action=newAction;}
/**
* @brief setPriority
* @param p
* permet de modifier la priorité
*/
void setPriority (unsigned int p) {priority = p ;}
/**
* @brief setDeadline
* @param newDl
* permet de modifier l'échéance
*/
void setDeadline (QDate newDl) {deadline=newDl ;}
/**
* @brief setState
* @param s
* modifier l'état a partir d'une chaine de caractère
*/
void setState (const QString& s) {status = toState(s);}
/**
* @brief setState
* @param s
* modifier l'état a partir d'un état donné
*/
void setState(state& s){status= s ;}
/**
* @brief saveNote
* @param stream
* voir Note
*/
void saveNote(QXmlStreamWriter &stream) const;
/**
* @brief setNotesListNote
* @return
* voir Note
*/
QString setNotesListNote();
///MEMENTO
/**
* @brief createMemento
* @return un pointeur sur une version précédente
* voir Article
*/
MementoT* createMemento() {
return new MementoT(getId(),getTitle(),getDateC(),getDateM(),GetArchive(),action,priority,deadline,status) ;
}
/**
* @brief addMemento
* @return
* voir Article
*/
Task& addMemento();
/**
* @brief getPreviousMemento
* @return
* voir Article
*/
Task* getPreviousMemento();
/**
* @brief editNote
* voir Article
*/
void editNote();
///destructeur
~Task() {}
};
/*********************************************************************/
/*********************************************************************
*** Memento Multimedia ***
**********************************************************************/
/*! \class MementoM
* \brief Classe qui hérite de MementoN
*
* Elle regroupe les même attributs qu'un Article avec des methodes différentes
* Elle permet permet d'instancier un objet d'une version précédentes :
* d'image
* de video
* d'audio
*/
class MementoM : public MementoN {
protected :
friend class Audio;
friend class Image;
friend class Video;
friend class Multimedia;
QString description;
QString image;
public :
///CONSTRUCTEUR
MementoM( int i, const QString t, QDate d_c, QDate d_lm, bool a, const QString& d, const QString& f) :
MementoN(i,t,d_c,d_lm,a), description(d), image(f) {}
};
/*********************************************************************/
/*********************************************************************
*** Multimedia ***
**********************************************************************/
/*! \class Multimedia
* \brief Classe qui hérite de Note
*
* Note avec un tableau et des attributs en plus :
* Un tableau (+taille max et taille actuelle) de MementoM pour sauvegarder ses versions précédentes
* une description
* une image/video/audio (on a choisi de mettre un Qstring pour représenter le lien vers ce fichier)
*
* C'est une classe abstraite dont herite les : Image/Video/Audio
*/
class Multimedia : public Note {
protected:
QString description;
QString image;
MementoM** careTaker;
public:
/**
* @brief Multimedia
* @param i
* @param t
* @param d_c
* @param d_lm
* @param a
* @param d
* @param f
* constructeur avec argument
*/
Multimedia (int i, const QString t, QDate d_c, QDate d_lm, bool a, const QString& d, const QString& f) :
Note(i,t,d_c,d_lm,a), description(d), image(f), careTaker(new MementoM*[5]){}
/**
* @brief Multimedia
* constructeur sans argument
*/
Multimedia() : Note(), description(""), image(""), careTaker(new MementoM*[5]) {}
/**
* @brief getDescription
* @return la description
*/
const QString& getDescription() const {return description;}
/**
* @brief getImage
* @return le lien vers l'image
*/
const QString& getImage() const {return image;}
const QString getType() const =0;
/**
* @brief setDescription
* @param d
* permet de modifier la description
*/
void setDescription(const QString& d) { description=d;}
/**
* @brief setImage
* @param i
* permet de modifier le lien vers l'image
*/
void setImage(const QString & i) { image = i;}
/**
* @brief clone
* @return voir les classes précédentes
*/
virtual Multimedia* clone()=0;
///Method save
/**
* @brief saveNote
* @param stream
* voir les classes précédente
*/
void saveNote(QXmlStreamWriter &stream) const;
///MEMENTO
/**
* @brief createMemento
* @return MementoM*
*/
MementoM* createMemento() {
return new MementoM(getId(),getTitle(),getDateC(),getDateM(),GetArchive(),description,image) ;
}
/**
* @brief addMemento
* @return Multimedia&
*/
Multimedia& addMemento();
/**
* @brief getPreviousMemento
* @return Multimedia*
*/
Multimedia* getPreviousMemento();
/**
* @brief editNote
*/
void editNote() =0;
///DESTRUCTEUR
~Multimedia(){}
};
/*********************************************************************/
/*********************************************************************
*** Image ***
**********************************************************************/
/*! \class Image
* \brief Classe qui hérite Multimedia (qui elle meme hérite de Note)
*
* Seules les methodes sont modifiées
*/
class Image : public Multimedia{
public:
/**
* @brief Image
* @param i
* @param t
* @param d_c
* @param d_m
* @param a
* @param d
* @param f
* constructeurs avec arguments
*/
Image(int i, const QString t, QDate d_c ,QDate d_m ,bool a, const QString& d, const QString& f):
Multimedia(i,t,d_c,d_m,a,d,f) {}
/**
* @brief Image
* constructeur sans argument
*/
Image() : Multimedia() {}
/**
* @brief clone
* @return Image *
*/
virtual Image * clone ();
///DESTRUCTEUR
~Image() {}
/**
* @brief getType
* @return le type
*/
const QString getType() const {return "Image";}
///SAVE
void saveNote(QXmlStreamWriter &stream) const;
/**
* @brief getPreviousMemento
* @return Image*
*/
Image* getPreviousMemento();
/**
* @brief editNote
*/
void editNote();
};
/*********************************************************************/
/*********************************************************************
*** Enregistrement Audio ***
**********************************************************************/
/*! \class Audio
* \brief Classe qui hérite Multimedia (qui elle meme hérite de Note)
*
* Seules les methodes sont modifiées
*/
class Audio : public Multimedia{
public:
///CONSTRUCTEUR
Audio(int i, const QString t, QDate d_c ,QDate d_m ,bool a, const QString& d, const QString& f):
Multimedia(i,t,d_c,d_m,a,d,f) {}
Audio(): Multimedia() {}
///CLONE
virtual Audio* clone ();
///DESTRUCTEUR
~Audio() {}
///ACESSEURS
const QString getType() const {return "Audio";}
///SAVE
void saveNote(QXmlStreamWriter &stream) const;
///MEMENTO
Audio* getPreviousMemento();
/**
* @brief editNote
*/
void editNote();
};
/*********************************************************************/
/*********************************************************************
*** video ***
**********************************************************************/
/*! \class Audio
* \brief Classe qui hérite Multimedia (qui elle meme hérite de Note)
*
* Seules les methodes sont modifiées
*/
class Video : public Multimedia{
public:
/**
* @brief Video
* @param i
* @param t
* @param d_c
* @param d_m
* @param a
* @param d
* @param f
* constructeur avec argument
*/
Video(int i, const QString t, QDate d_c ,QDate d_m ,bool a, const QString& d, const QString& f):
Multimedia(i,t,d_c,d_m,a,d,f) {}
/**
* @brief Video
* constructeur sans argument
*/
Video() : Multimedia() {}
///CLONE
virtual Video * clone ();
///DESTRUCTEUR
~Video() {}
/**
* @brief getType
* @return le type
*/
const QString getType() const {return "Video";}
///SAVE
void saveNote(QXmlStreamWriter &stream) const;
/**
* @brief getPreviousMemento
* @return Video*
*/
Video* getPreviousMemento();
/**
* @brief editNote
*/
void editNote();
};
/*********************************************************************/
#endif
|
#include "areainfopool.h"
CAreaInfoPool::CAreaInfoPool()
{
m_pBase = NULL;
m_AreaInfoList = NULL;
m_nPoolCount = 0;
m_nCurrIndex = 0;
}
CAreaInfoPool::~CAreaInfoPool()
{
Close();
}
void CAreaInfoPool::Close()
{
m_pBase = NULL;
m_AreaInfoList = NULL;
}
size_t CAreaInfoPool::Init(int nPoolCount, char* pData)
{
Close();
m_pBase = pData;
size_t nPos = 0;
//printf("[CAreaInfoPool::Init]nPos=%d.\n", nPos);
m_AreaInfoList = (_Area_Info* )&pData[nPos];
nPos += sizeof(_Area_Info) * nPoolCount;
for(int i = 0; i < nPoolCount; i++)
{
m_AreaInfoList[i].Init();
m_AreaInfoList[i].Set_Index(i);
//printf("[CAreaInfoPool::Init](0)nPos=%d.\n", nPos);
}
m_nPoolCount = nPoolCount;
m_nCurrIndex = 0;
return nPos;
}
size_t CAreaInfoPool::Load(int nPoolCount, char* pData)
{
Close();
m_pBase = pData;
size_t nPos = 0;
//printf("[CNodePool::Load]nPos=%d.\n", nPos);
m_AreaInfoList = (_Area_Info* )&pData[nPos];
nPos += sizeof(_Area_Info) * nPoolCount;
m_nPoolCount = nPoolCount;
m_nCurrIndex = 0;
return nPos;
}
_Area_Info* CAreaInfoPool::Create()
{
if(NULL == m_AreaInfoList)
{
return NULL;
}
if(m_nCurrIndex >= m_nPoolCount - 1)
{
m_nCurrIndex = 0;
}
if(m_AreaInfoList[m_nCurrIndex].m_cUsed == 0)
{
//printf("[CAreaInfoPool::Create]m_nCurrIndex=%d, nIndex=%d.\n", m_nCurrIndex, m_AreaInfoList[m_nCurrIndex].Get_Index());
m_AreaInfoList[m_nCurrIndex].m_cUsed = 1;
return &m_AreaInfoList[m_nCurrIndex++];
}
else
{
//循环寻找空位
for(int i = m_nCurrIndex + 1; i < m_nPoolCount; i++)
{
if(m_AreaInfoList[i].m_cUsed == 0)
{
m_nCurrIndex = i + 1;
if(m_nCurrIndex > m_nPoolCount - 1)
{
m_nCurrIndex = 0;
}
m_AreaInfoList[i].m_cUsed = 1;
return &m_AreaInfoList[i];
}
}
printf("[CAreaInfoPool::Create]m_nCurrIndex=%d,m_nPoolCount=%d.\n", m_nCurrIndex, m_nPoolCount);
int nStart = 0;
//没找到,再重头开始找
for(int i = nStart; i < m_nCurrIndex - 1; i++)
{
if(m_AreaInfoList[i].m_cUsed == 0)
{
m_nCurrIndex = i + 1;
m_AreaInfoList[i].m_cUsed = 1;
return &m_AreaInfoList[i];
}
}
//已经没有空位
return NULL;
}
}
int CAreaInfoPool::Get_Node_Offset(_Area_Info* pWordInfo)
{
int nOffset = 0;
if(NULL != pWordInfo)
{
nOffset = (int)((char* )pWordInfo - m_pBase);
}
return nOffset;
}
_Area_Info* CAreaInfoPool::Get_NodeOffset_Ptr(int nOffset)
{
return (_Area_Info* )(m_pBase + nOffset);
}
bool CAreaInfoPool::Delete(_Area_Info* pWordInfo)
{
if(NULL == m_AreaInfoList || NULL == pWordInfo)
{
return false;
}
if(-1 == pWordInfo->Get_Index())
{
return false;
}
if(pWordInfo->Get_Index() >= m_nPoolCount || pWordInfo->Get_Index() < 0)
{
printf("[CAreaInfoPool::Delete]Get_Index=%d is unvalid.\n", pWordInfo->Get_Index());
return false;
}
m_AreaInfoList[pWordInfo->Get_Index()].m_cUsed = 0;
return true;
}
|
#ifndef __SP_
#define __SP_
#include <float.h>
#include <stack>
#include "EdgeWeightedDigraph.h"
class SP
{
private:
vector<double> dist_to;
vector<DirectedEdge> edge_to;
private:
void relax(DirectedEdge e)
{
int v = e.from();
int w = e.to();
if(dist_to[w] > dist_to[v] + e.get_weight())
{
dist_to[w] = dist_to[v] + e.get_weight();
edge_to[w] = e;
}
}
void relax(EdgeWeightedDigraph &G,int v)
{
list<DirectedEdge> *l = G.adj_vertex();
for(DirectedEdge e: *l)
{
int w = e.to();
if(dist_to[w] > dist_to[v] + e.get_weight())
{
dist_to[w] = dist_to[v] + e.get_weight();
edge_to[w] = e;
}
}
}
public:
double distTO(int v)
{
return dist_to[v];
}
bool has_path_to(int v)
{
return dist_to[v] < DBL_MAX;
}
stack<DirectedEdge> path_to(int v)
{
if(!has_path_to(v))
return NULL;
stack<DirectedEdge> path;
for(DirectedEdge e = edge_to[v];e != NULL;e = edge_to[e.from()])
{
path.push(e);
}
return path;
}
};
|
//: C12:CopyingWithPointers.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Rozwiazanie problemu utozsamiania wskaznikow
// za pomoca kopiowania wskazywanych przez nie
// obszarow podczas przypisania i wywolania
// konstruktora kopiujacego
#include "../require.h"
#include <string>
#include <iostream>
using namespace std;
class Dog {
string nm;
public:
Dog(const string& name) : nm(name) {
cout << "Tworzenie psa: " << *this << endl;
}
// Utworzony przez kompilator konstruktor kopiujacy
// i operator= sa prawidlowe
// Utworzenie obiektu klasy Dog na podstawie wskaznika:
Dog(const Dog* dp, const string& msg)
: nm(dp->nm + msg) {
cout << "Pies " << *this << " skopiowany z "
<< *dp << endl;
}
~Dog() {
cout << "Usuniety pies: " << *this << endl;
}
void rename(const string& newName) {
nm = newName;
cout << "Pies zmienil imie na: " << *this << endl;
}
friend ostream&
operator<<(ostream& os, const Dog& d) {
return os << "[" << d.nm << "]";
}
};
class DogHouse {
Dog* p;
string houseName;
public:
DogHouse(Dog* dog, const string& house)
: p(dog), houseName(house) {}
DogHouse(const DogHouse& dh)
: p(new Dog(dh.p, " skopiowany konstruktorem")),
houseName(dh.houseName
+ " skopiowany konstruktorem") {}
DogHouse& operator=(const DogHouse& dh) {
// Sprawdzanie przypisania do samego siebie:
if(&dh != this) {
p = new Dog(dh.p, " przypisany");
houseName = dh.houseName + " przypisany";
}
return *this;
}
void renameHouse(const string& newName) {
houseName = newName;
}
Dog* getDog() const { return p; }
~DogHouse() { delete p; }
friend ostream&
operator<<(ostream& os, const DogHouse& dh) {
return os << "[" << dh.houseName
<< "] zawiera " << *dh.p;
}
};
int main() {
DogHouse fafika(new Dog("Fafik"), "DomekFafika");
cout << fafika << endl;
DogHouse fafika2 = fafika; // Uzycie konstruktora kopiujacego
cout << fafika2 << endl;
fafika2.getDog()->rename("Burek");
fafika2.renameHouse("DomekBurka");
cout << fafika2 << endl;
fafika = fafika2; // Przypisanie
cout << fafika << endl;
fafika.getDog()->rename("Reks");
fafika2.renameHouse("DomekReksa");
} ///:~
|
#include <bits/stdc++.h>
using namespace std;
bool judge(string S) {
string tmp = S;
reverse(tmp.begin(), tmp.end());
if (S == tmp)return true;
else return false;
}
int main(void) {
string S, substr1, substr2;
cin >> S;
substr1 = S.substr(0, (S.size() - 1) / 2);
substr2 = S.substr((S.size() + 3) / 2 -1, (S.size() - 1) / 2);
if (judge(S) && judge(substr1) && judge(substr2)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef DOM_EXTENSIONS_MENUEVENT_H
#define DOM_EXTENSIONS_MENUEVENT_H
#ifdef DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT
#include "modules/dom/src/domevents/domevent.h"
class OpDocumentContext;
class FramesDocument;
class HTML_Element;
class DOM_Node;
class DOM_MessagePort;
class DOM_ExtensionSupport;
class DOM_ExtensionMenuEvent_Base
: public DOM_Event
{
public:
~DOM_ExtensionMenuEvent_Base();
/* From DOM_Object: */
virtual ES_GetState GetName(OpAtom property_atom, ES_Value* value, ES_Runtime* origining_runtime);
virtual ES_PutState PutName(OpAtom property_atom, ES_Value* value, ES_Runtime* origining_runtime);
protected:
DOM_ExtensionMenuEvent_Base(OpDocumentContext* document_context);
OpDocumentContext* m_document_context;
};
class DOM_ExtensionMenuEvent_UserJS
: public DOM_ExtensionMenuEvent_Base
{
public:
/**
* Creates an event object for an extension menu click event for UserJS.
*
* @param new_event Set to newly created event object.
* @param context Document context in which the menu was triggered. NOT NULL.
* @param element Element HTML_Element for which the menu was triggered. NULL if it was not triggered in
* any specific element or if the event should not have access to it.
* @param runtime Runtime in which the event will be constructed. NOT NULL.
* @return OK or ERR_NO_MEMORY
*/
static OP_STATUS Make(DOM_Event*& new_event, OpDocumentContext* context, HTML_Element* element, DOM_Runtime* runtime);
/* From DOM_Object: */
virtual ES_GetState GetName(OpAtom property_atom, ES_Value* value, ES_Runtime* origining_runtime);
virtual void GCTrace();
private:
DOM_ExtensionMenuEvent_UserJS(OpDocumentContext* document_context, DOM_Node* node);
DOM_Node* m_node;
};
class DOM_ExtensionMenuEvent_Background
: public DOM_ExtensionMenuEvent_Base
{
public:
/**
* Creates an event object for an extension menu click event for Background process of extension.
*
* @param new_event Set to newly created event object.
* @param context Document context in which the menu was triggered. NOT NULL.
* @param document_url Url of a document for which the menu was triggered.
* This doesn't have to be top level document if the menu was invoked for
* example in an iframe.
* @param window_id Id of a window in which the context menu was invoked.
* @param extension_support Support object of the extension background which will receive the event.
* @param runtime Runtime in which the event will be constructed. NOT NULL.
* @return OK or ERR_NO_MEMORY.
*/
static OP_STATUS Make(DOM_Event*& new_event, OpDocumentContext* context, const uni_char* document_url, UINT32 window_id, DOM_ExtensionSupport* extension_support, DOM_Runtime* runtime);
/* From DOM_Object: */
virtual ES_GetState GetName(OpAtom property_atom, ES_Value* value, ES_Runtime* origining_runtime);
virtual void GCTrace();
private:
DOM_ExtensionMenuEvent_Background(OpDocumentContext* document_context, UINT32 window_id);
BOOL HasAccessToWindow(Window* window);
UINT32 m_window_id;
OpString m_document_url;
OpString m_page_url;
DOM_MessagePort* m_source;
};
#endif // DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT
#endif // DOM_EXTENSIONS_MENUEVENT_H
|
#include "Apriori.h"
using namespace std;
Apriori::Apriori(bitset<MAX_ITEM_LEN_> input[], int line_ans, double sup) {
for(int i = 0; i < MAX_INPUT_LINE_; i ++) {
data[i] = input[i];
}
min_sup = sup;
ans = line_ans;
}
Apriori::~Apriori() {
}
void Apriori::genL1() {
for (int i = 0; i < MAX_ITEM_LEN_; i ++) {
int tmp_sup = 0;
for (int j = 0; j < ans; j ++) {
if(data[j].test(i)) {
tmp_sup ++;
}
}
if(tmp_sup == 0) {
continue;
}
if((double)(tmp_sup) / ans < min_sup) {
continue;
}
bitset<MAX_ITEM_LEN_> tmp;
tmp.set(i);
L1_item.push_back(tmp);
L1_sup.push_back((double)(tmp_sup) / ans);
}
//printf("num: 1 , size: %d\n", L1_item.size());
}
void Apriori::genLk(vector<bitset<MAX_ITEM_LEN_>> Lk_1, int num) {
if(Lk_1.size() == 0) {
return;
}
vector<bitset<MAX_ITEM_LEN_>> Lk;
vector<int> tmp;
int tot = Lk_1.size();
printf("num: %d , size: %d\n", num - 1, tot);
vector<bitset<MAX_ITEM_LEN_>> freq_exist;
for(int i = 0; i < tot; i ++) {
for(int j = i; j < tot; j ++) {
tmp.clear();
bitset<MAX_ITEM_LEN_> bitset_tmp;
for(int k = 0; k < MAX_ITEM_LEN_; k ++) {
if(Lk_1[i].test(k) || Lk_1[j].test(k)) {
bitset_tmp.set(k);
tmp.push_back(k);
}
}
if(bitset_tmp.count() != num || find(freq_exist.begin(), freq_exist.end(), bitset_tmp) != freq_exist.end()) {
continue;
}
freq_exist.push_back(bitset_tmp);
int tmp_sup = 0;
for(int k = 0; k < ans; k ++) {
int flag = 1;
for(int m = 0; m < tmp.size(); m ++) {
if(data[k].test(tmp[m])) {
continue;
}
else {
flag = 0;
break;
}
}
tmp_sup += flag;
}
if((double)(tmp_sup) / ans >= min_sup) {
Lk.push_back(bitset_tmp);
}
}
}
genLk(Lk, num + 1);
}
void Apriori::getResult() {
genL1();
//printf("gen L1 done\n");
genLk(L1_item, 2);
}
|
#include "semantic_localization/semantic_localization.h"
boost::shared_ptr<SemanticLocalization> sl_ptr;
void sigintHandler(int sig)
{
// Save latest pose as we're shutting down.
sl_ptr->savePoseToServer();
sl_ptr.reset();
ros::shutdown();
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "semantic_localization");
ros::NodeHandle nh;
// Override default sigint handler
signal(SIGINT, sigintHandler);
// Make our node available to sigintHandler
sl_ptr.reset(new SemanticLocalization());
if (argc == 1)
{
// run using ROS input
ros::spin();
}
// Without this, our boost locks are not shut down nicely
sl_ptr.reset();
// To quote Morgan, Hooray!
return (0);
}
|
//
// Button.cpp
// Zengine
//
// Created by zs on 14-6-13.
//
//
#include "Button.h"
#include "GameScene.h"
Button::Button():_font(NULL),_fontScale(1),_sprite(NULL)
{
}
Button::~Button()
{
}
Button* Button::create(int id,const char* name)
{
Button* pRet = new Button();
if(pRet && pRet->init(id,name)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool Button::init(int id, const char *name)
{
if(Actor::init(name)) {
setID(id);
return true;
}
return false;
}
Button* Button::createWithFont(int id, const char *name, cocos2d::CCLabelBMFont *font,float fontScale)
{
Button* pRet = new Button();
if(pRet && pRet->initWithFont(id, name, font , fontScale)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool Button::initWithFont(int id, const char *name, cocos2d::CCLabelBMFont *font,float fontScale)
{
if (Actor::init(name)) {
setID(id);
_font = font;
_fontScale=fontScale;
_font->setScale(_fontScale);
addChild(_font,100);
return true;
}
return false;
}
Button* Button::createWithSprite(int id, const char *name, CCSprite *sprite,float spriteScale,CCPoint pos)
{
Button* pRet = new Button();
if(pRet && pRet->initWithSprite(id, name, sprite , spriteScale,pos)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool Button::initWithSprite(int id, const char *name, CCSprite *sprite,float spriteScale,CCPoint pos)
{
if (Actor::init(name)) {
setID(id);
_sprite = sprite;
_spriteScale = spriteScale;
_sprite->setScale(_spriteScale);
_sprite->setPosition(ccp(getBodyRect().size.width*pos.x, getBodyRect().size.height*pos.y));
addChild(_sprite,100);
return true;
}
return false;
}
//void Button::setAdd(float addX, float addY)
//{
//
//
// _addX = addX;
// _addY = addY;
//
// setBody();
//}
//
//void Button::setAdd(float add)
//{
// setAdd(add, add);
//
//}
bool Button::touchesBegan(CCSet * touchs,CCEvent * event)
{
for(CCSetIterator iter=touchs->begin();iter!=touchs->end();iter++){
CCTouch * mytouch=(CCTouch *)(* iter);
CCPoint pos=mytouch->getLocation();
if (toucheBeganAction(pos)) {
return true;
}
}
return false;
}
bool Button::touchesCancelled(CCSet * touchs,CCEvent * event)
{
for(CCSetIterator iter=touchs->begin();iter!=touchs->end();iter++){
CCTouch * mytouch=(CCTouch *)(* iter);
CCPoint pos=mytouch->getLocation();
if (toucheCancelledAction(pos)) {
return true;
}
}
return false;
}
bool Button::touchesMoved(CCSet * touchs,CCEvent * event)
{
for(CCSetIterator iter=touchs->begin();iter!=touchs->end();iter++){
CCTouch * mytouch=(CCTouch *)(* iter);
CCPoint pos=mytouch->getLocation();
if (toucheMovedAction(pos)) {
return true;
}
}
return false;
}
bool Button::touchesEnded(CCSet * touchs,CCEvent * event)
{
end();
for(CCSetIterator iter=touchs->begin();iter!=touchs->end();iter++){
CCTouch * mytouch=(CCTouch *)(* iter);
CCPoint pos=mytouch->getLocation();
if (toucheEndedAction(pos)) {
return true;
}
}
return false;
}
//void Button::setBody()
//{
// _body = CCRectMake(this->boundingBox().origin.x-_addX, boundingBox().origin.y+_addY, boundingBox().size.width+_addX*2, boundingBox().size.height+_addY*2);
//
//}
bool Button::toucheBegan(CCTouch *pTouch,CCEvent * event)
{
return toucheBeganAction(pTouch->getLocation());
}
bool Button::toucheCancelled(CCTouch *pTouch,CCEvent * event)
{
return toucheCancelledAction(pTouch->getLocation());
}
bool Button::toucheMoved(CCTouch *pTouch,CCEvent * event)
{
return toucheMovedAction(pTouch->getLocation());
}
bool Button::toucheEnded(CCTouch *pTouch,CCEvent * event)
{
end();
return toucheEndedAction(pTouch->getLocation());
}
bool Button::toucheBeganAction(cocos2d::CCPoint pos)
{
if (this->isVisible()) {
if (getBodyRect().containsPoint(pos)) {
this->getAnimation()->playByIndex(1);
if (_font) {
_font->setScale(_fontScale*0.8);
}
if (_sprite) {
_sprite->setScale(_spriteScale*0.8);
}
return true;
}
}
return false;
}
bool Button::toucheCancelledAction(cocos2d::CCPoint pos)
{
if (getBodyRect().containsPoint(pos)) {
return true;
}
return false;
}
bool Button::toucheMovedAction(cocos2d::CCPoint pos)
{
if (getBodyRect().containsPoint(pos)) {
return true;
}
return false;
}
bool Button::toucheEndedAction(cocos2d::CCPoint pos)
{
if (getBodyRect().containsPoint(pos)) {
return true;
}
return false;
}
void Button::end()
{
this->getAnimation()->playByIndex(0);
if (_font) {
_font->setScale(_fontScale);
}
if (_sprite) {
_sprite->setScale(_spriteScale);
}
}
|
#pragma once
#include <GL/glew.h>
#include <GLM/glm.hpp>
#include "Scene.h"
#include "Shader.h"
class FontRenderer {
public:
FontRenderer();
virtual ~FontRenderer();
void render(Scene &scene);
private:
Shader fontShader;
};
|
/*
* StateManagerMCB.h
* File defining the MCB monitor
* Author: Alex St. Clair
* October 2018
*/
#ifndef MONITORMCB_H_
#define MONITORMCB_H_
#include "InternalSerialDriverMCB.h"
#include "StorageManagerMCB.h"
#include "ConfigManagerMCB.h"
#include "LTC2983Manager.h"
#include "ActionsMCB.h"
#include "LevelWind.h"
#include "Reel.h"
#include "SafeBuffer.h"
#include <stdint.h>
#define TEMP_LOG_PERIOD 30000 // milliseconds
#define VOLT_LOG_PERIOD 30000 // milliseconds
#define CURR_LOG_PERIOD 30000 // milliseconds
#define FAST_TM_MAX_SAMPLES 10
#define SLOW_TM_MAX_SAMPLES (NUM_ROTATING_PARAMS * FAST_TM_MAX_SAMPLES)
#define MIN_DEPLOY_VOLTAGE 14.0f
enum Motor_Torque_Index_t : uint8_t {
REEL_INDEX = 0,
LEVEL_WIND_INDEX = 1
};
struct Temp_Sensor_t {
float last_temperature;
float limit_hi;
float limit_lo;
uint8_t channel_number;
Sensor_Type_t sensor_type;
bool sensor_error;
bool over_temp;
bool under_temp;
};
struct ADC_Voltage_t {
float last_voltage;
float limit_hi;
float limit_lo;
float voltage_divider;
uint16_t last_raw;
uint8_t channel_pin;
bool over_voltage;
bool under_voltage;
};
struct ADC_Current_t {
float last_current;
float limit_hi;
float limit_lo;
float pulldown_res;
uint16_t last_raw;
uint8_t channel_pin;
bool over_current;
bool under_current;
};
struct Motor_Torque_t {
float last_torque;
float limit_hi;
float limit_lo;
float conversion;
bool read_error;
bool over_torque;
bool under_torque;
};
struct Slow_TM_t {
uint16_t data[SLOW_TM_MAX_SAMPLES];
uint16_t running_max;
uint8_t curr_index;
};
struct Fast_TM_t {
uint16_t data[FAST_TM_MAX_SAMPLES];
uint16_t running_max;
uint8_t curr_index;
};
class MonitorMCB {
public:
MonitorMCB(SafeBuffer * monitor_q, SafeBuffer * action_q, Reel * reel_in, LevelWind * lw_in, InternalSerialDriverMCB * dibdriver, ConfigManagerMCB * cfgManager);
~MonitorMCB(void) { };
// interface methods
void InitializeSensors(void);
void UpdateLimits(void);
void Monitor(void);
bool VerifyDeployVoltage(void);
// if a limit is exceeded, the relevant info is written to this string
char limit_error[100];// temperature sensor table (hard-coded limits will be replace at init from EEPROM)
Temp_Sensor_t temp_sensors[NUM_TEMP_SENSORS] =
/* last_temp | limit_hi | limit_lo | channel_num | channel_type | sens_err | over_temp | under_temp */
{{ 0.0f, 100.0f, -100.0f, MTR1_THERM_CH, THERMISTOR_44006, false, false, false},
{ 0.0f, 100.0f, -100.0f, MTR2_THERM_CH, THERMISTOR_44006, false, false, false},
{ 0.0f, 100.0f, -100.0f, MC1_THERM_CH, THERMISTOR_44006, false, false, false},
{ 0.0f, 100.0f, -100.0f, MC2_THERM_CH, THERMISTOR_44006, false, false, false},
{ 0.0f, 100.0f, -100.0f, DCDC_THERM_CH, THERMISTOR_44006, false, false, false},
{ 0.0f, 100.0f, -100.0f, SPARE_THERM_CH, THERMISTOR_44006, false, false, false}};
// voltage ADC channel table (hard-coded limits will be replaced at init from EEPROM)
ADC_Voltage_t vmon_channels[NUM_VMON_CHANNELS] =
/* last_volt | limit_hi | limit_lo | volt_div | last_raw | channel_pin | over_volt | under_volt */
{{ 0.0f, 3.8f, 2.6f, 0.5f, 0, A_VMON_3V3, false, false},
{ 0.0f, 20.0f, 12.0f, 0.102f, 0, A_VMON_15V, false, false},
{ 0.0f, 26.0f, 18.0f, 0.0746f, 0, A_VMON_20V, false, false},
{ 0.0f, 3.6f, 0.0f, 1, 0, A_SPOOL_LEVEL, false, false}};
// current ADC channel table (hard-coded limits will be replaced at init from EEPROM)
ADC_Current_t imon_channels[NUM_IMON_CHANNELS] =
/* last_curr | limit_hi | limit_lo | pulldown_res | last_raw | channel_pin | over_curr | under_curr */
{{ 0.0f, 5.0f, -2.0f, RES_15K, 0, A_IMON_BRK, false, false},
{ 0.0f, 5.0f, -2.0f, RES_15K, 0, A_IMON_MC, false, false},
{ 0.0f, 4.5f, -2.0f, RES_2K, 0, A_IMON_MTR1, false, false},
{ 0.0f, 5.0f, -2.0f, RES_2K, 0, A_IMON_MTR2, false, false}};
Motor_Torque_t motor_torques[2] =
/* last torque | limit_hi | limit_lo | conversion | read_error | over_torque | under_torque */
{{0.0f, 500.0f, -500.0f, 500.0f, false, false, false},
{0.0f, 500.0f, -500.0f, 1.0f, false, false, false}};
private:
// read and respond to commands on the monitor_queue
void HandleCommands(void);
// functions for gathering and checking all of the sensor data
bool CheckTemperatures(void);
bool CheckVoltages(void);
bool CheckCurrents(void);
bool CheckTorques(void);
void UpdatePositions(void);
// old function for printing motor data
void PrintMotorData(void);
// called from the Monitor loop during motions
bool AggregateMotionData(void);
void SendMotionData(void);
// helpers for interfacing with TM averagers
void AddFastTM(Fast_TM_t * tm_type, uint16_t data);
void AddSlowTM(RotatingParam_t tm_index, uint16_t data);
uint16_t AverageResetFastTM(Fast_TM_t * tm_type);
uint16_t AverageResetSlowTM(RotatingParam_t tm_index);
// conversion helpers
uint16_t TorqueToUInt16(float torque);
uint16_t TempToUInt16(float temp);
// state variables
bool monitor_reel;
bool monitor_levelwind;
bool monitor_low_power;
// communication with state manager
SafeBuffer * monitor_queue;
SafeBuffer * action_queue;
// hardware objects
LTC2983Manager ltcManager;
StorageManagerMCB storageManager;
LevelWind * levelWind;
Reel * reel;
InternalSerialDriverMCB * dibDriver;
ConfigManagerMCB * configManager;
// motion data buffer for sending to the DIB/PIB
uint8_t tm_buffer[MOTION_TM_SIZE];
// motion data trackers
uint32_t last_send_millis = 0;
uint8_t rotating_parameter = FIRST_ROTATING_PARAM; // index = 0
// running averages for motion telemetry (fast - 10s period)
Fast_TM_t reel_torques = {{0},0,0};
Fast_TM_t lw_torques = {{0},0,0};
Fast_TM_t reel_currents = {{0},0,0};
Fast_TM_t lw_currents = {{0},0,0};
Slow_TM_t slow_tm[NUM_ROTATING_PARAMS] = {{{0},0,0}};
};
#endif
|
#include "api/FRCNN/frcnn_api.hpp"
namespace FRCNN_API{
void Detector:: preprocess(const cv::Mat &img_in, const int blob_idx) {
const vector<Blob<float> *> &input_blobs = net_->input_blobs();
cv::Mat img_out;
img_in.convertTo(img_out, CV_32FC1);
CHECK(img_out.isContinuous()) << "Warning : cv::Mat img_out is not Continuous !";
input_blobs[blob_idx]->Reshape(1, img_out.channels(), img_out.rows, img_out.cols);
float *blob_data = input_blobs[blob_idx]->mutable_cpu_data();
for (int i = 0; i < img_out.cols * img_out.rows; i++) {
blob_data[img_out.cols * img_out.rows * 0 + i] =
reinterpret_cast<float*>(img_out.data)[i * 3 + 0] - mean_[0];
blob_data[img_out.cols * img_out.rows * 1 + i] =
reinterpret_cast<float*>(img_out.data)[i * 3 + 1] - mean_[1];
blob_data[img_out.cols * img_out.rows * 2 + i] =
reinterpret_cast<float*>(img_out.data)[i * 3 + 2] - mean_[2];
}
}
void Detector::preprocess(const vector<float> &data, const int blob_idx){
const vector<Blob<float> *> &input_blobs = net_->input_blobs();
input_blobs[blob_idx]->Reshape(1, data.size(), 1, 1);
float *blob_data = input_blobs[blob_idx]->mutable_cpu_data();
std::memcpy(blob_data, &data[0], sizeof(float) * data.size());
}
void Detector::Set_Model(std::string &proto_file, std::string &model_file, std::string default_config, std::string override_config, int gpu_id){
if (gpu_id >= 0) {
#ifndef CPU_ONLY
caffe::Caffe::SetDevice(gpu_id);
caffe::Caffe::set_mode(caffe::Caffe::GPU);
#else
LOG(FATAL) << "CPU ONLY MODEL, BUT PROVIDE GPU ID";
#endif
} else {
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
net_.reset(new Net<float>(proto_file, caffe::TEST));
net_->CopyTrainedLayersFrom(model_file);
FrcnnParam::load_param(override_config, default_config);
mean_[0] = FrcnnParam::pixel_means[0];
mean_[1] = FrcnnParam::pixel_means[1];
mean_[2] = FrcnnParam::pixel_means[2];
caffe::Frcnn::FrcnnParam::print_param();
LOG(INFO) << "SET MODEL DONE";
}
vector<boost::shared_ptr<Blob<float> > > Detector::predict(const vector<std::string> blob_names) {
LOG(ERROR) << "FORWARD BEGIN";
net_->ForwardPrefilled();
vector<boost::shared_ptr<Blob<float> > > output;
for (int i = 0; i < blob_names.size(); ++i) {
output.push_back(net_->blob_by_name(blob_names[i]));
}
LOG(ERROR) << "FORWARD END";
return output;
}
void Detector::predict(const cv::Mat &img_in, std::vector<caffe::Frcnn::BBox<float> > &results){
CHECK(FrcnnParam::test_scales.size() == 1) << "Only single-image batch implemented";
float scale_factor = caffe::Frcnn::get_scale_factor(img_in.cols, img_in.rows, FrcnnParam::test_scales[0], FrcnnParam::test_max_size);
cv::Mat img;
const float height = img_in.rows;
const float width = img_in.cols;
LOG(ERROR) << "height: " << height << " width: " << width;
cv::resize(img_in, img, cv::Size(), scale_factor, scale_factor);
std::vector<float> im_info(3);
im_info[0] = img.rows;
im_info[1] = img.cols;
im_info[2] = scale_factor;
this->preprocess(img, 0);
this->preprocess(im_info, 1);
vector<std::string> blob_names(3);
blob_names[0] = "rois";
blob_names[1] = "cls_prob";
blob_names[2] = "bbox_pred";
vector<boost::shared_ptr<Blob<float> > > output = this->predict(blob_names);
boost::shared_ptr<Blob<float> > rois(output[0]);
boost::shared_ptr<Blob<float> > cls_prob(output[1]);
boost::shared_ptr<Blob<float> > bbox_pred(output[2]);
const int box_num = bbox_pred->num();
const int cls_num = cls_prob->channels();
CHECK_GT(cls_num , 0);
results.clear();
for (int cls = 1; cls < cls_num; cls++) {
vector<BBox<float> > bbox;
for (int i = 0; i < box_num; i++) {
float score = cls_prob->cpu_data()[i * cls_num + cls];
Point4f<float> roi(rois->cpu_data()[(i * 5) + 1]/scale_factor,
rois->cpu_data()[(i * 5) + 2]/scale_factor,
rois->cpu_data()[(i * 5) + 3]/scale_factor,
rois->cpu_data()[(i * 5) + 4]/scale_factor);
Point4f<float> delta(bbox_pred->cpu_data()[(i * cls_num + cls) * 4 + 0],
bbox_pred->cpu_data()[(i * cls_num + cls) * 4 + 1],
bbox_pred->cpu_data()[(i * cls_num + cls) * 4 + 2],
bbox_pred->cpu_data()[(i * cls_num + cls) * 4 + 3]);
Point4f<float> box = caffe::Frcnn::bbox_transform_inv(roi, delta);
box[0] = std::max(1.0f, box[0]);
box[1] = std::max(1.0f, box[1]);
box[2] = std::min(width, box[2]);
box[3] = std::min(height, box[3]);
// BBox tmp(box, score, cls);
// LOG(ERROR) << "cls: " << tmp.id << " score: " << tmp.confidence;
// LOG(ERROR) << "roi: " << roi.to_string();
bbox.push_back(BBox<float>(box, score, cls));
}
sort(bbox.begin(), bbox.end());
vector<bool> select(box_num, true);
// Apply NMS
for (int i = 0; i < box_num; i++)
if (select[i]) {
if (bbox[i].confidence < FrcnnParam::test_score_thresh)
break;
for (int j = i + 1; j < box_num; j++)
if (select[j]) {
if (get_iou(bbox[i], bbox[j]) > FrcnnParam::test_nms) {
select[j] = false;
}
}
results.push_back(bbox[i]);
}
}
}
} // FRCNN_API
|
#include "Peon.h"
#include "ETSIDI.h"
#define M 8
#define PX_X 800
#define PX_Y 800
Peon::Peon()
{
tipo = PEON;
}
Peon::~Peon()
{
}
void Peon::Mueve()
{
}
void Peon::SetColor(Color col)
{
color = col;
}
void Peon::SetRadio(float rad)
{
radio = rad;
}
void Peon::SetPos(float ix, float iy)
{
posicion[0] = ix;
posicion[1] = iy;
}
int Peon::GetPosX()
{
return posicion[0];
}
int Peon::GetPosY()
{
return posicion[1];
}
Color Peon::GetColor()
{
return color;
}
Tipo Peon::GetTipo()
{
return tipo;
}
void Peon::Mueve(int pos_finX, int pos_finY)
{
posicion[0] = pos_finX;
posicion[1] = pos_finY;
}
void Peon::Dibuja()
{
int x, y;
float theta;
radio = (PX_X / M) * 0.4; //definir en el set radio
glEnable(GL_TEXTURE_2D);
if (color == ROJO)
{
glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("bin/imagenes/PeonRojo.png").id);//Pinta de color rojo la ficha (ROJO=0)
}
else if (color == VERDE) //color de cuando lo seleccionas
{
glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("bin/imagenes/FichaElegida.png").id);
}
else if (color == BLANCO)
{
glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("bin/imagenes/PeonBlanco.png").id); //pinta de color blanco la ficha
}
//El vector posicion corresponde con coordenadas en el dibujo (x,y).
//Lo ideal es que fuesen los indices (i,j) del elemento de la matriz del tablero
//y después, en función del tamaño del dibujo calcular las coordenadas (x,y)
//algo como:
//posicion.x=i*DIST_ENTRE_CUADRADOS + DISTANCIA_ENTRE_CUADRADOS/2
//posicion.y=-j*DIST_ENTRE_CUADRADOS - DISTANCIA_ENTRE_CUADRADOS/2
//x = i * (PX_X / M) + (PX_X / (2 * M));
//y = PX_Y - (j * (PX_Y / M) + (PX_Y / (2 * M))); //CUIDADO CON EL OFFSET
x = posicion[1] * (PX_X / M) + (PX_X / (2 * M));
y = PX_Y - (posicion[0] * (PX_Y / M) + (PX_Y / (2 * M)));
glDisable(GL_LIGHTING);
glBegin(GL_POLYGON);
glColor3f(1, 1, 1);
glTexCoord2d(0, 1); glVertex2d(x-40, y-40);
glTexCoord2d(1, 1); glVertex2d(x+40, y-40);
glTexCoord2d(1, 0); glVertex2d(x+40, y+40);
glTexCoord2d(0, 0); glVertex2d(x-40, y+40);
glEnd();
glEnable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
}
void Peon::BorraFicha() {
delete this;
}
|
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <utility>
using namespace std;
struct Node{
char c;
int prev;
int status;
vector<Node*> nexts;
Node(char project);
};
Node::Node(char project){
c = project;
nexts = vector<Node*>();
prev = 0;
}
void findNext(unordered_map<char, Node*>* projectMap, vector<char>* ans){
if(projectMap->empty()){
return;
}
for(auto it = projectMap->begin(); it != projectMap->end(); it++){
if(it->second->prev == 0){
ans->push_back(it->first);
Node* node = it->second;
vector<Node*> nexts = node->nexts;
for(Node* next: nexts){
next->prev--;
}
projectMap->erase(it);
findNext(projectMap, ans);
// ALEX: don't forget to free the heap memory you allocated!
delete node;
break;
}
}
}
vector<char> decideOrder(const vector<char>& projects, const vector<pair<char, char>> dependencies){
unordered_map<char, Node*> projectMap;
for(char project: projects){
Node* node = new Node(project);
projectMap.insert({project, node});
}
for(auto pair: dependencies){
Node* current = projectMap[pair.second];
Node* next = projectMap[pair.first];
current->nexts.push_back(next);
next->prev++;
}
vector<char> ans;
findNext(&projectMap, &ans);
if(ans.size() != projects.size()){
cout << "Error" << endl;
return vector<char>();
}
return ans;
}
#define COMPLETED 2
#define PARTIAL 1
#define BLANK 0
Node* findNext2(Node* node){
if(node){}
findNext2(node->nexts[0]);
}
vector<char> decideOrder2(const vector<char>& projects, const vector<pair<char, char>> dependencies){
unordered_map<char, Node*> projectMap;
Node* node;
for(char project: projects){
node = new Node(project);
projectMap.insert({project, node});
}
for(auto pair: dependencies){
Node* current = projectMap[pair.second];
Node* next = projectMap[pair.first];
current->nexts.push_back(next);
}
findNext2(node);
}
int main(void){
vector<char> projects = {'a', 'b', 'c', 'd', 'e', 'f'};
vector<pair<char, char>> dependencies = {
make_pair('d', 'a'),
make_pair('b', 'f'),
make_pair('d', 'b'),
make_pair('a', 'f'),
make_pair('c', 'd')};
vector<char> ans = decideOrder(projects, dependencies);
for(char c: ans){
cout << c << " ";
}
cout << endl;
return 0;
}
|
#include "PHG4TPCPadPlaneReadout.h"
#include <g4detectors/PHG4Cellv1.h>
#include <g4detectors/PHG4CellContainer.h>
#include <g4detectors/PHG4CylinderCellGeom.h>
#include <g4detectors/PHG4CylinderCellGeomContainer.h>
#include <g4main/PHG4HitContainer.h>
#include "TF1.h"
#include <TSystem.h>
#include <TNtuple.h>
#include <cmath>
#include <iostream>
using namespace std;
PHG4TPCPadPlaneReadout::PHG4TPCPadPlaneReadout(const string &name):
PHG4TPCPadPlane(name),
fcharge(nullptr),
GeomContainer(nullptr),
LayerGeom(nullptr),
rad_gem(NAN),
output_radius(NAN),
neffelectrons_threshold(NAN),
MinLayer(),
MaxLayer(),
MinRadius(),
MaxRadius(),
Thickness(),
MinZ(NAN),
MaxZ(NAN),
sigmaT(NAN),
sigmaL(),
PhiBinWidth(),
ZBinWidth(NAN),
tpc_drift_velocity(NAN),
tpc_adc_clock(NAN),
NZBins(INT_MAX),
NPhiBins(),
NTpcLayers(),
tpc_region(INT_MAX),
zigzag_pads(INT_MAX)
{
InitializeParameters();
hit = 0;
fcharge = new TF1("fcharge", "gaus(0)");
for(int ipad = 0;ipad < 10; ipad++)
{
char name[500];
sprintf(name,"fpad%i",ipad);
fpad[ipad] = new TF1(name,"[0]-abs(x-[1])");
}
output_radius = 0; // turns off diagnostic output
return;
}
int PHG4TPCPadPlaneReadout::CreateReadoutGeometry(PHCompositeNode *topNode, PHG4CylinderCellGeomContainer *seggeo)
{
if (Verbosity()) cout << "PHG4TPCPadPlaneReadout: CreateReadoutGeometry: " << endl;
for (int iregion = 0; iregion < 3; ++iregion)
{
for (int layer = MinLayer[iregion]; layer < MinLayer[iregion] + NTpcLayers[iregion]; ++layer)
{
if (Verbosity())
{
cout << " layer " << layer << " MinLayer " << MinLayer[iregion] << " region " << iregion
<< " radius " << MinRadius[iregion] + ((double) (layer - MinLayer[iregion]) + 0.5) * Thickness[iregion]
<< " thickness " << Thickness[iregion]
<< " NZbins " << NZBins << " zmin " << MinZ << " zstep " << ZBinWidth
<< " phibins " << NPhiBins[iregion] << " phistep " << PhiBinWidth[iregion] << endl;
}
PHG4CylinderCellGeom *layerseggeo = new PHG4CylinderCellGeom();
layerseggeo->set_layer(layer);
layerseggeo->set_radius(MinRadius[iregion] + ((double) (layer - MinLayer[iregion]) + 0.5) * Thickness[iregion]);
layerseggeo->set_thickness(Thickness[iregion]);
layerseggeo->set_binning(PHG4CellDefs::sizebinning);
layerseggeo->set_zbins(NZBins);
layerseggeo->set_zmin(MinZ);
layerseggeo->set_zstep(ZBinWidth);
layerseggeo->set_phibins(NPhiBins[iregion]);
layerseggeo->set_phistep(PhiBinWidth[iregion]);
// Chris Pinkenburg: greater causes huge memory growth which causes problems
// on our farm. If you need to increase this - TALK TO ME first
if (NPhiBins[iregion] * NZBins > 5100000)
{
cout << "increase TPC cellsize, number of cells "
<< NPhiBins[iregion] * NZBins << " for layer " << layer
<< " exceed 5.1M limit" << endl;
gSystem->Exit(1);
}
seggeo->AddLayerCellGeom(layerseggeo);
}
}
GeomContainer = seggeo;
return 0;
}
void PHG4TPCPadPlaneReadout::MapToPadPlane(PHG4CellContainer *g4cells, const double x_gem, const double y_gem, const double z_gem, PHG4HitContainer::ConstIterator hiter, TNtuple *ntpad, TNtuple *nthit)
{
// One electron per call of this method
// The x_gem and y_gem values have already been randomized within the transverse drift diffusion width
// The z_gem value already reflects the drift time of the primary electron from the production point, and is randomized within the longitudinal diffusion witdth
double phi = atan2(y_gem,x_gem);
if (phi > +M_PI) phi -= 2 * M_PI;
if (phi < -M_PI) phi += 2 * M_PI;
rad_gem = sqrt(x_gem*x_gem + y_gem*y_gem);
unsigned int layernum = 0;
// Find which readout layer this electron ends up in
PHG4CylinderCellGeomContainer::ConstRange layerrange = GeomContainer->get_begin_end();
for(PHG4CylinderCellGeomContainer::ConstIterator layeriter = layerrange.first;
layeriter != layerrange.second;
++layeriter)
{
double rad_low = layeriter->second->get_radius() - layeriter->second->get_thickness() / 2.0;
double rad_high = layeriter->second->get_radius() + layeriter->second->get_thickness() / 2.0;
if(rad_gem > rad_low && rad_gem < rad_high)
{
// capture the layer where this electron hits sthe gem stack
LayerGeom = layeriter->second;
layernum = LayerGeom->get_layer();
if(Verbosity())
cout << " g4hit id " << hiter->first << " rad_gem " << rad_gem << " rad_low " << rad_low << " rad_high " << rad_high
<< " layer " << hiter->second->get_layer() << " want to change to " << layernum << endl;
hiter->second->set_layer(layernum); // have to set here, since the stepping action knows nothing about layers
}
}
if(layernum == 0)
{
return;
}
// Create the distribution function of charge on the pad plane around the electron position
// The resolution due to pad readout includes the charge spread during GEM multiplication.
// this now defaults to 400 microns during construction from Tom (see 8/11 email).
// Use the setSigmaT(const double) method to update...
// We use a double gaussian to represent the smearing due to the SAMPA chip shaping time - default values of fShapingLead and fShapingTail are for 80 ns SAMPA
// amplify the single electron in the gem stack
//===============================
// should be obtained from a distribution of avalanche gains, make constant for now
float nelec = 2000.0;
// Distribute the charge between the pads in phi
//====================================
if(Verbosity() > 200)
cout << " populate phi bins for "
<< " layernum " << layernum
<< " phi " << phi
<< " sigmaT " << sigmaT
<< " zigzag_pads " << zigzag_pads
<< endl;
pad_phibin.clear();
pad_phibin_share.clear();
if(zigzag_pads)
populate_zigzag_phibins(layernum, phi, sigmaT, pad_phibin, pad_phibin_share);
else
populate_rectangular_phibins(layernum, phi, sigmaT, pad_phibin, pad_phibin_share);
// Normalize the shares so they add up to 1
double norm1 = 0.0;
for(unsigned int ipad = 0; ipad < pad_phibin.size(); ++ipad)
{
double pad_share = pad_phibin_share[ipad];
norm1 += pad_share;
}
for(unsigned int iphi = 0; iphi < pad_phibin.size(); ++iphi)
pad_phibin_share[iphi] /= norm1;
// Distribute the charge between the pads in z
//====================================
if(Verbosity() > 100 && layernum == 47)
cout << " populate z bins for layernum " << layernum
<< " with z_gem " << z_gem << " sigmaL[0] " << sigmaL[0] << " sigmaL[1] " << sigmaL[1] << endl;
adc_zbin.clear();
adc_zbin_share.clear();
populate_zbins(z_gem, sigmaL, adc_zbin, adc_zbin_share);
// Normalize the shares so that they add up to 1
double znorm = 0.0;
for(unsigned int iz = 0; iz < adc_zbin.size(); ++iz)
{
double bin_share = adc_zbin_share[iz];
znorm += bin_share;
}
for(unsigned int iz = 0; iz < adc_zbin.size(); ++iz)
adc_zbin_share[iz] /= znorm;
// Fill cells
//========
// These are used to do a quick clustering for checking
double phi_integral = 0.0;
double z_integral = 0.0;
double weight = 0.0;
for(unsigned int ipad = 0; ipad < pad_phibin.size(); ++ipad)
{
int pad_num = pad_phibin[ipad];
double pad_share = pad_phibin_share[ipad];
for(unsigned int iz = 0; iz<adc_zbin.size(); ++iz)
{
int zbin_num = adc_zbin[iz];
double adc_bin_share = adc_zbin_share[iz];
// Divide electrons from avalanche between bins
float neffelectrons = nelec * (pad_share) * (adc_bin_share);
if (neffelectrons < neffelectrons_threshold) continue; // skip signals that will be below the noise suppression threshold
if(zbin_num >= LayerGeom->get_zbins() ) cout << " Error making key: adc_zbin " << zbin_num << " nzbins " << LayerGeom->get_zbins() << endl;
if(pad_num >= LayerGeom->get_phibins()) cout << " Error making key: pad_phibin " << pad_num << " nphibins " << LayerGeom->get_phibins() << endl;
// collect information to do simple clustering. Checks operation of PHG4CylinderCellTPCReco, and
// is also useful for comparison with PHG4TPCClusterizer result when running single track events.
// The only information written to the cell other than neffelectrons is zbin and pad number, so get those from geometry
double zcenter = LayerGeom->get_zcenter(zbin_num);
double phicenter = LayerGeom->get_phicenter(pad_num);
phi_integral += phicenter*neffelectrons;
z_integral += zcenter*neffelectrons;
weight += neffelectrons;
if(Verbosity() > 100 && layernum == 47)
cout << " zbin_num " << zbin_num << " zcenter " << zcenter << " pad_num " << pad_num << " phicenter " << phicenter
<< " neffelectrons " << neffelectrons << " neffelectrons_threshold " << neffelectrons_threshold << endl;
// Add edep from this electron for this zbin and phi bin combination to the appropriate cell
PHG4CellDefs::keytype key = PHG4CellDefs::SizeBinning::genkey(layernum,zbin_num,pad_num);
PHG4Cell *cell = g4cells->findCell(key);
if (! cell)
{
cell = new PHG4Cellv1(key);
g4cells->AddCell(cell);
}
cell->add_edep(neffelectrons);
cell->add_edep(hiter->first, neffelectrons); // associates g4hit with this edep
//if(Verbosity() > 100 && layernum == 50) cell->identify();
} // end of loop over adc Z bins
} // end of loop over zigzag pads
// Capture the input values at the gem stack and the quick clustering results, elecron-by-electron
if(Verbosity() > 0)
ntpad->Fill(layernum, phi, phi_integral/weight, z_gem, z_integral/weight);
if(Verbosity() > 100)
if( layernum == 47)
{
cout << " hit " << hit << " quick centroid for this electron " << endl;
cout << " phi centroid = " << phi_integral / weight << " phi in " << phi << " phi diff " << phi_integral/weight - phi << endl;
cout << " z centroid = " << z_integral / weight << " z in " << z_gem << " z diff " << z_integral/weight - z_gem << endl;
// For a single track event, this captures the distribution of single electron centroids on the pad plane for layer 47.
// The centroid of that should match the cluster centroid found by PHG4TPCClusterizer for layer 47, if everything is working
// - matches to < .01 cm for a few cases that I checked
nthit->Fill(hit, layernum, phi, phi_integral/weight, z_gem, z_integral/weight, weight);
}
hit ++;
return;
}
void PHG4TPCPadPlaneReadout::populate_rectangular_phibins(const unsigned int layernum, const double phi, const double cloud_sig_rp, std::vector<int> &pad_phibin, std::vector<double> &pad_phibin_share)
{
double cloud_sig_rp_inv = 1. / cloud_sig_rp;
//int phibin = get_phibin(tpc_region, phi);
//int nphibins = NPhiBins[tpc_region];
int phibin = LayerGeom->get_phibin(phi);
int nphibins = LayerGeom->get_phibins();
double radius = LayerGeom->get_radius();
double phidisp = phi - LayerGeom->get_phicenter(phibin);
double phistepsize = LayerGeom->get_phistep();
// bin the charge in phi - consider phi bins up and down 3 sigma in r-phi
int n_rp = int(3 * cloud_sig_rp / (radius * phistepsize) + 1);
for (int iphi = -n_rp; iphi != n_rp + 1; ++iphi)
{
int cur_phi_bin = phibin + iphi;
// correcting for continuity in phi
if (cur_phi_bin < 0)
cur_phi_bin += nphibins;
else if (cur_phi_bin >= nphibins)
cur_phi_bin -= nphibins;
if ((cur_phi_bin < 0) || (cur_phi_bin >= nphibins))
{
std::cout << "PHG4CylinderCellTPCReco => error in phi continuity. Skipping" << std::endl;
continue;
}
// Get the integral of the charge probability distribution in phi inside the current phi step
double phiLim1 = 0.5 * M_SQRT2 * ((iphi + 0.5) * phistepsize * radius - phidisp * radius) * cloud_sig_rp_inv;
double phiLim2 = 0.5 * M_SQRT2 * ((iphi - 0.5) * phistepsize * radius - phidisp * radius) * cloud_sig_rp_inv;
double phi_integral = 0.5 * (erf(phiLim1) - erf(phiLim2));
pad_phibin.push_back(cur_phi_bin);
pad_phibin_share.push_back(phi_integral);
}
return;
}
void PHG4TPCPadPlaneReadout::populate_zigzag_phibins(const unsigned int layernum, const double phi, const double cloud_sig_rp, std::vector<int> &pad_phibin, std::vector<double> &pad_phibin_share)
{
double nsigmas = 5.0;
double radius = LayerGeom->get_radius();
double phistepsize = LayerGeom->get_phistep();
// make the charge distribution gaussian
double rphi = phi * radius;
fcharge->SetParameter(0, 1.0);
fcharge->SetParameter(1, rphi);
fcharge->SetParameter(2, cloud_sig_rp);
if(Verbosity() > 100)
if(LayerGeom->get_layer() == 47)
{
cout << " populate_zigzag_phibins for layer " << layernum << " with radius " << radius << " phi " << phi
<< " rphi " << rphi << " phistepsize " << phistepsize << endl;
cout << " fcharge created: radius " << radius << " rphi " << rphi << " cloud_sig_rp " << cloud_sig_rp << endl;
}
// Get the range of phi values that completely contains all pads that touch the charge distribution - (nsigmas + 1/2 pad width) in each direction
double philim_low = phi - (nsigmas * cloud_sig_rp / radius) - phistepsize;
double philim_high = phi + (nsigmas * cloud_sig_rp / radius) + phistepsize ;
// Find the pad range that covers this phi range
int phibin_low = LayerGeom->get_phibin(philim_low);
int phibin_high = LayerGeom->get_phibin(philim_high);
int npads = phibin_high - phibin_low;
if(Verbosity() > 100)
if(layernum == 47)
cout << " zigzags: phi " << phi << " philim_low " << philim_low << " phibin_low " << phibin_low
<< " philim_high " << philim_high << " phibin_high " << phibin_high << " npads " << npads << endl;
if(npads < 0 || npads >9) npads = 9; // can happen if phibin_high wraps around. If so, limit to 10 pads and fix below
// Calculate the maximum extent in r-phi of pads in this layer. Pads are assumed to touch the center of the next phi bin on both sides.
double pad_rphi = 2.0 * LayerGeom->get_phistep() * radius;
// Make a TF1 for each pad in the phi range
int pad_keep[10];
for(int ipad = 0; ipad<=npads;ipad++)
{
int pad_now = phibin_low + ipad;
// check that we do not exceed the maximum number of pads, wrap if necessary
if( pad_now >= LayerGeom->get_phibins() ) pad_now -= LayerGeom->get_phibins();
pad_keep[ipad] = pad_now;
double rphi_pad_now = LayerGeom->get_phicenter(pad_now) * radius;
fpad[ipad]->SetParameter(0,pad_rphi/2.0);
fpad[ipad]->SetParameter(1, rphi_pad_now);
if(Verbosity() > 100)
if(layernum == 47)
cout << " zigzags: make fpad for ipad " << ipad << " pad_now " << pad_now << " pad_rphi/2 " << pad_rphi/2.0
<< " rphi_pad_now " << rphi_pad_now << endl;
}
// Now make a loop that steps through the charge distribution and evaluates the response at that point on each pad
double overlap[10];
for(int i=0;i<10;i++)
overlap[i]=0;
int nsteps = 100;
double xstep = 2.0 * nsigmas * cloud_sig_rp / (double) nsteps;
for(int i=0;i<nsteps;i++)
{
double x = rphi - 4.5 * cloud_sig_rp + (double) i * xstep;
double charge = fcharge->Eval(x);
for(int ipad = 0;ipad<=npads;ipad++)
{
if(fpad[ipad]->Eval(x) > 0.0)
{
double prod = charge * fpad[ipad]->Eval(x);
overlap[ipad] += prod;
}
} // pads
} // steps
// now we have the overlap for each pad
for(int ipad = 0;ipad <= npads;ipad++)
{
pad_phibin.push_back(pad_keep[ipad]);
pad_phibin_share.push_back(overlap[ipad]);
if(rad_gem < output_radius) cout << " zigzags: for pad " << ipad << " integral is " << overlap[ipad] << endl;
}
return;
}
void PHG4TPCPadPlaneReadout::populate_zbins( const double z, const double cloud_sig_zz[2], std::vector<int> &adc_zbin, std::vector<double> &adc_zbin_share)
{
int zbin = LayerGeom->get_zbin(z);
if(zbin < 0 || zbin > LayerGeom->get_zbins() )
{
//cout << " z bin is outside range, return" << endl;
return;
}
double zstepsize = LayerGeom->get_zstep();
double zdisp = z - LayerGeom->get_zcenter(zbin);
if(Verbosity() > 100)
cout << " input: z " << z << " zbin " << zbin << " zstepsize " << zstepsize << " z center " << LayerGeom->get_zcenter(zbin) << " zdisp " << zdisp << endl;
// Because of diffusion, hits can be shared across the membrane, so we allow all z bins
int min_cell_zbin = 0;
int max_cell_zbin = NZBins-1;
double cloud_sig_zz_inv[2];
cloud_sig_zz_inv[0] = 1. / cloud_sig_zz[0];
cloud_sig_zz_inv[1] = 1. / cloud_sig_zz[1];
int zsect = 0;
if(z < 0)
zsect = -1;
else
zsect = 1;
int n_zz = int(3 * (cloud_sig_zz[0] + cloud_sig_zz[1]) / (2.0 * zstepsize) + 1);
if(Verbosity() > 100) cout << " n_zz " << n_zz << " cloud_sigzz[0] " << cloud_sig_zz[0] << " cloud_sig_zz[1] " << cloud_sig_zz[1] << endl;
for (int iz = -n_zz; iz != n_zz + 1; ++iz)
{
int cur_z_bin = zbin + iz;
if ((cur_z_bin < min_cell_zbin) || (cur_z_bin > max_cell_zbin)) continue;
if(Verbosity() > 100)
cout << " iz " << iz << " cur_z_bin " << cur_z_bin << " min_cell_zbin " << min_cell_zbin << " max_cell_zbin " << max_cell_zbin << endl;
double z_integral = 0.0;
if(iz == 0)
{
// the crossover between lead and tail shaping occurs in this bin
int index1 = -1;
int index2 = -1;
if(zsect == -1)
{
index1 = 0; index2 = 1;
}
else
{
index1 = 1; index2 = 0;
}
double zLim1 = 0.0;
double zLim2 = 0.5 * M_SQRT2 * (- 0.5 * zstepsize - zdisp) * cloud_sig_zz_inv[index1];
// 1/2 * the erf is the integral probability from the argument Z value to zero, so this is the integral probability between the Z limits
double z_integral1 = 0.5 * (erf(zLim1) - erf(zLim2));
if(Verbosity() > 100)
if(LayerGeom->get_layer() == 47)
cout << " populate_zbins: cur_z_bin " << cur_z_bin << " center z " << LayerGeom->get_zcenter(cur_z_bin)
<< " index1 " << index1 << " zLim1 " << zLim1 << " zLim2 " << zLim2 << " z_integral1 " << z_integral1 << endl;
zLim2 = 0.0;
zLim1 = 0.5 * M_SQRT2 * ( 0.5 * zstepsize - zdisp) * cloud_sig_zz_inv[index2];
double z_integral2 = 0.5 * (erf(zLim1) - erf(zLim2));
if(Verbosity() > 100)
if(LayerGeom->get_layer() == 47)
cout << " populate_zbins: cur_z_bin " << cur_z_bin << " center z " << LayerGeom->get_zcenter(cur_z_bin)
<< " index2 " << index2 << " zLim1 " << zLim1 << " zLim2 " << zLim2 << " z_integral2 " << z_integral2 << endl;
z_integral = z_integral1 + z_integral2;
}
else
{
// The non zero bins are entirely in the lead or tail region
// lead or tail depends on which side of the membrane
int index = 0;
if(iz < 0)
{
if(zsect == -1)
index = 0;
else
index = 1;
}
else
{
if(zsect == -1)
index = 1;
else
index = 0;
}
double zLim1 = 0.5 * M_SQRT2 * ((iz + 0.5) * zstepsize - zdisp) * cloud_sig_zz_inv[index];
double zLim2 = 0.5 * M_SQRT2 * ((iz - 0.5) * zstepsize - zdisp) * cloud_sig_zz_inv[index];
z_integral = 0.5 * (erf(zLim1) - erf(zLim2));
if(Verbosity() > 100)
if(LayerGeom->get_layer() == 47)
cout << " populate_zbins: z_bin " << cur_z_bin << " center z " << LayerGeom->get_zcenter(cur_z_bin)
<< " index " << index << " zLim1 " << zLim1 << " zLim2 " << zLim2 << " z_integral " << z_integral << endl;
}
adc_zbin.push_back(cur_z_bin);
adc_zbin_share.push_back(z_integral);
}
return;
}
void PHG4TPCPadPlaneReadout::SetDefaultParameters()
{
set_default_int_param("ntpc_layers_inner",16);
set_default_int_param("ntpc_layers_mid",16);
set_default_int_param("ntpc_layers_outer",16);
set_default_int_param("tpc_minlayer_inner",7);
set_default_double_param("tpc_minradius_inner",30.0); // cm
set_default_double_param("tpc_minradius_mid",40.0);
set_default_double_param("tpc_minradius_outer",60.0);
set_default_double_param("tpc_maxradius_inner",40.0); // cm
set_default_double_param("tpc_maxradius_mid",60.0);
set_default_double_param("tpc_maxradius_outer",77.0); // from Tom
set_default_double_param("neffelectrons_threshold",1.0);
set_default_double_param("maxdriftlength",105.5); // cm
set_default_double_param("drift_velocity",8.0 / 1000.0); // cm/ns
set_default_double_param("tpc_adc_clock",53.0); // ns, for 18.8 MHz clock
set_default_double_param("gem_cloud_sigma",0.04); // cm = 400 microns
set_default_double_param("sampa_shaping_lead",32.0); // ns, for 80 ns SAMPA
set_default_double_param("sampa_shaping_tail",48.0); // ns, for 80 ns SAMPA
set_default_int_param("ntpc_phibins_inner",1152);
set_default_int_param("ntpc_phibins_mid",1536);
set_default_int_param("ntpc_phibins_outer",2304);
set_default_int_param("zigzag_pads",1);
return;
}
void PHG4TPCPadPlaneReadout::UpdateInternalParameters()
{
NTpcLayers[0] = get_int_param("ntpc_layers_inner");
NTpcLayers[1] = get_int_param("ntpc_layers_mid");
NTpcLayers[2] = get_int_param("ntpc_layers_outer");
MinLayer[0] = get_int_param("tpc_minlayer_inner");
MinLayer[1] = MinLayer[0]+NTpcLayers[0];
MinLayer[2] = MinLayer[1]+NTpcLayers[1];
neffelectrons_threshold = get_double_param("neffelectrons_threshold");
MinRadius[0] = get_double_param("tpc_minradius_inner");
MinRadius[1] = get_double_param("tpc_minradius_mid");
MinRadius[2] = get_double_param("tpc_minradius_outer");
MaxRadius[0] = get_double_param("tpc_maxradius_inner");
MaxRadius[1] = get_double_param("tpc_maxradius_mid");
MaxRadius[2] = get_double_param("tpc_maxradius_outer");
Thickness[0] = (MaxRadius[0] - MinRadius[0]) / NTpcLayers[0];
Thickness[1] = (MaxRadius[1] - MinRadius[1]) / NTpcLayers[1];
Thickness[2] = (MaxRadius[2] - MinRadius[2]) / NTpcLayers[2];
MaxRadius[0] = get_double_param("tpc_maxradius_inner");
MaxRadius[1] = get_double_param("tpc_maxradius_mid");
MaxRadius[2] = get_double_param("tpc_maxradius_outer");
sigmaT = get_double_param("gem_cloud_sigma");
sigmaL[0] = get_double_param("sampa_shaping_lead") * get_double_param("drift_velocity");
sigmaL[1] = get_double_param("sampa_shaping_tail") * get_double_param("drift_velocity");
tpc_drift_velocity = get_double_param("drift_velocity");
tpc_adc_clock = get_double_param("tpc_adc_clock");
ZBinWidth = tpc_adc_clock * tpc_drift_velocity;
MaxZ = get_double_param("maxdriftlength");
MinZ = -MaxZ;
NZBins = (int) ( (MaxZ-MinZ) / ZBinWidth) + 1;
NPhiBins[0] = get_int_param("ntpc_phibins_inner");
NPhiBins[1] = get_int_param("ntpc_phibins_mid");
NPhiBins[2] = get_int_param("ntpc_phibins_outer");
PhiBinWidth[0] = 2.0 * M_PI / (double) NPhiBins[0];
PhiBinWidth[1] = 2.0 * M_PI / (double) NPhiBins[1];
PhiBinWidth[2] = 2.0 * M_PI / (double) NPhiBins[2];
zigzag_pads = get_int_param("zigzag_pads");
}
|
#include<stdio.h>
int function(int &x)
{
char ret;
char ran[9],dom[9],uni[3], uni2[3];
char open,close,comma,separ,brak;
int temp[9];
uni[1]='a';
uni2[1]='a';
uni[2]='b';
uni[3]='c';
uni2[2]='b';
uni2[3]='c';
for(int init=0;init<=8;init++)
temp[init]=1;
printf("\n\t\tU= { %c,%c,%c }\n\n", uni[1],uni[2],uni[3]);
printf("\n\tWhen you are inputting, do not separate with space.\n\tIn R, if first time input like {(a,a),\n\t\totherwise, input like (a,a).\n\tTo end the relations input }.");
if(x==2)
printf("\n\n\tR= ");
else
printf("\n\n\tR= {");
for(init=1;open!='}';init++)
{ scanf("%c", &brak);
scanf("%c", &open);
scanf("%c", &dom[init]);
scanf("%c", &comma);
scanf("%c", &ran[init]);
scanf("%c", &close);
scanf("%c", &separ);
if(separ=='}')
break;
}
int final=init;
for(init=1;init<=final;init++)
{
if(dom[init]==uni[1]||dom[init]==uni[2]||dom[init]==uni[3])
;
else
{ return 1;
x++;
}
if(ran[init]==uni[1]||ran[init]==uni[2]||ran[init]==uni[3])
;
else
{ return 0;
x++;
}
}
printf("\n\t\t\t\tDomain\tRang?e\n");
for(init=1;init<=final;init++)
{
printf("\tRelation %d\t\t%c\t%c\n",init,dom[init] ,ran[init]);
}
printf("\n\nR-1\n\tR-1={");
for(init=1;init<=final;init++)
{
printf("(%c,%c)", ran[init],dom[init]);
if(init==final-1)
printf(",");
if (init==final)
printf("}\n\n");
}
printf("\n\nRc\n\tRc={");
int init3=0;
for(init=1;init<=3;init++)
{
for(int init1=1;init1<=3;init1++)
{
for(int init2=1;init2<=final;init2++)
{
if( (dom[init2]==uni[init]) && (ran[init2]==uni2[init1]))
{
init2=final;
temp[init3]*=0;
}
else
{
temp[init3]*=1;
}
}
init3++;
}
}
init3=0;
for(init=1;init<=3;init++)
{
for(int init1=1;init1<=3;init1++)
{
if(temp[init3]==0)
;
else
printf("(%c,%c)",uni[init],uni2[init1]);
init3++;
if((init==3&&init1==3)||temp[init3]==0)
;
else
printf(",");
}
}
printf("}\n\n");
return x++;
}
int main()
{ int x=2;
char repeat='y';
while(repeat=='y')
{
int exact=function(x);
if(exact>=2)
{ printf("Do you want to run the program again?Y/y or N/n: ");
scanf("%s", &repeat);
}
else if (exact==1)
{
printf("\nThe domain you entered is invalid.\nDo you want to run the program again?Y/y or N/n: ");
scanf("%s", &repeat);
}
else if (exact==0)
{
printf("\nThe range you entered is invalid.\nDo you want to run the program again?Y/y or N/n: ");
scanf("%s", &repeat);
}
}
return 0;
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QWebElement>
#include <QWebFrame>
#include <QMessageBox>
// ---------------------------------------
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(&webView,SIGNAL(loadFinished(bool)),this,SLOT(zaladowano()) );
QWebSettings * globalSettings = QWebSettings::globalSettings();
globalSettings->setAttribute(QWebSettings::AutoLoadImages, false);
globalSettings->setAttribute(QWebSettings::JavaEnabled, false);
globalSettings->setAttribute(QWebSettings::PluginsEnabled, false);
globalSettings->setAttribute(QWebSettings::JavascriptCanOpenWindows, false);
globalSettings->setAttribute(QWebSettings::JavascriptCanCloseWindows, false);
globalSettings->setAttribute(QWebSettings::JavascriptCanAccessClipboard, false);
globalSettings->setAttribute(QWebSettings::DeveloperExtrasEnabled, false);
globalSettings->setAttribute(QWebSettings::SpatialNavigationEnabled, false);
globalSettings->setAttribute(QWebSettings::PrintElementBackgrounds, false);
}
MainWindow::~MainWindow()
{
webView.close();
delete ui;
}
void MainWindow::on_losuj_clicked()
{
// zablokujmy możlwiość wciśnięcia przycisku "Losuj" dopóki nie wczytamy strony
ui->losuj->setEnabled(false);
// rozpoczynamy wczytywanie strony
webView.load(QUrl("http://www.cubetimer.com/"));
}
void MainWindow::zaladowano()
{
// szukamy wszystkich tagów <b>
QWebElement strona = webView.page()->mainFrame()->documentElement().findFirst("div[id=scramble]");
QString scr = strona.toPlainText();
// skracamy go aby był bez napisu "Scramble: "
scr.remove(0,9);
// z racji, że strona w tych tagach ma także numer scramble'a to pobieramy drugi
ui->scramble->setText(scr);
// aktywujemy możlwiość losowania
ui->losuj->setEnabled(true);
}
|
#ifndef FILE_H
#define FILE_H
#include <iostream>
#include <fstream>
#include <string>
bool isFileExist(std::string name_of_file);
void createFile(std::string name_of_file);
int defineNumberOfNotesInFile(std::string name_of_file);
void showFileContent(std::string name_of_file);
#endif
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
const int TARGET = 2020;
int find_target(const std::vector<int> numbers)
{
int index_of_second_number = 0, index_of_third_number = 1;
for (int number : numbers)
{
while (index_of_second_number < numbers.size())
{
while (index_of_third_number < numbers.size())
{
int second_number = numbers[index_of_second_number];
int third_number = numbers[index_of_third_number];
int sum = number + second_number + third_number;
if (sum == TARGET)
{
return number * numbers[index_of_second_number] * numbers[index_of_third_number];
}
++index_of_third_number;
}
++index_of_second_number;
index_of_third_number = 1;
}
index_of_second_number = 0;
}
}
int main()
{
std::ifstream f("./input.txt");
std::vector<int> numbers;
std::string line;
while (getline(f, line))
{
numbers.push_back(std::stoi(line));
}
std::cout << find_target(numbers) << std::endl; // Answer = 212_428_694
return 0;
}
|
#include <string>
#include "PugiXml/src/pugiconfig.hpp"
#include "PugiXml/src/pugixml.hpp"
#include "j1ObjManager.h"
#include "App.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "Object.h"
#include "j1Window.h"
#include "j1Scene.h"
#include "PugiXml/src/pugiconfig.hpp"
#include "PugiXml/src/pugixml.hpp"
#include "Obj_Player.h"
#include "j1Map.h"
#include "Camera.h"
j1ObjManager::j1ObjManager()
{
name.assign("object_manager");
}
// Destructor
j1ObjManager::~j1ObjManager()
{
}
bool j1ObjManager::PreUpdate()
{
std::list<Object*>::iterator iterator;
for (iterator = objects.begin(); iterator != objects.end(); iterator++)
{
if ((*iterator) != nullptr)
{
(*iterator)->PreUpdate();
}
}
return true;
}
bool j1ObjManager::Update(float dt)
{
for (std::list<Object*>::iterator iterator = objects.begin(); iterator != objects.end(); ++iterator)
{
if ((*iterator) != nullptr)
{
(*iterator)->Update(dt);
}
}
return true;
}
bool j1ObjManager::PostUpdate()
{
for (std::vector<Camera*>::iterator item_cam = App->render->cameras.begin(); item_cam != App->render->cameras.end(); ++item_cam)
{
SDL_RenderSetClipRect(App->render->renderer, &(*item_cam)->screen_section);
for (std::list<Object*>::iterator item = objects.begin(); item != objects.end(); ++item)
{
(*item)->Draw(*item_cam);
}
}
SDL_RenderSetClipRect(App->render->renderer, nullptr);
return true;
}
// Called before quitting
bool j1ObjManager::CleanUp()
{
DeleteObjects();
return true;
}
Object* j1ObjManager::CreateObject(ObjectType type, fPoint pos)
{
Object* ret = nullptr;
switch (type)
{
case ObjectType::PLAYER:
ret = new Obj_Player(pos);
ret->type = ObjectType::PLAYER;
break;
}
if (ret != nullptr)
{
ret->Start();
objects.push_back(ret);
}
return ret;
}
void j1ObjManager::DeleteObjects()
{
for (std::list<Object*>::iterator iterator = objects.begin(); iterator != objects.end(); ++iterator)
{
if ((*iterator) != nullptr)
{
(*iterator)->CleanUp();
delete (*iterator);
(*iterator) = nullptr;
}
}
objects.clear();
}
|
#include <HTStack/App/App.hpp>
#include <HTStack/Server/Server.hpp>
#include <HTStack/Request/Request.hpp>
#include <map>
#include <string>
class App : public HTStack::App {
public:
App (HTStack::Server & server, std::map <std::string, std::string> & settings);
void handleRequest (HTStack::Request & request);
};
extern "C" HTStack::App* factory (HTStack::Server & server, std::map <std::string, std::string> & settings);
|
/*
* Copyright 2019 LogMeIn
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "asyncly/future/Future.h"
namespace asyncly {
/// split produces two Future<T> from a single one. This can be used to represent forks in
/// asynchronous computation graphs. This only works if T is copyable, as we have to deliver it two
/// destinations. This function consumes the future supplied to it.
template <typename T> std::tuple<Future<T>, Future<T>> split(Future<T>&& future)
{
static_assert(
std::is_copy_constructible<T>::value,
"You can only split futures for copy-constructible types");
auto lazy1 = make_lazy_future<T>();
auto future1 = std::get<0>(lazy1);
auto promise1 = std::get<1>(lazy1);
auto lazy2 = make_lazy_future<T>();
auto future2 = std::get<0>(lazy2);
auto promise2 = std::get<1>(lazy2);
std::move(future)
.then([promise1, promise2](T value) mutable {
promise1.set_value(value);
promise2.set_value(value);
})
.catch_error([promise1, promise2](auto error) mutable {
promise1.set_exception(error);
promise2.set_exception(error);
});
return std::make_tuple(future1, future2);
}
template <> inline std::tuple<Future<void>, Future<void>> split(Future<void>&& future)
{
auto lazy1 = make_lazy_future<void>();
auto future1 = std::get<0>(lazy1);
auto promise1 = std::get<1>(lazy1);
auto lazy2 = make_lazy_future<void>();
auto future2 = std::get<0>(lazy2);
auto promise2 = std::get<1>(lazy2);
std::move(future)
.then([promise1, promise2]() mutable {
promise1.set_value();
promise2.set_value();
})
.catch_error([promise1, promise2](auto error) mutable {
promise1.set_exception(error);
promise2.set_exception(error);
});
return std::make_tuple(future1, future2);
}
}
|
//
// Created by dylan on 23-5-2020.
//
#include "game_moves.hpp"
/// Constructor of the class game_moves
/// \param player: Represents either player 1 or player 2
/// \param x_cor: Represents: the x coordinate of the move
/// \param y_cor: Represents: the y coordinte of the move
game_moves::game_moves(const bool &player, const int &x_cor, const int &y_cor):
player(player), coordinates({x_cor,y_cor}){};
/// This function gets the value of the player variable and returns it
/// \return: A boolean, true means player 2 and false means player 1
bool game_moves::get_player() const {
return player;
}
/// This function gets the value of coordinates and returns it
/// \return: The coordinates of the move as an int array
std::array<int, 2> game_moves::get_move() const {
return coordinates;
}
|
#include <chrono>
#include <thread>
#include "Context.hpp"
#include "GUIEventDispatcher.hpp"
using namespace uipf;
void Context::displayImage(const std::string& strTitle, const Matrix& oMat, bool bBlocking, bool bAutoClose)
{
// if we are running in the gui, open the window using Qt in the Qt MainWindow thread
if (bHasGUI_) {
GUIEventDispatcher::instance()->triggerCreateWindow(strTitle, oMat.getContent(false));
// block if blocking is true
if (bBlocking) {
waitKey();
if (bAutoClose)
GUIEventDispatcher::instance()->triggerCloseWindow(strTitle);
}
} else {
// otherwise use OpenCV imshow function
cv::namedWindow( strTitle.c_str(), cv::WINDOW_AUTOSIZE );
cv::imshow( strTitle.c_str(), oMat.getContent() );
// block if blocking is true
if (bBlocking) {
waitKey();
if (bAutoClose)
cv::destroyWindow(strTitle.c_str());
} else {
// calls waitKey to actually show the window
cv::waitKey(1);
}
}
}
void Context::waitKey(std::string message)
{
if (message.empty()) {
message = "Press any key to continue...";
}
if (bHasGUI_) {
LOG_I(message);
// when we run in the GUI we have to communicate with the GUI
bPaused_ = true;
// wait until pause is set to false
while(bPaused_ && !bStopRequested_) {
std::this_thread::sleep_for( std::chrono::milliseconds (250) );
}
LOG_D("Key has been pressed, not waiting anymore.");
} else {
// on console use opencv waitKey()
std::cout << message << std::endl;
cv::waitKey(0);
}
}
// TODO maybe implement logger here?
|
///< @author Michael Kulik
void start_part() // начальная расстоновка фигур
{
for(int i = 7; i >= 0; i--) // пешки белые
{
figures.push_back(new Pawn(0,i,1));
cells[1][i]->set_figure(figures.back());
}
for(int j = 7; j >= 0; j--) // пешки чёрные
{
figures.push_back(new Pawn(1,j,6));
cells[6][j]->set_figure(figures.back());
}
// ладьи белые
figures.push_back(new Rook(0, 0, 0));
cells[0][0]->set_figure(figures.back());
figures.push_back(new Rook(0,7,0));
cells[0][7]->set_figure(figures.back());
// ладьи чёрные
figures.push_back(new Rook(1, 0, 7));
cells[0][7]->set_figure(figures.back());
figures.push_back(new Rook(1, 7, 7));
cells[7][7]->set_figure(figures.back());
// кони белые
figures.push_back(new Knight(0, 1, 0));
cells[0][7]->set_figure(figures.back());
figures.push_back(new Knight(0, 6, 0));
cells[0][7]->set_figure(figures.back());
// кони чёрные
figures.push_back(new Knight(1, 1, 7));
cells[7][1]->set_figure(figures.back());
figures.push_back(new Knight(1, 6, 7));
cells[7][6]->set_figure(figures.back());
// слоны белые
figures.push_back(new Bishop(0, 2, 0));
cells[0][2]->set_figure(figures.back());
figures.push_back(new Bishop(0, 5, 0));
cells[0][5]->set_figure(figures.back());
// слоны чёрные
figures.push_back(new Bishop(1, 2, 7));
cells[7][2]->set_figure(figures.back());
figures.push_back(new Bishop(1, 5, 7));
cells[7][5]->set_figure(figures.back());
// ферзь белый
figures.push_back(new Queen(0, 3, 0));
cells[0][3]->set_figure(figures.back());
// ферзь чёрный
figures.push_back(new Queen(1, 3, 7));
cells[7][3]->set_figure(figures.back());
// король белый
figures.push_back(new King(0, 4, 0));
cells[0][4]->set_figure(figures.back());
// король чёрный
figures.push_back(new King(1, 4, 7));
cells[7][4]->set_figure(figures.back());
}
|
// ИК-приемник подключить к Digital Pin-02 на MEGA или Duemilanove
// Кнопку начала сканирования подключить между землей и Digital Pin-04
// Arduino Mega
#if defined(__AVR_ATmega2560__)
#define IRpin_PIN PINE
#define IRpin 4
// Arduino Duemilanove
#else
#define IRpin_PIN PIND
#define IRpin 4
#endif
#define MAXPULSE 65000
#define RESOLUTION 20 // Timing resolution
int buttonPin = 4;
int buttonState = 0;
uint16_t pulses[200][2]; // 100 pairs standart
uint8_t currentpulse = 0;
uint8_t sendpulse = 0;
void setup(void){
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
Serial.begin(9600);
Serial.println("\nPress Receive key...");
};
void loop(void){
buttonState = digitalRead(buttonPin);
uint16_t highpulse, lowpulse;
highpulse = lowpulse = 0;
while (IRpin_PIN & (1 << IRpin))
{
highpulse++;
delayMicroseconds(RESOLUTION);
if ((highpulse >= MAXPULSE) && (currentpulse != 0))
{
printpulses();
sendpulse=currentpulse;
currentpulse=0;
return;
}
}
pulses[currentpulse][0] = highpulse;
while (! (IRpin_PIN & _BV(IRpin)))
{
// pin is still LOW
lowpulse++;
delayMicroseconds(RESOLUTION);
if ((lowpulse >= MAXPULSE) && (currentpulse != 0))
{
printpulses();
sendpulse=currentpulse;
currentpulse=0;
return;
}
}
pulses[currentpulse][1] = lowpulse;
currentpulse++;
};
void printpulses(void){
Serial.println("\nReceived:");
Serial.print("\nunsigned int IRsignal[");
Serial.print(currentpulse*2-1);
Serial.print("] = {");
for (uint8_t i = 0; i < currentpulse-1; i++)
{
Serial.print(pulses[i][1] * RESOLUTION, DEC);
Serial.print(", ");
Serial.print(pulses[i+1][0] * RESOLUTION, DEC);
Serial.print(", ");
}
Serial.print(pulses[currentpulse-1][1] * RESOLUTION, DEC);
Serial.print("};");
Serial.println("");
};
|
#include <iostream>
class Vector {
private:
int erk;
int* arr;
int tamp ;
int count = 0;
int i = 0;
int* newArr(int size, int& er) {
int* array;
if(size == 1) {
array = new int [er * 2];
for(int j = 0; j < i; ++j) {
array[j] = arr[j];
}
for(int j = i; j < i * 2; ++j) {
array[j] = tamp;
}
er = 2 * er;
} else {
array = new int [er - 1];
for(int j = 0; j < er - 1; ++j) {
array[j] = arr[j];
}
er = er - 1;
}
delete []arr;
return array;
}
public:
Vector() {
erk = 10;
tamp = 0;
for(int j = 0; j < erk; ++j) {
arr[i] = tamp;
}
}
Vector(int n, int a) {
arr = new int [n];
for(int j = 0; j < n; ++j) {
arr[j] = a;
}
erk = n;
tamp = a;
}
Vector(const Vector& obj) {
erk = obj.erk;
i = obj.i;
arr = obj.arr;
for(int j = 0; j < erk; ++j) {
arr[j] = obj.arr[j];
}
}
Vector(Vector&& obj) {
erk = obj.erk;
i = obj.i;
arr = obj.arr;
obj.arr = nullptr;
}
~Vector() {
delete []arr;
arr = nullptr;
}
int push(int num) {
if(i < erk) {
arr[i] = num;
} else {
arr = newArr(1, erk);
arr[i] = num;
}
++i;
}
void pop() {
--i;
arr[i] = tamp;
arr = newArr(0, erk);
}
int get(int index) {
return arr[index];
}
void print() {
for(int j = 0; j < erk; ++j) {
std :: cout << arr[j] << " ";
}
}
};
int main() {
int size, num;
std :: cin >> size >> num;
Vector v(size ,num);
int tiv = 0;
do {
std :: cout << "durs galu hamar nermuceq 2018" << std :: endl;
std :: cin >> tiv;
v.push(tiv);
} while (tiv != 2018);
v.print();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 2010-2011
*
* WebGL compiler -- compilation context.
*
*/
#include "core/pch.h"
#ifdef CANVAS3D_SUPPORT
#include "modules/webgl/src/wgl_context.h"
#include "modules/webgl/src/wgl_symbol.h"
#include "modules/webgl/src/wgl_string.h"
#include "modules/webgl/src/wgl_intrinsics.h"
#include "modules/webgl/src/wgl_lexer.h"
#ifndef WGL_STANDALONE
#include "modules/libcrypto/include/CryptoHash.h"
#endif // !WGL_STANDALONE
/* static */ OP_STATUS
WGL_Context::Make(WGL_Context *&new_context, OpMemGroup *region, BOOL support_oes_extension)
{
new_context = OP_NEWGRO(WGL_Context, (region), region);
if (!new_context)
return OpStatus::ERR_NO_MEMORY;
new_context->strings_table = WGL_Identifier_List::Make(new_context, 4);
if (!new_context->strings_table)
return OpStatus::ERR_NO_MEMORY;
new_context->unique_table = WGL_Identifier_List::Make(new_context, 4);
if (!new_context->unique_table)
return OpStatus::ERR_NO_MEMORY;
new_context->extensions_supported = support_oes_extension ? WGL_GLSLBuiltins::Extension_OES_standard_derivatives : 0;
unsigned count = 0;
unsigned s = new_context->extensions_supported;
while (s)
{
if ((s & 0x1) != 0)
count++;
s = s >> 1;
}
new_context->extensions_supported_count = count;
return OpStatus::OK;
}
void
WGL_Context::SetSourceContextL(const char *s)
{
if (s)
{
int val_len = static_cast<int>(op_strlen(s));
int str_len = val_len + 1;
file_name = OP_NEWGROA_L(uni_char, str_len, Arena());
uni_char *str = const_cast<uni_char *>(file_name);
make_doublebyte_in_buffer(s, val_len, str, str_len);
}
else
file_name = NULL;
}
BOOL
WGL_Context::IsTypeName(WGL_String *s)
{
unsigned position;
return types_table->IndexOf(s, position);
}
WGL_Type *
WGL_ValidationState::LookupTypeName(WGL_VarName *name)
{
List<WGL_Type> *existing_type;
if (OpStatus::IsSuccess(types_map.GetData(name, &existing_type)) && existing_type && existing_type->Cardinal() > 0)
return existing_type->First();
else
return NULL;
}
WGL_Type *
WGL_ValidationState::LookupVarType(WGL_String *i, WGL_VarName **alias_var, BOOL current_scope_only, BOOL deref_name)
{
for (WGL_BindingScope<WGL_VarAlias> *scope = alias_scope.First(); scope; scope = scope->Suc())
{
if (scope->list)
for (WGL_VarAlias *v = scope->list->First(); v; v = v->Suc())
if (i->Equals(v->var1))
{
if (alias_var)
*alias_var = v->var2;
i = v->var2;
break;
}
if (current_scope_only)
break;
}
WGL_Type *var_type = NULL;
for (WGL_BindingScope<WGL_VarBinding> *scope = variable_environment.First(); scope; scope = scope->Suc())
{
for (WGL_VarBinding *v = scope->list->First(); v; v = v->Suc())
if (i->Equals(v->var))
{
var_type = v->type;
break;
}
if (current_scope_only)
return var_type;
}
if (!var_type)
{
for (WGL_VarBinding *v = global_scope.First(); v; v = v->Suc())
if (i->Equals(v->var))
{
var_type = v->type;
break;
}
}
if (!var_type)
{
List<WGL_Builtin> *list = LookupBuiltin(i);
if (list && list->First() && list->First()->IsBuiltinVar())
return FromBuiltinType(&static_cast<WGL_BuiltinVar *>(list->First())->type);
}
else if (deref_name && var_type->GetType() == WGL_Type::Name)
{
/* The identifier is a struct name, which we resolve to the struct type */
return LookupTypeName(static_cast<WGL_NameType *>(var_type)->name);
}
return var_type;
}
WGL_VarBinding *
WGL_ValidationState::LookupVarBinding(WGL_String *i)
{
for (WGL_BindingScope<WGL_VarBinding> *scope = variable_environment.First(); scope; scope = scope->Suc())
{
for (WGL_VarBinding *v = scope->list->First(); v; v = v->Suc())
if (i->Equals(v->var))
return v;
}
for (WGL_BindingScope<WGL_VarAlias> *scope = alias_scope.First(); scope; scope = scope->Suc())
{
for (WGL_VarAlias *v = scope->list ? scope->list->First() : NULL; v; v = v->Suc())
if (i->Equals(v->var1))
return LookupVarBinding(v->var2);
}
for (WGL_VarBinding *v = global_scope.First(); v; v = v->Suc())
if (i->Equals(v->var))
return v;
return NULL;
}
WGL_Type *
WGL_ValidationState::LookupLocalVar(WGL_String *i, BOOL current_scope_only)
{
for (WGL_BindingScope<WGL_VarBinding> *scope = variable_environment.First(); scope; scope = scope->Suc())
{
for (WGL_VarBinding *v = scope->list->First(); v; v = v->Suc())
if (i->Equals(v->var))
return v->type;
if (current_scope_only)
break;
}
for (WGL_BindingScope<WGL_VarAlias> *scope = alias_scope.First(); scope; scope = scope->Suc())
{
for (WGL_VarAlias *v = scope->list ? scope->list->First() : NULL; v; v = v->Suc())
if (i->Equals(v->var1))
return LookupLocalVar(v->var2, current_scope_only);
if (current_scope_only)
break;
}
return NULL;
}
WGL_Type *
WGL_ValidationState::LookupGlobal(WGL_String *i)
{
for (WGL_VarBinding *v = global_scope.First(); v; v = v->Suc())
if (i->Equals(v->var))
return v->type;
return NULL;
}
WGL_VaryingOrUniform *
WGL_ValidationState::LookupUniform(WGL_String *i, BOOL record_use)
{
for (WGL_VaryingOrUniform *u = uniforms.First(); u; u = u->Suc())
if (i->Equals(u->var))
{
if (record_use)
u->usages++;
return u;
}
return NULL;
}
WGL_VaryingOrUniform *
WGL_ValidationState::LookupVarying(WGL_String *i, BOOL record_use)
{
for (WGL_VaryingOrUniform *u = varyings.First(); u; u = u->Suc())
if (i->Equals(u->var))
{
if (record_use)
u->usages++;
return u;
}
return NULL;
}
WGL_Attribute *
WGL_ValidationState::LookupAttribute(WGL_String *i, BOOL record_use)
{
for (WGL_Attribute *attr = attributes.First(); attr; attr = attr->Suc())
if (i->Equals(attr->var))
{
if (record_use)
attr->usages++;
return attr;
}
return NULL;
}
WGL_FunctionData *
WGL_ValidationState::LookupFunction(WGL_String *i)
{
for (WGL_FunctionData *f = function_scope.First(); f; f = f->Suc())
if (i->Equals(f->name))
return f;
return NULL;
}
List<WGL_Builtin> *
WGL_ValidationState::LookupBuiltin(WGL_String *i)
{
List<WGL_Builtin> *list;
if (OpStatus::IsSuccess(builtins_map.GetData(i, &list)))
return list;
else
return NULL;
}
WGL_Field *
WGL_ValidationState::LookupField(WGL_FieldList *field_list, WGL_String *i)
{
for (WGL_Field *f = field_list ? field_list->list.First() : NULL; f; f = f->Suc())
if (i->Equals(f->name))
return f;
return NULL;
}
BOOL
WGL_VariableUse::IsIn(List<WGL_VariableUse> &list, WGL_VarName *g)
{
for (WGL_VariableUse *f = list.First(); f; f = f->Suc())
if (f->var->Equals(g))
return TRUE;
return FALSE;
}
void
WGL_ValidationState::AddFunctionCall(WGL_VarName *f)
{
if (current_function)
{
if (!current_callers)
current_callers = OP_NEWGRO_L(List<WGL_VariableUse>, (), context->Arena());
if (!WGL_VariableUse::IsIn(*current_callers, f))
{
WGL_VariableUse *f_use = OP_NEWGRO_L(WGL_VariableUse, (f), context->Arena());
f_use->Into(current_callers);
}
}
}
BOOL
WGL_Context::IsUnique(WGL_String *s)
{
unsigned index;
return unique_table->IndexOf(s, index);
}
WGL_Context::~WGL_Context()
{
}
void
WGL_Context::Release()
{
file_name = NULL;
validation_state.Release();
}
void
WGL_Context::ResetLocalsL()
{
GetValidationState().precision_environment.RemoveAll();
GetValidationState().variable_environment.RemoveAll();
GetValidationState().alias_scope.RemoveAll();
}
void
WGL_Context::ResetL(BOOL for_vertex)
{
errors.RemoveAll();
ResetLocalsL();
ResetGlobalsL();
line_number = 1;
if (for_vertex != !processing_fragment)
{
processing_fragment = !for_vertex;
extensions_enabled = 0;
}
}
void
WGL_Context::ResetGlobalsL()
{
/* No need to delete; assumed to be an arena allocated list.
The string & unique tables are separately allocated and freed. */
/* Create, and leave be across resets. */
if (!strings_table)
LEAVE_IF_NULL(strings_table = WGL_Identifier_List::Make(this, 4));
LEAVE_IF_NULL(types_table = WGL_Identifier_List::Make(this, 4));
GetValidationState().ResetL();
}
void
WGL_Context::EnterLocalScope(WGL_Type *return_type)
{
GetValidationState().EnterScope(return_type);
}
void
WGL_Context::LeaveLocalScope()
{
GetValidationState().LeaveScope();
}
BOOL
WGL_Context::IsVectorType(unsigned i)
{
return (i <= WGL_Lexer::TYPE_UVEC4);
}
/* static */ WGL_VectorType::Type
WGL_Context::ToVectorType(unsigned i)
{
return static_cast<WGL_VectorType::Type>(1 + (i - WGL_Lexer::TYPE_VEC2));
}
/* static */ BOOL
WGL_Context::IsMatrixType(unsigned i)
{
return (i >= WGL_Lexer::TYPE_MAT2 && i <= WGL_Lexer::TYPE_MAT4X4);
}
/* static */ WGL_MatrixType::Type
WGL_Context::ToMatrixType(unsigned i)
{
return static_cast<WGL_MatrixType::Type>(1 + (i - WGL_Lexer::TYPE_MAT2));
}
/* static */ BOOL
WGL_Context::IsSamplerType(unsigned i)
{
return (i >= WGL_Lexer::TYPE_SAMPLER1D && i <= WGL_Lexer::TYPE_USAMPLER2DMSARRAY);
}
/* static */ WGL_SamplerType::Type
WGL_Context::ToSamplerType(unsigned i)
{
return static_cast<WGL_SamplerType::Type>(1 + (i - WGL_Lexer::TYPE_SAMPLER1D));
}
BOOL
WGL_Context::IsSupportedExtension(const uni_char *extension, unsigned extension_length)
{
for (unsigned i = 0; i < WGL_GLSLBuiltins::extension_info_elements; i++)
if ((WGL_GLSLBuiltins::extension_info[i].id & extensions_supported) != 0)
if (processing_fragment && WGL_GLSLBuiltins::extension_info[i].fragment_name && uni_strncmp(WGL_GLSLBuiltins::extension_info[i].fragment_name, extension, extension_length) == 0 ||
!processing_fragment && WGL_GLSLBuiltins::extension_info[i].vertex_name && uni_strncmp(WGL_GLSLBuiltins::extension_info[i].vertex_name, extension, extension_length) == 0)
return TRUE;
return FALSE;
}
BOOL
WGL_Context::IsEnabledExtension(unsigned idx, WGL_GLSLBuiltins::FunctionInfo **functions, unsigned *functions_count)
{
OP_ASSERT(idx < 8 * sizeof(unsigned));
unsigned mask = 0x1 << idx;
if ((extensions_enabled & mask) != 0)
{
if (functions)
{
*functions = processing_fragment ? WGL_GLSLBuiltins::extension_info[idx].fragment_functions : WGL_GLSLBuiltins::extension_info[idx].vertex_functions;
*functions_count = processing_fragment ? WGL_GLSLBuiltins::extension_info[idx].fragment_functions_count : WGL_GLSLBuiltins::extension_info[idx].vertex_functions_count;
}
return TRUE;
}
else
return FALSE;
}
unsigned
WGL_Context::GetExtensionCount()
{
return extensions_supported_count;
}
BOOL
WGL_Context::EnableExtension(unsigned idx, const uni_char **cpp_define)
{
OP_ASSERT(idx < 8 * sizeof(unsigned));
if ((extensions_supported & (0x1 << idx)) != 0)
{
if ((extensions_enabled & (0x1 << idx)) != 0)
return FALSE;
else if (processing_fragment && WGL_GLSLBuiltins::extension_info[idx].fragment_name ||
!processing_fragment && WGL_GLSLBuiltins::extension_info[idx].vertex_name)
{
extensions_enabled |= (0x1 << idx);
if (cpp_define)
*cpp_define = WGL_GLSLBuiltins::extension_info[idx].cpp_enabled_define;
return TRUE;
}
else
return FALSE;
}
else
return FALSE;
}
BOOL
WGL_Context::EnableExtension(const uni_char *extension, unsigned extension_length, const uni_char **cpp_define)
{
for (unsigned i = 0; WGL_GLSLBuiltins::extension_info_elements; i++)
if (processing_fragment && WGL_GLSLBuiltins::extension_info[i].fragment_name && uni_strncmp(WGL_GLSLBuiltins::extension_info[i].fragment_name, extension, extension_length) == 0 ||
!processing_fragment && WGL_GLSLBuiltins::extension_info[i].vertex_name && uni_strncmp(WGL_GLSLBuiltins::extension_info[i].vertex_name, extension, extension_length) == 0)
{
if ((extensions_enabled & WGL_GLSLBuiltins::extension_info[i].id) != 0)
return FALSE;
else
{
extensions_enabled |= WGL_GLSLBuiltins::extension_info[i].id;
if (cpp_define)
*cpp_define = WGL_GLSLBuiltins::extension_info[i].cpp_enabled_define;
return TRUE;
}
}
return FALSE;
}
BOOL
WGL_Context::DisableExtension(unsigned idx, const uni_char **cpp_define)
{
OP_ASSERT(idx < 8 * sizeof(unsigned));
if ((extensions_supported & (0x1 << idx)) != 0)
{
if ((extensions_enabled & (0x1 << idx)) == 0)
return FALSE;
else if (processing_fragment && WGL_GLSLBuiltins::extension_info[idx].fragment_name ||
!processing_fragment && WGL_GLSLBuiltins::extension_info[idx].vertex_name)
{
extensions_enabled &= ~(0x1 << idx);
if (cpp_define)
*cpp_define = WGL_GLSLBuiltins::extension_info[idx].cpp_enabled_define;
return TRUE;
}
else
return FALSE;
}
else
return FALSE;
}
BOOL
WGL_Context::DisableExtension(const uni_char *extension, unsigned extension_length, const uni_char **cpp_define)
{
for (unsigned i = 0; WGL_GLSLBuiltins::extension_info_elements; i++)
if (processing_fragment && WGL_GLSLBuiltins::extension_info[i].fragment_name && uni_strncmp(WGL_GLSLBuiltins::extension_info[i].fragment_name, extension, extension_length) == 0 ||
!processing_fragment && WGL_GLSLBuiltins::extension_info[i].vertex_name && uni_strncmp(WGL_GLSLBuiltins::extension_info[i].vertex_name, extension, extension_length) == 0)
{
if ((extensions_enabled & WGL_GLSLBuiltins::extension_info[i].id) == 0)
return FALSE;
else
{
extensions_enabled &= ~(WGL_GLSLBuiltins::extension_info[i].id);
if (cpp_define)
*cpp_define = WGL_GLSLBuiltins::extension_info[i].cpp_enabled_define;
return TRUE;
}
}
return FALSE;
}
BOOL
WGL_Context::GetExtensionIndex(unsigned idx, WGL_GLSLBuiltins::Extension &id)
{
if (idx >= GetExtensionCount())
return FALSE;
unsigned flag = 1;
while (idx > 0)
{
flag = flag << 1;
idx--;
}
id = static_cast<WGL_GLSLBuiltins::Extension>(flag);
return TRUE;
}
BOOL
WGL_Context::GetExtensionInfo(WGL_GLSLBuiltins::Extension id, const uni_char **vertex_name, const uni_char **fragment_name, const uni_char **supported_define)
{
for (unsigned i = 0; i < WGL_GLSLBuiltins::extension_info_elements; i++)
{
if (id == WGL_GLSLBuiltins::extension_info[i].id)
{
if (vertex_name)
*vertex_name = WGL_GLSLBuiltins::extension_info[i].vertex_name;
if (fragment_name)
*fragment_name = WGL_GLSLBuiltins::extension_info[i].fragment_name;
if (supported_define)
*supported_define = WGL_GLSLBuiltins::extension_info[i].cpp_supported_define;
return TRUE;
}
}
return FALSE;
}
BOOL
WGL_Context::IsExtensionEnabled(unsigned int i, BOOL fragment, const uni_char *&define)
{
OP_ASSERT(i < GetExtensionCount());
if (extensions_enabled & (1 << i))
if (fragment && WGL_GLSLBuiltins::extension_info[i].fragment_name || !fragment && WGL_GLSLBuiltins::extension_info[i].vertex_name)
{
define = WGL_GLSLBuiltins::extension_info[i].cpp_supported_define;
return TRUE;
}
return FALSE;
}
void
WGL_Context::AddError(WGL_Error::Type t, const uni_char *msg)
{
WGL_Error *item = OP_NEWGRO_L(WGL_Error, (this, t, GetSourceContext(), line_number), Arena());
item->SetMessageL(msg);
AddError(item);
}
WGL_Type *
WGL_Context::NewTypeName(uni_char const *name)
{
WGL_String *str = WGL_String::Make(this, name);
WGL_NameType *name_type = OP_NEWGRO_L(WGL_NameType, (str, FALSE), Arena());
unsigned position;
types_table->AppendL(this, str, position);
return name_type;
}
WGL_Type *
WGL_Context::NewTypeName(WGL_String *str)
{
WGL_NameType *name_type = OP_NEWGRO_L(WGL_NameType, (str, FALSE), Arena());
unsigned position;
types_table->AppendL(this, str, position);
return name_type;
}
WGL_Literal *
WGL_Context::BuildLiteral(WGL_Literal::Type t)
{
return OP_NEWGRO_L(WGL_Literal, (t), Arena());
}
OP_STATUS
WGL_Context::RecordResult(BOOL for_vertex_shader, WGL_ShaderVariables *result)
{
TRAPD(status, RecordResultL(for_vertex_shader, result));
if (OpStatus::IsError(status))
result->Release();
return status;
}
/* private */ void
WGL_Context::RecordResultL(BOOL for_vertex_shader, WGL_ShaderVariables *result)
{
for (WGL_VaryingOrUniform *uni = validation_state.uniforms.First(); uni; uni = uni->Suc())
{
/* Declared uniforms must be 'statically used'; otherwise declarations are ignored. */
if (uni->usages == 0)
continue;
uni_char *name = OP_NEWA_L(uni_char, WGL_String::Length(uni->var) + 1);
uni_strcpy(name, Storage(this, uni->var));
ANCHOR_ARRAY(uni_char, name);
WGL_Type *type = WGL_Type::CopyL(uni->type);
OpStackAutoPtr<WGL_Type> anchor_type(type);
WGL_ShaderVariable *var = OP_NEW_L(WGL_ShaderVariable, (WGL_ShaderVariable::Uniform, name, uni->precision, type, TRUE));
ANCHOR_ARRAY_RELEASE(name);
anchor_type.release();
OpStackAutoPtr<WGL_ShaderVariable> anchor_var(var);
if (WGL_VarName *alias = FindAlias(name))
var->SetAliasL(Storage(this, alias), TRUE);
anchor_var.release();
result->AddUniform(var);
}
for (WGL_VaryingOrUniform *varying = validation_state.varyings.First(); varying; varying = varying->Suc())
{
/* When outputting to GLSL, declared varying variables without any uses
in the fragment shader are ignored. We can't do this when outputting
to HLSL as shader signatures need to match up (CT-2182). */
if (WGL_Validator::IsGL(configuration->output_format) && !for_vertex_shader && varying->usages == 0)
continue;
uni_char *name = OP_NEWA_L(uni_char, WGL_String::Length(varying->var) + 1);
uni_strcpy(name, Storage(this, varying->var));
ANCHOR_ARRAY(uni_char, name);
WGL_Type *type = WGL_Type::CopyL(varying->type);
OpStackAutoPtr<WGL_Type> anchor_type(type);
WGL_ShaderVariable *var = OP_NEW_L(WGL_ShaderVariable, (WGL_ShaderVariable::Varying, name, varying->precision, type, TRUE));
ANCHOR_ARRAY_RELEASE(name);
anchor_type.release();
OpStackAutoPtr<WGL_ShaderVariable> anchor_var(var);
if (WGL_VarName *alias = FindAlias(name))
var->SetAliasL(Storage(this, alias), TRUE);
anchor_var.release();
result->AddVarying(var);
}
for (WGL_Attribute *attr = validation_state.attributes.First(); attr; attr = attr->Suc())
{
if (attr->usages == 0)
continue;
uni_char *name = OP_NEWA_L(uni_char, WGL_String::Length(attr->var) + 1);
uni_strcpy(name, Storage(this, attr->var));
ANCHOR_ARRAY(uni_char, name);
WGL_Type *type = WGL_Type::CopyL(attr->type);
OpStackAutoPtr<WGL_Type> anchor_type(type);
WGL_ShaderVariable *var = OP_NEW_L(WGL_ShaderVariable, (WGL_ShaderVariable::Attribute, name, WGL_Type::NoPrecision, type, TRUE));
ANCHOR_ARRAY_RELEASE(name);
anchor_type.release();
OpStackAutoPtr<WGL_ShaderVariable> anchor_var(var);
if (WGL_VarName *alias = FindAlias(name))
var->SetAliasL(Storage(this, alias), TRUE);
anchor_var.release();
result->AddAttribute(var);
}
}
/* WGL_ValidationState */
void
WGL_ValidationState::Release()
{
builtins_map.RemoveAll();
types_map.RemoveAll();
}
void
WGL_ValidationState::ResetL()
{
attributes.RemoveAll();
uniforms.RemoveAll();
varyings.RemoveAll();
global_scope.RemoveAll();
function_scope.RemoveAll();
variable_environment.RemoveAll();
precision_environment.RemoveAll();
alias_scope.RemoveAll();
scope_level = 0;
WGL_BindingScope<WGL_Precision> *new_scope = OP_NEWGRO_L(WGL_BindingScope<WGL_Precision>, (), context->Arena());
List<WGL_Precision> *list = OP_NEWGRO_L(List<WGL_Precision>, (), context->Arena());
new_scope->list = list;
new_scope->IntoStart(&precision_environment);
WGL_BindingScope<WGL_VarAlias> *new_alias = OP_NEWGRO_L(WGL_BindingScope<WGL_VarAlias>, (), context->Arena());
new_alias->IntoStart(&alias_scope);
}
void
WGL_ValidationState::EnterScope(WGL_Type *return_type)
{
WGL_BindingScope<WGL_Precision> *new_scope = OP_NEWGRO_L(WGL_BindingScope<WGL_Precision>, (), context->Arena());
List<WGL_Precision> *list = OP_NEWGRO_L(List<WGL_Precision>, (), context->Arena());
new_scope->list = list;
new_scope->IntoStart(&precision_environment);
WGL_BindingScope<WGL_VarBinding> *new_var_scope = OP_NEWGRO_L(WGL_BindingScope<WGL_VarBinding>, (), context->Arena());
List<WGL_VarBinding> *bind_list = OP_NEWGRO_L(List<WGL_VarBinding>, (), context->Arena());
new_var_scope->list = bind_list;
new_var_scope->IntoStart(&variable_environment);
WGL_BindingScope<WGL_VarAlias> *new_alias_scope = OP_NEWGRO_L(WGL_BindingScope<WGL_VarAlias>, (), context->Arena());
new_alias_scope->IntoStart(&alias_scope);
scope_level++;
OP_ASSERT(!return_type || scope_level == 1);
}
void
WGL_ValidationState::LeaveScope()
{
WGL_BindingScope<WGL_Precision> *prec_scope = precision_environment.First();
prec_scope->Out();
WGL_BindingScope<WGL_VarBinding> *var_scope = variable_environment.First();
var_scope->Out();
WGL_BindingScope<WGL_VarAlias> *ali_scope = alias_scope.First();
ali_scope->Out();
scope_level--;
}
void
WGL_ValidationState::AddAttribute(WGL_Type *t, WGL_VarName *i, unsigned l)
{
WGL_SourceLoc loc(context->GetSourceContext(), l);
WGL_Attribute *attr = OP_NEWGRO_L(WGL_Attribute, (loc), context->Arena());
if (t && t->GetType() == WGL_Type::Name)
t = LookupTypeName(static_cast<WGL_NameType *>(t)->name);
attr->type = t;
attr->var = i;
attr->Into(&attributes);
}
void
WGL_ValidationState::AddUniform(WGL_Type *t, WGL_VarName *v, WGL_Type::Precision p, unsigned line_number)
{
WGL_SourceLoc loc(context->GetSourceContext(), line_number);
WGL_VaryingOrUniform *unif = OP_NEWGRO_L(WGL_VaryingOrUniform, (t, v, p, loc), context->Arena());
if (t && t->GetType() == WGL_Type::Name)
t = LookupTypeName(static_cast<WGL_NameType *>(t)->name);
unif->type = t;
unif->Into(&uniforms);
}
void
WGL_ValidationState::AddVarying(WGL_Type *t, WGL_VarName *v, WGL_Type::Precision p, unsigned line_number)
{
WGL_SourceLoc loc(context->GetSourceContext(), line_number);
WGL_VaryingOrUniform *unif = OP_NEWGRO_L(WGL_VaryingOrUniform, (t, v, p, loc), context->Arena());
if (t && t->GetType() == WGL_Type::Name)
t = LookupTypeName(static_cast<WGL_NameType *>(t)->name);
unif->type = t;
unif->Into(&varyings);
}
void
WGL_ValidationState::AddPrecision(WGL_Type *t, WGL_Type::Precision p)
{
WGL_BindingScope<WGL_Precision> *current_scope = precision_environment.First();
WGL_Precision *prec = OP_NEWGRO_L(WGL_Precision, (t, p), context->Arena());
prec->IntoStart(current_scope->list);
}
WGL_VarBinding *
WGL_ValidationState::AddVariable(WGL_Type *t, WGL_VarName *v, BOOL is_read_only)
{
WGL_VarBinding *binding = OP_NEWGRO_L(WGL_VarBinding, (t, v, is_read_only), context->Arena());
WGL_BindingScope<WGL_VarBinding> *current_scope = variable_environment.First();
if (current_scope)
binding->IntoStart(current_scope->list);
else
binding->IntoStart(&global_scope);
return binding;
}
WGL_VarName *
WGL_Context::NewUniqueVar(BOOL record_name)
{
uni_char unique_name[100]; // ARRAY OK 2011-02-09 sof
uni_snprintf(unique_name, ARRAY_SIZE(unique_name), UNI_L("%s_%u"), WGL_UNIQUE_VAR_PREFIX, id_unique++);
WGL_VarName *name = WGL_String::Make(this, unique_name);
unsigned dummy;
if (record_name)
GetUniques()->AppendL(this, name, dummy);
return name;
}
WGL_VarName *
WGL_Context::NewUniqueHashVar(WGL_String *existing)
{
uni_char unique_name[128]; // ARRAY OK 2011-10-22 sof
/* Use the hash as the unique; the risk of SHA2 collisions
is slight. Only intended used with longer existing identifiers,
where the same unique value (across shaders) must be computed/used. */
#ifndef WGL_STANDALONE
OpString8 hash_string;
hash_string.SetUTF8FromUTF16L(Storage(this, existing));
CryptoHash *hasher = CryptoHash::Create(CRYPTO_HASH_TYPE_SHA256);
LEAVE_IF_NULL(hasher);
OpStackAutoPtr<CryptoHash> anchor_hasher(hasher);
LEAVE_IF_ERROR(hasher->InitHash());
hasher->CalculateHash(hash_string.CStr());
unsigned char result[32]; // ARRAY OK 2011-10-26 sof
OP_ASSERT(ARRAY_SIZE(result) == hasher->Size());
hasher->ExtractHash(result);
uni_char result_digits[65]; // ARRAY OK 2011-10-26 sof
const uni_char *hex = UNI_L("0123456789abcdef");
for (unsigned i = 0; i < ARRAY_SIZE(result); i++)
{
result_digits[2 * i + 1] = hex[result[i] & 0x0f];
result_digits[2 * i] = hex[(result[i] & 0xf0) >> 4];
}
result_digits[ARRAY_SIZE(result_digits) - 1] = 0;
uni_snprintf(unique_name, ARRAY_SIZE(unique_name), UNI_L("%s_h%s"), WGL_UNIQUE_VAR_PREFIX, result_digits);
#else
/* Simpler hashing in standalone. */
unsigned hash = existing->CalculateHash();
uni_snprintf(unique_name, ARRAY_SIZE(unique_name), UNI_L("%s_h%u"), WGL_UNIQUE_VAR_PREFIX, hash);
#endif // !WGL_STANDALONE
/* If collisions should occur; append a unique sequence number. */
unsigned i = 0;
while (FindAlias(unique_name))
#ifndef WGL_STANDALONE
uni_snprintf(unique_name, ARRAY_SIZE(unique_name), UNI_L("%s_h%s_%u"), WGL_UNIQUE_VAR_PREFIX, result_digits, i++);
#else
uni_snprintf(unique_name, ARRAY_SIZE(unique_name), UNI_L("%s_h%u_%u"), WGL_UNIQUE_VAR_PREFIX, hash, i++);
#endif // !WGL_STANDALONE
return WGL_String::Make(this, unique_name);
}
WGL_VarName *
WGL_Context::FindAlias(WGL_VarName *name)
{
for (WGL_BindingScope<WGL_VarAlias> *scope = GetValidationState().alias_scope.First(); scope; scope = scope->Suc())
for (WGL_VarAlias *alias = scope->list ? scope->list->First() : NULL; alias; alias = alias->Suc())
if (name->Equals(alias->var2))
return alias->var1;
return NULL;
}
WGL_VarName *
WGL_Context::FindAlias(const uni_char *name)
{
for (WGL_BindingScope<WGL_VarAlias> *scope = GetValidationState().alias_scope.First(); scope; scope = scope->Suc())
for (WGL_VarAlias *alias = scope->list ? scope->list->First() : NULL; alias; alias = alias->Suc())
if (alias->var2->Equals(name))
return alias->var1;
return NULL;
}
void
WGL_ValidationState::AddAlias(WGL_VarName *old_name, WGL_VarName *new_name)
{
WGL_VarAlias *var_alias = OP_NEWGRO_L(WGL_VarAlias, (old_name, new_name), context->Arena());
WGL_BindingScope<WGL_VarAlias> *current_scope = alias_scope.First();
if (current_scope)
{
if (!current_scope->list)
{
List<WGL_VarAlias> *new_list = OP_NEWGRO_L(List<WGL_VarAlias>, (), context->Arena());
current_scope->list = new_list;
}
var_alias->IntoStart(current_scope->list);
}
}
WGL_String*
WGL_ValidationState::AddStructType(WGL_String *str, WGL_Type *type)
{
OP_ASSERT(type && type->GetType() == WGL_Type::Struct);
List<WGL_Type> *existing_type;
if (OpStatus::IsSuccess(types_map.GetData(str, &existing_type)))
{
WGL_Error *error = OP_NEWGRO_L(WGL_Error, (context, WGL_Error::DUPLICATE_NAME, context->GetSourceContext(), 0), context->Arena());
error->SetMessageL(Storage(context, str));
context->AddError(error);
}
else
{
List<WGL_Type> *new_list = OP_NEWGRO_L(List<WGL_Type>, (), context->Arena());
type->Into(new_list);
types_map.Add(str, new_list);
}
return str;
}
void
WGL_ValidationState::AddFunction(WGL_VarName *fun_name, WGL_Type *return_type, WGL_ParamList *params, BOOL is_proto, WGL_SourceLoc &loc)
{
WGL_FunctionDecl *fun_decl = OP_NEWGRO_L(WGL_FunctionDecl, (loc, return_type, params, is_proto), context->Arena());
WGL_FunctionData *fun = function_scope.First();
for (; fun; fun = fun->Suc())
{
if (fun->name->Equals(fun_name))
{
BOOL is_duplicate = TRUE;
WGL_FunctionDecl *overlap = NULL;
if (IsOverlappingOverload(params, return_type, is_proto, overlap, is_duplicate, fun->decls))
{
WGL_Error::Type err = is_duplicate ? WGL_Error::ILLEGAL_FUNCTION_OVERLOAD_DUPLICATE : WGL_Error::ILLEGAL_FUNCTION_OVERLOAD_MISMATCH;
context->AddError(err, Storage(context, fun_name));
}
else if (ConflictsWithBuiltin(fun_name, params, return_type))
context->AddError(WGL_Error::ILLEGAL_FUNCTION_OVERLOAD_BUILTIN_OVERLAP, Storage(context, fun_name));
else
fun_decl->Into(&fun->decls);
return;
}
}
fun = OP_NEWGRO_L(WGL_FunctionData, (fun_name), context->Arena());
fun_decl->Into(&fun->decls);
fun->Into(&function_scope);
}
WGL_Type::Precision
WGL_ValidationState::LookupPrecision(WGL_Type *t)
{
WGL_BindingScope<WGL_Precision> *prec_scope = precision_environment.First();
while (prec_scope)
{
for (WGL_Precision *binding = prec_scope->list ? prec_scope->list->First() : NULL; binding; binding = binding->Suc())
if (IsSameType(t, binding->type, TRUE))
return binding->precision;
prec_scope = prec_scope->Suc();
}
return WGL_Type::NoPrecision;
}
BOOL
WGL_ValidationState::IsOverlappingOverload(WGL_ParamList *params, WGL_Type *return_type, BOOL is_proto, WGL_FunctionDecl *&overlap, BOOL &duplicate, List<WGL_FunctionDecl> &existing)
{
for(WGL_FunctionDecl *f = existing.First(); f; f = f->Suc())
{
BOOL matches_params = TRUE;
if (!f->parameters || !params)
matches_params = (f->parameters == params);
else if (f->parameters->list.Cardinal() == params->list.Cardinal())
{
WGL_Param *p1 = params->list.First();
for (WGL_Param *p2 = f->parameters->list.First(); p2; p1 = p1->Suc(), p2 = p2->Suc())
if (!IsSameType(p1->type, p2->type, TRUE))
{
matches_params = FALSE;
break;
}
}
else
continue;
if (matches_params)
{
BOOL is_same = IsSameType(return_type, f->return_type, TRUE);
if (!is_same || f->is_proto == is_proto)
{
overlap = f;
duplicate = is_same;
return TRUE;
}
}
}
return FALSE;
}
BOOL
WGL_ValidationState::ConflictsWithBuiltin(WGL_VarName *fun_name, WGL_ParamList *params, WGL_Type *return_type)
{
List<WGL_Builtin> *builtins;
if (OpStatus::IsSuccess(builtins_map.GetData(fun_name, &builtins)))
{
for (WGL_Builtin *b = builtins->First(); b; b = b->Suc())
if (!b->IsBuiltinVar())
{
WGL_BuiltinFun *bfun = static_cast<WGL_BuiltinFun *>(b);
if (bfun->parameters.Empty() && !params || bfun->parameters.Cardinal() == params->list.Cardinal())
{
BOOL matches_builtin = TRUE;
WGL_Param *p1 = params->list.First();
for (WGL_BuiltinType *p2 = bfun->parameters.First(); p2; p1 = p1->Suc(), p2 = p2->Suc())
if (!MatchesBuiltinType(p2, p1->type))
{
matches_builtin = FALSE;
break;
}
if (matches_builtin)
return TRUE;
}
}
}
return FALSE;
}
BOOL
WGL_ValidationState::IsLegalReferenceArg(WGL_Expr *e)
{
switch(e->GetType())
{
case WGL_Expr::Var:
if (WGL_VarBinding *bind = LookupVarBinding(static_cast<WGL_VarExpr *>(e)->name))
return (!bind->is_read_only && (!bind->type->type_qualifier || !(bind->type->type_qualifier->storage == WGL_TypeQualifier::Const || bind->type->type_qualifier->storage == WGL_TypeQualifier::Uniform)));
else
return FALSE;
default:
return FALSE;
}
}
List<WGL_Builtin> *
WGL_Context::NewBuiltinVar(const uni_char *name, WGL_VectorType::Type vt, WGL_Type::Precision prec, BOOL is_read_only, BOOL for_output, BOOL for_vertex, const char *symbolic_size)
{
WGL_BuiltinVar *bv = OP_NEWGRO_L(WGL_BuiltinVar, (), Arena());
List <WGL_Builtin> *list = OP_NEWGRO_L(List<WGL_Builtin>, (), Arena());
bv->name = name;
bv->precision = prec;
bv->type.type = WGL_BuiltinType::Vector;
bv->type.value.vector_type = vt;
bv->array_size = WGL_ArraySize(symbolic_size);
bv->is_read_only = is_read_only;
bv->is_output = for_output;
bv->is_const = FALSE;
bv->const_value = -1;
bv->for_vertex = for_vertex;
bv->Into(list);
return list;
}
List<WGL_Builtin> *
WGL_Context::NewBuiltinVar(const uni_char *name, WGL_BasicType::Type t, WGL_Type::Precision prec, BOOL is_read_only, BOOL is_out, BOOL for_vertex)
{
WGL_BuiltinVar *bv = OP_NEWGRO_L(WGL_BuiltinVar, (), Arena());
List <WGL_Builtin> *list = OP_NEWGRO_L(List<WGL_Builtin>, (), Arena());
bv->name = name;
bv->precision = prec;
bv->type.type = WGL_BuiltinType::Basic;
bv->type.value.basic_type = t;
bv->is_read_only = is_read_only;
bv->is_output = is_out;
bv->is_const = FALSE;
bv->const_value = -1;
bv->for_vertex = for_vertex;
bv->Into(list);
return list;
}
List<WGL_Builtin> *
WGL_Context::NewBuiltinConstant(const uni_char *name, WGL_BasicType::Type t, WGL_Type::Precision prec, int v)
{
WGL_BuiltinVar *bv = OP_NEWGRO_L(WGL_BuiltinVar, (), Arena());
List <WGL_Builtin> *list = OP_NEWGRO_L(List<WGL_Builtin>, (), Arena());
bv->name = name;
bv->precision = prec;
bv->type.type = WGL_BuiltinType::Basic;
bv->type.value.basic_type = t;
bv->is_read_only = TRUE;
bv->is_output = FALSE;
bv->is_const = TRUE;
bv->const_value = v;
bv->for_vertex = TRUE;
bv->Into(list);
return list;
}
WGL_BuiltinType*
ToBuiltinType(WGL_Context *context, const char *ty_spec)
{
WGL_BuiltinType *ret_type = OP_NEWGRO_L(WGL_BuiltinType, (), context->Arena());
if (ty_spec[0] == 'G' && !ty_spec[1])
ret_type->type = WGL_BuiltinType::Gen;
else if (ty_spec[0] == 'V' && !ty_spec[1])
ret_type->type = WGL_BuiltinType::Vec;
else if (ty_spec[0] == 'V')
{
ret_type->type = WGL_BuiltinType::Vector;
char x = ty_spec[1];
OP_ASSERT(!ty_spec[2] && (x == '2' || x == '3' || x == '4'));
ret_type->value.vector_type = x == '2' ? WGL_VectorType::Vec2 : (x == '3' ? WGL_VectorType::Vec3 : WGL_VectorType::Vec4);
}
else if (ty_spec[0] == 'B' && !ty_spec[1])
{
ret_type->type = WGL_BuiltinType::Basic;
ret_type->value.basic_type = WGL_BasicType::Bool;
}
else if (ty_spec[0] == 'B' && ty_spec[1] == 'V')
{
ret_type->type = WGL_BuiltinType::BVec;
OP_ASSERT(!ty_spec[2]);
}
else if (ty_spec[0] == 'I' && ty_spec[1] == 'V')
{
ret_type->type = WGL_BuiltinType::IVec;
OP_ASSERT(!ty_spec[2]);
}
else if (ty_spec[0] == 'M' && !ty_spec[1])
ret_type->type = WGL_BuiltinType::Mat;
else if (ty_spec[0] == 'F' && !ty_spec[1])
{
ret_type->type = WGL_BuiltinType::Basic;
ret_type->value.basic_type = WGL_BasicType::Float;
}
else if (ty_spec[0] == 'S' && ty_spec[1] == 'C' && !ty_spec[2])
{
ret_type->type = WGL_BuiltinType::Sampler;
ret_type->value.sampler_type = WGL_SamplerType::SamplerCube;
}
else if (ty_spec[0] == 'S' && ty_spec[1] == '2' && ty_spec[2] == 'D' && !ty_spec[3])
{
ret_type->type = WGL_BuiltinType::Sampler;
ret_type->value.sampler_type = WGL_SamplerType::Sampler2D;
}
else
OP_ASSERT(!"unexpected type specifier");
return ret_type;
}
void
WGL_Context::Initialise(WGL_Validator::Configuration *config)
{
OpPointerHashTable<WGL_String, List<WGL_Builtin> > &builtins_map = GetValidationState().builtins_map;
builtins_map.RemoveAll();
if (!config || config->for_vertex)
{
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_Position")), NewBuiltinVar(UNI_L("gl_Position"), WGL_VectorType::Vec4, WGL_Type::High, FALSE, TRUE, TRUE));
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_PointSize")), NewBuiltinVar(UNI_L("gl_PointSize"), WGL_BasicType::Float, WGL_Type::Medium, FALSE, TRUE, TRUE));
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_DepthRange")), NewBuiltinVar(UNI_L("gl_DepthRange"), WGL_VectorType::Vec3, WGL_Type::High, FALSE, FALSE, TRUE));
}
else
{
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_FragCoord")), NewBuiltinVar(UNI_L("gl_FragCoord"), WGL_VectorType::Vec4, WGL_Type::Medium, FALSE, TRUE, FALSE));
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_FrontFacing")), NewBuiltinVar(UNI_L("gl_FrontFacing"), WGL_BasicType::Bool, WGL_Type::NoPrecision, TRUE, FALSE, FALSE));
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_FragColor")), NewBuiltinVar(UNI_L("gl_FragColor"), WGL_VectorType::Vec4, WGL_Type::Medium, FALSE, TRUE, FALSE));
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_FragData")), NewBuiltinVar(UNI_L("gl_FragData"), WGL_VectorType::Vec4, WGL_Type::Medium, FALSE, TRUE, FALSE, "gl_MaxDrawBuffers"));
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_PointCoord")), NewBuiltinVar(UNI_L("gl_PointCoord"), WGL_VectorType::Vec2, WGL_Type::Medium, FALSE, FALSE, FALSE));
builtins_map.Add(WGL_String::Make(this, UNI_L("gl_DepthRange")), NewBuiltinVar(UNI_L("gl_DepthRange"), WGL_VectorType::Vec3, WGL_Type::High, FALSE, FALSE, FALSE));
}
/* Constants available to both */
if (config)
{
for (unsigned i = 0; i < WGL_GLSLBuiltins::vertex_shader_constant_elements; i++)
{
WGL_GLSLBuiltins::ConstantInfo info = WGL_GLSLBuiltins::vertex_shader_constant[i];
builtins_map.Add(WGL_String::Make(this, info.name), NewBuiltinConstant(info.name, info.basic_type, info.precision, WGL_GLSLBuiltins::GetConstantValue(*config, info.const_value)));
}
}
for (unsigned i = 0; i < WGL_GLSLBuiltins::shader_intrinsics_elements; i++)
{
WGL_GLSLBuiltins::FunctionInfo info = WGL_GLSLBuiltins::shader_intrinsics[i];
WGL_BuiltinFun *fun = OP_NEWGRO_L(WGL_BuiltinFun, (), Arena());
fun->name = info.name;
fun->intrinsic = info.intrinsic;
fun->arity = info.arity;
fun->return_type = ToBuiltinType(this, info.return_type);
if (info.arg1_type)
{
WGL_BuiltinType *arg = ToBuiltinType(this, info.arg1_type);
arg->Into(&fun->parameters);
}
if (info.arg2_type)
{
WGL_BuiltinType *arg = ToBuiltinType(this, info.arg2_type);
arg->Into(&fun->parameters);
}
if (info.arg3_type)
{
WGL_BuiltinType *arg = ToBuiltinType(this, info.arg3_type);
arg->Into(&fun->parameters);
}
List <WGL_Builtin> *list;
WGL_String *builtin_name = WGL_String::Make(this, info.name);
if (OpStatus::IsError(builtins_map.GetData(builtin_name, &list)))
{
list = OP_NEWGRO_L(List<WGL_Builtin>, (), Arena());
builtins_map.Add(builtin_name, list);
}
fun->Into(list);
}
for (unsigned i = 0; i < GetExtensionCount(); i++)
{
WGL_GLSLBuiltins::FunctionInfo *funs = NULL;
unsigned count = 0;
if (IsEnabledExtension(i, &funs, &count))
{
for (unsigned j = 0; j < count; j++)
{
WGL_GLSLBuiltins::FunctionInfo info = funs[j];
WGL_BuiltinFun *fun = OP_NEWGRO_L(WGL_BuiltinFun, (), Arena());
fun->name = info.name;
fun->intrinsic = info.intrinsic;
fun->arity = info.arity;
fun->return_type = ToBuiltinType(this, info.return_type);
if (info.arg1_type)
{
WGL_BuiltinType *arg = ToBuiltinType(this, info.arg1_type);
arg->Into(&fun->parameters);
}
if (info.arg2_type)
{
WGL_BuiltinType *arg = ToBuiltinType(this, info.arg2_type);
arg->Into(&fun->parameters);
}
if (info.arg3_type)
{
WGL_BuiltinType *arg = ToBuiltinType(this, info.arg3_type);
arg->Into(&fun->parameters);
}
List <WGL_Builtin> *list;
WGL_String *builtin_name = WGL_String::Make(this, info.name);
if (OpStatus::IsError(builtins_map.GetData(builtin_name, &list)))
{
list = OP_NEWGRO_L(List<WGL_Builtin>, (), Arena());
builtins_map.Add(builtin_name, list);
}
fun->Into(list);
}
}
}
configuration = config;
}
BOOL
WGL_BuiltinType::Matches(WGL_BasicType::Type t, BOOL strict)
{
switch(t)
{
case WGL_BasicType::Void:
return FALSE;
case WGL_BasicType::UInt:
t = WGL_BasicType::Int;
/* fall through */
case WGL_BasicType::Float:
if (t == WGL_BasicType::Float && this->type == Gen)
return TRUE;
case WGL_BasicType::Bool:
case WGL_BasicType::Int:
return (this->type == Basic && (this->value.basic_type == t || !strict && this->value.basic_type != WGL_BasicType::Void));
default:
return FALSE;
}
}
BOOL
WGL_BuiltinType::Matches(WGL_VectorType::Type t, BOOL strict)
{
/* NOTE: strict argument is currently unused; determine if there will be a need for it. */
switch(t)
{
case WGL_VectorType::Vec2:
case WGL_VectorType::Vec3:
case WGL_VectorType::Vec4:
return (this->type == Vector && this->value.vector_type == t || this->type == Gen || this->type == Vec);
case WGL_VectorType::BVec2:
case WGL_VectorType::BVec3:
case WGL_VectorType::BVec4:
return (this->type == BVec || this->type == Vector && this->value.vector_type == t);
case WGL_VectorType::IVec2:
case WGL_VectorType::IVec3:
case WGL_VectorType::IVec4:
return (this->type == IVec || this->type == Vector && this->value.vector_type == t);
case WGL_VectorType::UVec2:
case WGL_VectorType::UVec3:
case WGL_VectorType::UVec4:
return (this->type == Vector && this->value.vector_type == t);
default:
return FALSE;
}
}
BOOL
WGL_BuiltinType::Matches(WGL_MatrixType::Type t, BOOL strict)
{
switch(t)
{
case WGL_MatrixType::Mat2:
case WGL_MatrixType::Mat3:
case WGL_MatrixType::Mat4:
return (this->type == Matrix && this->value.matrix_type == t || this->type == Mat);
case WGL_MatrixType::Mat2x2:
case WGL_MatrixType::Mat2x3:
case WGL_MatrixType::Mat2x4:
case WGL_MatrixType::Mat3x2:
case WGL_MatrixType::Mat3x3:
case WGL_MatrixType::Mat3x4:
case WGL_MatrixType::Mat4x2:
case WGL_MatrixType::Mat4x3:
case WGL_MatrixType::Mat4x4:
return (this->type == Matrix && this->value.matrix_type == t);
default:
return FALSE;
}
}
BOOL
WGL_BuiltinType::Matches(WGL_SamplerType::Type t, BOOL strict)
{
return (this->type == Sampler && this->value.sampler_type == t);
}
#endif // CANVAS3D_SUPPORT
|
#include "amelie.h"
#include <vector>
#include <QFileInfo>
#include <QResource>
#pragma region AmelieEvent
AmelieEvent::AmelieEvent()
{
this->amelie = AmelieApplication::getInstance();
}
AmelieEvent* AmelieEvent::getInstance()
{
static AmelieEvent* instance = new AmelieEvent();
return instance;
}
QUrl AmelieEvent::initSettingsWindow()
{
return amelie->initSettingsWindow();
}
QString AmelieEvent::chatConversation(bool enableVoice, QString input)
{
return amelie->chatConversation(enableVoice, input);
}
bool AmelieEvent::setUsername(QString nameValue)
{
return amelie->setUsername(nameValue);
}
QString AmelieEvent::getUsername()
{
return amelie->getUsername();
}
void AmelieEvent::setLanguage(QString langValue)
{
amelie->setLanguage(langValue);
}
QString AmelieEvent::getLanguage()
{
return amelie->getLanguage();
}
std::vector<const char*> AmelieEvent::getSupportingLangs()
{
return amelie->getSupportingLangs();
}
QString AmelieEvent::getUserInput()
{
return amelie->getUserInput();
}
std::vector<const char*> AmelieEvent::getBotAvatars()
{
return amelie->getBotAvatars();
}
std::vector<const char*> AmelieEvent::getUserAvatars()
{
return amelie->getUserAvatars();
}
QString AmelieEvent::getBotAvatar()
{
return amelie->getBotAvatar();
}
QString AmelieEvent::getUserAvatar()
{
return amelie->getUserAvatar();
}
void AmelieEvent::setBotAvatar(QString avatarName)
{
amelie->setBotAvatar(avatarName);
}
void AmelieEvent::setUserAvatar(QString avatarName)
{
amelie->setUserAvatar(avatarName);
}
QString AmelieEvent::setPreviewAvatar(QString avatarType, QString avatarName)
{
QFileInfo p("../resources/AppIcon/" + avatarType + "/avatar/" + avatarName + ".png");
return QUrl::fromLocalFile(p.absoluteFilePath()).toString();
}
void AmelieEvent::closeAmelieEvent()
{
delete amelie;
}
AmelieEvent::~AmelieEvent()
{
delete amelie;
}
#pragma endregion
#pragma region AmelieApplication
AmelieApplication::AmelieApplication()
{
this->settings = Settings::getInstance();
this->chat = nullptr;
this->gui = nullptr;
}
AmelieApplication* AmelieApplication::getInstance()
{
static AmelieApplication* instance = new AmelieApplication();
return instance;
}
void AmelieApplication::initChatBot()
{
this->chat = Chat::getInstance(settings->getLanguage());
}
char* AmelieApplication::chatConversation(bool enableVoice, QString input)
{
return chat->conversation(enableVoice, input.toStdString().c_str());
}
void AmelieApplication::setLanguage(QString langValue)
{
settings->setLanguage(langValue);
if(chat != nullptr)
chat->changeLanguage(langValue.toStdString().c_str());
}
std::vector<const char*> AmelieApplication::getSupportingLangs()
{
return settings->getSupportingLangs();
}
QString AmelieApplication::getLanguage()
{
return settings->getLanguage();
}
bool AmelieApplication::setUsername(QString nameValue)
{
return settings->setUsername(nameValue);
}
QString AmelieApplication::getUsername()
{
return settings->getUsername();
}
QString AmelieApplication::getUserInput()
{
return chat->getUserInput();
}
std::vector<const char*> AmelieApplication::getBotAvatars()
{
return settings->getBotAvatars();
}
std::vector<const char*> AmelieApplication::getUserAvatars()
{
return settings->getUserAvatars();
}
void AmelieApplication::setBotAvatar(QString avatarName)
{
settings->setBotAvatar(avatarName);
}
void AmelieApplication::setUserAvatar(QString avatarName)
{
settings->setUserAvatar(avatarName);
}
QString AmelieApplication::getBotAvatar()
{
return settings->getBotAvatar();
}
QString AmelieApplication::getUserAvatar()
{
return settings->getUserAvatar();
}
int AmelieApplication::main(int argc, char** argv)
{
this->gui = new GUI(argc, argv);
// Filling the settings file
while(settings->getLanguage() == "-" || settings->getUsername() == "")
{
gui->showSettingsWindow();
}
initChatBot();
return gui->showMainWindow();
}
QUrl AmelieApplication::initSettingsWindow()
{
return this->gui->initSettingsWindow();
}
AmelieApplication::~AmelieApplication()
{
// this->gui will be deleted automatically when QML window triggers close event.
delete chat;
delete settings;
}
#pragma endregion
#pragma region Chat
AmelieApplication::Chat::Chat(const char* appLanguage)
{
this->classInstance = AmelieCreateInstance(appLanguage);
}
AmelieApplication::Chat* AmelieApplication::Chat::getInstance(const char* appLanguage)
{
static Chat* instance = new Chat(appLanguage);
return instance;
}
void AmelieApplication::Chat::changeLanguage(const char* language)
{
AmelieChangeLanguage(classInstance, language);
}
char* AmelieApplication::Chat::conversation(bool enableVoice, const char* userInput)
{
return AmelieConversation(classInstance, enableVoice, userInput);
}
void AmelieApplication::Chat::tts(const char* phrase)
{
AmelieTTS(classInstance, phrase);
}
bool AmelieApplication::Chat::getVoice()
{
return AmelieGetVoice(classInstance);
}
const char* AmelieApplication::Chat::getUserInput()
{
return AmelieGetUserInput(classInstance);
}
AmelieApplication::Chat::~Chat()
{
AmelieDelete(classInstance);
}
#pragma endregion
#pragma region Settings
AmelieApplication::Settings::Settings()
{
this->classInstance = SettingsCreateInstance();
}
AmelieApplication::Settings* AmelieApplication::Settings::getInstance()
{
static Settings* instance = new Settings();
return instance;
}
void AmelieApplication::Settings::setLanguage(QString langValue)
{
SettingsSetLanguage(classInstance, langValue.toStdString().c_str());
}
bool AmelieApplication::Settings::setUsername(QString nameValue)
{
return SettingsSetUsername(classInstance, nameValue.toStdString().c_str());
}
const char* AmelieApplication::Settings::getLanguage()
{
return SettingsGetLanguage(classInstance);
}
std::vector<const char*> AmelieApplication::Settings::getSupportingLangs()
{
return SettingsGetSupportingLangs(classInstance);
}
QString AmelieApplication::Settings::getUsername()
{
return SettingsGetUsername(classInstance);
}
void AmelieApplication::Settings::setBotAvatar(QString avatarName)
{
SettingsSetBotAvatar(classInstance, avatarName.toStdString().c_str());
}
void AmelieApplication::Settings::setUserAvatar(QString avatarName)
{
SettingsSetUserAvatar(classInstance, avatarName.toStdString().c_str());
}
std::vector<const char*> AmelieApplication::Settings::getBotAvatars()
{
return SettingsGetBotAvatars(classInstance);
}
std::vector<const char*> AmelieApplication::Settings::getUserAvatars()
{
return SettingsGetUserAvatars(classInstance);
}
const char* AmelieApplication::Settings::getBotAvatar()
{
return SettingsGetBotAvatar(classInstance);
}
const char* AmelieApplication::Settings::getUserAvatar()
{
return SettingsGetUserAvatar(classInstance);
}
std::multimap<const char*, void*> AmelieApplication::Settings::getMethodsToResolveErrors()
{
return SettingsGetMethodsToResolveErrors(classInstance);
}
AmelieApplication::Settings::~Settings()
{
SettingsDelete(classInstance);
}
#pragma endregion
#pragma region GUI
AmelieApplication::GUI::GUI(int argc, char** argv)
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
this->app = new QGuiApplication(argc, argv);
this->engine = new QQmlApplicationEngine();
}
int AmelieApplication::GUI::showMainWindow()
{
engine->rootContext()->setContextProperty("Event", AmelieEvent::getInstance());
/* This is a crutch to fix a crash of the application.
* aftter the call of engine->load it's raising an unhanlded excpetion in ucrtbase module.
*
* The stack trace:
* > ucrtbase.dll!00007ffd1d0bdb8e() -> raise the 0xC0000409 exception.
* > ucrtbase.dll!00007ffd1d0bd2cf()
* > AmelieBot.exe!__scrt_unhandled_exception_filter(_EXCEPTION_POINTERS * const pointers) in crt -> utility_app.cpp line 91
*/
while(true)
{
try
{
engine->load("qrc:///qml/main.qml");
break;
}
catch(...)
{
continue;
}
}
return app->exec();
}
QUrl AmelieApplication::GUI::initSettingsWindow()
{
// TODO: Refactoring.
AmelieEvent* event = AmelieEvent::getInstance();
engine->rootContext()->setContextProperty("Event", event);
std::vector<const char*> langs = event->getSupportingLangs();
QVariantList supLangs;
QString currentLang = event->getLanguage();
// If value is actually language value
if(currentLang != '-')
{
auto currentLangValue = std::find(langs.begin(), langs.end(), currentLang);
if(currentLangValue != langs.end())
{
langs.erase(currentLangValue);
supLangs.append(currentLang);
}
}
for(int i = 0; i < langs.size(); ++i)
{
supLangs.append(langs[i]);
}
engine->rootContext()->setContextProperty("Langs", supLangs);
std::vector<const char*> botAvatars = event->getBotAvatars();
QVariantList botAvatarList;
QString currentBotAvatarName = event->getBotAvatar();
auto currentBotAvatarPosition = std::find(botAvatars.begin(), botAvatars.end(), currentBotAvatarName);
if(currentBotAvatarPosition != botAvatars.end())
{
botAvatars.erase(currentBotAvatarPosition);
botAvatarList.append(currentBotAvatarName);
}
for(int i = 0; i < botAvatars.size(); ++i)
{
botAvatarList.append(botAvatars[i]);
}
engine->rootContext()->setContextProperty("botAvatarList", botAvatarList);
std::vector<const char*> userAvatars = event->getUserAvatars();
QVariantList userAvatarList;
QString currentUserAvatarName = event->getUserAvatar();
auto currentUserAvatarPosition = std::find(userAvatars.begin(), userAvatars.end(), currentUserAvatarName);
if(currentUserAvatarPosition != userAvatars.end())
{
userAvatars.erase(currentUserAvatarPosition);
userAvatarList.append(currentUserAvatarName);
}
for(int i = 0; i < userAvatars.size(); ++i)
{
userAvatarList.append(userAvatars[i]);
}
engine->rootContext()->setContextProperty("userAvatarList", userAvatarList);
return QUrl("qrc:///qml/settingsWindow.qml");
}
void AmelieApplication::GUI::showSettingsWindow()
{
engine->load(initSettingsWindow());
app->exec();
}
AmelieApplication::GUI::~GUI()
{
delete engine;
delete app;
}
#pragma endregion
|
#include <boost/lexical_cast.hpp>
#include <gui/TextPainter.h>
#include "NeuronsStackPainter.h"
static logger::LogChannel neuronsstackpainterlog("neuronsstackpainterlog", "[NeuronsStackPainter] ");
NeuronsStackPainter::NeuronsStackPainter() :
_section(0),
_showSingleNeuron(false),
_currentNeuron(0),
_showEnds(true),
_showContinuations(true),
_showBranches(true),
_showSliceIds(false),
_zScale(15) {}
void
NeuronsStackPainter::setNeurons(boost::shared_ptr<SegmentTrees> neurons) {
// aquire a read lock on the neurons
boost::shared_lock<boost::shared_mutex> lockNeurons(neurons->getMutex());
LOG_DEBUG(neuronsstackpainterlog) << "got new neurons" << std::endl;
_neurons = neurons;
assignColors();
loadTextures();
setCurrentSection(_section);
}
void
NeuronsStackPainter::showNeuron(unsigned int neuron) {
if (neuron >= _neurons->size())
return;
_showSingleNeuron = true;
_currentNeuron = neuron;
}
void
NeuronsStackPainter::showAllNeurons() {
_showSingleNeuron = false;
}
void
NeuronsStackPainter::showEnds(bool show) {
LOG_DEBUG(neuronsstackpainterlog) << "showing ends: " << show << std::endl;
_showEnds = show;
}
void
NeuronsStackPainter::showContinuations(bool show) {
LOG_DEBUG(neuronsstackpainterlog) << "showing continuations: " << show << std::endl;
_showContinuations = show;
}
void
NeuronsStackPainter::showBranches(bool show) {
LOG_DEBUG(neuronsstackpainterlog) << "showing branches: " << show << std::endl;
_showBranches = show;
}
void
NeuronsStackPainter::showSliceIds(bool show) {
_showSliceIds = show;
}
void
NeuronsStackPainter::assignColors() {
LOG_DEBUG(neuronsstackpainterlog) << "assigning colors" << std::endl;
_colors.clear();
// assign a color to each neuron
for (unsigned int i = 0; i < _neurons->size(); i++) {
// draw a random color
double r = (double)rand()/RAND_MAX;
double g = (double)rand()/RAND_MAX;
double b = (double)rand()/RAND_MAX;
_colors[i][0] = r;
_colors[i][1] = g;
_colors[i][2] = b;
}
LOG_DEBUG(neuronsstackpainterlog) << "done" << std::endl;
}
void
NeuronsStackPainter::loadTextures() {
_textures.clear();
foreach (boost::shared_ptr<SegmentTree> neuron, *_neurons) {
// aquire a read lock on the neuron
boost::shared_lock<boost::shared_mutex> lockNeuron(neuron->getMutex());
foreach (boost::shared_ptr<EndSegment> end, neuron->getEnds())
_textures.load(*end->getSlice());
foreach (boost::shared_ptr<ContinuationSegment> continuation, neuron->getContinuations()) {
_textures.load(*continuation->getSourceSlice());
_textures.load(*continuation->getTargetSlice());
}
foreach (boost::shared_ptr<BranchSegment> branch, neuron->getBranches()) {
_textures.load(*branch->getSourceSlice());
_textures.load(*branch->getTargetSlice1());
_textures.load(*branch->getTargetSlice2());
}
}
}
void
NeuronsStackPainter::setCurrentSection(unsigned int section) {
_section = std::min(section, (unsigned int)std::max((int)0, (int)_neurons->getNumSections() - 1));
// get the size of the painter
util::rect<double> size(0, 0, 0, 0);
foreach (boost::shared_ptr<SegmentTree> neuron, *_neurons) {
foreach (boost::shared_ptr<EndSegment> end, neuron->getEnds())
size = sizeAddSlice(size, *end->getSlice());
foreach (boost::shared_ptr<ContinuationSegment> continuation, neuron->getContinuations()) {
size = sizeAddSlice(size, *continuation->getSourceSlice());
size = sizeAddSlice(size, *continuation->getTargetSlice());
}
foreach (boost::shared_ptr<BranchSegment> branch, neuron->getBranches()) {
size = sizeAddSlice(size, *branch->getSourceSlice());
size = sizeAddSlice(size, *branch->getTargetSlice1());
size = sizeAddSlice(size, *branch->getTargetSlice2());
}
}
setSize(size);
LOG_DEBUG(neuronsstackpainterlog) << "current section set to " << _section << std::endl;
LOG_DEBUG(neuronsstackpainterlog) << "current size set to " << size << std::endl;
}
util::rect<double>
NeuronsStackPainter::sizeAddSlice(const util::rect<double>& currentSize, const Slice& slice) {
if (currentSize.width() == 0 && currentSize.height() == 0)
return slice.getComponent()->getBoundingBox();
util::rect<double> size;
size.minX = std::min(currentSize.minX, (double)slice.getComponent()->getBoundingBox().minX);
size.minY = std::min(currentSize.minY, (double)slice.getComponent()->getBoundingBox().minY);
size.maxX = std::max(currentSize.maxX, (double)slice.getComponent()->getBoundingBox().maxX);
size.maxY = std::max(currentSize.maxY, (double)slice.getComponent()->getBoundingBox().maxY);
return size;
}
void
NeuronsStackPainter::draw(
const util::rect<double>& roi,
const util::point<double>& resolution) {
// aquire a read lock
boost::shared_lock<boost::shared_mutex> lockMe(getMutex());
boost::shared_lock<boost::shared_mutex> lockNeurons(_neurons->getMutex());
if (_neurons->size() == 0)
return;
LOG_ALL(neuronsstackpainterlog) << "redrawing section " << _section << std::endl;
// from previous section
if (_showSingleNeuron) {
_currentNeuron = std::min(_currentNeuron, _neurons->size() - 1);
drawNeuron(*(*(_neurons->begin() + _currentNeuron)), _currentNeuron, roi, resolution);
} else {
unsigned int neuronNum = 0;
foreach (boost::shared_ptr<SegmentTree> neuron, *_neurons) {
// read lock on neuron
boost::shared_lock<boost::shared_mutex> lockNeuron(neuron->getMutex());
drawNeuron(*neuron, neuronNum, roi, resolution);
neuronNum++;
}
}
}
void
NeuronsStackPainter::drawNeuron(
SegmentTree& neuron,
unsigned int neuronNum,
const util::rect<double>& roi,
const util::point<double>& resolution) {
// set up lighting
GLfloat ambient[4] = { 0, 0, 0, 1 };
glCheck(glLightfv(GL_LIGHT0, GL_AMBIENT, ambient));
GLfloat diffuse[4] = { 0.1, 0.1, 0.1, 1 };
glCheck(glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse));
GLfloat specular[4] = { 0.1, 0.1, 0.1, 1 };
glCheck(glLightfv(GL_LIGHT0, GL_SPECULAR, specular));
glCheck(glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular)); GLfloat emission[4] = { 0, 0, 0, 1 };
glCheck(glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emission));
// enable alpha blending
glCheck(glEnable(GL_BLEND));
glCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
glCheck(glEnable(GL_CULL_FACE));
glCheck(glEnable(GL_LIGHTING));
glCheck(glEnable(GL_LIGHT0));
glCheck(glEnable(GL_COLOR_MATERIAL));
double red = _colors[neuronNum][0];
double green = _colors[neuronNum][1];
double blue = _colors[neuronNum][2];
// we want to show the slices of the current section and the links to slices
// in the previous and next section
if (_showEnds) {
// for all ends in the previous inter-section interval
foreach (boost::shared_ptr<EndSegment> end, neuron.getEnds(_section)) {
// is their slice in our section?
if (end->getDirection() == Left) {
// draw the slice
drawSlice(*end->getSlice(), red, green, blue, 0.75, roi, resolution);
// draw the end-link
drawEnd(end->getSlice()->getComponent()->getCenter(), Left, roi, resolution);
}
}
// for all ends in the next inter-section interval
foreach (boost::shared_ptr<EndSegment> end, neuron.getEnds(_section + 1)) {
// is their slice in our section?
if (end->getDirection() == Right) {
// draw the end-link
drawEnd(end->getSlice()->getComponent()->getCenter(), Right, roi, resolution);
}
}
}
if (_showContinuations) {
// for all continuations in the previous inter-section interval
foreach (boost::shared_ptr<ContinuationSegment> continuation, neuron.getContinuations(_section)) {
if (continuation->getDirection() == Left) {
drawSlice(
*continuation->getSourceSlice(),
red, green, blue,
0.75,
roi, resolution);
drawContinuation(
continuation->getSourceSlice()->getComponent()->getCenter(),
continuation->getTargetSlice()->getComponent()->getCenter(),
Left,
roi, resolution);
} else {
drawSlice(
*continuation->getTargetSlice(),
red, green, blue,
0.75,
roi, resolution);
drawContinuation(
continuation->getTargetSlice()->getComponent()->getCenter(),
continuation->getSourceSlice()->getComponent()->getCenter(),
Left,
roi, resolution);
}
}
// for all continuations in the next inter-section interval
foreach (boost::shared_ptr<ContinuationSegment> continuation, neuron.getContinuations(_section + 1)) {
if (continuation->getDirection() == Left) {
drawContinuation(
continuation->getTargetSlice()->getComponent()->getCenter(),
continuation->getSourceSlice()->getComponent()->getCenter(),
Right,
roi, resolution);
} else {
drawContinuation(
continuation->getSourceSlice()->getComponent()->getCenter(),
continuation->getTargetSlice()->getComponent()->getCenter(),
Right,
roi, resolution);
}
}
}
if (_showBranches) {
// for all branches in the previous inter-section interval
foreach (boost::shared_ptr<BranchSegment> branch, neuron.getBranches(_section)) {
if (branch->getDirection() == Left) {
drawSlice(
*branch->getSourceSlice(),
red, green, blue,
0.75,
roi, resolution);
drawBranch(
branch->getSourceSlice()->getComponent()->getCenter(),
branch->getTargetSlice1()->getComponent()->getCenter(),
branch->getTargetSlice2()->getComponent()->getCenter(),
Left,
roi, resolution);
} else {
drawSlice(
*branch->getTargetSlice1(),
red, green, blue,
0.75,
roi, resolution);
drawSlice(
*branch->getTargetSlice2(),
red, green, blue,
0.75,
roi, resolution);
drawMerge(
branch->getTargetSlice1()->getComponent()->getCenter(),
branch->getTargetSlice2()->getComponent()->getCenter(),
branch->getSourceSlice()->getComponent()->getCenter(),
Left,
roi, resolution);
}
}
// for all branches in the next inter-section interval
foreach (boost::shared_ptr<BranchSegment> branch, neuron.getBranches(_section + 1)) {
if (branch->getDirection() == Left) {
drawMerge(
branch->getTargetSlice1()->getComponent()->getCenter(),
branch->getTargetSlice2()->getComponent()->getCenter(),
branch->getSourceSlice()->getComponent()->getCenter(),
Right,
roi, resolution);
} else {
drawBranch(
branch->getSourceSlice()->getComponent()->getCenter(),
branch->getTargetSlice1()->getComponent()->getCenter(),
branch->getTargetSlice2()->getComponent()->getCenter(),
Right,
roi, resolution);
}
}
}
glCheck(glDisable(GL_BLEND));
glCheck(glDisable(GL_LIGHTING));
glCheck(glDisable(GL_CULL_FACE));
}
void
NeuronsStackPainter::drawSlice(
const Slice& slice,
double red, double green, double blue,
double alpha,
const util::rect<double>& roi,
const util::point<double>& resolution) {
glCheck(glColor4f(red, green, blue, alpha));
glCheck(glEnable(GL_TEXTURE_2D));
try {
_textures.get(slice.getId())->bind();
} catch (SliceTextures::MissingTexture& e) {
loadTextures();
_textures.get(slice.getId())->bind();
}
glBegin(GL_QUADS);
const util::rect<double>& bb = slice.getComponent()->getBoundingBox();
double offset = 0;
// right side
glTexCoord2d(0.0, 0.0); glNormal3d(0, 0, 1); glVertex3d(bb.minX, bb.minY + offset, 0);
glTexCoord2d(0.0, 1.0); glNormal3d(0, 0, 1); glVertex3d(bb.minX, bb.maxY + offset, 0);
glTexCoord2d(1.0, 1.0); glNormal3d(0, 0, 1); glVertex3d(bb.maxX, bb.maxY + offset, 0);
glTexCoord2d(1.0, 0.0); glNormal3d(0, 0, 1); glVertex3d(bb.maxX, bb.minY + offset, 0);
glCheck(glEnd());
if (_showSliceIds) {
gui::TextPainter idPainter(boost::lexical_cast<std::string>(slice.getId()));
idPainter.setTextSize(10.0);
idPainter.setTextColor(1.0 - red, 1.0 - green, 1.0 - blue);
double x = slice.getComponent()->getCenter().x;
double y = slice.getComponent()->getCenter().y + offset;
glTranslatef(x, y, 0);
idPainter.draw(roi - util::point<double>(x, y), resolution);
glTranslatef(-x, -y, 0);
}
}
void
NeuronsStackPainter::drawEnd(
const util::point<double>& center,
Direction direction,
const util::rect<double>&,
const util::point<double>&) {
if (direction == Left)
setPrevColor();
else
setNextColor();
double size = 7;
glCheck(glDisable(GL_TEXTURE_2D));
glCheck(glEnable(GL_LINE_SMOOTH));
glCheck(glLineWidth(5.0));
glBegin(GL_QUADS);
glVertex3d(center.x - size, center.y - size, 0);
glVertex3d(center.x - size, center.y + size, 0);
glVertex3d(center.x + size, center.y + size, 0);
glVertex3d(center.x + size, center.y - size, 0);
glEnd();
}
void
NeuronsStackPainter::drawContinuation(
const util::point<double>& source,
const util::point<double>& target,
Direction direction,
const util::rect<double>&,
const util::point<double>&) {
if (direction == Left)
setPrevColor();
else
setNextColor();
glCheck(glDisable(GL_TEXTURE_2D));
glCheck(glEnable(GL_LINE_SMOOTH));
glCheck(glLineWidth(5.0));
glBegin(GL_LINES);
glVertex3d(source.x, source.y, 0);
glVertex3d(target.x, target.y, 0);
glEnd();
}
void
NeuronsStackPainter::drawBranch(
const util::point<double>& source,
const util::point<double>& target1,
const util::point<double>& target2,
Direction direction,
const util::rect<double>&,
const util::point<double>&) {
if (direction == Left)
setPrevColor();
else
setNextColor();
glCheck(glDisable(GL_TEXTURE_2D));
glBegin(GL_LINES);
glVertex3d(source.x, source.y, 0);
glVertex3d(target1.x, target1.y, 0);
glEnd();
glBegin(GL_LINES);
glVertex3d(source.x, source.y, 0);
glVertex3d(target2.x, target2.y, 0);
glEnd();
}
void
NeuronsStackPainter::drawMerge(
const util::point<double>& source1,
const util::point<double>& source2,
const util::point<double>& target,
Direction direction,
const util::rect<double>&,
const util::point<double>&) {
if (direction == Left)
setPrevColor();
else
setNextColor();
glCheck(glDisable(GL_TEXTURE_2D));
glCheck(glEnable(GL_LINE_SMOOTH));
glCheck(glLineWidth(5.0));
glBegin(GL_LINES);
glVertex3d(source1.x, source1.y, 0);
glVertex3d(target.x, target.y, 0);
glEnd();
glBegin(GL_LINES);
glVertex3d(source2.x, source2.y, 0);
glVertex3d(target.x, target.y, 0);
glEnd();
}
void
NeuronsStackPainter::setNextColor() {
glColor4f(0.9, 0.9, 1.0, 0.9);
}
void
NeuronsStackPainter::setPrevColor() {
glColor4f(0.1, 0.1, 0.0, 0.9);
}
|
//
// GameUI.h
// GetFish
//
// Created by zhusu on 15/1/27.
//
//
#ifndef __GetFish__GameUI__
#define __GetFish__GameUI__
#include "cocos2d.h"
#include "ButtonWithSpriteManage.h"
USING_NS_CC;
class GameUI : public CCLayer
{
public:
static const int DIR_NONE = 0;
static const int DIR_LEFT = 1;
static const int DIR_RIGHT = 2;
CREATE_FUNC(GameUI);
GameUI();
virtual bool init();
virtual ~GameUI();
virtual void onEnter();
virtual void onExit();
bool GameUItouchesBegan(CCSet * touchs,CCEvent * event);
void GameUItouchesMoved(CCSet * touchs,CCEvent * event);
void GameUItouchesCancelled(CCSet * touchs,CCEvent * event);
void GameUItouchesEnded(CCSet * touchs,CCEvent * event);
void GameUItouchesDir(CCSet * touchs,CCEvent * event);
void GameUItouchesMovedDir(CCSet * touchs,CCEvent * event);
// void GameUItouchesEndDir(CCSet * touchs,CCEvent * event);
int getNowButtonID() const;
void setTime(int time);
void setScoreTiao(float sc);
void setScoreTiao1(float sc);
void setScore(int sc);
void setScore1(int sc);
void addMubiaoScore( std::vector<int> mubiao);
void addSucLab(int type , int );
void setSucNum(std::string str);
void setSuc();
CCSprite* getLeft();
CCSprite* getRight();
CCSprite* getHook();
CC_SYNTHESIZE(int, _dir, Dir);
CC_SYNTHESIZE(bool, _ishook, isHook);
CC_SYNTHESIZE(bool, _set, isSet);
void setCitieNum(int num);
private:
CCSize _screenSize;
ButtonWithSpriteManage* _buttons;
CCLabelAtlas* _timeLabel;
CCLabelAtlas* _citieLabel;
CCLabelAtlas* _score_Label;
CCLabelAtlas* _score_Label1;
CCProgressTimer* _score_tiao;
CCProgressTimer* _score_tiao1;
CCSprite* _left;
CCSprite* _right;
CCSprite* _hook;
CCLabelAtlas* _num;
CCNode* _node;
CCSprite* zuodi;
};
#endif /* defined(__GetFish__GameUI__) */
|
#include "GlowEffect.h"
#include "Window.h"
#include <GL/glew.h>
GlowEffect::GlowEffect() {
preGlowFbo = new Fbo(window::getWindowSize(), false);
fbo = new Fbo(window::getWindowSize(), false);
glowShader.addShader("shaders/gui.vsh", GL_VERTEX_SHADER);
glowShader.addShader("shaders/glowEffect.fsh", GL_FRAGMENT_SHADER);
glowShader.start();
glowShader.bindTextureUnit("textureSampler", 0);
glowShader.bindTextureUnit("glowTexture", 1);
glowShader.activateUniform("useGlow");
glowShader.activateUniform("useMMatrix");
glowShader.stop();
preGlowShader.addShader("shaders/preGlowEffect.vsh", GL_VERTEX_SHADER);
preGlowShader.addShader("shaders/preGlowEffect.fsh", GL_FRAGMENT_SHADER);
preGlowShader.start();
preGlowShader.activateUniform("mvpMatrix");
preGlowShader.activateUniform("glowColor");
preGlowShader.stop();
}
void GlowEffect::applyGlow(unsigned int vaoId, unsigned int rgbTexture, bool useGlow, std::map<Model,std::vector<Entity*>>& entities, Camera& cam, glm::mat4& projectionMatrix) {
//render Glow Image
preGlowShader.start();
preGlowFbo->bindFrameBuffer();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 viewMatrix = cam.getViewMatrix();
for(auto it = entities.begin(); it != entities.end(); it++){
Model model = it->first;
std::vector<Entity*> entityList = it->second;
if(model.hasGlow){
glBindVertexArray(model.vaoId);
glEnableVertexAttribArray(0);
for(int i = 0; i < model.elementBufferIds.size(); i++){
preGlowShader.setUniformVariable("glowColor", model.materials[i].glowColor);
//Bind Indice Buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, model.elementBufferIds[i]);
//Render Single
for(Entity* entity: entityList){
//Calculate and Load MVP Matrix
glm::mat4 modelMatrix = entity->transform.getModelMatrix();
glm::mat4 mvpMatrix = projectionMatrix * viewMatrix * modelMatrix;
preGlowShader.setUniformVariable("mvpMatrix", mvpMatrix);
glDrawElements(GL_TRIANGLES, model.elementBufferSizes[i], GL_UNSIGNED_INT, 0);
}
//Unbind Indice Buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
}
preGlowFbo->unbindFrameBuffer();
preGlowShader.stop();
blurEffect.applyBlur(vaoId, preGlowFbo->getColorBuffer(0), 1000, 15, glm::vec2(0.1f, 0.1f), true);
//Render Final Image
glowShader.start();
glBindVertexArray(vaoId);
glEnableVertexAttribArray(0);
fbo->bindFrameBuffer();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glowShader.setUniformVariable("useMMatrix", false);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, rgbTexture);
if(useGlow){
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, blurEffect.fbo->getColorBuffer(0));
}
glowShader.setUniformVariable("useGlow", useGlow);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
fbo->unbindFrameBuffer();
glDisableVertexAttribArray(0);
glBindVertexArray(0);
glowShader.stop();
}
GlowEffect::~GlowEffect() {
delete fbo;
delete preGlowFbo;
}
|
#include<cstdio>
#include<iostream>
#include<queue>
#include<map>
#include<vector>
using namespace std;
typedef long long ll;
int main(){
int res=0;
for(ll i=3;i<=59084709587505;++i){
ll temp=i;
bool flag=false;
while(temp%3==0){temp/=3;flag=true;}
while(temp%5==0){temp/=5;flag=true;}
while(temp%7==0){temp/=7;flag=true;}
if(temp==1&&flag)++res;
}
cout<<res;
return 0;
}
|
#include "stdafx.h"
#include <iostream>
#include <list>
#include <map>
#include <deque>
#include <algorithm>
#include <string>
#include <iterator>
#include <initializer_list>
#include <memory>
#include "List.h"
using namespace std;
bool sort_function_ubiv(List* object1, List* object2)
{
return (object1->showFirst()>object2->showFirst());
}
bool sort_function_vosrast(List* object1, List* object2)
{
return (object1->showFirst()<object2->showFirst());
}
void main() {
setlocale(LC_CTYPE, "rus");
List* element1 = new List; element1->add(1);
List* element2 = new List; element2->add(2);
List* element3 = new List; element3->add(3);
List* element4 = new List; element4->add(4);
list<List*> lst;
list<List*>::iterator it = lst.begin();
lst.insert(it, element1);
lst.insert(it, element2);
lst.insert(it, element3);
lst.insert(it, element4);
cout << "_______новый список_________";
for (auto el : lst)
{
cout << endl << el << endl;
}
lst.sort(sort_function_ubiv);
cout << "_______сортируем лист по убыванию_________";
for (auto el : lst)
{
cout << endl << el << endl;
}
cout << "______выбираем нужные объекты и суем их в multimap__________" << endl;
multimap<string, List*> mmap;
int val; string key_val;
while (true) {
cout << "значение искомого объекта(при вводе 0 ввод прекращается): "; cin >> val;
if (val == 0)
break;
list<List*>::iterator for_ = lst.begin();
while (for_ != lst.end())
{
for_ = find_if(for_, lst.end(), [&](List* object) {return object->showFirst() == val; });
if (for_ != lst.end())
{
_itoa(val, const_cast<char*>(key_val.c_str()), 10);
mmap.insert(pair<string, List*>(const_cast<char*>(key_val.c_str()), *for_));
for_++;
}
}
}
cout << "_______вывод контейнера с конца_________" << endl;
multimap<string,List*>::iterator begin_from_end = mmap.end();
multimap<string, List*>::iterator iter = mmap.begin();
do{
begin_from_end--;
cout << begin_from_end->first << ":" << begin_from_end->second << endl;
} while ( begin_from_end != iter);
cout << "_________сортируем по возрастанию и смотрим К-ый элемент_______" << endl;
lst.sort(sort_function_vosrast);
for (auto el : lst)
{
cout << endl << el << endl;
}
list<List*>::iterator for_k = lst.begin();
int k;
cout << "введите k: "; cin >> k;
for (int i = 1; i < k; i++)
{
for_k++;
}
cout << "статистика К-го элемента: " << endl << *for_k << endl;
cout << "_________объеденяем два контейнера_______" << endl;
deque<List*> deq;
for (auto it2 = lst.begin(); it2 != lst.end(); it2++) {
deq.push_back(*it2);
}
for (auto it3 = mmap.begin(); it3 != mmap.end(); it3++) {
deq.push_back(it3->second);
}
for (auto el : deq)
{
cout << endl << el << endl;
}
cout << "________количество элеметов с таким то параметром________" << endl;
int kol_in_deq = 0;
while (true) {
kol_in_deq = 0;
cout << "значение искомого объекта(при вводе 0 ввод прекращается): "; cin >> val;
if (val == 0)
break;
deque<List*>::iterator for_2 = deq.begin();
while (for_2 != deq.end())
{
for_2 = find_if(for_2, deq.end(), [&](List* object) {return object->showFirst() == val; });
if (for_2 != deq.end())
{
kol_in_deq++;
for_2++;
}
}
cout << kol_in_deq << "\n";
}
cout << "_______string_________" << endl;
string s_param("lococb");
string copyr(s_param);
string bez_param;
string s_ciklom(5, 'H');
cout << "без параметров: " <<
bez_param << endl
<< "с параметрами: " <<
s_param << endl
<< "копирования: " <<
copyr << endl
<< "с зацикливанием константы: " <<
s_ciklom << endl;
cout << typeid(s_param.c_str()).name() << endl;
if (bez_param.empty())
cout << "пуст" << endl;
cout << "длина copyr " << copyr.size() << endl;
cout << "_______первый функтор_________" << endl;
struct FirstFunk
{
void operator() (list<List*> obj)
{
for(auto itr = obj.begin(); itr != obj.end(); itr++)
cout << *itr << endl;
}
}showAll;
//
showAll(lst);
list<List*> lst2;
List* element5 = new List; element5->add(5);
list<List*>::iterator head = lst2.begin();
lst2.insert(head,element5);
lst2.insert(head, element1);
cout << "_______второй функтор_________" << endl;
struct SecondFunk
{
bool operator() (list<List*> obj, list<List*> obj2)
{
list<List*>::iterator it = obj.begin();
list<List*>::iterator it2 = obj2.begin();
bool answer = true;
for (; it != obj.end() && it2 != obj2.end(); it++, it2++) {
if (*it != *it2)
answer = false;
}
return answer;
}
}Compare;
cout << "сравнение списков: " << Compare(lst, lst);
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "DoorInteractorComponent.h"
#include "Door1.h"
bool UDoorInteractorComponent::Interact(UObjectInfo* info) {
ADoor1* owner = (ADoor1*)GetOwner();
if (owner) {
if (owner->IsLocked) {
owner->PlaySound("locked", owner->GetActorLocation());
return false;
}
else {
owner->FindComponentByClass<UActionComponent>()->DoAction();
return true;
}
}
return false;
}
|
#include <QApplication>
#include <QLabel>
#include <QPixmap>
#include <QPushButton>
#include <QGridLayout>
#include <QHBoxLayout> //horizontal box layout
#include <QVBoxLayout> //vertical box layout
#include <QGroupBox> //group radio buttons
#include <QRadioButton>
#include <QSlider>
#include <QSpinBox>
#include <QString>
#include <QLineEdit>
#include <QFontMetrics>
#include "mainwindow.h"
#include "btree.h"
#include <iostream>
#include <stdlib.h> //for rand()
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
// RsaToolbox includes
#include "VnaMath.h"
#include "VnaTrace.h"
#include "Vna.h"
using namespace RsaToolbox;
// Qt includes
// #include <QDebug>
VnaMath::VnaMath(QObject *parent) :
QObject(parent)
{
placeholder.reset(new Vna());
_vna = placeholder.data();
_trace.reset(new VnaTrace());
_channel = 0;
}
VnaMath::VnaMath(const VnaMath &other) :
QObject(other.parent())
{
if (other.isFullyInitialized()) {
_vna = other._vna;
_trace.reset(new VnaTrace(*other._trace.data()));
_channel = other._channel;
}
else {
placeholder.reset(new Vna());
_vna = placeholder.data();
_trace.reset(new VnaTrace());
_channel = 0;
}
}
VnaMath::VnaMath(Vna *vna, VnaTrace *trace, QObject *parent) :
QObject(parent)
{
_vna = vna;
_trace.reset(new VnaTrace(*trace));
_channel= trace->channel();
}
VnaMath::VnaMath(Vna *vna, QString traceName, QObject *parent) :
QObject(parent)
{
_vna = vna;
_trace.reset(new VnaTrace(vna, traceName));
_channel = _trace->channel();
}
VnaMath::~VnaMath() {
}
bool VnaMath::isOn() {
QString scpi = ":CALC%1:MATH:STAT?\n";
scpi = scpi.arg(_channel);
_trace->select();
return _vna->query(scpi).trimmed() == "1";
}
bool VnaMath::isOff() {
return !isOn();
}
void VnaMath::on(bool isOn) {
QString scpi = ":CALC%1:MATH:STAT %2\n";
scpi = scpi.arg(_channel);
if (isOn)
scpi = scpi.arg(1);
else
scpi = scpi.arg(0);
_trace->select();
_vna->write(scpi);
}
void VnaMath::off(bool isOff) {
on(!isOff);
}
bool VnaMath::isWaveQuantity() {
QString scpi = ":CALC%1:MATH:WUN?\n";
scpi = scpi.arg(_trace->channel());
_trace->select();
return _vna->query(scpi).trimmed() == "1";
}
void VnaMath::setWaveQuantity(bool isOn) {
QString scpi = ":CALC%1:MATH:WUN %2\n";
scpi = scpi.arg(_trace->channel());
if (isOn)
scpi = scpi.arg(1);
else
scpi = scpi.arg(0);
_trace->select();
_vna->write(scpi);
}
QString VnaMath::expression() {
QString scpi = ":CALC%1:MATH:SDEF?\n";
scpi = scpi.arg(_channel);
_trace->select();
return _vna->query(scpi).trimmed().remove("\'");
}
void VnaMath::setExpression(QString expression) {
QString scpi = ":CALC%1:MATH:SDEF \'%2\'\n";
scpi = scpi.arg(_channel);
scpi = scpi.arg(expression);
_trace->select();
_vna->write(scpi);
}
void VnaMath::divideBy(QString trace) {
QString exp = "%1 / %2";
exp = exp.arg(_trace->name());
exp = exp.arg(trace);
setExpression(exp);
on();
}
void VnaMath::operator=(VnaMath const &other) {
if (other.isFullyInitialized()) {
_vna = other._vna;
_trace.reset(new VnaTrace(other._trace.data()));
_channel = other._channel;
}
else {
placeholder.reset(new Vna());
_vna = placeholder.data();
_trace.reset(new VnaTrace());
_channel = 0;
}
}
// Private
bool VnaMath::isFullyInitialized() const {
if (_vna == NULL)
return(false);
if (_vna == placeholder.data())
return(false);
//else
return(true);
}
|
/*******************************************************************\
Module:
Author: CM Wintersteiger
\*******************************************************************/
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#include <direct.h>
#endif
#include <stdlib.h>
#include <string.h>
#ifdef __MACH__
#include <unistd.h>
#endif
#ifdef __linux__
#include <unistd.h>
#endif
#include "tempdir.h"
#include "file_util.h"
/*******************************************************************\
Function: get_temporary_directory
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string get_temporary_directory(const std::string &name_template)
{
std::string result;
#ifdef _WIN32
DWORD dwBufSize = MAX_PATH;
char lpPathBuffer[MAX_PATH];
DWORD dwRetVal = GetTempPath(dwBufSize, lpPathBuffer);
if(dwRetVal > dwBufSize || (dwRetVal == 0))
throw "GetTempPath failed";
char t[MAX_PATH];
strncpy(t, name_template.c_str(), MAX_PATH);
UINT uRetVal=GetTempFileName(lpPathBuffer, "TLO", 0, t);
if(uRetVal == 0)
throw "GetTempFileName failed";
unlink(t);
if(_mkdir(t)!=0)
throw "_mkdir failed";
result=std::string(t);
#else
char t[1000];
strncpy(t, ("/tmp/"+name_template).c_str(), 1000);
const char *td = mkdtemp(t);
if(!td) throw "mkdtemp failed";
result=std::string(td);
#endif
return result;
}
/*******************************************************************\
Function: temp_dirt::temp_dirt
Inputs:
Outputs:
Purpose:
\*******************************************************************/
temp_dirt::temp_dirt(const std::string &name_template)
{
path=get_temporary_directory(name_template);
}
/*******************************************************************\
Function: temp_dirt::operator()
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string temp_dirt::operator()(const std::string &file)
{
#ifdef _WIN32
return path+"\\"+file;
#else
return path+"/"+file;
#endif
}
/*******************************************************************\
Function: temp_dirt::~temp_dirt
Inputs:
Outputs:
Purpose:
\*******************************************************************/
temp_dirt::~temp_dirt()
{
delete_directory(path);
}
/*******************************************************************\
Function: temp_working_dirt::temp_working_dirt
Inputs:
Outputs:
Purpose:
\*******************************************************************/
temp_working_dirt::temp_working_dirt(const std::string &name_template):
temp_dirt(name_template)
{
old_working_directory=get_current_working_directory();
chdir(path.c_str());
}
/*******************************************************************\
Function: temp_working_dirt::~temp_working_dirt
Inputs:
Outputs:
Purpose:
\*******************************************************************/
temp_working_dirt::~temp_working_dirt()
{
chdir(old_working_directory.c_str());
}
|
class ItemPickaxe : ItemCore
{
scope = 2;
model = "z\addons\dayz_communityweapons\models\pickaxe\pickaxe.p3d";
picture = "\z\addons\dayz_communityweapons\models\pickaxe\pickaxe.paa";
displayName = $STR_EQUIP_NAME_PICKAXE;
descriptionShort = $STR_EQUIP_DESC_PICKAXE;
class ItemActions
{
class Use
{
text = $STR_ACTIONS_MINE_STONE;
script = "spawn player_mineStone;";
};
};
};
class ItemPickaxeBroken : ItemCore
{
scope = 2;
model = "z\addons\dayz_communityweapons\models\pickaxe\pickaxe.p3d";
picture = "\dayz_epoch_c\icons\tools\ItemPickaxeBroken.paa";
displayName = $STR_name_ItemPickaxeBroken;
descriptionShort = $STR_desc_ItemPickaxeBroken;
class ItemActions
{
class Repair
{
text = $STR_ACTIONS_FIX_PICKAXE;
script = ";['Repair','CfgWeapons', _id] spawn player_craftItem;";
neednearby[] = {};
requiretools[] = {};
output[] = {};
outputweapons[] = {"ItemPickaxe"};
input[] = {{"equip_duct_tape",1},{"equip_lever",1}};
inputweapons[] = {"ItemPickaxeBroken"};
};
};
};
|
#include <iostream>
#include <stdlib.h>
#define MAXF 50
#define MAXC 50
using namespace std;
void imprimeMatriz(unsigned int W[MAXF][MAXC], unsigned int m);
void imprimeMatrizStr(string W[MAXF][MAXC], unsigned int m);
void leeMatriz(unsigned int W[MAXF][MAXC], unsigned int m);
int main()
{
char c = 164;
unsigned int i, j, m, k,
W[MAXF][MAXC],
Q[MAXF][MAXC];
string Wrec[MAXF][MAXC], //Matrices de recorridos
Qrec[MAXF][MAXC];
cout << "Ingresa el tama" << c << "o de la matriz de pesos (matriz cuadrada mxm): ";
cin >> m;
cout << "Ingresa la matriz de pesos:" << endl;
leeMatriz(W,m);
system("cls");
//Imprime matriz de pesos
cout << "Matriz W=" << endl;
imprimeMatriz(W, m);
//Genera matriz Q
for(i=0; i<m; i++){
for(j=0; j<m; j++){
if(W[i][j] == 0)
Q[i][j] = 2147483647;
else
Q[i][j] = W[i][j];
}
}
//Inicializar matriz Q de recorridos
for(i=0; i<m; i++){
for(j=0; j<m; j++){
Qrec[i][j] = "";
}
}
//Genera matriz Q de recorridos
for(i=0; i<m; i++){
for(j=0; j<m; j++){
if(Q[i][j] < 2147483647){
if(i == 0)
Qrec[i][j] = Qrec[i][j] + "R";
if(i == 1)
Qrec[i][j] = Qrec[i][j] + "S";
if(i == 2)
Qrec[i][j] = Qrec[i][j] + "T";
if(i == 3)
Qrec[i][j] = Qrec[i][j] + "U";
if(j == 0)
Qrec[i][j] = Qrec[i][j] + "R";
if(j == 1)
Qrec[i][j] = Qrec[i][j] + "S";
if(j == 2)
Qrec[i][j] = Qrec[i][j] + "T";
if(j == 3)
Qrec[i][j] = Qrec[i][j] + "U";
}
else
Qrec[i][j] = Qrec[i][j] + "";
}
}
//Imprime matriz Q
cout << endl << endl << "Matriz Q_0=" << endl;
imprimeMatriz(Q,m);
//Comparaciones
for(k=0; k<m; k++){
for(i=0; i<m; i++){
for(j=0; j<m; j++)
Q[i][j] = min(Q[i][j], Q[i][k]+Q[k][j]);
}
cout << endl << "Matriz Q_" << k+1 << "=" << endl;
imprimeMatriz(Q,m);
}
//Imprime matriz Q de recorridos
cout << endl << "Matriz Q de recorridos:" << endl;
imprimeMatrizStr(Qrec,m);
}
void leeMatriz(unsigned int W[MAXF][MAXC], unsigned int m){
for(unsigned int i=0; i<m; i++){
for(unsigned int j=0; j<m; j++){
cout << "Ingresa elemento [" << i+1 << "][" << j+1 <<"] ";
cin >> W[i][j];
}
}
}
void imprimeMatriz(unsigned int W[MAXF][MAXC], unsigned int m){
char c = 145;
for(unsigned int i=0; i<m; i++){
for(unsigned int j=0; j<m; j++){
if(W[i][j] > 2147483646)
cout << "\t" << "INF" << "\t";
else
cout << "\t" << W[i][j] << "\t";
}
cout << endl;
}
}
void imprimeMatrizStr(string W[MAXF][MAXC], unsigned int m){
for(unsigned int i=0; i<m; i++){
for(unsigned int j=0; j<m; j++){
if(W[i][j] != "")
cout << "\t" << W[i][j] << "\t";
else
cout << "\t" << "-" << "\t";
}
cout << endl;
}
}
|
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
#include <ctime>
#include <cstdlib>
#include <curses.h>
bool** genGrid (int rows, int cols)
{
bool** grid = 0;
grid = new bool*[rows];
srand(time(0));
for (int i = 0; i < rows; i++)
{
grid[i] = new bool[cols];
for (int j = 0; j < cols; j++)
{
if ( rand() % 100 < 25 ) grid[i][j] = false;
else grid[i][j] = true;
}
}
return grid;
}
bool** genGridGliderGun (int rows, int cols)
{
bool **grid = 0;
grid = new bool*[rows];
bool gL[rows][cols] = {
{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true},
{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,false,true},
{false,false,false,false,false,false,false,false,false,false,false,false,true,true,false,false,false,false,false,false,true,true,false,false,false,false,false,false,false,false,false,false,false,false,true,true},
{false,false,false,false,false,false,false,false,false,false,false,true,false,false,false,true,false,false,false,false,true,true,false,false,false,false,false,false,false,false,false,false,false,false,true,true},
{true,true,false,false,false,false,false,false,false,false,true,false,false,false,false,false,true,false,false,false,true,true},
{true,true,false,false,false,false,false,false,false,false,true,false,false,false,true,false,true,true,false,false,false,false,true,false,true},
{false,false,false,false,false,false,false,false,false,false,true,false,false,false,false,false,true,false,false,false,false,false,false,false,true},
{false,false,false,false,false,false,false,false,false,false,false,true,false,false,false,true},
{false,false,false,false,false,false,false,false,false,false,false,false,true,true},
};
for (int i = 0; i < rows; i++)
{
grid[i] = new bool[cols];
for (int j = 0; j < cols; j++)
{
if (gL[i][j]) grid[i][j] = true;
else grid[i][j] = false;
}
}
return grid;
}
void delGrid(bool** grid, int rows)
{
for (int i = 0; i < rows; i++) delete [] grid[i];
delete [] grid;
grid = 0;
}
bool** stepGrid (bool** grid, int rows, int cols)
{
bool **newGrid;
newGrid = new bool*[rows];
for (int i = 0; i < rows; i++)
{
newGrid[i] = new bool[cols];
for (int j = 0; j < cols; j++)
{
int lN = 0; //live neighbor counter
//Check states for neighboring cells
if (i != 0)
{
if (grid[i-1][j]) lN++;
if (j != 0 && grid[i-1][j-1]) lN++;
if (j != cols-1 && grid[i-1][j+1]) lN++;
}
if (i != rows-1)
{
if (grid[i+1][j]) lN++;
if (j != 0 && grid[i+1][j-1]) lN++;
if (j != cols-1 && grid[i+1][j+1]) lN++;
}
if (j != 0 && grid[i][j-1]) lN++;
if (j != cols-1 && grid[i][j+1]) lN++;
//Determine state of this cell
if (grid[i][j])
{
if (lN < 2 || lN > 3) newGrid[i][j] = false;
else newGrid[i][j] = true;
}
else
{
if (lN == 3) newGrid[i][j] = true;
else newGrid[i][j] = false;
}
//printw("[%d,%d]: %d\n", i, j, lN);
}
}
delGrid(grid, rows);
return newGrid;
}
void printGrid (bool** grid, int rows, int cols)
{
erase();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (grid[i][j]) mvprintw(i, j, "0");
//grid[i][j] ? printw("0") : printw(" ");// printw("■") : printw(" ");
}
//printw("\n");
}
refresh();
}
bool **gridCp (bool **origGrid, int rows, int cols)
{
bool **grid;
grid = new bool*[rows];
for (int i = 0; i < rows; i++)
{
grid[i] = new bool[cols];
for (int j = 0; j < cols; j++)
{
grid[i][j] = origGrid[i][j];
}
}
return grid;
}
bool sameGrid (bool** lGrid, bool** curGrid, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (lGrid[i][j] != curGrid[i][j]) return false;
}
}
return true;
}
int main (int argc, char **argv)
{
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
int rows = w.ws_row, cols = w.ws_col;
int generation = 0;
bool** lastGrid, **llGrid, **lllGrid, **llllGrid, **curGrid = genGrid(rows, cols);
WINDOW *win = initscr();
idlok(win, true);
printGrid(curGrid, rows, cols);
while (1)
{
if (generation > 3)
{
if (generation > 5) delGrid(lllGrid, rows);// llllGrid = gridCp(lllGrid,rows,cols);
if (generation > 4)
{
lllGrid = gridCp(curGrid, rows, cols);
delGrid(llGrid, rows);
}
llGrid = gridCp(lastGrid,rows,cols);
delGrid(lastGrid, rows);
}
lastGrid = gridCp(curGrid,rows,cols);
curGrid = stepGrid(curGrid, rows, cols);
generation ++;
printGrid(curGrid, rows, cols);
if (sameGrid(lastGrid, curGrid, rows, cols)) {
delGrid(curGrid, rows);
curGrid = genGrid(rows, cols);
generation = 0;
}
else if (generation > 10)
{
if (sameGrid(llGrid,curGrid, rows, cols))
{
delGrid(curGrid, rows);
curGrid = genGrid(rows, cols);
generation = 0;
}
if (sameGrid(lllGrid, curGrid, rows, cols))
{
delGrid(curGrid, rows);
curGrid = genGrid(rows,cols);
generation = 0;
}
/*if (sameGrid(llllGrid, curGrid, rows, cols))
{
curGrid = genGrid(rows,cols);
generation = 0;
}*/
}
//sleep(1);
//usleep(10000);
}
return 0; // make sure your main returns int
}
|
// Copyright (c) 2018 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BSplCLib_CacheParams_Headerfile
#define _BSplCLib_CacheParams_Headerfile
#include <BSplCLib.hxx>
//! Simple structure containing parameters describing parameterization
//! of a B-spline curve or a surface in one direction (U or V),
//! and data of the current span for its caching
struct BSplCLib_CacheParams
{
const Standard_Integer Degree; ///< degree of Bezier/B-spline
const Standard_Boolean IsPeriodic; ///< true of the B-spline is periodic
const Standard_Real FirstParameter; ///< first valid parameter
const Standard_Real LastParameter; ///< last valid parameter
const Standard_Integer SpanIndexMin; ///< minimal index of span
const Standard_Integer SpanIndexMax; ///< maximal index of span
Standard_Real SpanStart; ///< parameter for the frst point of the span
Standard_Real SpanLength; ///< length of the span
Standard_Integer SpanIndex; ///< index of the span
//! Constructor, prepares data structures for caching.
//! \param theDegree degree of the B-spline (or Bezier)
//! \param thePeriodic identify whether the B-spline is periodic
//! \param theFlatKnots knots of Bezier / B-spline parameterization
BSplCLib_CacheParams (Standard_Integer theDegree, Standard_Boolean thePeriodic,
const TColStd_Array1OfReal& theFlatKnots)
: Degree(theDegree),
IsPeriodic(thePeriodic),
FirstParameter(theFlatKnots.Value(theFlatKnots.Lower() + theDegree)),
LastParameter(theFlatKnots.Value(theFlatKnots.Upper() - theDegree)),
SpanIndexMin(theFlatKnots.Lower() + theDegree),
SpanIndexMax(theFlatKnots.Upper() - theDegree - 1),
SpanStart(0.),
SpanLength(0.),
SpanIndex(0)
{}
//! Normalizes the parameter for periodic B-splines
//! \param theParameter the value to be normalized into the knots array
Standard_Real PeriodicNormalization (Standard_Real theParameter) const
{
if (IsPeriodic)
{
if (theParameter < FirstParameter)
{
Standard_Real aPeriod = LastParameter - FirstParameter;
Standard_Real aScale = IntegerPart ((FirstParameter - theParameter) / aPeriod);
return theParameter + aPeriod * (aScale + 1.0);
}
if (theParameter > LastParameter)
{
Standard_Real aPeriod = LastParameter - FirstParameter;
Standard_Real aScale = IntegerPart ((theParameter - LastParameter) / aPeriod);
return theParameter - aPeriod * (aScale + 1.0);
}
}
return theParameter;
}
//! Verifies validity of the cache using flat parameter of the point
//! \param theParameter parameter of the point placed in the span
Standard_Boolean IsCacheValid (Standard_Real theParameter) const
{
Standard_Real aNewParam = PeriodicNormalization (theParameter);
Standard_Real aDelta = aNewParam - SpanStart;
return ((aDelta >= 0.0 || SpanIndex == SpanIndexMin) &&
(aDelta < SpanLength || SpanIndex == SpanIndexMax));
}
//! Computes span for the specified parameter
//! \param theParameter parameter of the point placed in the span
//! \param theFlatKnots knots of Bezier / B-spline parameterization
void LocateParameter (Standard_Real& theParameter, const TColStd_Array1OfReal& theFlatKnots)
{
SpanIndex = 0;
BSplCLib::LocateParameter (Degree, theFlatKnots, BSplCLib::NoMults(),
theParameter, IsPeriodic, SpanIndex, theParameter);
SpanStart = theFlatKnots.Value(SpanIndex);
SpanLength = theFlatKnots.Value(SpanIndex + 1) - SpanStart;
}
private:
// copying is prohibited
BSplCLib_CacheParams (const BSplCLib_CacheParams&);
void operator = (const BSplCLib_CacheParams&);
};
#endif
|
#ifndef DIALOG_H
#define DIALOG_H
#include <QMessageBox>
#include <QPushButton>
#include <QLabel>
class MessageBox : public QMessageBox
{
public:
MessageBox(QString message);
~MessageBox();
private:
QPushButton *button_dialog;
QLabel *label_dialog;
};
#endif // DIALOG_H
|
#pragma once
#include <iberbar/RHI/Types.h>
#include <iberbar/RHI/OpenGL/Headers.h>
namespace iberbar
{
namespace RHI
{
namespace OpenGL
{
void ConvertVertexFormat( UVertexFormat nFormat, uint32* pnSize, GLenum* pnType );
GLenum ConvertPrimitiveType( UPrimitiveType nPrimitiveType );
GLenum ConvertIndexFormat( UIndexFormat nIndexFormat );
void ConvertVertexAttrName( std::string& str, UVertexDeclareUsage nSemantic, uint32 nSemanticIndex );
GLuint ConvertTextureFilterType( UTextureFilterType nFilterType );
GLuint ConvertTextureAddress( UTextureAddress nAddress );
GLsizei GetDataTypeSize( GLenum size );
}
}
}
inline void iberbar::RHI::OpenGL::ConvertVertexFormat( UVertexFormat nFormat, uint32* pnSize, GLenum* pnType )
{
switch ( nFormat )
{
case UVertexFormat::FLOAT:
*pnSize = 1;
*pnType = GL_FLOAT;
break;
case UVertexFormat::FLOAT2:
*pnSize = 2;
*pnType = GL_FLOAT;
break;
case UVertexFormat::FLOAT3:
*pnSize = 3;
*pnType = GL_FLOAT;
break;
case UVertexFormat::FLOAT4:
*pnSize = 4;
*pnType = GL_FLOAT;
break;
case UVertexFormat::UBYTE4:
*pnSize = 4;
*pnType = GL_UNSIGNED_BYTE;
break;
case UVertexFormat::COLOR:
*pnSize = 4;
*pnType = GL_UNSIGNED_BYTE;
break;
default:
break;
}
}
inline GLenum iberbar::RHI::OpenGL::ConvertPrimitiveType( UPrimitiveType nPrimitiveType )
{
switch ( nPrimitiveType )
{
case UPrimitiveType::Point:
return GL_POINTS;
case UPrimitiveType::Line:
return GL_LINES;
case UPrimitiveType::LineStrip:
return GL_LINE_STRIP;
case UPrimitiveType::Triangle:
return GL_TRIANGLES;
case UPrimitiveType::TriangleStrip:
return GL_TRIANGLE_STRIP;
default:
break;
}
return 0;
}
inline GLenum iberbar::RHI::OpenGL::ConvertIndexFormat( UIndexFormat nIndexFormat )
{
switch ( nIndexFormat )
{
case UIndexFormat::U_Int:
return GL_UNSIGNED_INT;
case UIndexFormat::U_Short:
return GL_UNSIGNED_SHORT;
default:
break;
}
return GL_BYTE;
}
inline void iberbar::RHI::OpenGL::ConvertVertexAttrName( std::string& str, UVertexDeclareUsage nSemantic, uint32 nSemanticIndex )
{
switch ( nSemantic )
{
case UVertexDeclareUsage::Position:
str = "a_position";
break;
case UVertexDeclareUsage::Normal:
str = "a_normal";
break;
case UVertexDeclareUsage::Color:
str = "a_color";
break;
case UVertexDeclareUsage::TexCoord:
str = "a_texcoord";
break;
default:
break;
}
if ( nSemanticIndex > 0 )
{
str += nSemanticIndex;
}
}
inline GLuint iberbar::RHI::OpenGL::ConvertTextureFilterType( UTextureFilterType nFilterType )
{
switch ( nFilterType )
{
case UTextureFilterType::Point:
return GL_NEAREST;
case UTextureFilterType::Linear:
return GL_LINEAR;
default:break;
}
return GL_LINEAR;
}
inline GLuint iberbar::RHI::OpenGL::ConvertTextureAddress( UTextureAddress nAddress )
{
switch ( nAddress )
{
case UTextureAddress::Wrap:
return GL_REPEAT;
case UTextureAddress::Clamp:
#ifdef _WIN32
return GL_CLAMP;
#endif
#ifdef __ANDROID__
return GL_CLAMP_TO_EDGE;
#endif
default:break;
}
return GL_REPEAT;
}
inline GLsizei iberbar::RHI::OpenGL::GetDataTypeSize( GLenum size )
{
GLsizei ret = 0;
switch ( size )
{
case GL_BOOL:
case GL_BYTE:
case GL_UNSIGNED_BYTE:
ret = sizeof( GLbyte );
break;
case GL_BOOL_VEC2:
case GL_SHORT:
case GL_UNSIGNED_SHORT:
ret = sizeof( GLshort );
break;
case GL_BOOL_VEC3:
ret = sizeof( GLboolean );
break;
case GL_BOOL_VEC4:
case GL_INT:
case GL_UNSIGNED_INT:
case GL_FLOAT:
ret = sizeof( GLfloat );
break;
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
ret = sizeof( GLfloat ) * 2;
break;
case GL_FLOAT_VEC3:
case GL_INT_VEC3:
ret = sizeof( GLfloat ) * 3;
break;
case GL_FLOAT_MAT2:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
ret = sizeof( GLfloat ) * 4;
break;
case GL_FLOAT_MAT3:
ret = sizeof( GLfloat ) * 9;
break;
case GL_FLOAT_MAT4:
ret = sizeof( GLfloat ) * 16;
break;
default:
break;
}
return ret;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.