text
stringlengths 8
6.88M
|
|---|
#include "scene.hpp"
#include "config/utils.hpp"
#include "log.hpp"
#include "config/options_ptts.hpp"
#include "proto/ss_common_resource.pb.h"
#include "utils/client_process_mgr.hpp"
#include "config/recharge_ptts.hpp"
namespace nora {
namespace common_resource {
using scene_mgr = client_process_mgr<scene>;
shared_ptr<db::connector> scene::db_;
map<string, scene::fanli> scene::username2fanli_;
map<string, scene::back> scene::come_backs_;
function<void()> scene::done_cb_;
string scene::base_name() {
return "scene";
}
scene::scene(const string& conn_name) : name_("common_resource-scene-" + conn_name) {
}
void scene::static_init(const shared_ptr<service_thread>& st) {
register_proto_handler(ps::s2cr_lock_fanli_req::descriptor(), &scene::process_lock_fanli_req);
register_proto_handler(ps::s2cr_remove_fanli::descriptor(), &scene::process_remove_fanli);
register_proto_handler(ps::s2cr_lock_come_back_req::descriptor(), &scene::process_lock_come_back_req);
register_proto_handler(ps::s2cr_remove_come_back::descriptor(), &scene::process_remove_come_back);
PTTS_LOAD(recharge);
auto ptt = PTTS_GET_COPY(options, 1);
db_ = make_shared<db::connector>(ptt.common_resource_info().db().ipport(),
ptt.common_resource_info().db().user(),
ptt.common_resource_info().db().password(),
ptt.common_resource_info().db().database());
db_->start();
ASSERT(st);
auto shandang_db_msg = make_shared<db::message>("load_shandang_fanli",
db::message::req_type::rt_select,
[] (const shared_ptr<db::message>& msg) {
auto& results = msg->results();
for (const auto& i : results) {
ASSERT(i.size() == 2);
auto username = boost::any_cast<string>(i[0]);
auto recharge_id = boost::any_cast<string>(i[1]);
for (const auto& i : PTTS_GET_ALL(recharge)) {
if (i.second.yunying_id() == recharge_id) {
if (username2fanli_.count(username) <= 0 ) {
username2fanli_[username].recharge_id2count_[i.second.id()] = 1;
} else {
if (username2fanli_[username].recharge_id2count_.count(i.second.id()) <= 0) {
username2fanli_.at(username).recharge_id2count_[i.second.id()] = 1;
} else {
username2fanli_.at(username).recharge_id2count_[i.second.id()] += 1;
}
}
}
}
}
done_cb_();
});
db_->push_message(shandang_db_msg, st);
auto cb_db_msg = make_shared<db::message>("load_come_back",
db::message::req_type::rt_select,
[] (const shared_ptr<db::message>& msg) {
auto& results = msg->results();
for (const auto& i : results) {
ASSERT(i.size() == 1);
come_backs_[boost::any_cast<string>(i[0])];
}
done_cb_();
});
db_->push_message(cb_db_msg, st);
}
void scene::process_lock_fanli_req(const ps::base *msg) {
const auto& req = msg->GetExtension(ps::s2cr_lock_fanli_req::slfr);
proto::ss::base rsp_msg;
auto *rsp = rsp_msg.MutableExtension(ps::cr2s_lock_fanli_rsp::clfr);
auto result = pd::OK;
do {
auto iter = username2fanli_.find(req.username());
if (iter == username2fanli_.end()) {
result = pd::FANLI_NO_FANLI;
break;
}
auto& fanli = iter->second;
if (!fanli.locked_by_.empty() && fanli.locked_by_ != req.username()) {
result = pd::FANLI_LOCKED_BY_OTHER;
break;
}
fanli.locked_by_ = req.username();
auto *fanli_array = rsp->mutable_fanlis();
for (const auto& i : fanli.recharge_id2count_) {
auto *fanlis = fanli_array->add_fanlis();
fanlis->set_recharge(i.first);
fanlis->set_count(i.second);
}
if (!fanli.lock_timer_) {
fanli.lock_timer_ = ADD_TIMER(
st_,
([this, username = req.username()] (auto canceled, const auto& timer) {
auto iter = username2fanli_.find(username);
if (iter == username2fanli_.end()) {
return;
}
auto& fanli = iter->second;
if (fanli.lock_timer_ == timer) {
fanli.lock_timer_.reset();
}
if (!canceled) {
fanli.locked_by_.clear();
}
}),
5s);
}
} while (false);
rsp->set_username(req.username());
rsp->set_result(result);
scene_mgr::instance().send_msg(id(), rsp_msg);
}
void scene::process_remove_fanli(const ps::base *msg) {
const auto& req = msg->GetExtension(ps::s2cr_remove_fanli::srf);
auto iter = username2fanli_.find(req.username());
ASSERT(iter != username2fanli_.end());
auto& fanli = iter->second;
if (fanli.locked_by_ != req.username()) {
return;
}
ASSERT(fanli.lock_timer_);
fanli.lock_timer_->cancel();
fanli.lock_timer_.reset();
username2fanli_.erase(req.username());
ASSERT(db_);
auto db_msg = make_shared<db::message>("delete_shandang_fanli", db::message::req_type::rt_update);
db_msg->push_param(req.username());
db_->push_message(db_msg);
}
void scene::process_lock_come_back_req(const ps::base *msg) {
const auto& req = msg->GetExtension(ps::s2cr_lock_come_back_req::slcbr);
proto::ss::base rsp_msg;
auto *rsp = rsp_msg.MutableExtension(ps::cr2s_lock_come_back_rsp::clcbr);
auto result = pd::OK;
do {
auto iter = come_backs_.find(req.username());
if (iter == come_backs_.end()) {
result = pd::COME_BACK_NO_COME_BACK;
break;
}
auto& back = iter->second;
if (!back.locked_by_.empty() && back.locked_by_ != req.username()) {
result = pd::COME_BACK_LOCKED_BY_OTHER;
break;
}
back.locked_by_ = req.username();
if (!back.lock_timer_) {
back.lock_timer_ = ADD_TIMER(
st_,
([this, username = req.username()] (auto canceled, const auto& timer) {
auto iter = come_backs_.find(username);
if (iter == come_backs_.end()) {
return;
}
auto& back = iter->second;
if (back.lock_timer_ == timer) {
back.lock_timer_.reset();
}
if (!canceled) {
back.locked_by_.clear();
}
}),
5s);
}
} while (false);
rsp->set_username(req.username());
rsp->set_result(result);
scene_mgr::instance().send_msg(id(), rsp_msg);
}
void scene::process_remove_come_back(const ps::base *msg) {
const auto& req = msg->GetExtension(ps::s2cr_remove_come_back::srcb);
auto iter = come_backs_.find(req.username());
ASSERT(iter != come_backs_.end());
auto& back = iter->second;
if (back.locked_by_ != req.username()) {
return;
}
ASSERT(back.lock_timer_);
back.lock_timer_->cancel();
back.lock_timer_.reset();
come_backs_.erase(req.username());
ASSERT(db_);
auto db_msg = make_shared<db::message>("delete_come_back", db::message::req_type::rt_update);
db_msg->push_param(req.username());
db_->push_message(db_msg);
}
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
int soundex(char k){
string str[6] = {"BFPV","CGJKQSXZ","DT","L","MN","R"};
for(int i = 0 ; i < 6 ; i++)
for(int j = 0 ; j < str[i].size() ; j++ )
if( k == str[i][j] )
return i+1;
return 0;
}
int main(int argc, char const *argv[])
{
string str;
int pre,now;
while( cin >> str ){
pre = 0;
for(int i = 0; i < str.size() ; i++ ){
int tmp = soundex(str[i]);
if( tmp != pre && tmp != 0 )
printf("%d",tmp);
pre = tmp;
}
printf("\n");
}
return 0;
}
|
#pragma once
#include <vector>
#include "stringview.h"
namespace json {
///JSON is often full of enums. To easy convert enum to string and vice versa, you can use this class
/**
* To use this class, you need to define table where each row has enum value and string value. This
* table must be used to construct NamedEnum instance. The object act as associative array. You
* can easily pick value by string or string by value
*/
template<typename EnumType>
class NamedEnum {
public:
struct Def {
EnumType val;
StrViewA name;
};
template<std::size_t N>
NamedEnum(const Def(&x)[N]) {
byVal.reserve(N);
byName.reserve(N);
for (auto v : x) {
byVal.push_back(v);
byName.push_back(v);
}
std::sort(byVal.begin(), byVal.end(), &cmpByVal);
std::sort(byName.begin(), byName.end(), &cmpByName);
}
EnumType operator[](const StrViewA &name) const;
StrViewA operator[](EnumType val) const;
const EnumType *find(const StrViewA &name) const;
typename std::vector<Def>::const_iterator begin() const {return byName.begin();}
typename std::vector<Def>::const_iterator end() const {return byName.end();}
std::size_t size() const {return byName.size();}
std::string allEnums(StrViewA separator=", ") const;
protected:
std::vector<Def> byVal;
std::vector<Def> byName;
static bool cmpByVal(const Def &a, const Def &b) {
return a.val < b.val;
}
static bool cmpByName(const Def &a, const Def &b) {
return a.name < b.name;
}
};
class UnknownEnumException: public std::exception {
public:
UnknownEnumException(std::string &&errorEnum, std::vector<StrViewA> &&availableEnums);
virtual const char *what() const throw();
const std::string& getErrorEnum() const {
return errorEnum;
}
const std::vector<StrViewA>& getListEnums() const {
return listEnums;
}
protected:
mutable std::string whatMsg;
std::vector<StrViewA> listEnums;
std::string errorEnum;
};
template<typename EnumType>
inline EnumType NamedEnum<EnumType>::operator [](const StrViewA &name) const {
Def d;
d.name = name;
auto f = std::lower_bound(byName.begin(), byName.end(), d, &cmpByName);
if (f == byName.end() || f->name != name) {
std::vector<StrViewA> lst;
lst.reserve(byName.size());
for (auto &x:byName) lst.push_back(x.name);
throw UnknownEnumException(std::string(name.data,name.length),std::move(lst));
}
else {
return f->val;
}
}
template<typename EnumType>
inline const EnumType *NamedEnum<EnumType>::find(const StrViewA &name) const {
Def d;
d.name = name;
auto f = std::lower_bound(byName.begin(), byName.end(), d, &cmpByName);
if (f == byName.end() || f->name != name) {
return nullptr;
}
else {
return &f->val;
}
}
template<typename EnumType>
inline StrViewA NamedEnum<EnumType>::operator [](EnumType val) const {
Def d;
d.val=val;
auto f = std::lower_bound(byVal.begin(), byVal.end(), d, &cmpByVal);
if (f == byVal.end() || f->val != val) return StrViewA();
else return f->name;
}
}
template<typename EnumType>
inline std::string json::NamedEnum<EnumType>::allEnums(StrViewA separator) const {
std::size_t needsz=0;
for (auto &x : byName) needsz+=x.name.length;
needsz += separator.length*byName.size();
std::string res;
res.reserve(needsz);
StrViewA cursep;
for (auto &x : byName) {
res.append(cursep.data,cursep.length);
res.append(x.name.data, x.name.length);
cursep = separator;
}
return cursep;
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Bryce Lelbach
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <pika/config.hpp>
#include <pika/runtime/state.hpp>
#include <pika/threading_base/scheduler_state.hpp>
namespace pika::threads {
// return whether thread manager is in the state described by 'mask'
PIKA_EXPORT bool thread_manager_is(runtime_state st);
PIKA_EXPORT bool thread_manager_is_at_least(runtime_state st);
} // namespace pika::threads
|
#include "Connection.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if defined(_MSC_VER)
#include <Windows.h>
#include <process.h>
#define LockMutex EnterCriticalSection
#define UnlockMutex LeaveCriticalSection
#else
#include <unistd.h>
#include <pthread.h>
#define LockMutex pthread_mutex_lock
#define UnlockMutex pthread_mutex_unlock
#endif
//Forward declarations
static void setFrame(const LEAP_TRACKING_EVENT *frame) {};
static void setDevice(const LEAP_DEVICE_INFO *deviceProps) {};
//Threading variables
#if defined(_MSC_VER)
HANDLE pollingThread;
CRITICAL_SECTION dataLock;
#else
pthread_t pollingThread;
pthread_mutex_t dataLock;
#endif
Connection::Connection() : buffer(64)
{
//External state
isConnected = false;
//Internal state
isRunning = false;
connectionHandle = NULL;
lastFrame = new LEAP_TRACKING_EVENT();
lastDevice = new LEAP_DEVICE_INFO();
}
Connection::~Connection()
{
delete lastDevice;
delete lastFrame;
if (isRunning)
{
DestroyConnection();
}
}
/**
* Creates the connection handle and opens a connection to the Leap Motion
* service. On success, creates a thread to service the LeapC message pump.
*/
LEAP_CONNECTION* Connection::OpenConnection() {
if (isRunning) {
return &connectionHandle;
}
if (connectionHandle || LeapCreateConnection(NULL, &connectionHandle) == eLeapRS_Success) {
eLeapRS result = LeapOpenConnection(connectionHandle);
if (result == eLeapRS_Success) {
isRunning = true;
#if defined(_MSC_VER)
InitializeCriticalSection(&dataLock);
pollingThread = (HANDLE)_beginthreadex(0, 0, (_beginthreadex_proc_type)&Connection::messageThread, this, 0, 0);
#else
pthread_create(&pollingThread, NULL, serviceMessageLoop, NULL);
#endif
}
}
return &connectionHandle;
}
void Connection::CloseConnection() {
if (!isRunning) {
return;
}
isRunning = false;
LeapCloseConnection(connectionHandle);
#if defined(_MSC_VER)
WaitForSingleObject(pollingThread, INFINITE);
CloseHandle(pollingThread);
#else
pthread_join(pollingThread, NULL);
#endif
}
void Connection::DestroyConnection() {
CloseConnection();
LeapDestroyConnection(connectionHandle);
}
/** Close the connection and let message thread function end. */
void Connection::CloseConnectionHandle(LEAP_CONNECTION* connectionHandle) {
LeapDestroyConnection(*connectionHandle);
setRunning(false);
}
/** Called by serviceMessageLoop() when a connection event is returned by LeapPollConnection(). */
void Connection::handleConnectionEvent(const LEAP_CONNECTION_EVENT *connection_event) {
setConnect(true);
struct Callbacks & call = getCallbacks();
call.on_connection();
}
/** Called by serviceMessageLoop() when a connection lost event is returned by LeapPollConnection(). */
void Connection::handleConnectionLostEvent(const LEAP_CONNECTION_LOST_EVENT *connection_lost_event) {
setConnect(false);
struct Callbacks & call = getCallbacks();
call.on_connection_lost();
}
/**
* Called by serviceMessageLoop() when a device event is returned by LeapPollConnection()
* Demonstrates how to access device properties.
*/
void Connection::handleDeviceEvent(const LEAP_DEVICE_EVENT *device_event) {
LEAP_DEVICE deviceHandle;
//Open device using LEAP_DEVICE_REF from event struct.
eLeapRS result = LeapOpenDevice(device_event->device, &deviceHandle);
if (result != eLeapRS_Success) {
std::cout << "Could not open device " << ResultString(result) << std::endl;
return;
}
//Create a struct to hold the device properties, we have to provide a buffer for the serial string
LEAP_DEVICE_INFO deviceProperties = { sizeof(deviceProperties) };
// Start with a length of 1 (pretending we don't know a priori what the length is).
// Currently device serial numbers are all the same length, but that could change in the future
deviceProperties.serial_length = 1;
deviceProperties.serial = (char*)malloc(deviceProperties.serial_length);
//This will fail since the serial buffer is only 1 character long
// But deviceProperties is updated to contain the required buffer length
result = LeapGetDeviceInfo(deviceHandle, &deviceProperties);
if (result == eLeapRS_InsufficientBuffer) {
//try again with correct buffer size
deviceProperties.serial = (char*)realloc(deviceProperties.serial, deviceProperties.serial_length);
result = LeapGetDeviceInfo(deviceHandle, &deviceProperties);
if (result != eLeapRS_Success) {
std::cout << " to get device info " << ResultString(result) << std::endl;
free(deviceProperties.serial);
return;
}
}
setDevice(&deviceProperties);
struct Callbacks & call = getCallbacks();
call.on_device_found(&deviceProperties);
free(deviceProperties.serial);
LeapCloseDevice(deviceHandle);
}
/** Called by serviceMessageLoop() when a device lost event is returned by LeapPollConnection(). */
void Connection::handleDeviceLostEvent(const LEAP_DEVICE_EVENT *device_event) {
struct Callbacks & call = getCallbacks();
call.on_device_lost();
}
/** Called by serviceMessageLoop() when a device failure event is returned by LeapPollConnection(). */
void Connection::handleDeviceFailureEvent(const LEAP_DEVICE_FAILURE_EVENT *device_failure_event) {
struct Callbacks & call = getCallbacks();
call.on_device_failure(device_failure_event->status, device_failure_event->hDevice);
}
/** Called by serviceMessageLoop() when a tracking event is returned by LeapPollConnection(). */
void Connection::handleTrackingEvent(const LEAP_TRACKING_EVENT *tracking_event, CircularBuffer & buff) {
setFrame(tracking_event); //support polling tracking data from different thread
struct Callbacks & call = getCallbacks();
call.on_frame(tracking_event, buff);
}
/** Called by serviceMessageLoop() when a log event is returned by LeapPollConnection(). */
void Connection::handleLogEvent(const LEAP_LOG_EVENT *log_event) {
struct Callbacks & call = getCallbacks();
call.on_log_message(log_event->severity, log_event->timestamp, log_event->message);
}
/** Called by serviceMessageLoop() when a log event is returned by LeapPollConnection(). */
void Connection::handleLogEvents(const LEAP_LOG_EVENTS *log_events) {
struct Callbacks & call = getCallbacks();
for (int i = 0; i < (int)(log_events->nEvents); i++) {
const LEAP_LOG_EVENT* log_event = &log_events->events[i];
call.on_log_message(log_event->severity, log_event->timestamp, log_event->message);
}
}
/** Called by serviceMessageLoop() when a policy event is returned by LeapPollConnection(). */
void Connection::handlePolicyEvent(const LEAP_POLICY_EVENT *policy_event) {
struct Callbacks & call = getCallbacks();
call.on_policy(policy_event->current_policy);
}
/** Called by serviceMessageLoop() when a config change event is returned by LeapPollConnection(). */
void Connection::handleConfigChangeEvent(const LEAP_CONFIG_CHANGE_EVENT *config_change_event) {
struct Callbacks & call = getCallbacks();
call.on_config_change(config_change_event->requestID, config_change_event->status);
}
/** Called by serviceMessageLoop() when a config response event is returned by LeapPollConnection(). */
void Connection::handleConfigResponseEvent(const LEAP_CONFIG_RESPONSE_EVENT *config_response_event) {
struct Callbacks & call = getCallbacks();
call.on_config_response(config_response_event->requestID, config_response_event->value);
}
/** Called by serviceMessageLoop() when a point mapping change event is returned by LeapPollConnection(). */
void Connection::handleImageEvent(const LEAP_IMAGE_EVENT *image_event) {
struct Callbacks & call = getCallbacks();
call.on_image(image_event);
}
/** Called by serviceMessageLoop() when a point mapping change event is returned by LeapPollConnection(). */
void Connection::handlePointMappingChangeEvent(const LEAP_POINT_MAPPING_CHANGE_EVENT *point_mapping_change_event) {
struct Callbacks & call = getCallbacks();
call.on_point_mapping_change(point_mapping_change_event);
}
/** Called by serviceMessageLoop() when a point mapping change event is returned by LeapPollConnection(). */
void Connection::handleHeadPoseEvent(const LEAP_HEAD_POSE_EVENT *head_pose_event) {
struct Callbacks & call = getCallbacks();
call.on_head_pose(head_pose_event);
}
/**
* Services the LeapC message pump by calling LeapPollConnection().
* The average polling time is determined by the framerate of the Leap Motion service.
*/
#if defined(_MSC_VER)
void __stdcall Connection::serviceMessageLoop(void * unused) {
#else
void* Connection::serviceMessageLoop(void * unused) {
#endif
eLeapRS result;
LEAP_CONNECTION_MESSAGE msg;
LEAP_CONNECTION & handler = getHandler();
while (getRunning()) {
unsigned int timeout = 1000;
result = LeapPollConnection(handler, timeout, &msg);
if (result != eLeapRS_Success) {
std::cout << " PollConnection call was " << ResultString(result) << std::endl;
continue;
}
switch (msg.type) {
case eLeapEventType_Connection:
handleConnectionEvent(msg.connection_event);
break;
case eLeapEventType_ConnectionLost:
handleConnectionLostEvent(msg.connection_lost_event);
break;
case eLeapEventType_Device:
handleDeviceEvent(msg.device_event);
break;
case eLeapEventType_DeviceLost:
handleDeviceLostEvent(msg.device_event);
break;
case eLeapEventType_DeviceFailure:
handleDeviceFailureEvent(msg.device_failure_event);
break;
case eLeapEventType_Tracking:
handleTrackingEvent(msg.tracking_event, buffer);
break;
case eLeapEventType_ImageComplete:
// Ignore
break;
case eLeapEventType_ImageRequestError:
// Ignore
break;
case eLeapEventType_LogEvent:
handleLogEvent(msg.log_event);
break;
case eLeapEventType_Policy:
handlePolicyEvent(msg.policy_event);
break;
case eLeapEventType_ConfigChange:
handleConfigChangeEvent(msg.config_change_event);
break;
case eLeapEventType_ConfigResponse:
handleConfigResponseEvent(msg.config_response_event);
break;
case eLeapEventType_Image:
handleImageEvent(msg.image_event);
break;
case eLeapEventType_PointMappingChange:
handlePointMappingChangeEvent(msg.point_mapping_change_event);
break;
case eLeapEventType_LogEvents:
handleLogEvents(msg.log_events);
break;
case eLeapEventType_HeadPose:
handleHeadPoseEvent(msg.head_pose_event);
break;
default:
//discard unknown message types
std::cout << "Unhandled message type. " << msg.type << std::endl;
} //switch on msg.type
}
#if !defined(_MSC_VER)
return NULL;
#endif
}
/* Used in Polling Example: */
/**
* Caches the newest frame by copying the tracking event struct returned by
* LeapC.
*/
void Connection::setFrame(const LEAP_TRACKING_EVENT *frame) {
LockMutex(&dataLock);
if (!lastFrame) lastFrame = (LEAP_TRACKING_EVENT *)malloc(sizeof(*frame));
*lastFrame = *frame;
UnlockMutex(&dataLock);
}
/** Returns a pointer to the cached tracking frame. */
LEAP_TRACKING_EVENT* Connection::GetFrame() {
LEAP_TRACKING_EVENT *currentFrame;
LockMutex(&dataLock);
currentFrame = lastFrame;
UnlockMutex(&dataLock);
return currentFrame;
}
/**
* Caches the last device found by copying the device info struct returned by
* LeapC.
*/
static void setDevice(Connection & c, const LEAP_DEVICE_INFO *deviceProps) {
LockMutex(&dataLock);
LEAP_DEVICE_INFO * lastDevice = c.getLastDevice();
if (lastDevice) {
free(lastDevice->serial);
}
else {
lastDevice = (LEAP_DEVICE_INFO*)malloc(sizeof(*deviceProps));
}
*lastDevice = *deviceProps;
lastDevice->serial = (char*)malloc(deviceProps->serial_length);
memcpy(lastDevice->serial, deviceProps->serial, deviceProps->serial_length);
UnlockMutex(&dataLock);
}
/** Returns a pointer to the cached device info. */
LEAP_DEVICE_INFO* Connection::GetDeviceProperties() {
LEAP_DEVICE_INFO *currentDevice;
LockMutex(&dataLock);
currentDevice = lastDevice;
UnlockMutex(&dataLock);
return currentDevice;
}
//End of polling example-specific code
/** Translates eLeapRS result codes into a human-readable string. */
const std::string Connection::ResultString(eLeapRS r) {
switch (r) {
case eLeapRS_Success: return "eLeapRS_Success";
case eLeapRS_UnknownError: return "eLeapRS_UnknownError";
case eLeapRS_InvalidArgument: return "eLeapRS_InvalidArgument";
case eLeapRS_InsufficientResources: return "eLeapRS_InsufficientResources";
case eLeapRS_InsufficientBuffer: return "eLeapRS_InsufficientBuffer";
case eLeapRS_Timeout: return "eLeapRS_Timeout";
case eLeapRS_NotConnected: return "eLeapRS_NotConnected";
case eLeapRS_HandshakeIncomplete: return "eLeapRS_HandshakeIncomplete";
case eLeapRS_BufferSizeOverflow: return "eLeapRS_BufferSizeOverflow";
case eLeapRS_ProtocolError: return "eLeapRS_ProtocolError";
case eLeapRS_InvalidClientID: return "eLeapRS_InvalidClientID";
case eLeapRS_UnexpectedClosed: return "eLeapRS_UnexpectedClosed";
case eLeapRS_UnknownImageFrameRequest: return "eLeapRS_UnknownImageFrameRequest";
case eLeapRS_UnknownTrackingFrameID: return "eLeapRS_UnknownTrackingFrameID";
case eLeapRS_RoutineIsNotSeer: return "eLeapRS_RoutineIsNotSeer";
case eLeapRS_TimestampTooEarly: return "eLeapRS_TimestampTooEarly";
case eLeapRS_ConcurrentPoll: return "eLeapRS_ConcurrentPoll";
case eLeapRS_NotAvailable: return "eLeapRS_NotAvailable";
case eLeapRS_NotStreaming: return "eLeapRS_NotStreaming";
case eLeapRS_CannotOpenDevice: return "eLeapRS_CannotOpenDevice";
default: return "unknown result type.";
}
}
/** Cross-platform sleep function */
void Connection::millisleep(int milliseconds) {
#ifdef _WIN32
Sleep(milliseconds);
#else
usleep(milliseconds * 1000);
#endif
}
//End-of-ExampleConnection.c
|
#include "engone.h"
#include "ui_engone.h"
#include "voice.h"
#include"dialog.h"
#include"sentence.h"
#include"vocab.h"
#include"speech.h"
engone::engone(QWidget *parent) :
QDialog(parent),
ui(new Ui::engone)
{
ui->setupUi(this);
QPixmap pix("C:\\Users\\nayan\\Desktop\\image1.png");
ui->label_2->setPixmap(pix);
}
engone::~engone()
{
delete ui;
}
void engone::on_voice_clicked()
{
hide();
voice v;
v.setModal(true);
v.exec();
}
void engone::on_sentence_clicked()
{
hide();
sentence s;
s.setModal(true);
s.exec();
}
void engone::on_vocab_clicked()
{
hide();
vocab vocab;
vocab.setModal(true);
vocab.exec();
}
void engone::on_speech_clicked()
{
hide();
speech sp;
sp.setModal(true);
sp.exec();
}
void engone::on_vocab_2_clicked()
{
hide();
Dialog sp;
sp.setModal(true);
sp.exec();
}
|
/* Portions Copyright (c) 2005 Nokia Corporation */
#include "Python.h"
#include <ctype.h>
#include <e32std.h>
/* snprintf() wrappers. If the platform has vsnprintf, we use it, else we
emulate it in a half-hearted way. Even if the platform has it, we wrap
it because platforms differ in what vsnprintf does in case the buffer
is too small: C99 behavior is to return the number of characters that
would have been written had the buffer not been too small, and to set
the last byte of the buffer to \0. At least MS _vsnprintf returns a
negative value instead, and fills the entire buffer with non-\0 data.
The wrappers ensure that str[size-1] is always \0 upon return.
PyOS_snprintf and PyOS_vsnprintf never write more than size bytes
(including the trailing '\0') into str.
If the platform doesn't have vsnprintf, and the buffer size needed to
avoid truncation exceeds size by more than 512, Python aborts with a
Py_FatalError.
Return value (rv):
When 0 <= rv < size, the output conversion was unexceptional, and
rv characters were written to str (excluding a trailing \0 byte at
str[rv]).
When rv >= size, output conversion was truncated, and a buffer of
size rv+1 would have been needed to avoid truncation. str[size-1]
is \0 in this case.
When rv < 0, "something bad happened". str[size-1] is \0 in this
case too, but the rest of str is unreliable. It could be that
an error in format codes was detected by libc, or on platforms
with a non-C99 vsnprintf simply that the buffer wasn't big enough
to avoid truncation, or on platforms without any vsnprintf that
PyMem_Malloc couldn't obtain space for a temp buffer.
CAUTION: Unlike C99, str != NULL and size > 0 are required.
*/
extern "C" {
DL_EXPORT(int)
PyOS_snprintf(char *str, size_t size, const char *format, ...)
{
int rc;
va_list va;
va_start(va, format);
rc = PyOS_vsnprintf(str, size, format, va);
va_end(va);
return rc;
}
DL_EXPORT(int)
PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
{
int len; /* # bytes written, excluding \0 */
char *buffer;
TLocale locale;
TChar dec_sep;
assert(str != NULL);
assert(size > 0);
assert(format != NULL);
buffer = (char*)PyMem_MALLOC(size + 512);
if (buffer == NULL) {
len = -666;
goto Done;
}
/* This is not a nice thing to do. */
dec_sep = locale.DecimalSeparator();
if ((TUint)dec_sep != '.') {
locale.SetDecimalSeparator(TChar('.'));
locale.Set();
}
len = vsprintf(buffer, format, va);
if ((TUint)dec_sep != '.') {
locale.SetDecimalSeparator(dec_sep);
locale.Set();
}
if (len < 0)
/* ignore the error */;
else if ((size_t)len >= size + 512)
Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf");
else {
const size_t to_copy = (size_t)len < size ?
(size_t)len : size - 1;
assert(to_copy < size);
memcpy(str, buffer, to_copy);
str[to_copy] = '\0';
}
PyMem_FREE(buffer);
Done:
str[size-1] = '\0';
return len;
}
} /* extern "C" */
|
//
// Created by andyw1997 on 12/3/18.
//
#ifndef CPP_TFPREPROCESS_H
#define CPP_TFPREPROCESS_H
#include <string>
#include <vector>
#include <functional>
#include <mutex>
#include <sstream>
#include "cirrus/src/Configuration.h"
#include "cirrus/src/SparseDataset.h"
class TFPreprocess {
public:
cirrus::SparseDataset read_criteo_sparse_tf(const std::string& input_file,
const std::string& delimiter,
const cirrus::Configuration& config);
private:
void parse_criteo_tf_line(
const std::string& line, const std::string& delimiter,
std::vector<std::pair<int, int64_t>>& output_features,
uint32_t& label, const cirrus::Configuration& config);
void read_criteo_tf_thread(std::ifstream& fin, std::mutex& fin_lock,
const std::string& delimiter,
std::vector<std::vector<std::pair<int, int64_t>>>& samples_res,
std::vector<uint32_t>& labels_res,
uint64_t limit_lines, std::atomic<unsigned int>& lines_count,
std::function<void(const std::string&, const std::string&,
std::vector<std::pair<int, int64_t>>&, uint32_t&)> fun);
void preprocess(std::vector<std::vector<std::pair<int, int64_t>>>& samples);
int find_bucket(int64_t value, const std::vector<float>& buckets);
void print_sparse_sample(std::vector<std::pair<int, int64_t>> sample);
template<class C>
C hex_string_to(const char* s) {
std::stringstream ss;
ss << std::hex << s;
C c;
ss >> c;
return c;
}
};
#endif //CPP_TFPREPROCESS_H
|
#include<iostream>
#include<queue>
#include<stack>
#define FOR(i,n) for(i=0;i<n;i++)
using namespace std;
int N;
queue<int>q[100];
stack<int>s;
int allempty()
{
int count=0,i;
FOR(i,N){if(q[i].empty()==1)count++;}
if(count==N && s.empty()==1)
return 1;
else return 0;
}
int main()
{
int set,n,S,Q,i,j,temp,time;
cin>>set;
while(set--)
{
cin>>N>>S>>Q;
FOR(i,N)
{
cin>>n;
FOR(j,n){cin>>temp;q[i].push(temp);}
}
i=0;time=0;
while(allempty()==0)
{
while((q[i].size()<Q&&s.empty()!=1)||(s.empty()!=1&&s.top()==i+1))
{
if(s.top()==i+1){s.pop();time+=1;}
else {q[i].push(s.top());s.pop();time+=1;}
}
while(s.size()<S&&q[i].empty()!=1)
{
s.push(q[i].front());q[i].pop();time+=1;
}
time+=2;i++;
if(i==N)i=0;
}
time-=2;
cout<<time<<endl;
}
return 0;
}
|
/* XMRig
* Copyright (c) 2018-2019 tevador <tevador@gmail.com>
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "crypto/rx/RxMsr.h"
#include "backend/cpu/Cpu.h"
#include "backend/cpu/CpuThread.h"
#include "base/io/log/Log.h"
#include "base/tools/Chrono.h"
#include "crypto/rx/RxConfig.h"
#include "hw/msr/Msr.h"
#include <algorithm>
#include <set>
namespace xmrig {
bool RxMsr::m_cacheQoS = false;
bool RxMsr::m_enabled = false;
bool RxMsr::m_initialized = false;
static MsrItems items;
#ifdef XMRIG_OS_WIN
static constexpr inline int32_t get_cpu(int32_t) { return -1; }
#else
static constexpr inline int32_t get_cpu(int32_t cpu) { return cpu; }
#endif
static bool wrmsr(const MsrItems &preset, const std::vector<CpuThread> &threads, bool cache_qos, bool save)
{
auto msr = Msr::get();
if (!msr) {
return false;
}
if (save) {
items.reserve(preset.size());
for (const auto &i : preset) {
auto item = msr->read(i.reg());
if (!item.isValid()) {
items.clear();
return false;
}
LOG_VERBOSE("%s " CYAN_BOLD("0x%08" PRIx32) CYAN(":0x%016" PRIx64) CYAN_BOLD(" -> 0x%016" PRIx64), Msr::tag(), i.reg(), item.value(), MsrItem::maskedValue(item.value(), i.value(), i.mask()));
items.emplace_back(item);
}
}
// Which CPU cores will have access to the full L3 cache
std::set<int32_t> cacheEnabled;
bool cacheQoSDisabled = threads.empty();
if (cache_qos) {
const auto &units = Cpu::info()->units();
for (const auto &t : threads) {
const auto affinity = static_cast<int32_t>(t.affinity());
// If some thread has no affinity or wrong affinity, disable cache QoS
if (affinity < 0 || std::find(units.begin(), units.end(), affinity) == units.end()) {
cacheQoSDisabled = true;
LOG_WARN("%s " YELLOW_BOLD("cache QoS can only be enabled when all mining threads have affinity set"), Msr::tag());
break;
}
cacheEnabled.insert(affinity);
}
}
return msr->write([&msr, &preset, cache_qos, &cacheEnabled, cacheQoSDisabled](int32_t cpu) {
for (const auto &item : preset) {
if (!msr->write(item, get_cpu(cpu))) {
return false;
}
}
if (!cache_qos) {
return true;
}
// Assign Class Of Service 0 to current CPU core (default, full L3 cache available)
if (cacheQoSDisabled || cacheEnabled.count(cpu)) {
return msr->write(0xC8F, 0, get_cpu(cpu));
}
// Disable L3 cache for Class Of Service 1
if (!msr->write(0xC91, 0, get_cpu(cpu))) {
// Some CPUs don't let set it to all zeros
if (!msr->write(0xC91, 1, get_cpu(cpu))) {
return false;
}
}
// Assign Class Of Service 1 to current CPU core
return msr->write(0xC8F, 1ULL << 32, get_cpu(cpu));
});
}
} // namespace xmrig
bool xmrig::RxMsr::init(const RxConfig &config, const std::vector<CpuThread> &threads)
{
if (isInitialized()) {
return isEnabled();
}
m_initialized = true;
m_enabled = false;
const auto &preset = config.msrPreset();
if (preset.empty()) {
return false;
}
const uint64_t ts = Chrono::steadyMSecs();
m_cacheQoS = config.cacheQoS();
if (m_cacheQoS && !Cpu::info()->hasCatL3()) {
LOG_WARN("%s " YELLOW_BOLD("this CPU doesn't support cat_l3, cache QoS is unavailable"), Msr::tag());
m_cacheQoS = false;
}
if ((m_enabled = wrmsr(preset, threads, m_cacheQoS, config.rdmsr()))) {
LOG_NOTICE("%s " GREEN_BOLD("register values for \"%s\" preset have been set successfully") BLACK_BOLD(" (%" PRIu64 " ms)"), Msr::tag(), config.msrPresetName(), Chrono::steadyMSecs() - ts);
}
else {
LOG_ERR("%s " RED_BOLD("FAILED TO APPLY MSR MOD, HASHRATE WILL BE LOW"), Msr::tag());
}
return isEnabled();
}
void xmrig::RxMsr::destroy()
{
if (!isInitialized()) {
return;
}
m_initialized = false;
m_enabled = false;
if (items.empty()) {
return;
}
const uint64_t ts = Chrono::steadyMSecs();
if (!wrmsr(items, std::vector<CpuThread>(), m_cacheQoS, false)) {
LOG_ERR("%s " RED_BOLD("failed to restore initial state" BLACK_BOLD(" (%" PRIu64 " ms)")), Msr::tag(), Chrono::steadyMSecs() - ts);
}
}
|
#include <ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Twist.h>
#include <stdlib.h>
int OdomCount = 0;
int OdomWait = 3;
int LMotor = 1;
int RMotor = 0;
bool left_forward;
bool right_forward;
int MotorNum[2] = {LMotor, RMotor};
double Vels[2] = {0,0};
int CVEL[2]= {0,0};
int Mspeeds[2] = {0,0};
double WCS[2] = {0,0};
long EncoderVal[2] = {0,0};
double DDis[2] = {0,0};
long Time[2] = {0,0};
long Time_fb = 0;
double DDis_fb = 0;
float WheelSeparation = 0.35; //0.17
float WheelDiameter = 0.07; //60 to fast
int TPR_forward = 210;
int TPR_backward = 210; //720
volatile int counterL_forward = 0;
volatile int counterR_forward = 0;
volatile int counterL_backward = 0;
volatile int counterR_backward = 0;
int AccParam = 3; //3; //acceleration multiplie8Ur.
int bot_vel;
int count = 0;
int dir1 = 38, pwm1 = 44, dir2 = 39, pwm2 = 45;
int motor_speed_l = 0,motor_speed_r = 0;
ros::NodeHandle nh;
geometry_msgs::Twist odom_msg;
geometry_msgs::Twist odom_msg2;
ros::Publisher Pub ("ard_odom", &odom_msg);
void countL_forward() {
if(WCS[0] > 0)
counterL_forward++;
}
void countR_forward() {
if(WCS[1] > 0)
counterR_forward++;
}
void countL_backward() {
if(WCS[0] < 0)
counterL_backward--;
}
void countR_backward() {
if(WCS[1] < 0)
counterR_backward--;
}
void right() {
digitalWrite(dir1,0); //0
digitalWrite(dir2,1); //1
}
void left() {
digitalWrite(dir1,1);
digitalWrite(dir2,0);
}
void forward() {
digitalWrite(dir1,0);
digitalWrite(dir2,0);
}
void backward() {
digitalWrite(dir1,1);
digitalWrite(dir2,1);
}
void stop() { // pwm1 = 13; dir1 = 12; pwm2 = 11; dir2 = 10;
analogWrite(pwm1, 0);
analogWrite(pwm2, 0);
}
void velCallback( const geometry_msgs::Twist& CVel){
double vel_x = CVel.linear.x;
double vel_th = CVel.angular.z;
double right_vel = 0.0;
double left_vel = 0.0;
// turning
if(vel_x == 0){
right_vel = vel_th * WheelSeparation / 2.0;
left_vel = (-1) * right_vel;
}
// forward / backward
else if(vel_th == 0){
left_vel = right_vel = vel_x;
}
// moving doing arcs
else{
right_vel = vel_x + vel_th * WheelSeparation / 2.0;
left_vel = vel_x - vel_th * WheelSeparation / 2.0;
}
//write new command speeds to global vars
WCS[0] = left_vel;
WCS[1] = right_vel;
}
ros::Subscriber<geometry_msgs::Twist> sub("cmd_vel" , &velCallback);
//motor write speed - in motor units
double MWS[2]= {0,0};
double CorrectedSpeed_FB(double CVel){ //only forward, backward
if(Time_fb==0){
Time_fb = millis();
return 0;
}
if(CVel >= 0) {
EncoderVal[0] = counterL_forward;
EncoderVal[1] = counterL_forward;
counterL_forward = counterR_forward = 0;
}
else if(CVel < 0){
EncoderVal[0] = counterL_backward;
EncoderVal[1] = counterL_backward;
counterL_backward = counterR_backward = 0;
}
long T = millis();
int DTime = T-Time_fb;
Time_fb = T;
if(CVel >= 0)
DDis_fb = TicksToMeters(EncoderVal[0],0);
else
DDis_fb = TicksToMeters(EncoderVal[0],1);
double EVel = (DDis_fb/DTime)*1000;
Vels[0] = EVel;
Vels[1] = EVel;
EVel = abs(EVel);
CVel = abs(CVel);
double dif = EVel - CVel;
MWS[0] = MWS[0]-(dif * (AccParam));
if(MWS[0]<0) {
MWS[0] = 0;
MWS[1] = 0;
}
/* if(CVel == 0) {
MWS[0] = 0;
MWS[1] = 0;
} */
//DEBUG
CVEL[0] = MWS[0];
return MWS[0];
}
double CorrectedSpeed(int M, double CVel){
if(Time[0]==0 && Time[1] == 0){
Time[0] = millis();
Time[1] = millis();
return 0;
}
if(M == 0){
if(CVel >= 0) {
EncoderVal[0] = counterL_forward;
counterL_forward = 0;
}
else if(CVel < 0){
EncoderVal[0] = counterL_backward;
counterL_backward = 0;
}
}
else if(M == 1){
if(CVel >= 0) {
EncoderVal[1] = counterR_forward;
counterR_forward = 0;
}
else if(CVel < 0){
EncoderVal[1] = counterR_backward;
counterR_backward = 0;
}
}
long T = millis();
int DTime = T-Time[M];
Time[M] = T;
if(CVel >= 0)
DDis[M] = TicksToMeters(EncoderVal[M],0);
else
DDis[M] = TicksToMeters(EncoderVal[M],1);
double EVel = (DDis[M]/DTime)*1000;
Vels[M] = EVel;
EVel = abs(EVel);
CVel = abs(CVel);
double dif = EVel - CVel;
MWS[M] = MWS[M]-(dif * (AccParam));
if(MWS[M]<0)
MWS[M] = 0;
if(CVel == 0) //HERE
MWS[M] = 0; //HERE
//DEBUG
CVEL[M] = MWS[M];
return MWS[M];
}
double TicksToMeters(int Ticks,int mode){
if(mode == 0) //forward
return (Ticks*3.14*WheelDiameter)/TPR_forward;
else
return (Ticks*3.14*WheelDiameter)/TPR_backward;
}
void MotorWrite() {
int DIR;
int min_speed;
double MSpeed;
if( ((WCS[0] > 0 && WCS[1] > 0) || (WCS[0] < 0 && WCS[1] < 0)) && (WCS[0] == WCS[1]) ) {
//forward/backward
motor_speed_l = CorrectedSpeed_FB(WCS[0]);
motor_speed_r = motor_speed_l;
}
else { //left / right / arc
for(int i = 0; i<2; i++){
MSpeed = CorrectedSpeed(i, WCS[i]);
if(i == 0)
motor_speed_l = MSpeed;
else if(i == 1)
motor_speed_r = MSpeed;
}
}
motorGo(motor_speed_l,motor_speed_r);
}
void motorGo(uint8_t l, uint8_t r) {
if(WCS[0] > 0 && WCS[1] > 0)
forward();
else if(WCS[0] < 0 && WCS[1] < 0)
backward();
else if(WCS[0] > 0 && WCS[1] < 0)
right();
else if(WCS[0] < 0 && WCS[1] > 0)
left();
analogWrite(pwm1,l);
analogWrite(pwm2,r);
}
void setup() {
nh.initNode();
nh.advertise(Pub);
nh.subscribe(sub);
pinMode(38, OUTPUT);
pinMode(39, OUTPUT);
pinMode(44, OUTPUT);
pinMode(45, OUTPUT);
attachInterrupt(digitalPinToInterrupt(2), countL_forward, RISING); //interrupt pins for encoder Achange
attachInterrupt(digitalPinToInterrupt(3), countR_forward, RISING);
attachInterrupt(digitalPinToInterrupt(18), countL_backward, RISING); //interrupt pins for encoder Achange
attachInterrupt(digitalPinToInterrupt(19), countR_backward, RISING);
}
void loop() {
float ang_vel;
nh.spinOnce();
if(OdomCount > OdomWait){
if(Vels[0] == 0 and Vels[1] == 0) {
odom_msg.linear.x = 0;
odom_msg.linear.y = 0;
}
else if(WCS[0] == WCS[1]) {
odom_msg.linear.x = Vels[0];
odom_msg.linear.y = Vels[0];
}
else {
odom_msg.linear.x = Vels[0];
odom_msg.linear.y = Vels[1];
}
Pub.publish(&odom_msg);
}
else
OdomCount++;
MotorWrite(); //Takes WCS and corrects speed of motors with encoders
}
|
#ifndef NOTEBOOK_H
#define NOTEBOOK_H
#include "widgetList.h"
#include "note.h"
#include <QFile>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include "memory"
#include "settings.h"
class Notebook
{
friend class NoteListWindow;
public:
Notebook(const std::weak_ptr<Settings>);
~Notebook();
void loadNotes();
void saveNotes() const;
void addNote(Note * const note);
bool deleteNote(Note * const note);
int deleteOutdated(const QDate &date);
int deleteAll();
int contains (const QDate &date) const;
Note* findClosest(const QDate &date) const;
std::unique_ptr<QList<Note*>> getNotesFromDate(const QDate &date) const;
std::unique_ptr<QList<Note*>> getNotificationsFromDate(const QDate &date) const;
private:
const QString filePath = QApplication::applicationDirPath() + "/Notes.xml";
QList<Note*> notes;
std::shared_ptr<Settings> settings;
bool noteOnDate(Note * const note, const QDate &date) const;
bool notificationOnDate(Note * const note, const QDate &date) const;
QDate getClosestDate(Note * const note, const QDate &date) const;
Note* parseNote(QXmlStreamReader&) const;
};
#endif // NOTEBOOK_H
|
//////////////////////////////
// Filename: main.cpp
//////////////////////////////
#include "GameManager.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
{
GameManager* gameManager;
bool result;
//Create the GameManager object
gameManager = new GameManager;
if (!gameManager)
{
return 0;
}
//Initialize the run the GameManager object
result = gameManager->Initialize();
if (result)
{
gameManager->Run();
}
//Shutdown and release the GameManager object
gameManager->Shutdown();
delete gameManager;
gameManager = 0;
return 0;
}
|
#ifndef Compound_h
#define Compound_h
//Depricated
#include <vector>
#include <tr1/array>
#include <tr1/memory>
#include "Manifold.h"
#include <Eigen/Core>
using Eigen::Vector3d;
using Eigen::Matrix3d;
class Compound : public Manifold {
public:
class Point;
class PointOfReference;
class Geodesic;
typedef std::tr1::shared_ptr<Point> PointPtr;
typedef std::tr1::shared_ptr<PointOfReference> PointOfReferencePtr;
typedef std::tr1::shared_ptr<Geodesic> GeodesicPtr;
class Point {
public:
Compound* getSpace();
Vector3d getVector();
Point(Manifold::PointPtr position, Compound* space);
Manifold* getSubspace();
std::tr1::shared_ptr<Manifold::Point> getPosition();
private:
std::tr1::shared_ptr<Manifold::Point> position;
Compound* space;
};
class PointOfReference : public Manifold::PointOfReference {
public:
PointOfReference(std::tr1::shared_ptr<Manifold::PointOfReference> pointOfReference);
Vector3d vectorFromPointAndNearVector(PointPtr point, Vector3d vector);
//std::tr1::shared_ptr<Point> pointFromVector(Vector3d vector);
Manifold::PointPtr getPosition();
void rotate(Matrix3d rot);
private:
std::tr1::shared_ptr<Manifold::PointOfReference> pointOfReference;
};
class Geodesic : public Manifold::Geodesic {
public:
Geodesic(PointOfReferencePtr start, PointOfReferencePtr end, Vector3d vector);
Manifold::PointPtr getEndPoint();
Manifold::PointOfReferencePtr getEndPointOfReference();
Vector3d getVector();
private:
PointOfReferencePtr start;
PointOfReferencePtr end;
Vector3d vector;
};
GeodesicPtr getGeodesic(PointOfReferencePtr start, PointPtr end);
GeodesicPtr getGeodesic(PointOfReferencePtr start, Vector3d vector);
};
#endif
|
#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
int main(int argc, char const *argv[])
{
int kase;
scanf("%d",&kase);
int num;
for(int K = 1 ; K <= kase ; K++ ){
printf("Case #%d: ",K);
scanf("%d",&num);
string str = "";
if( num == 0 ) str = "0";
while( num != 0 ){
int tmp = num % -2;
num /= -2;
if( tmp < 0 ){
num++;
tmp *= -1;
}
char c = tmp+'0';
str = c+str;
}
cout << str << endl;
}
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
struct queue
{
char pw;
int x;
struct queue *next;
};
typedef struct queue Q;
Q *p,*head;
void enqueue(Q **list,char w)
{
Q *temp,*p;
int c=1;
temp=(Q*)malloc(sizeof(Q));
temp->x=w;
temp->next=NULL;
p=head;
if(p==NULL) {
head=temp;
}
else{
while(p->next!=NULL)
p=p->next;
temp->next=p->next;
p->next=temp;
}
}
void display(Q *list,int z)
{
Q *temp;
p=head;
while(p!=NULL) {
p->x-=z;
if(p->x > 0) {
printf("%d ",p->x);
p=p->next;
temp=p;
head=p->next;
while(p->next!=NULL)
p=p->next;
p->next=temp;
}
}
}
|
/* MBED RTOS Blinky
* Flash some simple LEDs using the RTOS
* Thread version
*/
#include <mbed.h>
DigitalOut red(LED1,1); /* initialise to 1 = off */
void flash_red(void)
{
while(true) {
red = !red;
wait(0.3);
}
}
int main(void)
{
Thread blink;
blink.start(flash_red);
blink.join();
}
|
#pragma once
#ifndef __ZIP_HELPER
#define __ZIP_HELPER
#include <map>
#include <string>
//1.暂时不支持子目录
//注意: 因为使用了zlib库,使用时加上预编译宏 ZLIB_WINAPI
class ZipHelper
{
public:
ZipHelper() {}
~ZipHelper() {}
//path: utf8 path
ZipHelper& AddFile(const char* input_path, const char* inzip_path = "");
ZipHelper& AddDir(const char* input_dir, const char* temp_dir = NULL);
//output_path :utf8 path
bool ToZip(const char* output_path);
private:
std::map<std::string, std::string> files_;
};
#endif
|
#pragma once
#include <vector>
#include <string>
#include <memory>
#include <PortableDeviceApi.h>
namespace WPD {
class WPDDevice;
class WPDObjectIterator {
static const int batch = 10;
using EnumPortableDeviceObjectIDs = std::unique_ptr<IEnumPortableDeviceObjectIDs, void (*)(
IEnumPortableDeviceObjectIDs *)>;
EnumPortableDeviceObjectIDs iter;
const WPDDevice *device;
bool ended;
const std::wstring path;
std::vector<std::wstring> pathes;
int offset;
int pos;
void nextFiles();
public:
static WPDObjectIterator endIterator(const WPDDevice *device, const std::wstring &path);
WPDObjectIterator(EnumPortableDeviceObjectIDs &&p, const WPDDevice *device, std::wstring path);
std::wstring operator*() const;
void operator++();
bool operator==(const WPDObjectIterator &it) const;
bool operator!=(const WPDObjectIterator &it) const;
void skip(int num);
void reset();
};
}
|
/*
** EPITECH PROJECT, 2019
** OOP_indie_studio_2018
** File description:
** Event
*/
#ifndef EVENT_HPP_
#define EVENT_HPP_
#include <irrlicht/irrlicht.h>
#include <string>
using namespace irr;
class EventReceiver : public IEventReceiver {
public:
EventReceiver(void);
~EventReceiver(void);
virtual bool OnEvent(const SEvent& event);
virtual bool IsKeyDown(EKEY_CODE keyCode) const;
private:
// We use this array to store the current state of each key
bool KeyIsDown[KEY_KEY_CODES_COUNT];
};
#endif /* !EVENT_HPP_ */
|
// Created on: 1995-12-07
// Created by: Jacques GOUSSARD
// Copyright (c) 1995-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 _BRepCheck_Result_HeaderFile
#define _BRepCheck_Result_HeaderFile
#include <Standard.hxx>
#include <Standard_Mutex.hxx>
#include <Standard_Transient.hxx>
#include <BRepCheck_DataMapOfShapeListOfStatus.hxx>
#include <BRepCheck_ListOfStatus.hxx>
DEFINE_STANDARD_HANDLE(BRepCheck_Result, Standard_Transient)
class BRepCheck_Result : public Standard_Transient
{
public:
Standard_EXPORT void Init (const TopoDS_Shape& S);
Standard_EXPORT virtual void InContext (const TopoDS_Shape& ContextShape) = 0;
Standard_EXPORT virtual void Minimum() = 0;
Standard_EXPORT virtual void Blind() = 0;
Standard_EXPORT void SetFailStatus (const TopoDS_Shape& S);
const BRepCheck_ListOfStatus& Status() const { return *myMap (myShape); }
Standard_Boolean IsMinimum() const { return myMin; }
Standard_Boolean IsBlind() const { return myBlind; }
Standard_EXPORT void InitContextIterator();
Standard_Boolean MoreShapeInContext() const { return myIter.More(); }
const TopoDS_Shape& ContextualShape() const { return myIter.Key(); }
const BRepCheck_ListOfStatus& StatusOnShape() const { return *myIter.Value(); }
Standard_EXPORT void NextShapeInContext();
Standard_EXPORT void SetParallel (Standard_Boolean theIsParallel);
Standard_Boolean IsStatusOnShape (const TopoDS_Shape& theShape) const
{
return myMap.IsBound (theShape);
}
const BRepCheck_ListOfStatus& StatusOnShape (const TopoDS_Shape& theShape) const
{
return *myMap.Find (theShape);
}
friend class BRepCheck_ParallelAnalyzer;
DEFINE_STANDARD_RTTIEXT(BRepCheck_Result,Standard_Transient)
protected:
Standard_EXPORT BRepCheck_Result();
protected:
TopoDS_Shape myShape;
Standard_Boolean myMin;
Standard_Boolean myBlind;
BRepCheck_DataMapOfShapeListOfStatus myMap;
mutable Handle(Standard_HMutex) myMutex;
private:
Standard_HMutex* GetMutex()
{
return myMutex.get();
}
private:
BRepCheck_DataMapIteratorOfDataMapOfShapeListOfStatus myIter;
};
#endif // _BRepCheck_Result_HeaderFile
|
#include "EuropeanOption.h"
#include "BasicMaths.h"
#include "MarketData.h"
#include "Pricer.h"
#include <cmath>
#include <iostream>
Results EuropeanOption::analyticPrice(const MarketData& m) const
{
Results out;
out.m_standardDeviation = 0;
double df = m.discountFactorTo(m_maturity);
double fwd = m.equityPrice()/df;
double d1 = (std::log(fwd/m_strike)+m_maturity*m.equityVolatility()*m.equityVolatility()*0.5)
/(m.equityVolatility()*std::sqrt(m_maturity));
double d2 = d1-m.equityVolatility()*std::sqrt(m_maturity);
//std::cout<<"Ns "<<Ncdf(d1)<<","<<Ncdf(d2)<<","<<df<<std::endl;
//std::cout<<"delta "<<Ncdf(d1)<<"\n";
//std::cout<<"gamma "<<Npdf(d1)/(m.equityVolatility()*sqrt(m_maturity)*m.equityPrice())<<"\n";
//std::cout<<"vega "<<Npdf(d1)*sqrt(m_maturity)*m.equityPrice()<<"\n";
if(!m_isPut)
{
out.m_price = m.equityPrice()*Ncdf(d1)-m_strike*Ncdf(d2)*df;
}
else
{
out.m_price = m_strike*Ncdf(-d2)*df-m.equityPrice()*Ncdf(-d1);
}
out.m_delta = Ncdf(d1) - (m_isPut ? 1.0 : 0.0);
out.m_gamma = Npdf(d1)/(m.equityPrice()*m.equityVolatility()*std::sqrt(m_maturity));
return out;
}
double EuropeanOption::timeToExpiry() const {return m_maturity;}
double EuropeanOption::payoffOnExpiry(double equityPrice) const {
double difference = equityPrice-m_strike;
if(m_isPut)
difference =- difference;
if(difference>0)
return difference;
return 0;
}
|
// Created on: 1993-06-22
// Created by: Laurent BOURESCHE
// Copyright (c) 1993-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 _BRepSweep_Revol_HeaderFile
#define _BRepSweep_Revol_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BRepSweep_Rotation.hxx>
#include <Standard_Boolean.hxx>
class TopoDS_Shape;
class gp_Ax1;
class Sweep_NumShape;
class TopLoc_Location;
//! Provides natural constructors to build BRepSweep
//! rotated swept Primitives.
class BRepSweep_Revol
{
public:
DEFINE_STANDARD_ALLOC
//! Builds the Revol of meridian S axis A and angle D. If
//! C is true S is copied.
Standard_EXPORT BRepSweep_Revol(const TopoDS_Shape& S, const gp_Ax1& A, const Standard_Real D, const Standard_Boolean C = Standard_False);
//! Builds the Revol of meridian S axis A and angle 2*Pi.
//! If C is true S is copied.
Standard_EXPORT BRepSweep_Revol(const TopoDS_Shape& S, const gp_Ax1& A, const Standard_Boolean C = Standard_False);
//! Returns the TopoDS Shape attached to the Revol.
Standard_EXPORT TopoDS_Shape Shape();
//! Returns the TopoDS Shape generated with aGenS
//! (subShape of the generating shape).
Standard_EXPORT TopoDS_Shape Shape (const TopoDS_Shape& aGenS);
//! Returns the first shape of the revol (coinciding with
//! the generating shape).
Standard_EXPORT TopoDS_Shape FirstShape();
//! Returns the first shape of the revol (coinciding with
//! the generating shape).
Standard_EXPORT TopoDS_Shape FirstShape (const TopoDS_Shape& aGenS);
//! Returns the TopoDS Shape of the top of the prism.
Standard_EXPORT TopoDS_Shape LastShape();
//! Returns the TopoDS Shape of the top of the prism.
//! generated with aGenS (subShape of the generating
//! shape).
Standard_EXPORT TopoDS_Shape LastShape (const TopoDS_Shape& aGenS);
//! returns the axis
Standard_EXPORT gp_Ax1 Axe() const;
//! returns the angle.
Standard_EXPORT Standard_Real Angle() const;
//! Returns true if the aGenS is used in resulting Shape
Standard_EXPORT Standard_Boolean IsUsed(const TopoDS_Shape& aGenS) const;
private:
//! builds the NumShape.
Standard_EXPORT Sweep_NumShape NumShape (const Standard_Real D) const;
//! Builds the Location
Standard_EXPORT TopLoc_Location Location (const gp_Ax1& Ax, const Standard_Real D) const;
//! Builds the axis
Standard_EXPORT gp_Ax1 Axe (const gp_Ax1& Ax, const Standard_Real D) const;
//! computes the angle.
Standard_EXPORT Standard_Real Angle (const Standard_Real D) const;
BRepSweep_Rotation myRotation;
};
#endif // _BRepSweep_Revol_HeaderFile
|
// codebit written by Tiantian Liu @ University of Pennsylvania, 2012
#ifndef MYGLWIDGET
#define MYGLWIDGET
#include "DisplayClass.h"
#include <iostream>
#include <istream>
#include <sstream>
#include <string>
#include <fstream>
#include <QTimer>
#include <QKeyEvent>
class MyGLWidget : public QGLWidget {
Q_OBJECT
private:
//Animation/transformation stuff
QTimer* timer;
// Display
public:
DisplayClass *displayClass;
bool* invertMode;
Node* selectedNode;
MyGLWidget(QWidget*);
~MyGLWidget(void);
protected:
Node* setPar(Node*,Node*, int, float*, int);
std::istringstream getNumStream(std::string);
glm::vec3 getVec(std::string);
void selectNextNode(bool,Node*);
void initializeGL(void);
void paintGL(void);
void resizeGL(int, int);
void keyPressEvent(QKeyEvent* e);
void keyReleaseEvent(QKeyEvent* e);
};
#endif
|
#ifndef MENUSTATE_H
#define MENUSTATE_H
#include "Game.h"
#include "GameDimens.h"
using std::string;
class MenuState: public State
{
public:
MenuState(GameDataRef);
virtual ~MenuState();
MenuState(const MenuState& other);
MenuState& operator=(const MenuState& other);
void init();
void handleInput();
void draw(float dt);
void update(float dt);
void setNewText();
void setTitleText();
protected:
private:
GameDataRef data;
sf::Clock clock;
sf::View view;
sf::Texture background;
sf::Sprite backgroundImage;
sf::Text newText;
sf::Font newFont;
sf::Text titleText;
sf::Font titleFont;
};
#endif // MENUSTATE_H
|
#include <fstream>
#include "mp23_16_opt.h"
int main() {
ofstream in_pix("input_pixels_regression_result_mp23_16_opt.txt");
ofstream fout("regression_result_mp23_16_opt.txt");
HWStream<hw_uint<512> > in_update_0_read;
HWStream<hw_uint<256> > mp23_16_update_0_write;
// Loading input data
// cmap : { in_update_0[root = 0, in_0, in_1, in_2] -> in_oc[0, 0] : 0 <= in_0 <= 7 and 0 <= in_1 <= 127 and 0 <= in_2 <= 63 }
// read map: { in_oc[0, 0] -> in_update_0[root = 0, in_0, in_1, in_2] : 0 <= in_0 <= 7 and 0 <= in_1 <= 127 and 0 <= in_2 <= 63 }
// rng : { in_update_0[root = 0, in_0, in_1, in_2] : 0 <= in_0 <= 7 and 0 <= in_1 <= 127 and 0 <= in_2 <= 63 }
for (int i = 0; i < 65536; i++) {
hw_uint<512> in_val;
set_at<0*32, 512, 32>(in_val, 16*i + 0);
in_pix << in_val << endl;
set_at<1*32, 512, 32>(in_val, 16*i + 1);
in_pix << in_val << endl;
set_at<2*32, 512, 32>(in_val, 16*i + 2);
in_pix << in_val << endl;
set_at<3*32, 512, 32>(in_val, 16*i + 3);
in_pix << in_val << endl;
set_at<4*32, 512, 32>(in_val, 16*i + 4);
in_pix << in_val << endl;
set_at<5*32, 512, 32>(in_val, 16*i + 5);
in_pix << in_val << endl;
set_at<6*32, 512, 32>(in_val, 16*i + 6);
in_pix << in_val << endl;
set_at<7*32, 512, 32>(in_val, 16*i + 7);
in_pix << in_val << endl;
set_at<8*32, 512, 32>(in_val, 16*i + 8);
in_pix << in_val << endl;
set_at<9*32, 512, 32>(in_val, 16*i + 9);
in_pix << in_val << endl;
set_at<10*32, 512, 32>(in_val, 16*i + 10);
in_pix << in_val << endl;
set_at<11*32, 512, 32>(in_val, 16*i + 11);
in_pix << in_val << endl;
set_at<12*32, 512, 32>(in_val, 16*i + 12);
in_pix << in_val << endl;
set_at<13*32, 512, 32>(in_val, 16*i + 13);
in_pix << in_val << endl;
set_at<14*32, 512, 32>(in_val, 16*i + 14);
in_pix << in_val << endl;
set_at<15*32, 512, 32>(in_val, 16*i + 15);
in_pix << in_val << endl;
in_update_0_read.write(in_val);
}
mp23_16_opt(in_update_0_read, mp23_16_update_0_write);
for (int i = 0; i < 32768; i++) {
hw_uint<256> actual = mp23_16_update_0_write.read();
auto actual_lane_0 = actual.extract<0*32, 31>();
fout << actual_lane_0 << endl;
auto actual_lane_1 = actual.extract<1*32, 63>();
fout << actual_lane_1 << endl;
auto actual_lane_2 = actual.extract<2*32, 95>();
fout << actual_lane_2 << endl;
auto actual_lane_3 = actual.extract<3*32, 127>();
fout << actual_lane_3 << endl;
auto actual_lane_4 = actual.extract<4*32, 159>();
fout << actual_lane_4 << endl;
auto actual_lane_5 = actual.extract<5*32, 191>();
fout << actual_lane_5 << endl;
auto actual_lane_6 = actual.extract<6*32, 223>();
fout << actual_lane_6 << endl;
auto actual_lane_7 = actual.extract<7*32, 255>();
fout << actual_lane_7 << endl;
}
in_pix.close();
fout.close();
return 0;
}
|
// ##########################################################
// By Eugene Ch'ng | www.complexity.io | 2018
// Email: genechng@gmail.com
// ----------------------------------------------------------
// A C++ SDL Application
// Loading and displaying a bitmap
//
// How to compile:
// g++ -I/usr/include <filename>.cpp -o <output file> -L/usr/lib -lSDL2
// -I define the path to the includes folder
// -L define the path to the library folder
// -l ask the compiler to use the library
// ##########################################################
#include <iostream>
#include <SDL2/SDL.h>
using namespace std;
SDL_Window *gWindow = NULL;
SDL_Surface *gSurface = NULL;
SDL_Surface* gImage = NULL;
int main()
{
SDL_Init( SDL_INIT_VIDEO ); // initialize SDL
// create an SDL window
gWindow = SDL_CreateWindow( "Basic Image", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, 800, 800, SDL_WINDOW_SHOWN );
gSurface = SDL_GetWindowSurface( gWindow ); // Get the surface of the window
gImage = SDL_LoadBMP( "images/zombie.bmp" ); // load bitmap
// apply the image to the surface of the window
SDL_BlitSurface( gImage, NULL, gSurface, NULL );
SDL_UpdateWindowSurface( gWindow ); // update the surface
SDL_Delay( 5000 ); // wait five seconds
// freeing and destroying memory objects
SDL_FreeSurface( gImage );
SDL_FreeSurface( gSurface );
gImage = NULL;
gSurface = NULL;
SDL_DestroyWindow( gWindow );
gWindow = NULL;
SDL_Quit(); // quit SDL
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright 2002-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#ifndef PC_APP_H
#define PC_APP_H
#include "modules/prefs/prefsmanager/opprefscollection_default.h"
#include "modules/viewers/viewers.h"
class PrefsSection;
class PrefsEntry;
/** Global PrefsCollectionApp object (singleton). */
#define g_pcapp (g_opera->prefs_module.PrefsCollectionApp())
/**
* Preferences for external applications and plug-ins.
*
* @author Peter Karlsson
*/
class PrefsCollectionApp : public OpPrefsCollectionDefault
{
public:
/**
* Create method.
*
* This method preforms all actions required to construct the object.
* PrefsManager calls this method to initialize the object, and will
* not call the normal constructor directly.
*
* @param reader Pointer to the PrefsFile object.
* @return Pointer to the created object.
*/
static PrefsCollectionApp *CreateL(PrefsFile *reader);
virtual ~PrefsCollectionApp();
#include "modules/prefs/prefsmanager/collections/pc_app_h.inl"
// Read ------
/**
* Read an integer preference.
*
* @param which Selects the preference to retrieve.
* retrieve the default context.
*/
inline int GetIntegerPref(integerpref which) const
{
return OpPrefsCollectionDefault::GetIntegerPref(int(which));
};
/**
* Read a string preference.
*
* @param which Selects the preference to retrieve.
* @param result Variable where the value will be stored.
* retrieve the default context.
*/
inline void GetStringPrefL(stringpref which, OpString &result) const
{
result.SetL(GetStringPref(which));
}
/**
* Read a string preference. Use of this method is slighlty deprecated,
* as it will return a pointer to internal data. Use it where performance
* demands it. The object is only guaranteed to live until the next call
* to a Write method.
*
* @param which Selects the preference to retrieve.
*/
inline const OpStringC GetStringPref(stringpref which) const
{
RETURN_OPSTRINGC(OpPrefsCollectionDefault::GetStringPref(int(which)));
}
#ifdef _PLUGIN_SUPPORT_
/**
* Check whether a given plugin is on the ignore list.
*
* @param plugname Name of plugin
* @return TRUE if the plugin should be ignored
*/
BOOL IsPluginToBeIgnored(const uni_char *plugname);
# if defined PREFS_IGNOREPLUGIN_CONFIGURE && defined PREFS_WRITE
/**
* Add or remove a plugin in the ignore list.
*
* @param plugname Name of plugin
* @param ignore TRUE if the plugin should be ignored.
*/
void WritePluginToBeIgnoredL(const uni_char *plugfilename, BOOL ignore);
# endif
#endif
#ifdef DYNAMIC_VIEWERS
/**
* Read viewer types defined in the fixed global, user and global
* preferences files. A type can only be returned once, and that is
* from the highest ranking file it is found in.
*
* Please note that reading this section may require reading back the
* file into the cache, so it may leave if you are low on memory. Also,
* make sure you read the section through to the end, as it will clean
* up its internal state only when it is ready.
*
* @param key Buffer receiving key name
* @param value Buffer receiving value data
* @param errval Returned error code, if any
* @param restart TRUE to restart reading, FALSE to continue.
* @return TRUE if another value exists, FALSE if we are done reading or
* if an error occured.
*/
BOOL ReadViewerTypesL(
OpString &key,
OpString &value,
OP_STATUS &errval,
BOOL restart = FALSE);
/**
* Read extended data associated with this viewer.
* @param key Key to lookup.
* @param buf String that receives extended data.
* @return TRUE if a value was read.
*/
BOOL ReadViewerExtensionL(const OpStringC &key, OpString &buf);
#endif // DYNAMIC_VIEWERS
#ifdef PREFS_HAVE_STRING_API
virtual BOOL GetPreferenceL(IniSection section, const char *key, OpString &target,
BOOL defval, const uni_char *)
{
return OpPrefsCollectionDefault::GetPreferenceInternalL(
section, key, target, defval,
m_stringprefdefault, PCAPP_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCAPP_NUMBEROFINTEGERPREFS);
}
#endif
// Defaults ------
/**
* Get default value for an integer preference.
*
* @param which Selects the preference to retrieve.
* @return The default value.
*/
inline int GetDefaultIntegerPref(integerpref which) const
{
return m_integerprefdefault[which].defval;
}
/**
* Get default value for a string preference.
*
* @param which Selects the preference to retrieve.
* @return The default value.
*/
const uni_char *GetDefaultStringPref(stringpref which) const;
#ifdef PREFS_WRITE
// Write ------
/** Write a string preference.
*
* @param which The preference to write.
* @param value Value for the write.
* @return ERR_NO_ACCESS if override is not allowed, OK otherwise.
*/
inline OP_STATUS WriteStringL(stringpref which, const OpStringC &value)
{
return OpPrefsCollection::WriteStringL(&m_stringprefdefault[which], int(which), value);
}
/** Write an integer preference.
*
* @param which The preference to write.
* @param value Value for the write.
* @return ERR_NO_ACCESS if override is not allowed, OK otherwise.
*/
inline OP_STATUS WriteIntegerL(integerpref which, int value)
{
return OpPrefsCollection::WriteIntegerL(&m_integerprefdefault[which], int(which), value);
}
# ifdef PREFS_HAVE_STRING_API
virtual BOOL WritePreferenceL(IniSection section, const char *key, const OpStringC &value)
{
return OpPrefsCollection::WritePreferenceInternalL(
section, key, value,
m_stringprefdefault, PCAPP_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCAPP_NUMBEROFINTEGERPREFS);
}
# endif
#endif // PREFS_WRITE
#ifdef PREFS_WRITE
// Reset ------
/** Reset a string preference. Resets the preference to default by
* removing the set value from the preference storage.
*
* @param which The preference to reset.
* @return TRUE if the delete succeeded.
*/
inline BOOL ResetStringL(stringpref which)
{
return OpPrefsCollection::ResetStringL(&m_stringprefdefault[which], int(which));
}
/** Reset an integer preference. Resets the preference to default by
* removing the set value from the preference storage.
*
* @param which The preference to reset.
* @return TRUE if the delete succeeded.
*/
inline BOOL ResetIntegerL(integerpref which)
{
return OpPrefsCollection::ResetIntegerL(&m_integerprefdefault[which], int(which));
}
#endif // PREFS_WRITE
// Fetch preferences from file ------
virtual void ReadAllPrefsL(PrefsModule::PrefsInitInfo *info);
#ifdef PREFS_ENUMERATE
// Enumeration helpers ------
virtual unsigned int GetNumberOfPreferences() const
{
return PCAPP_NUMBEROFSTRINGPREFS + PCAPP_NUMBEROFINTEGERPREFS;
}
virtual unsigned int GetPreferencesL(struct prefssetting *settings) const
{
return OpPrefsCollection::GetPreferencesInternalL(settings,
m_stringprefdefault, PCAPP_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCAPP_NUMBEROFINTEGERPREFS);
}
#endif
#if defined DYNAMIC_VIEWERS && defined UPGRADE_SUPPORT
/**
* Deletes Viewer sections in the main prefs file (since viewers were moved to their own file)
*/
void DeleteViewerSectionsL();
#endif // defined DYNAMIC_VIEWERS && defined UPGRADE_SUPPORT
private:
/** Single-phase constructor.
*
* @param reader Pointer to the PrefsFile object.
*/
PrefsCollectionApp(PrefsFile *reader)
: OpPrefsCollectionDefault(App, reader)
#if defined _PLUGIN_SUPPORT_ && defined PREFS_HAS_PREFSFILE && defined PREFS_READ
# ifdef PREFS_IGNOREPLUGIN_CONFIGURE
, m_ignoreini(NULL)
# else
, m_IgnorePlugins(NULL)
# endif
#endif
#ifdef DYNAMIC_VIEWERS
, m_viewersection(NULL)
, m_viewerextensionsection(NULL)
, m_viewer_current(NULL)
#endif
{
#ifndef HAS_COMPLEX_GLOBALS
InitStrings();
InitInts();
#endif
}
/** String preference information and default values */
PREFS_STATIC struct stringprefdefault
m_stringprefdefault[PCAPP_NUMBEROFSTRINGPREFS + 1];
/** Integer preference information and default values */
PREFS_STATIC struct integerprefdefault
m_integerprefdefault[PCAPP_NUMBEROFINTEGERPREFS + 1];
#ifdef PREFS_VALIDATE
virtual void CheckConditionsL(int which, int *value, const uni_char *host);
virtual BOOL CheckConditionsL(int which, const OpStringC &invalue,
OpString **outvalue, const uni_char *host);
#endif
#if defined PREFS_HAVE_STRING_API || defined PREFS_WRITE
virtual const uni_char *GetDefaultStringInternal(int, const struct stringprefdefault *);
#endif
#if defined _PLUGIN_SUPPORT_ && defined PREFS_HAS_PREFSFILE && defined PREFS_READ
void ReadPluginsToBeIgnoredL();
# ifdef PREFS_IGNOREPLUGIN_CONFIGURE
class PrefsFile *m_ignoreini; ///< File for plugins to be ignored
# else
PrefsSection *m_IgnorePlugins; ///< Plugins that should be ignored
# endif
#endif
#ifdef DYNAMIC_VIEWERS
PrefsSection *m_viewersection; ///< State for ReadViewerTypesL
PrefsSection *m_viewerextensionsection; ///< State for ReadViewerTypesL
const PrefsEntry *m_viewer_current; ///< State for ReadViewerTypesL
#endif // DYNAMIC_VIEWERS
#ifndef HAS_COMPLEX_GLOBALS
void InitStrings();
void InitInts();
#endif
};
#endif // PC_APP_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Karianne Ekern (karie)
*/
#ifndef QUIX_DESKTOP_ENVIRONMENT
#define QUIX_DESKTOP_ENVIRONMENT
/**
* @brief
*
* DesktopEnvironment
*
*/
class DesktopEnvironment
{
public:
enum ToolkitType
{
TOOLKIT_AUTOMATIC,
TOOLKIT_QT,
TOOLKIT_GTK,
TOOLKIT_KDE,
TOOLKIT_X11,
TOOLKIT_GTK3,
TOOLKIT_UNKNOWN
};
enum ToolkitEnvironment
{
ENVIRONMENT_GNOME,
ENVIRONMENT_GNOME_3,
ENVIRONMENT_UNITY,
ENVIRONMENT_KDE,
ENVIRONMENT_XFCE,
ENVIRONMENT_UNKNOWN,
ENVIRONMENT_TO_BE_DETERMINED
};
static DesktopEnvironment& GetInstance();
/**
* @return Desktop environment the user is running
*/
ToolkitEnvironment GetToolkitEnvironment();
void GetDesktopEnvironmentName(OpString8& name);
/**
* @return the preferred ToolkitType to use
* this can be forced by pref Dialog Toolkit
* and may be different from the ToolkitEnvironment
* Will always return a concrete toolkit type (ie. never TOOLKIT_AUTOMATIC or TOOLKIT_UNKNOWN)
*/
ToolkitType GetPreferredToolkit();
private:
void DetermineToolkitAutomatically();
bool IsGnomeRunning();
bool IsGnome3Running();
bool IsUbuntuUnityRunning();
bool IsKDERunning();
bool IsXfceRunning();
ToolkitType m_toolkit;
ToolkitEnvironment m_toolkit_environment;
bool m_initialized;
DesktopEnvironment();
~DesktopEnvironment() {}
};
#endif // QUIX_DESKTOP_ENVIRONMENT
|
#pragma once
#ifndef SLOTH_RAW_CAMERA_H_
#define SLOTH_RAW_CAMERA_H_
#include <sloth.h>
#include <window.h>
#include <config/header.hpp>
namespace sloth {
class RawCamera
{
protected:
// vectors of camera
glm::vec3 m_Position;
float m_Pitch;
float m_Yaw;
public:
RawCamera()
:m_Position(CAMERA_INIT_POS),
m_Pitch(CAMERA_INIT_PITCH), m_Yaw(CAMERA_INIT_YAW) {}
virtual ~RawCamera() {}
virtual void process(SlothWindow * window) = 0;
virtual glm::mat4 getViewMatrix() const = 0;
virtual glm::vec3 getFront() const = 0;
glm::vec3 getPosition() const { return m_Position; }
float getPitch() const { return m_Pitch; }
float getYaw() const { return m_Yaw; }
void setPosition(const glm::vec3 &position) { m_Position = position; }
};
}
#endif // !SLOTH_RAW_CAMERA_H_
|
#pragma once
#include "../Config.hpp"
#include "../SecureWiper.hpp"
#include "../Array.hpp"
#include "../Intrinsic.hpp"
#include <memory.h>
namespace accel::Crypto {
template<size_t __N>
class XXTEA_ALG {
static_assert(__N >= 2);
public:
static constexpr size_t BlockSizeValue = __N * sizeof(uint32_t);
static constexpr size_t KeySizeValue = 128 / 8;
private:
static constexpr uint32_t _Delta = 0x9E3779B9;
static constexpr size_t _Rounds = 6 + 52 / __N;
union BlockType {
uint8_t bytes[__N * sizeof(uint32_t)];
uint32_t dwords[__N];
};
static_assert(sizeof(BlockType) == BlockSizeValue);
SecureWiper<Array<uint32_t, 4>> _KeyWiper;
Array<uint32_t, 4> _Key;
ACCEL_FORCEINLINE
uint32_t _MX(uint32_t& e,
uint32_t& y,
uint32_t& z,
uint32_t& sum,
unsigned& p) const noexcept {
return ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum ^ y) + (_Key[(p % 4) ^ e] ^ z));
}
ACCEL_FORCEINLINE
void _EncryptProcess(BlockType& RefBlock) const noexcept {
uint32_t y, z, sum = 0;
unsigned p, e;
z = RefBlock.dwords[__N - 1];
for (size_t n = 0; n < _Rounds; ++n) {
sum += _Delta;
e = (sum >> 2) % 4;
for (p = 0; p < __N - 1; ++p) {
y = RefBlock.dwords[p + 1];
z = RefBlock.dwords[p] += _MX(e, y, z, sum, p);
}
y = RefBlock.dwords[0];
z = RefBlock.dwords[__N - 1] += _MX(e, y, z, sum, p);
}
}
ACCEL_FORCEINLINE
void _DecryptProcess(BlockType& RefBlock) const noexcept {
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4309)
#endif
uint32_t y, z, sum = static_cast<uint32_t>(_Rounds * _Delta);
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
unsigned p, e;
y = RefBlock.dwords[0];
for (size_t n = 0; n < _Rounds; ++n) {
e = (sum >> 2) % 4;
for (p = __N - 1; p > 0; --p) {
z = RefBlock.dwords[p - 1];
y = RefBlock.dwords[p] -= _MX(e, y, z, sum, p);
}
z = RefBlock.dwords[__N - 1];
y = RefBlock.dwords[0] -= _MX(e, y, z, sum, p);
sum -= _Delta;
}
}
public:
XXTEA_ALG() noexcept :
_KeyWiper(_Key) {}
constexpr size_t BlockSize() const noexcept {
return BlockSizeValue;
}
constexpr size_t KeySize() const noexcept {
return KeySizeValue;
}
[[nodiscard]]
bool SetKey(const void* pUserKey, size_t UserKeySize) noexcept {
if (UserKeySize != KeySizeValue) {
return false;
} else {
memcpy(_Key.CArray(), pUserKey, KeySizeValue);
_Key[0] = ByteSwap<uint32_t>(_Key[0]);
_Key[1] = ByteSwap<uint32_t>(_Key[1]);
_Key[2] = ByteSwap<uint32_t>(_Key[2]);
_Key[3] = ByteSwap<uint32_t>(_Key[3]);
return true;
}
}
size_t EncryptBlock(void* pPlaintext) const noexcept {
BlockType Text = *reinterpret_cast<BlockType*>(pPlaintext);
for (size_t i = 0; i < __N; ++i)
Text.dwords[i] = ByteSwap<uint32_t>(Text.dwords[i]);
_EncryptProcess(Text);
for (size_t i = 0; i < __N; ++i)
Text.dwords[i] = ByteSwap<uint32_t>(Text.dwords[i]);
*reinterpret_cast<BlockType*>(pPlaintext) = Text;
return BlockSizeValue;
}
size_t DecryptBlock(void* pCiphertext) const noexcept {
BlockType Text = *reinterpret_cast<BlockType*>(pCiphertext);
for (size_t i = 0; i < __N; ++i)
Text.dwords[i] = ByteSwap<uint32_t>(Text.dwords[i]);
_DecryptProcess(Text);
for (size_t i = 0; i < __N; ++i)
Text.dwords[i] = ByteSwap<uint32_t>(Text.dwords[i]);
*reinterpret_cast<BlockType*>(pCiphertext) = Text;
return BlockSizeValue;
}
void ClearKey() noexcept {
_Key.SecureZero();
}
};
}
|
//
// hash.h
// HashTable
//
// Created by Georgiy danielyan on 5/10/15.
// Copyright (c) 2015 Goga. All rights reserved.
//
// Hash Table Tutorial by PaulProgramming.
// Followed along and replicated the code.
// Hash Table and methods work properly.
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
using namespace std;
#ifndef _HASH_H
#define _HASH_H
const int TABLE_SIZE = 4;
class Hash
{
private:
struct item{
string name;
string favoriteDrink;
item* next;
};
item* HashTable[TABLE_SIZE];
public:
Hash();
int HashFunction(string key);
void addItem(string name, string drink);
int numberOfItemsInIndex(int index);
int printTotalNumberOfItems();
void printTable();
void printItemsInIndex(int index);
void findDrink(string drink);
void removeItem(string name);
}; // end Hash
#endif
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
int n,cuts;
while(true)
{
cin>>n;
if(n==0)
break;
cuts=0;
while(n>1)
{
cuts++;
n/=2;
}
cout<<cuts<<endl;
}
return 0;
}
|
#include <iostream>
#include "exam.h"
/***
* -------------------------------------------------------------------------------------------------------------------
* 题目
* -------------------------------------------------------------------------------------------------------------------
* 无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。并将结果按字符串从小到大排序
*
* 示例1:
* - 输入:S = "qwe"
* - 输出:["eqw", "ewq", "qew", "qwe", "weq", "wqe"]
*
* 示例2:
* - 输入:S = "ab"
* - 输出:["ab", "ba"]
*
* 要求:
* 1. 仅修改exam.h文件,通过所有单元测试。
* 2. 输出结果按照字典顺序排序
* 3. exam.h以外的文件不得修改,修改会被覆盖。
*/
int main() {
// auto tt = Exam::output2("qwe");
// for (auto &i : tt) {
// cout << i << endl;
// }
// TreeNode *root = new TreeNode(100);
// root->left = new TreeNode(110);
// root->right = new TreeNode(101);
// root->left->left = new TreeNode(110);
// root->left->left->right = new TreeNode(110);
// auto result = Exam::isBalanced(root);
//
// cout<< " isBalanced " << result << endl;
// vector<int> arr = {1, 0, 2, 3};
// Exam::duplicateZeros(arr);
//
// for (auto &i : arr) {
// cout << i << endl;
// }
// auto *head = new ListNode(1);
// head->next = new ListNode(2);
// head->next->next = new ListNode(3);
// head->next->next->next = new ListNode(4);
// head->next->next->next->next = new ListNode(5);
// head->next->next->next->next->next = new ListNode(6);
//
// auto result = Exam::getKthFromEnd(head, 6);
//
// cout << result->val << endl;
// int molecule = -10;
// int denominator = 2;
// Exam::reduce(molecule, denominator);
// cout << molecule << " " << denominator;
vector<int> arr = {3, 2, 0, 2};
auto result = Exam::fraction(arr);
for (auto &i : result) {
cout << i << endl;
}
return 0;
}
|
#ifndef S_GRAV_OBJ
#define S_GRAV_OBJ
#include "GravityObject.h"
class SelectGravityObject : public GravityObject
{
public:
SelectGravityObject();
SelectGravityObject(int weight, Vector* position = new Vector(), Vector* speed = new Vector(), Vector* acceleration = new Vector());
SelectGravityObject(const SelectGravityObject &gravObj);
~SelectGravityObject();
virtual void setWeight(int weight);
virtual double getSelectRadius() const;
virtual double getSquareSelectRadius() const;
virtual bool isInZone(double x, double y) const;
virtual bool isSelected() const;
virtual void setSelected(bool selected);
virtual void draw(SDL_Surface* screen, const Parameters* params) const;
// virtual void calculateGravityAcceleration(const std::vector<SelectGravityObject*> &universe);
protected:
double _selectRadius;
double _squareSelectRadius;
bool _selected;
private:
void initialize();
};
#endif
|
#include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
string s;
struct Solution {
int solve() {
int curr = 0, res = 0, start = 0;
for (char c : s) {
curr += c == '+' ? 1 : -1;
res = max(res, curr);
start = min(start, curr);
}
return res - start;
}
};
int main() {
ios::sync_with_stdio(false);
cin >> s;
Solution test;
cout << test.solve() << endl;
}
|
#pragma once
#include "State.h"
class GameEndState :
public State
{
private:
//
/*sf::RectangleShape Box;*/
sf::Clock quitTimer;
sf::RectangleShape BlackScreen;
int screen_a;
//Texture/Sprites
sf::Texture screen_texture;
sf::Sprite screen_sprite;
//game logic
PointData game_result;
long int temp_points;
int temp_combo, temp_good, temp_ok, temp_bad;
enum layer_display { POINTS, COMMENT, COMBO, FADE, FINISH} current_dp;
//Text
sf::Font taikoFont;
sf::Text PointText;
sf::Text ComboText;
sf::Text GoodText;
sf::Text BadText;
sf::Text OkText;
void InitVariables();
void InitFrame();
void InitText();
public:
//Constructors
GameEndState(sf::RenderWindow* window, std::stack<State*>* states, PointData data);
~GameEndState();
void endState();
//Update
void updateFadeOut();
void updateKeybinds(const float& dt, sf::Event::EventType eventType);
void update(const float& dt);
void updateCommentPoints();
void updateCombo();
void updatePoints();
void updateText();
//Render
void render(sf::RenderTarget* target = nullptr);
void renderText(sf::RenderTarget* target);
};
|
/**
* Peripheral Definition File
*
* NVIC - Nested Vector Interrupt Controller
*
* MCUs containing this peripheral:
* - Cortex-M0
* - Cortex-M0plus
* - Cortex-M3
* - Cortex-M4
* - Cortex-M7
*/
#pragma once
#include <cstdint>
#include <cstddef>
namespace io {
struct Nvic {
/** Software trigger interrupt register
* This register is on Cortex-M3, M4 and M7
*/
struct Stir {
Stir(const uint32_t raw=0) { r = raw; }
struct Bits {
uint32_t INTID : 9; // Software generated interrupt ID
uint32_t : 23;
};
union {
uint32_t r;
Bits b;
uint32_t INTID; // direct 32 bit access to INTID
};
};
volatile uint32_t ISER[8]; // Interrupt set-enable registers
uint32_t __res0[24];
volatile uint32_t ICER[8]; // Interrupt clear-enable registers
uint32_t __res1[24];
volatile uint32_t ISPR[8]; // Interrupt set-pending registers
uint32_t __res2[24];
volatile uint32_t ICPR[8]; // Interrupt clear-pending registers
uint32_t __res3[24];
volatile const uint32_t IABR[8]; // Interrupt active bit registers (M3, M4, M7)
uint32_t __res4[56];
volatile uint8_t IPR[240]; // Interrupt priority registers
uint32_t __res5[644];
volatile Stir STIR; // Software trigger interrupt register (M3, M4, M7)
/** Enable interrupt
* @param isr interrupt ID
*/
inline void iser(uint32_t isr) {
ISER[isr >> 5] = static_cast<uint32_t>(1 << (isr & 0x1f));
}
/** Disable interrupt
* @param isr interrupt ID
*/
inline void icer(uint32_t isr) {
ICER[isr >> 5] = static_cast<uint32_t>(1 << (isr & 0x1f));
}
/** Is interrupt enabled
* @param isr interrupt ID
* @return True if interrupt is enabled
*/
inline bool ier(uint32_t isr) const {
return ISER[isr >> 5] & static_cast<uint32_t>(1 << (isr & 0x1f));
}
/** Enable pending interrupt
* @param isr interrupt ID
*/
inline void ispr(uint32_t isr) {
ISPR[isr >> 5] = static_cast<uint32_t>(1 << (isr & 0x1f));
}
/** Disable pending interrupt
* @param isr interrupt ID
*/
inline void icpr(uint32_t isr) {
ICPR[isr >> 5] = static_cast<uint32_t>(1 << (isr & 0x1f));
}
/** Is pending interrupt
* @param isr interrupt ID
* @return True if interrupt is enabled
*/
inline bool ipr(uint32_t isr) const {
return ISPR[isr >> 5] & static_cast<uint32_t>(1 << (isr & 0x1f));
}
/** Is interrupt active
* @param isr interrupt ID
* @return True if interrupt is active
*/
inline bool iabr(uint32_t isr) const {
return IABR[isr >> 5] & static_cast<uint32_t>(1 << (isr & 0x1f));
}
/** Enable global interrupt
*/
static inline void isr_enable() {
__asm volatile ("cpsie i" : : : "memory");
}
/**
* disable global interrupt
*/
static inline void isr_disable() {
__asm volatile ("cpsid i" : : : "memory");
}
static const size_t BASE = 0xe000e100;
};
static Nvic &NVIC = *reinterpret_cast<Nvic *>(Nvic::BASE);
}
|
#include<stdio.h>
void shellSortBubble(int a[], int n)
{
int temp, i, j, flag, gap = n;
while (gap > 1) {
gap = gap / 2;
do {
flag = 0;
for (i = 0; i < n - gap; i ++) {
j = i + gap;
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
flag = 1;
}
}
} while (flag != 0);
}
}
int main()
{
int a[10] = {7,85,45,74,123,69,5,41,0,12};
for (int i = 0; i < 10; i ++) {
printf("%d ", a[i]);
}
printf("\n");
shellSortBubble(a, 10);
for (int i = 0; i < 10; i ++) {
printf("%d ", a[i]);
}
printf("\n");
}
|
#include<iostream.h>
#include<conio.h>
#include<string.h>
int max(int a,int b)
{
return (a>b)?a:b;
}
int lcs(char *x,char *y,int m,int n)
{
int i,j,l[10][10];
for(i=0;i<=m;i++)
{
for(j=0;j<=n;j++)
{
if(i==0||j==0)
{
l[i][j]=0;
}
else if(x[i-1]==y[j-1])
{
l[i][j]=l[i-1][j-1]+1;
}
else
{ l[i][j]=max(l[i-1][j],l[i][j-1]) ;
}
}
}
int k=l[m][n];
char l1[10];
l1[k]='\0';
i=m;
j=n;
while(i>0 && j>0)
{
if(x[i-1]==y[j-1])
{
l1[k-1]=x[i-1];
i--;
j--;
k--;
}
else if(l[i][j-1]>l[i][j-1])
i--;
else
j--;
}
cout<<"lcs is:" <<l1<<endl;
return l[m][n];
}
void main()
{
clrscr();
char x[100],y[100];
int m,n;
cout<<"enter first sequence:";
cin>>x;
cout<<"enter second sequence:";
cin>>y;
m=strlen(x);
n=strlen(y);
cout<<"Length of longest common subsequence:"<<lcs(x,y,m,n);
getch();
}
|
//
// codegen.cpp
// mini-sql
//
// Created by Дмитрий Маслюков on 25.02.2020.
// Copyright © 2020 Дмитрий Маслюков. All rights reserved.
//
#include "codegen.hpp"
void CodeGen::write_node (Parser::astnode * node, frame * fr){
switch (node->type) {
case Parser::NUMVAL:{
long val = (*(long*)node->val << 1) | 1;
fr->statics.push_back((void*)val);
write_op(fr, op::load_static, (int)fr->statics.size() - 1);
}break;
case Parser::STRVAL:{
fr->statics.push_back((void*)node->val);
write_op(fr, op::load_static, (int)fr->statics.size() - 1);
}break;
case Parser::SYMBOL:{
fr->statics.push_back((void*)node->val);
write_op(fr, op::load_prop, (int)fr->statics.size() - 1);
}break;
case Parser::EQUALS:{
write_node(node->children[1], fr);
write_node(node->children[0], fr);
if( node->children[1]->type == Parser::STRVAL ){
write_op(fr, op::eq_comp_str);
} else {
write_op(fr, op::eq_comp_int);
}
}break;
case Parser::LESS:{
write_node(node->children[1], fr);
write_node(node->children[0], fr);
if( node->children[1]->type == Parser::STRVAL ){
write_op(fr, op::less_comp_str);
} else {
write_op(fr, op::less_comp_int);
}
}break;
case Parser::GREATER:{
write_node(node->children[1], fr);
write_node(node->children[0], fr);
if( node->children[1]->type == Parser::STRVAL ){
write_op(fr, op::gt_comp_str);
} else {
write_op(fr, op::gt_comp_int);
}
}break;
case Parser::AND:{
write_node(node->children[1], fr);
write_node(node->children[0], fr);
write_op(fr, op::and_op);
}break;
case Parser::OR:{
write_node(node->children[1], fr);
write_node(node->children[0], fr);
write_op(fr, op::or_op);
}break;
case Parser::NOT:{
write_node(node->children[0], fr);
write_op(fr, op::not_op);
}break;
case Parser::SUBSCR:{
bool is_global = strcmp( (const char*)node->children[0]->val, "this" ) == 0;
if(!is_global){
write_node(node->children[0], fr);
write_node(node->children[1], fr);
} else {
size_t curpos = fr->operands.size();
write_node(node->children[1], fr);
fr->operands[curpos].type = op::load_global;
}
}break;
default:
break;
}
}
|
#include "CHSRandom.hpp"
CHSRandom::CHSRandom () {
this->seed_x = HSRANDOM_BASIC_SEED_X;
this->seed_y = HSRANDOM_BASIC_SEED_Y;
this->seed_z = HSRANDOM_BASIC_SEED_Z;
this->seed_w = HSRANDOM_BASIC_SEED_W;
}
void CHSRandom::SetSeed ( unsigned int seed ) {
if ( seed == 0 ) {
this->seed_x = HSRANDOM_BASIC_SEED_X;
this->seed_y = HSRANDOM_BASIC_SEED_Y;
this->seed_z = HSRANDOM_BASIC_SEED_Z;
this->seed_w = HSRANDOM_BASIC_SEED_W;
} else {
unsigned int b1 , b2;
seed_x = seed;
seed_y = ( ( seed & 0xFFFF0000 ) >> 16 ) | ( ( seed & 0x0000FFFF ) << 16 );
b1 = seed & 0x0000000F;
b1 |= ( seed & 0x00000F00 ) >> 4;
b1 |= ( seed & 0x000F0000 ) >> 8;
b1 |= ( seed & 0x0F000000 ) >> 12;
b2 = ( seed & 0x000000F0 ) >> 4;
b2 |= ( seed & 0x0000F000 ) >> 8;
b2 |= ( seed & 0x00F00000 ) >> 12;
b2 |= ( seed & 0xF0000000 ) >> 16;
seed_z = b1 | ( b2 << 16 );
seed_w = ( b1 << 16 ) | b2;
}
}
void CHSRandom::SetSeedEx ( unsigned int seed ) {
unsigned int seed2 = reinterpret_cast<unsigned int>( this );
seed_x = seed;
seed_y = seed2;
seed_z = ( ( seed & 0xFFFF0000 ) >> 16 ) | ( ( seed & 0x0000FFFF ) << 16 );
seed_w = ( ( seed2 & 0xFFFF0000 ) >> 16 ) | ( ( seed2 & 0x0000FFFF ) << 16 );
}
void CHSRandom::SetSeedFromLocalTime ( void ) {
this->SetSeed ( (unsigned) time ( NULL ) );
}
void CHSRandom::SetSeedFromLocalTimeEx ( void ) {
this->SetSeedEx ( (unsigned) time ( NULL ) );
}
unsigned int CHSRandom::Next ( void ) {
unsigned int t = seed_x ^ ( seed_x << 11 );
seed_x = seed_y;
seed_y = seed_z;
seed_z = seed_w;
seed_w = ( seed_w ^ ( seed_w >> 19 ) ) ^ ( t ^ ( t >> 8 ) );
return seed_w;
}
unsigned int CHSRandom::RangeNext ( unsigned int minValue , unsigned int maxValue ) {
unsigned int range = maxValue - minValue + 1;
return ( Next () % range ) + minValue;
}
int CHSRandom::RangeNextSigned ( int minValue , int maxValue ) {
int range = maxValue - minValue + 1;
return ( Next () % range ) + minValue;
}
|
#include "kg/util/log.hh"
#include "kg_features.hh"
#include <include/cef_app.h>
#include <include/cef_client.h>
class cef_client : public CefClient, public CefLifeSpanHandler, public CefLoadHandler, public CefDisplayHandler {
public:
cef_client() : CefClient {}, CefLifeSpanHandler {}, CefDisplayHandler {}, _browser { nullptr } {}
~cef_client() {}
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override {
return this;
}
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() override {
return this;
}
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() override {
return this;
}
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) override {
kg::log::debug() << "OnAfterCreated";
_browser = browser;
}
virtual bool DoClose(CefRefPtr<CefBrowser> browser) override {
kg::log::debug() << "DoClose";
CefQuitMessageLoop();
return false;
}
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) override {
kg::log::debug() << "OnBeforeClose";
_browser = nullptr;
}
virtual void
OnLoadingStateChange(CefRefPtr<CefBrowser> browser, bool isLoading, bool canGoBack, bool canGoForward) override {
kg::log::debug() << "OnLoadingStateChange isLoading = " << isLoading;
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override {
kg::log::debug() << "OnLoadEnd status = " << httpStatusCode;
}
virtual void OnLoadError(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefLoadHandler::ErrorCode errorCode,
CefString const & errorText, CefString const & failedUrl) override {
kg::log::debug() << "OnLoadError error = (" << errorCode << ") " << errorText << ", url = " << failedUrl;
}
virtual void OnLoadStart(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefLoadHandler::TransitionType transition) override {
kg::log::debug() << "OnLoadStart";
}
virtual void
OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefString const & url) override {
kg::log::debug() << "OnAddressChange url = " << url;
}
virtual void OnTitleChange(CefRefPtr<CefBrowser> browser, CefString const & title) override {
kg::log::debug() << "OnTitleChange title = " << title;
}
IMPLEMENT_REFCOUNTING(cef_client);
private:
CefRefPtr<CefBrowser> _browser;
};
class cef_app : public CefApp, public CefBrowserProcessHandler {
public:
cef_app() : CefApp {}, CefBrowserProcessHandler {} {}
virtual CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler() override {
return this;
}
virtual void OnContextInitialized() override {
kg::log::debug() << "OnContextInitialized";
CefBrowserSettings browserSettings;
CefWindowInfo window;
CefRefPtr<cef_client> client { new cef_client {} };
#ifdef _WIN32
window.SetAsPopup(nullptr, "Sandbox");
#endif
CefBrowserHost::CreateBrowser(window, client, "https://www.google.com", browserSettings, nullptr, nullptr);
}
IMPLEMENT_REFCOUNTING(cef_app);
};
#ifdef _WIN32
int wWinMain(HINSTANCE instance, HINSTANCE, LPWSTR, INT) {
CefMainArgs args { instance };
CefEnableHighDPISupport();
#else
int main(int argc, char ** argv) {
CefMainArgs args { argc, argv };
#endif
int ret { CefExecuteProcess(args, nullptr, nullptr) };
if (ret >= 0) {
return 0;
}
CefSettings settings;
CefRefPtr<cef_app> app { new cef_app {} };
// auto helper = std_fs_impl::current_path() / "kg.sandbox.exe";
// CefString(&settings.browser_subprocess_path) = helper.native();
if (!CefInitialize(args, settings, app, nullptr)) {
abort();
}
CefRunMessageLoop();
CefShutdown();
return 0;
}
|
#ifndef ParamsModel_H
#define ParamsModel_H
#include <QAbstractTableModel>
#include <QStyleOptionViewItem>
#include "../framework/ProcessingStep.hpp"
#include <../framework/ModuleManager.hpp>
#include <../framework/MetaData.hpp>
namespace uipf {
class ParamsModel : public QAbstractTableModel
{
Q_OBJECT
public:
// constructor
ParamsModel(ModuleManager&, QObject *parent);
// sets the number of rows for the widget
int rowCount(const QModelIndex &parent = QModelIndex()) const ;
// sets the number of columns for the widget
int columnCount(const QModelIndex &parent = QModelIndex()) const;
// this method is triggered when a parameter has been edited
bool setData(const QModelIndex &index, const QVariant &value, int role);
// describes the data that is displayed in the widget
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
// describes what is displayed in the headers of the table
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
// sets the processing step this widget represents and updates the content
void setProcessingStep(uipf::ProcessingStep);
// set flags for the fields, allows them to be editable
Qt::ItemFlags flags (const QModelIndex &index) const;
signals:
void paramChanged(std::string, std::string);
private:
ModuleManager& mm_;
// the processing step represented by this widget
ProcessingStep step_;
// vector of available param names, index is equal to index in the widget
std::vector<std::string> paramNames_;
};
} // namespace
#endif // ParamsModel_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2003 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 "desktop_starter.h"
#include "platforms/windows/windows_ui/res/#BuildNr.rci"
#ifdef AUTO_UPDATE_SUPPORT
#include "adjunct/autoupdate/updater/auupdater.h"
#include "adjunct/autoupdate/updater/pi/auinstaller.h"
#include "adjunct/autoupdate/updater/pi/aufileutils.h"
#endif
#include "adjunct/quick/managers/LaunchManager.h"
#include "platforms/crashlog/crashlog.h"
#include "platforms/windows/utils/shared.h"
#include "platforms/windows/desktop_starter/dep.h"
#include "platforms/windows/desktop_starter/win_file_utils.h"
BOOL GetIntegrityLevel(DWORD process_id,DWORD& integrity_level)
{
OSVERSIONINFOA osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
if (!GetVersionExA(&osvi) || osvi.dwMajorVersion < 6) // Older than Vista.
return FALSE;
integrity_level = 0;
HANDLE hProcess = 0;
HANDLE hToken = 0;
DWORD size = 0;
TOKEN_MANDATORY_LABEL* label = 0;
do
{
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process_id);
if (!hProcess)
break;
if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
break;
if (!GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS)TokenIntegrityLevel, NULL, 0, &size) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
break;
label = (TOKEN_MANDATORY_LABEL*) malloc(size);
if (!label)
break;
if (!GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS)TokenIntegrityLevel, label, size, &size) || !IsValidSid(label->Label.Sid))
break;
integrity_level = *(GetSidSubAuthority(label->Label.Sid, *(GetSidSubAuthorityCount(label->Label.Sid))-1));
} while (0);
if (label)
free(label);
if (hToken)
CloseHandle(hToken);
if (hProcess)
CloseHandle(hProcess);
return (integrity_level != 0);
}
void RestartWithMediumIntegrityLevel()
{
HANDLE hProcess = 0;
HANDLE hToken = 0;
HANDLE hDupToken = 0;
PROCESS_INFORMATION proc_info = {0};
STARTUPINFOW startup_info = {0};
HWND hWnd_progman = ::FindWindowA("Progman", NULL);
if (!hWnd_progman) // This should only happen if Explorer has crashed
return;
DWORD explorer_pid = 0;
GetWindowThreadProcessId(hWnd_progman, &explorer_pid);
if (!explorer_pid)
return;
//If explorer has a high integrity level, it means UAC is turned off, so no need to restart.
DWORD integrity_level;
if (!GetIntegrityLevel(explorer_pid, integrity_level) || integrity_level > SECURITY_MANDATORY_MEDIUM_RID)
return;
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, explorer_pid);
if (!hProcess)
return;
do
{
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, &hToken))
break;
if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS | TOKEN_ADJUST_SESSIONID, 0, SecurityImpersonation, TokenPrimary, &hDupToken))
break;
if (!OPCreateProcessWithTokenW(hDupToken, 0, NULL, GetCommandLine(), 0, 0, 0, &startup_info, &proc_info))
break;
ExitProcess(0);
} while (0);
if (hToken)
CloseHandle(hToken);
if (hDupToken)
CloseHandle(hDupToken);
if (hProcess)
CloseHandle(hProcess);
return;
}
UINT_PTR simple_hextoint(char *str)
{
if (!str)
return 0;
UINT_PTR retval = 0;
unsigned char c;
while ((c = *str) != 0)
{
// Make alphabetical characters lowercase (does not affect digits).
c |= 0x20;
// If we have a digit || letter (c-('a'-'0'-0xA)) && letter is not bigger than f.
if ((c -= '0') <= 9 || ((c -= 0x27) >= 10 && c <= 15))
retval = retval << 4 | c; // Multiply by 16 and add the value of the current digit.
else
break; // Break on other characters or space.
str++;
}
return retval;
}
char* GetNextWord(char* str)
{
while (*str && *str != ' ')
++str;
while (*str && *str == ' ')
++str;
return str;
}
#ifdef WIDGET_RUNTIME_SUPPORT
const uni_char DEFAULT_DLL_PATH[] = UNI_L("Opera.dll");
const uni_char BROWSER_EXE_NAME[]= UNI_L("opera.exe");
const uni_char KNOWN_BROWSER_EXE_NAME[2][20] = { {UNI_L("opera.exe")},{UNI_L("operaupgrader.exe")}};
const uni_char GADGET_INSTALL_CONF_NAME[] = UNI_L("install.conf");
BOOL IsBrowserExePath(const uni_char* path)
{
const uni_char *file_name = uni_strrchr(path, '\\');
file_name = (NULL != file_name) ? (file_name + 1) : (path);
const uni_char *file_name_backup = file_name;
// inlined uni_stricmp
const uni_char* browser_name;
for (UINT32 i = 0; i < ARRAY_SIZE(KNOWN_BROWSER_EXE_NAME); i++)
{
browser_name = KNOWN_BROWSER_EXE_NAME[i];
while (*browser_name)
{
if ((*browser_name | 0x20) != (*file_name | 0x20))
{
break;
}
++file_name;
++browser_name;
}
if (!*file_name)
return TRUE;
file_name = file_name_backup;
}
return FALSE;
}
BOOL GetOperaPathsFromGadget(uni_char* exe_path, uni_char* dll_path)
{
uni_char *exe_name = uni_strrchr(exe_path, '\\');
exe_name = (NULL != exe_name) ? (exe_name + 1) : (exe_path);
*exe_name = 0;
uni_char config_path[MAX_PATH];
uni_strncpy(config_path, exe_path,
MAX_PATH - ARRAY_SIZE(GADGET_INSTALL_CONF_NAME));
uni_strcat(config_path, GADGET_INSTALL_CONF_NAME);
char* file_data = NULL;
size_t file_size = size_t(-1);
if (WinFileUtils::Read(config_path, &file_data, file_size) != ERROR_SUCCESS)
{
return FALSE;
}
// Start with a 2-byte offset: skip the BOM.
const uni_char* dir_path = (const uni_char*)(file_data + 2);
const uni_char* dir_path_end = uni_strchr(dir_path, '\n');
// Limit the directory path length so that the entire path fits in MAX_PATH.
const size_t max_dir_path_length = MAX_PATH
- MAX(ARRAY_SIZE(BROWSER_EXE_NAME), ARRAY_SIZE(DEFAULT_DLL_PATH));
const size_t dir_path_length =
MIN(dir_path_end - dir_path, max_dir_path_length);
uni_strncpy(exe_path, dir_path, dir_path_length);
uni_strcpy(exe_path + dir_path_length, BROWSER_EXE_NAME);
uni_strncpy(dll_path, dir_path, dir_path_length);
uni_strcpy(dll_path + dir_path_length, DEFAULT_DLL_PATH);
delete [] file_data;
return TRUE;
}
/**
* Initializes the paths to the Opera executable and main DLL.
*
* @param exe_path Receives the path to the executable to be set as the spawner.
* The buffer must be large enough to accommodate any path name (MAX_PATH
* or more).
* @param dll_path Receives the path to Opera.dll.
* The buffer must be large enough to accommodate any path name (MAX_PATH
* or more).
* @return @c TRUE on success
*/
BOOL InitOperaPaths(uni_char* exe_path, uni_char* dll_path)
{
// Set up the defaults.
uni_strcpy(dll_path, DEFAULT_DLL_PATH);
const DWORD exe_path_length = GetModuleFileName(0, exe_path, MAX_PATH);
if (!exe_path_length || exe_path_length == MAX_PATH)
{
return FALSE;
}
// If we're the browser, we're done.
if (IsBrowserExePath(exe_path))
{
return TRUE;
}
return GetOperaPathsFromGadget(exe_path, dll_path);
}
#endif // WIDGET_RUNTIME_SUPPORT
/**
* This function is called for each toplevel window in system after the call to EnumWindows().
* The idea is to find the AutoUpdateDialog window and bring user's attention to it,
* taking the window to front of the other windows and/or flashing it.
* Since we can't really know the ID of the process that opened the dialog, and since we can't
* rely on translated strings to compare the window title, we find any window that has the
* OperaWindowClass class and doesn't have the maximize window title button.
*
* This function returns TRUE if EnumWindows() should call it again for the next window in the system,
* FALSE otherwise.
*/
BOOL CALLBACK FindAutoUpdaterDialog(HWND hwnd, LPARAM)
{
char clsName[32];
GetClassNameA(hwnd, clsName, sizeof(clsName));
if(strcmp(clsName, "OperaWindowClass") == 0)
{
WINDOWINFO info;
info.cbSize = sizeof(info);
GetWindowInfo(hwnd, &info);
// This is some other Opera window, keep looking
if (info.dwStyle & WS_MAXIMIZEBOX)
return TRUE;
// We have found the dialog, hopefully, now bring it to front or at least get user's attention
FlashWindow(hwnd, TRUE);
SetActiveWindow(hwnd);
SetForegroundWindow(hwnd);
// We're done.
return FALSE;
}
// Keep looking
return TRUE;
}
int g_null_mem = 0;
// DSK-365815
// The symptom of this bug is that all registers are messed up, including the one used to compare against null.
// When this occurs, the following if-test will be true, and the forced crash will tell us WTF happened
#define CHECK_NULL_REGISTER if (g_null_mem) forced_crash();
#ifndef _WIN64
__declspec(naked)
#endif
void forced_crash()
{
// push some API pointers to the stack, this way enough code bytes will appear in the crash log memory dump
// to be able to tell whether some broken API hook causes this
#ifndef _WIN64
_asm mov esi, DeleteFile
_asm add esi, 15
_asm push esi
_asm add esi,32
_asm push esi
_asm mov esi, RemoveDirectory
_asm add esi, 15
_asm push esi
_asm add esi,32
_asm push esi
#endif
*(char *)0 = 0;
}
HINSTANCE hInst;
HWND g_main_hwnd = NULL;
///////////////////////////////////////////////////////////
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
OSVERSIONINFOA osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
if (!GetVersionExA(&osvi) || osvi.dwMajorVersion < 6)
{
// Not needed on Vista and higher, where the NXCOMPAT exe flag takes care of this
SetEnableDEP();
}
g_CmdLine = lpCmdLine;
if (str_begins_with(lpCmdLine, "-unelevate"))
{
DWORD integrity_level;
if (GetIntegrityLevel(GetCurrentProcessId(), integrity_level) && integrity_level > SECURITY_MANDATORY_MEDIUM_RID)
RestartWithMediumIntegrityLevel();
}
// How the commandline might look like, with "-write_crashlog <pid> <g_gpu_info address>":
char* char_ptr = str_begins_with(lpCmdLine, "-write_crashlog"); // lpCmdLine = "-write_crashlog 4204 4884672"
if (char_ptr)
{
bool no_restart = *char_ptr == '!'; // char_ptr = " 4204 4884672"
DWORD process_id = *char_ptr ? simple_hextoint(++char_ptr) : 0; // char_ptr = "4204 4884672"
char_ptr = GetNextWord(char_ptr); // char_ptr = "4884672"
GpuInfo* gpu_info = (GpuInfo*)simple_hextoint(char_ptr);
char filename[MAX_PATH] = {};
UINT len_path = WriteCrashlog(process_id, gpu_info, NULL, filename);
if (no_restart)
{
static char crash_msg[] = "Opera crashed while trying to show the crash dialogue for a previous crash.\nA crash log was created here:\n%s\nPlease send us this log manually.";
char *msg_buf = new char[len_path + ARRAY_SIZE(crash_msg)-2];
if (msg_buf)
{
wsprintfA(msg_buf, crash_msg, filename);
MessageBoxA(0, msg_buf, "Opera Crash Logging", 0);
delete[] msg_buf;
}
}
else
{
lpCmdLine = GetNextWord(char_ptr);
BOOL is_installer = (*lpCmdLine == '/' || *lpCmdLine == '-') && str_begins_with(lpCmdLine+1, "install");
// Remove trailing slash if there is one.
char *path_end = filename + len_path - 1;
if (len_path && *path_end == '\\')
{
*path_end = 0;
--len_path;
}
char* cmd_line = NULL;
if (len_path)
{
static char format_string[] = "-crashlog \"%s\"";
UINT cmdline_len = op_strlen(lpCmdLine);
if (cmdline_len)
cmdline_len++;
len_path += cmdline_len + ARRAY_SIZE(format_string)-2;
cmd_line = new char[len_path];
if (!cmd_line)
return 0;
char *dest = cmd_line + wsprintfA(cmd_line, format_string, filename);
if (*lpCmdLine)
{
*dest++ = ' ';
op_strcpy(dest, lpCmdLine);
}
lpCmdLine = cmd_line;
}
if (GetModuleFileNameA(NULL, filename, MAX_PATH))
{
SHELLEXECUTEINFOA info = {};
info.cbSize = sizeof(info);
if (is_installer)
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpFile = filename;
info.lpParameters = lpCmdLine;
info.nShow = SW_NORMAL;
// start a new Opera instance, which will present the crashlog upload dialogue and then continue
if (ShellExecuteExA(&info) && info.hProcess)
{
//if the installer crashed, we should wait until the user is done viewing the crashlog dialog,
//since closing this will cause the package to be cleaned up.
WaitForSingleObject(info.hProcess, INFINITE);
CloseHandle(info.hProcess);
}
}
delete[] cmd_line;
}
// quit this instance, which will automatically terminate the crashed instance as well
return 0;
}
SetUnhandledExceptionFilter(ExceptionFilter);
hInst = hInstance;
PF_OperaDesktopStart OpStartDesktopInstance;
PF_OperaSetSpawnerPath OpSetSpawnerPath;
PF_OperaSetLaunchMan OpSetLaunchMan;
PF_OperaGetNextUninstallFile OpGetNextUninstallFile;
PF_OpWaitFileWasPresent OpWaitFileWasPresent;
PF_OpSetGpuInfo OpSetGpuInfo;
#ifdef AUTO_UPDATE_SUPPORT
// DSK-345746 - terminate right away if the updater is already running.
// Also, if there is the AutoUpdaterDialog waiting for user's input, bring it to user's attention.
// DSK-345746: If there is an OperaUpgrader.exe running and there is NO mutex allowing Opera.exe to start,
// then refuse to start and try to catch the user's attention with the OperaUpgrader.exe window.
if (WindowsUtils::GetOperaProcess(true) != 0)
{
AUInstaller* au_installer = AUInstaller::Create();
if (!au_installer)
return 1;
bool not_allowed_to_start = false;
if (au_installer && !au_installer->IsUpgraderMutexPresent())
not_allowed_to_start = true;
delete au_installer;
if (not_allowed_to_start)
{
// Play an exclamation system sound
MessageBeep(MB_ICONEXCLAMATION);
// Start looking for the AutoUpdaterDialog, if any
EnumWindows(FindAutoUpdaterDialog, 0);
// Exit now, don't bother to start another copy of self while upgrading
return 0;
}
}
// If the same opera instance is already running, then there is no reason to
// run the update check again, because that might start the installer, if the update is ready.
if (!str_begins_with(lpCmdLine, "/ReinstallBrowser") && !str_begins_with(lpCmdLine, "/uninstall") && !str_begins_with(lpCmdLine, "/addfirewallexception") && !WindowsUtils::GetOperaProcess())
{
AUUpdater au_updater;
if (!au_updater.Run())
return 0;
}
AUFileUtils* au_fileutils = AUFileUtils::Create();
if (!au_fileutils)
return 1;
BOOL is_updater;
if (au_fileutils->IsUpdater(is_updater) == AUFileUtils::ERR)
is_updater = TRUE;
delete au_fileutils;
//if we are running the updater, we should stop here regardless, otherwise,
//we risk to start a proper opera instance from %TEMP%
if (is_updater)
return 0;
#endif
#ifdef WIDGET_RUNTIME_SUPPORT
uni_char exe_path[MAX_PATH];
uni_char dll_path[MAX_PATH];
if (!InitOperaPaths(exe_path, dll_path))
{
MessageBoxA(NULL, "Failed to start application.", "Opera Error",
MB_OK | MB_ICONERROR);
return 0;
}
LPITEMIDLIST pidl;
if (SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, &pidl) == NOERROR)
{
uni_char mg_ini_path[MAX_PATH];
if (SHGetPathFromIDList(pidl, mg_ini_path))
{
uni_char *mg_ini_path_end = mg_ini_path;
while (*++mg_ini_path_end);
UINT maxlen_fname = MAX_PATH - (mg_ini_path_end-mg_ini_path);
static uni_char ini_files[] = UNI_L("\\MemGuard*.ini");
if (ARRAY_SIZE(ini_files) <= maxlen_fname)
{
memcpy(mg_ini_path_end++, ini_files, sizeof(ini_files));
WIN32_FIND_DATA fd;
HANDLE fhandle = FindFirstFile(mg_ini_path, &fd);
if (fhandle != INVALID_HANDLE_VALUE)
{
int choice = 0;
do
{
UINT fname_len = uni_strlen(fd.cFileName);
if (fname_len > maxlen_fname)
continue;
memcpy(mg_ini_path_end, fd.cFileName, UNICODE_SIZE(fname_len+1));
HANDLE hnd = CreateFile(mg_ini_path, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
if (hnd == INVALID_HANDLE_VALUE)
continue;
DWORD bytes_read;
char *mg_ini = new char[fd.nFileSizeLow+1];
if (!mg_ini)
continue;
OpAutoArray<char> ap_mg_ini(mg_ini);
mg_ini[fd.nFileSizeLow] = 0;
BOOL read_ok = ReadFile(hnd, mg_ini, fd.nFileSizeLow, &bytes_read, 0);
CloseHandle(hnd);
if (!read_ok)
continue;
#ifdef _WIN64
char *args = str_begins_with(mg_ini, VER_NUM_STR "." VER_BUILD_NUMBER_STR ".x64");
#else
char *args = str_begins_with(mg_ini, VER_NUM_STR "." VER_BUILD_NUMBER_STR);
if (args && *args > ' ')
continue;
#endif
if (!args)
{
args = str_begins_with(mg_ini, "all");
if (!args)
continue;
}
if (*args == '*')
args++;
else
{
if (str_begins_with(lpCmdLine, "/install") ||
str_begins_with(lpCmdLine, "/uninstall") ||
str_begins_with(lpCmdLine, "-crashlog"))
{
break;
}
}
if (*args == 'q')
{
choice = IDYES;
args++;
}
if (!choice)
choice = MessageBoxA(0, "Press Yes to run Opera in memory guarding mode\n"
"to improve the information gathered when a crash is logged.\n"
"This causes Opera to consume much more memory and run slower.\n"
"Press No to start normally.\n"
"Press Cancel to delete the file MemGuard.ini from your desktop\n"
"to disable this message in the future.", "Opera MemGuard", MB_YESNOCANCEL);
if (choice == IDYES)
{
if (!InitializeMemGuard(args))
{
DestroyMemGuard();
MessageBoxA(0, "Couldn't initialize MemGuard, address space exhausted!", "Opera Error", MB_OK);
break;
}
continue;
}
else if (choice == IDCANCEL)
{
DeleteFile(mg_ini_path);
}
break;
} while (FindNextFile(fhandle, &fd));
FindClose(fhandle);
}
}
}
CoTaskMemFree(pidl);
}
if (!str_begins_with(lpCmdLine, "-newprocess "))
WinFileUtils::PreLoadDll(dll_path, 0);
HINSTANCE operaLibrary = LoadLibrary(dll_path);
#else
HINSTANCE operaLibrary = LoadLibraryA("Opera.dll");
#endif // WIDGET_RUNTIME_SUPPORT
int retval = 0;
if (operaLibrary)
{
OpStartDesktopInstance = (PF_OperaDesktopStart)GetProcAddress(operaLibrary, "OpStart");
OpSetSpawnerPath = (PF_OperaSetSpawnerPath)GetProcAddress(operaLibrary, "OpSetSpawnPath");
OpSetLaunchMan = (PF_OperaSetLaunchMan)GetProcAddress(operaLibrary, "OpSetLaunchMan");
OpGetNextUninstallFile = (PF_OperaGetNextUninstallFile)GetProcAddress(operaLibrary, "OpGetNextUninstallFile");
OpWaitFileWasPresent = (PF_OpWaitFileWasPresent)GetProcAddress(operaLibrary, "OpWaitFileWasPresent");
OpSetGpuInfo = (PF_OpSetGpuInfo)GetProcAddress(operaLibrary, "OpSetGpuInfo");
if (OpStartDesktopInstance && OpSetSpawnerPath && OpSetLaunchMan && OpGetNextUninstallFile && OpWaitFileWasPresent && OpSetGpuInfo &&
InstallMemGuardHooks(operaLibrary))
{
#ifdef WIDGET_RUNTIME_SUPPORT
OpSetSpawnerPath(exe_path);
#else
wchar_t modulefilename[MAX_PATH]; /* ARRAY OK 2005-08-10 andre */
GetModuleFileName(0,modulefilename,MAX_PATH);
OpSetSpawnerPath(modulefilename);
#endif // WIDGET_RUNTIME_SUPPORT
#ifdef AUTO_UPDATE_SUPPORT
if (OpSetLaunchMan)
{
OpSetLaunchMan(g_launch_manager);
}
if (OpWaitFileWasPresent && AUUpdater::WaitFileWasPresent())
{
OpWaitFileWasPresent();
}
#endif // AUTO_UPDATE_SUPPORT
OpSetGpuInfo(&g_gpu_info);
CHECK_NULL_REGISTER;
retval = OpStartDesktopInstance(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
CHECK_NULL_REGISTER;
//If the dll reports there are files left to uninstall (There will always be some when trying to uninstall)
uni_char* uninstall_file;
if ((uninstall_file = OpGetNextUninstallFile()) != NULL)
{
//remove the files we can. Nevermind if it fails at this point.
//Note the Opera.exe and Opera.dll will fail regardless since we are running.
do
{
CHECK_NULL_REGISTER;
DeleteFile(uninstall_file);
CHECK_NULL_REGISTER;
uni_char* sep;
//Try removing hierarchies of empty folder.
//It's ok to do it this way, because the Opera folder won't be empty at this point (Opera.exe is there).
do
{
sep = uni_strrchr(uninstall_file, '\\');
if (!sep) break;
*sep = 0;
CHECK_NULL_REGISTER;
}
while (RemoveDirectory(uninstall_file));
CHECK_NULL_REGISTER;
}
while ((uninstall_file = OpGetNextUninstallFile()) != NULL);
//Since we are uninstalling, we shall remove the dll and the executable as well.
//This is one of the possible ways to make a self-deleting process.
//We create a batch file to finish the cleanup, since those are able to delete themselves.
//
//~julienp
uni_char self_destruct_bat_path[MAX_PATH];
uni_strncpy(self_destruct_bat_path, exe_path, MAX_PATH);
uni_strncpy(uni_strrchr(self_destruct_bat_path, '\\') + 1, UNI_L("k.bat"), 6);
HANDLE self_destruct_bat;
do
{
self_destruct_bat = CreateFile(self_destruct_bat_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (self_destruct_bat == INVALID_HANDLE_VALUE)
break;
char buffer[4*MAX_PATH + 200];
uni_char dll_full_path[MAX_PATH];
uni_strncpy(dll_full_path, exe_path, MAX_PATH);
uni_strcpy(uni_strrchr(dll_full_path, '\\') + 1, DEFAULT_DLL_PATH);
sprintf(buffer, ":Repeat1\r\ndel \"%S\"\r\nif exist \"%S\" goto Repeat1\r\n:Repeat2\r\ndel \"%S\"\r\nif exist \"%S\" goto Repeat2\r\ndel %%0\r\n", exe_path, exe_path, dll_full_path, dll_full_path);
DWORD len = op_strlen(buffer);
DWORD written;
BOOL success = WriteFile(self_destruct_bat, buffer, len, &written, NULL) && written == len ;
CloseHandle(self_destruct_bat);
if (!success) break;
SHELLEXECUTEINFO info;
memset(&info, 0, sizeof(info));
info.cbSize = sizeof(info);
info.fMask = SEE_MASK_NOASYNC;
info.lpFile = self_destruct_bat_path;
info.lpVerb = UNI_L("open");
info.nShow = SW_HIDE;
ShellExecuteEx(&info);
}
while (FALSE);
}
}
else
{
WindowsUtils::ShowError("Opera failed to start because: \n%s");
}
#ifdef AUTO_UPDATE_SUPPORT
uni_char* update_path = g_launch_manager->GetUpdatePath();
#endif
FreeLibrary(operaLibrary);
DestroyMemGuard();
#ifdef AUTO_UPDATE_SUPPORT
if (update_path)
{
g_launch_manager->LaunchOnExitApplication(update_path);
delete [] update_path;
}
#endif
}
else
{
WindowsUtils::ShowError("Failed to load Opera.DLL because: \n%s");
}
if (g_crash_thread_id != 0)
{
// another thread crashed - suspend current thread, otherwise CRT might
// terminate current process before crash logging subprocess attaches
// itself as a debugger (DSK-362561)
SuspendThread(GetCurrentThread());
}
return retval;
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "StringTools.h"
#include <fstream>
namespace common {
namespace {
const uint8_t characterValues[256] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
}
std::string asString(const void* data, size_t size) {
return std::string(static_cast<const char*>(data), size);
}
std::string asString(const std::vector<uint8_t>& data) {
return std::string(reinterpret_cast<const char*>(data.data()), data.size());
}
std::vector<uint8_t> asBinaryArray(const std::string& data) {
auto dataPtr = reinterpret_cast<const uint8_t*>(data.data());
return std::vector<uint8_t>(dataPtr, dataPtr + data.size());
}
uint8_t fromHex(char character) {
uint8_t value = characterValues[static_cast<unsigned char>(character)];
if (value > 0x0f) {
throw std::runtime_error("fromHex: invalid character");
}
return value;
}
bool fromHex(char character, uint8_t& value) {
if (characterValues[static_cast<unsigned char>(character)] > 0x0f) {
return false;
}
value = characterValues[static_cast<unsigned char>(character)];
return true;
}
size_t fromHex(const std::string& text, void* data, size_t bufferSize) {
if ((text.size() & 1) != 0) {
throw std::runtime_error("incorrect string size in fromHex");
}
if (text.size() >> 1 > bufferSize) {
throw std::runtime_error("incorrect buffer size in fromHex");
}
for (size_t i = 0; i < text.size() >> 1; ++i) {
static_cast<uint8_t*>(data)[i] = fromHex(text[i << 1]) << 4 | fromHex(text[(i << 1) + 1]);
}
return text.size() >> 1;
}
bool fromHex(const std::string& text, void* data, size_t bufferSize, size_t& size) {
if ((text.size() & 1) != 0) {
return false;
}
if (text.size() >> 1 > bufferSize) {
return false;
}
for (size_t i = 0; i < text.size() >> 1; ++i) {
uint8_t value1;
if (!fromHex(text[i << 1], value1)) {
return false;
}
uint8_t value2;
if (!fromHex(text[(i << 1) + 1], value2)) {
return false;
}
static_cast<uint8_t*>(data)[i] = value1 << 4 | value2;
}
size = text.size() >> 1;
return true;
}
std::vector<uint8_t> fromHex(const std::string& text) {
if ((text.size() & 1) != 0) {
throw std::runtime_error("incorrect string size in fromHex");
}
std::vector<uint8_t> data(text.size() >> 1);
for (size_t i = 0; i < data.size(); ++i) {
data[i] = fromHex(text[i << 1]) << 4 | fromHex(text[(i << 1) + 1]);
}
return data;
}
bool fromHex(const std::string& text, std::vector<uint8_t>& data) {
if ((text.size() & 1) != 0) {
return false;
}
for (size_t i = 0; i < text.size() >> 1; ++i) {
uint8_t value1;
if (!fromHex(text[i << 1], value1)) {
return false;
}
uint8_t value2;
if (!fromHex(text[(i << 1) + 1], value2)) {
return false;
}
data.push_back(value1 << 4 | value2);
}
return true;
}
std::string toHex(const void* data, size_t size) {
std::string text;
for (size_t i = 0; i < size; ++i) {
text += "0123456789abcdef"[static_cast<const uint8_t*>(data)[i] >> 4];
text += "0123456789abcdef"[static_cast<const uint8_t*>(data)[i] & 15];
}
return text;
}
void toHex(const void* data, size_t size, std::string& text) {
for (size_t i = 0; i < size; ++i) {
text += "0123456789abcdef"[static_cast<const uint8_t*>(data)[i] >> 4];
text += "0123456789abcdef"[static_cast<const uint8_t*>(data)[i] & 15];
}
}
std::string toHex(const std::vector<uint8_t>& data) {
std::string text;
for (size_t i = 0; i < data.size(); ++i) {
text += "0123456789abcdef"[data[i] >> 4];
text += "0123456789abcdef"[data[i] & 15];
}
return text;
}
void toHex(const std::vector<uint8_t>& data, std::string& text) {
for (size_t i = 0; i < data.size(); ++i) {
text += "0123456789abcdef"[data[i] >> 4];
text += "0123456789abcdef"[data[i] & 15];
}
}
std::string extract(std::string& text, char delimiter) {
size_t delimiterPosition = text.find(delimiter);
std::string subText;
if (delimiterPosition != std::string::npos) {
subText = text.substr(0, delimiterPosition);
text = text.substr(delimiterPosition + 1);
} else {
subText.swap(text);
}
return subText;
}
std::string extract(const std::string& text, char delimiter, size_t& offset) {
size_t delimiterPosition = text.find(delimiter, offset);
if (delimiterPosition != std::string::npos) {
offset = delimiterPosition + 1;
return text.substr(offset, delimiterPosition);
} else {
offset = text.size();
return text.substr(offset);
}
}
namespace {
static const std::string base64chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
}
std::string base64Decode(std::string const& encoded_string) {
size_t in_len = encoded_string.size();
size_t i = 0;
size_t j = 0;
size_t in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i == 4) {
for (i = 0; i <4; i++)
char_array_4[i] = (unsigned char)base64chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = (unsigned char)base64chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
bool loadFileToString(const std::string& filepath, std::string& buf) {
try {
std::ifstream fstream;
fstream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fstream.open(filepath, std::ios_base::binary | std::ios_base::in | std::ios::ate);
size_t fileSize = static_cast<size_t>(fstream.tellg());
buf.resize(fileSize);
if (fileSize > 0) {
fstream.seekg(0, std::ios::beg);
fstream.read(&buf[0], buf.size());
}
} catch (const std::exception&) {
return false;
}
return true;
}
bool saveStringToFile(const std::string& filepath, const std::string& buf) {
try {
std::ofstream fstream;
fstream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fstream.open(filepath, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
fstream << buf;
} catch (const std::exception&) {
return false;
}
return true;
}
std::string ipAddressToString(uint32_t ip) {
uint8_t bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
char buf[16];
snprintf(buf, sizeof(buf), "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]);
return std::string(buf);
}
bool parseIpAddressAndPort(uint32_t& ip, uint32_t& port, const std::string& addr) {
uint32_t v[4];
uint32_t localPort;
if (sscanf(addr.c_str(), "%d.%d.%d.%d:%d", &v[0], &v[1], &v[2], &v[3], &localPort) != 5) {
return false;
}
for (int i = 0; i < 4; ++i) {
if (v[i] > 0xff) {
return false;
}
}
ip = (v[3] << 24) | (v[2] << 16) | (v[1] << 8) | v[0];
port = localPort;
return true;
}
std::string timeIntervalToString(uint64_t intervalInSeconds) {
auto tail = intervalInSeconds;
auto days = tail / (60 * 60 * 24);
tail = tail % (60 * 60 * 24);
auto hours = tail / (60 * 60);
tail = tail % (60 * 60);
auto minutes = tail / (60);
tail = tail % (60);
auto seconds = tail;
return
"d" + std::to_string(days) +
".h" + std::to_string(hours) +
".m" + std::to_string(minutes) +
".s" + std::to_string(seconds);
}
std::string makeCenteredString(size_t width, const std::string& text) {
if (text.size() >= width) {
return text;
}
size_t offset = (width - text.size() + 1) / 2;
return std::string(offset, ' ') + text + std::string(width - text.size() - offset, ' ');
}
}
|
/* XMRig
* Copyright (c) 2018-2019 tevador <tevador@gmail.com>
* Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "crypto/rx/RxBasicStorage.h"
#include "backend/common/Tags.h"
#include "base/io/log/Log.h"
#include "base/io/log/Tags.h"
#include "base/tools/Chrono.h"
#include "crypto/rx/RxAlgo.h"
#include "crypto/rx/RxCache.h"
#include "crypto/rx/RxDataset.h"
#include "crypto/rx/RxSeed.h"
namespace xmrig {
constexpr size_t oneMiB = 1024 * 1024;
class RxBasicStoragePrivate
{
public:
XMRIG_DISABLE_COPY_MOVE(RxBasicStoragePrivate)
inline RxBasicStoragePrivate() = default;
inline ~RxBasicStoragePrivate() { deleteDataset(); }
inline bool isReady(const Job &job) const { return m_ready && m_seed == job; }
inline RxDataset *dataset() const { return m_dataset; }
inline void deleteDataset() { delete m_dataset; m_dataset = nullptr; }
inline void setSeed(const RxSeed &seed)
{
m_ready = false;
if (m_seed.algorithm() != seed.algorithm()) {
RxAlgo::apply(seed.algorithm());
}
m_seed = seed;
}
inline bool createDataset(bool hugePages, bool oneGbPages, RxConfig::Mode mode)
{
const uint64_t ts = Chrono::steadyMSecs();
m_dataset = new RxDataset(hugePages, oneGbPages, true, mode, 0);
if (!m_dataset->cache()->get()) {
deleteDataset();
LOG_INFO("%s" RED_BOLD("failed to allocate RandomX memory") BLACK_BOLD(" (%" PRIu64 " ms)"), Tags::randomx(), Chrono::steadyMSecs() - ts);
return false;
}
printAllocStatus(ts);
return true;
}
inline void initDataset(uint32_t threads, int priority)
{
const uint64_t ts = Chrono::steadyMSecs();
m_ready = m_dataset->init(m_seed.data(), threads, priority);
if (m_ready) {
LOG_INFO("%s" GREEN_BOLD("dataset ready") BLACK_BOLD(" (%" PRIu64 " ms)"), Tags::randomx(), Chrono::steadyMSecs() - ts);
}
}
private:
void printAllocStatus(uint64_t ts)
{
if (m_dataset->get() != nullptr) {
const auto pages = m_dataset->hugePages();
LOG_INFO("%s" GREEN_BOLD("allocated") CYAN_BOLD(" %zu MB") BLACK_BOLD(" (%zu+%zu)") " huge pages %s%1.0f%% %u/%u" CLEAR " %sJIT" BLACK_BOLD(" (%" PRIu64 " ms)"),
Tags::randomx(),
pages.size / oneMiB,
RxDataset::maxSize() / oneMiB,
RxCache::maxSize() / oneMiB,
(pages.isFullyAllocated() ? GREEN_BOLD_S : (pages.allocated == 0 ? RED_BOLD_S : YELLOW_BOLD_S)),
pages.percent(),
pages.allocated,
pages.total,
m_dataset->cache()->isJIT() ? GREEN_BOLD_S "+" : RED_BOLD_S "-",
Chrono::steadyMSecs() - ts
);
}
else {
LOG_WARN(CLEAR "%s" YELLOW_BOLD_S "failed to allocate RandomX dataset, switching to slow mode" BLACK_BOLD(" (%" PRIu64 " ms)"), Tags::randomx(), Chrono::steadyMSecs() - ts);
}
}
bool m_ready = false;
RxDataset *m_dataset = nullptr;
RxSeed m_seed;
};
} // namespace xmrig
xmrig::RxBasicStorage::RxBasicStorage() :
d_ptr(new RxBasicStoragePrivate())
{
}
xmrig::RxBasicStorage::~RxBasicStorage()
{
delete d_ptr;
}
bool xmrig::RxBasicStorage::isAllocated() const
{
return d_ptr->dataset() && d_ptr->dataset()->cache() && d_ptr->dataset()->cache()->get();
}
xmrig::HugePagesInfo xmrig::RxBasicStorage::hugePages() const
{
if (!d_ptr->dataset()) {
return {};
}
return d_ptr->dataset()->hugePages();
}
xmrig::RxDataset *xmrig::RxBasicStorage::dataset(const Job &job, uint32_t) const
{
if (!d_ptr->isReady(job)) {
return nullptr;
}
return d_ptr->dataset();
}
void xmrig::RxBasicStorage::init(const RxSeed &seed, uint32_t threads, bool hugePages, bool oneGbPages, RxConfig::Mode mode, int priority)
{
d_ptr->setSeed(seed);
if (!d_ptr->dataset() && !d_ptr->createDataset(hugePages, oneGbPages, mode)) {
return;
}
d_ptr->initDataset(threads, priority);
}
|
//
// Created by OLD MAN on 2019/9/3.
//
#include <iostream>
using namespace std;
int main(){
// why 20组测试,通过8组
// int m,n;
// cin>>m>>n;
// if(m%17 != 0)
// m += 17 - m%17;
// if(n%17 != 0)
// n -= 17 - n%17;
// //cout<<m<<" "<<n<<endl;
// int num = (n-m)/17 + 1;
// //cout<<num<<endl;
// cout<<0.5*num*(n+m);
int m,n;
cin>>m>>n;
if(m%17 != 0)
m += 17 - m%17;
if(n%17==0)
n+=1;
int sum=0;
for(int i=m;i<n;i+=17){
sum+=i;
}
cout<<sum;
}
|
/*
* AdminConsoleRepositoryImpl.cc
*
* Created on: Nov 11, 2017
* Author: cis505
*/
#include "AdminConsoleRepositoryImpl.h"
using namespace std;
Status AdminConsoleRepositoryImpl::GetRowForUser(ServerContext* context, const GetUserRowRequest* request, BigTableRow* response) {
// TODO: fill out method
return Status::OK;
}
Status AdminConsoleRepositoryImpl::GetRows(ServerContext* context, const GetRowsRequest* request, ServerWriter<BigTableRow>* writer) {
// TODO: fill out method
request->count();
request->offset();
vector<string> users = bigTablePtr->get_users();
for (string user : users) {
BigTableRow row;
row.set_key(user);
unordered_map<string, Metadata> files = bigTablePtr->get_user_files(user);
map<string, File> fileMap;
for (auto file = files.begin(); file != files.end(); file++) {
string fileName = file->first;
Metadata metadata = file->second;
File fileData;
fileData.set_username(metadata.username);
fileData.set_filename(metadata.filename);
fileData.set_filetype(metadata.filetype);
fileData.set_disk_filename(metadata.disk_filename);
fileData.set_start(metadata.start);
fileData.set_filesize(metadata.filesize);
fileData.set_is_flushed(metadata.is_flushed);
string value = bigTablePtr->get(user, fileName);
fileData.set_content(value.substr(0, 5000));
fileMap.insert(pair<string, File>(fileName, fileData));
}
row.mutable_columns()->insert(fileMap.begin(), fileMap.end());
writer->Write(row);
}
return Status::OK;
}
|
#include <iostream>
using namespace std;
//IDEA: use something like lamuto partition. One traversal solution
typedef struct Node
{
int key;
Node *next;
Node(int x)
{
key = x;
next = NULL;
}
} Node;
Node *insert(Node *head, int key) //O(1)
{
Node *temp = new Node(key);
temp->next = head;
return temp;
}
void printList(Node *head)
{
Node *curr = head;
while (curr != NULL)
{
cout << curr->key << " ";
curr = curr->next;
}
cout << endl;
}
void segregate(Node *head)
{
Node *j = head;
Node *curr = head;
while (curr != NULL)
{
if ((curr->key) % 2 == 0)
{
int temp = curr->key;
curr->key = j->key;
j->key = temp;
j = j->next;
}
curr = curr->next;
}
}
int main(int argc, char const *argv[])
{
Node *head = NULL;
head = insert(head, 4);
head = insert(head, 5);
head = insert(head, 10);
head = insert(head, 12);
head = insert(head, 8);
head = insert(head, 15);
head = insert(head, 17);
cout << "List before segregation" << endl;
printList(head);
cout << "After: " << endl;
segregate(head);
printList(head);
return 0;
}
|
// Created on: 2001-04-24
// Created by: Christian CAILLET
// Copyright (c) 2001-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 _StepShape_PlusMinusTolerance_HeaderFile
#define _StepShape_PlusMinusTolerance_HeaderFile
#include <Standard.hxx>
#include <StepShape_ToleranceMethodDefinition.hxx>
#include <StepShape_DimensionalCharacteristic.hxx>
#include <Standard_Transient.hxx>
class StepShape_PlusMinusTolerance;
DEFINE_STANDARD_HANDLE(StepShape_PlusMinusTolerance, Standard_Transient)
//! Added for Dimensional Tolerances
class StepShape_PlusMinusTolerance : public Standard_Transient
{
public:
Standard_EXPORT StepShape_PlusMinusTolerance();
Standard_EXPORT void Init (const StepShape_ToleranceMethodDefinition& range, const StepShape_DimensionalCharacteristic& toleranced_dimension);
Standard_EXPORT StepShape_ToleranceMethodDefinition Range() const;
Standard_EXPORT void SetRange (const StepShape_ToleranceMethodDefinition& range);
Standard_EXPORT StepShape_DimensionalCharacteristic TolerancedDimension() const;
Standard_EXPORT void SetTolerancedDimension (const StepShape_DimensionalCharacteristic& toleranced_dimension);
DEFINE_STANDARD_RTTIEXT(StepShape_PlusMinusTolerance,Standard_Transient)
protected:
private:
StepShape_ToleranceMethodDefinition theRange;
StepShape_DimensionalCharacteristic theTolerancedDimension;
};
#endif // _StepShape_PlusMinusTolerance_HeaderFile
|
#ifndef CPUSHBUTTON_H
#define CPUSHBUTTON_H
#include <QPushButton>
#include <QLinearGradient>
class CPushButton : public QPushButton
{
Q_OBJECT
public:
enum State{
Normal,
Enter,
Pressed,
Disable
};
CPushButton(const QChar& fchar, const QString& text, QWidget *parent);
~CPushButton();
void setState(State state);
void setShowTips(bool bTips = false);
public Q_SLOTS:
void setTipsNumber(int num);
protected:
virtual void paintEvent(QPaintEvent *);
virtual void enterEvent(QEvent *);
virtual void leaveEvent(QEvent *);
virtual void mousePressEvent(QMouseEvent *e);
virtual void mouseReleaseEvent(QMouseEvent *e);
private:
QLinearGradient linearGraident(State state);
private:
QString m_btnText;
QChar m_btnIconChar;
QSize m_btnIconCharSize;
QSize m_btnTextSize;
State m_curState;
QFont m_btnIconFont;
QFont m_btnTextFont;
bool m_bShowTips;
int m_tipsNumber;
};
#endif // CPUSHBUTTON_H
|
#pragma once
#include "RigidBody.h"
class Sphere : public RigidBody
{
public:
Sphere(glm::vec2 position, glm::vec2 velocity, float fAngRot, float mass, float elasticity, float fFricCoStatic, float fFricCoDynamic, float fDrag, float fAngDrag, float radius, glm::vec4 colour);
~Sphere();
virtual void makeGizmo();
virtual bool checkCollision(PhysicsObject* pOther);
inline float getRadius() { return m_radius; }
inline glm::vec4 getColour() { return m_colour; }
inline void HideDirLine() { m_bDirLine = false; };
protected:
float m_radius;
glm::vec4 m_colour;
bool m_bDirLine = true;
};
|
#ifndef ALPHATREE_H
#define ALPHATREE_H
#include "pixel.h"
#include "alphalevel.h"
#include "filereader.h"
#include <vector>
#include "dissimilarity.h"
#include "recognizer.h"
class AlphaTree {
public:
//Constructors
AlphaTree();
//Functions
void initialize(FileReader fileReader);
int calculateDissimilarity(std::vector<double> position_1, std::vector<double> position_2);
void setAlphaStep();
Pixel* findRoot(Pixel *pixel);
Pixel* findRootWithCompression(Pixel* pixel, Pixel origin);
void setPixel(int n, int m, std::vector<double> value);
void doAlphaStep(int image_height, int image_width, bool initialize);
void finishTree(int image_height, int image_width);
int getDepth();
void findTrafficSigns(int height, int width);
Pixel getPixel(int height, int width);
int resetAndFindId(int current_id);
//This function gets the id of a pixel at a certain alphalevel
int getPixelValueAtAlphaLevel(int level, int image_height, int image_width);
void findAllDissimilarities(int image_height, int image_width, std::vector<std::vector<std::vector<double>>> image);
std::vector<int> labtorgb(double l_, double a_, double b_);
private:
//Variables
int alphaLevel;
int id;
int depth;
int counter;
int a;
int b;
Recognizer recognizer;
bool bottomReached;
Dissimilarity diss;
AlphaLevel ap;
Pixel* pointer;
Pixel pixl;
Pixel isRoot;
std::vector<Dissimilarity> dissimilarity;
std::vector<std::vector<Pixel>> pixelObjArray;
std::vector<AlphaLevel> alphatreeLevels;
std::vector<std::vector<int>> idConnection;
//FileReader fileReader;
};
#endif
|
#include "stdafx.h"
#include "SphericalHarmonicLight.h"
//#include
SphericalHarmonicLight::SphericalHarmonicLight() {
}
void SphericalHarmonicLight::SHProjectEnvMap(ComPtr<ID3D11DeviceContext> d3dContext) {
/*Renderer::ThrowIfFailed(
SHProjectCubeMap(d3dContext.Get(), 3, envMap.Get(), resultR.data(), resultG.data(), resultB.data())
);*/
}
void SphericalHarmonicLight::SetupEnvMap(ComPtr<ID3D11Device> d3dDevice, ComPtr<ID3D11DeviceContext> d3dContext) {
Image cubeImage[6];
ScratchImage cube;
cube.InitializeCube(DXGI_FORMAT_R16G16B16A16_FLOAT, 32, 32, 1, 1);
TexMetadata texMeta = cube.GetMetadata();
//texMeta.dimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
wstring filename[6] = {
L"Texture/WoodBaseColor.tga",
L"Texture/WoodBaseColor.tga",
L"Texture/WoodBaseColor.tga",
L"Texture/WoodBaseColor.tga",
L"Texture/WoodBaseColor.tga",
L"Texture/WoodBaseColor.tga"
};
ScratchImage image[6];
for (auto i = 0; i < 6; i++) {
Renderer::ThrowIfFailed(
LoadFromTGAFile(filename[i].c_str(), nullptr, image[i])
);
cubeImage[i] = image[i].GetImages()[0];
}
Renderer::ThrowIfFailed(
CreateShaderResourceView(d3dDevice.Get(), cubeImage, 6, texMeta, &EnvMapView)
);
/*<ID3D11Resource> envMapRes;
EnvMapView->GetResource(&envMapRes);
Renderer::ThrowIfFailed(
SHProjectCubeMap(d3dContext.Get(), 3, (ID3D11Texture2D *) envMapRes.Get(), resultR.data(), resultG.data(), resultB.data())
);*/
}
|
#include "Log.h"
void Log(const char *fmt, ...)
{
va_list list;
static char buffer[1024];
static DWORD w;
FILE *f;
va_start(list, fmt);
// To console
DWORD len = wvsprintfA(buffer, fmt, list);
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), buffer, len, (DWORD *)&w, NULL);
if (fopen_s(&f, "dinput8.log", "a+") == 0)
{
vfprintf(f, fmt, list);
fflush(f);
fclose(f);
}
va_end(list);
}
void Hexdump(void *ptr, int buflen)
{
unsigned char *buf = (unsigned char*)ptr;
int i, j;
for (i = 0; i<buflen; i += 16) {
Log("%06x: ", i);
for (j = 0; j<16; j++)
if (i + j < buflen)
Log("%02x ", buf[i + j]);
else
Log(" ");
Log(" ");
for (j = 0; j<16; j++)
if (i + j < buflen)
Log("%c", isprint(buf[i + j]) ? buf[i + j] : '.');
Log("\n");
}
}
|
#ifndef LISTA_HPP
#define LISTA_HPP
struct ELEMENT{
int wartosc;
ELEMENT *nast; //wskaznik do nastepnego elementu listy
};
class Lista {
private: //zeby z zewnatrz nie tykac sie tych wartosci pisze sie private (hermetyzacja danych)
ELEMENT *head;
ELEMENT *tail;
public: //interfejs publiczny (API klasy)
Lista(); //konstrkutor
~Lista(); //destruktor
//memory leaks - wycieki pamieci(programy nie informuja systemu ze pamiec ktora wykorzystywal nie jest im juz potrzebna
void Dodaj(int);
void Wyswietl();
bool Usun();
void Wstaw(int, int);
};
#endif
|
#pragma once
#include "CShaderResource.h"
#include "Effect\CEffectEngine.h"
#include "../graphics/RenderTarget.h"
#include "../graphics/font/CFONT.h"
class CShaderResource;
class CEffectEngine;
enum EnRenderMode {
enRenderMode_Invalid, //不正なレンダリングモード。
enRenderMode_CreateShadowMap, //シャドウマップ生成。
enRenderMode_Normal, //通常レンダリング。
enRenderMode_Num, //レンダリングモードの数。
};
class GraphicsEngine
{
public:
GraphicsEngine();
~GraphicsEngine();
void InitDirectX(HWND hwnd);
void Release();
CShaderResource &GetShaderResources()
{
return m_shaderResources;
}
ID3D11Device* GetD3DDevice() {
return m_pd3dDevice;
}
ID3D11DeviceContext* GetD3DDeviceContext()
{
return m_pd3dDeviceContext;
}
DirectX::SpriteBatch* GetSpriteBatch() const
{
return m_spriteBatch.get();
}
DirectX::SpriteFont* GetSpriteFont(CFont::TextType type) const
{
switch (type) {
case CFont::TextType::en_Alphabet:
return m_spriteFont.get();
break;
case CFont::TextType::en_Japanese:
return m_spriteFontJa.get();
break;
case CFont::TextType::en_JapaneseBIG:
return m_spriteFontJaBig.get();
case CFont::TextType::en_JPLog:
return m_spriteFontJPLog.get();
}
}
int GetFrameBufferWidth() const
{
return m_frameBufferWidth;
}
int GetFrameBufferHeight() const
{
return m_frameBufferHeight;
}
int Get2DSpaceScreenWidth() const
{
return m_2dSpaceScreenWidth;
}
int Get2DSpaceScreenHeight() const
{
return m_2dSpaceScreenHeight;
}
/*!
*@brief エフェクトエンジンの取得。
*/
CEffectEngine& GetEffectEngine()
{
return m_effectEngine;
}
ID3D11RenderTargetView* GetTarget() {
return m_backBuffer;
}
void BegineRender();
void EndRender();
void ChangeRenderTarget(RenderTarget* renderTarget, D3D11_VIEWPORT* viewport);
void ChangeRenderTarget(ID3D11RenderTargetView* renderTarget, ID3D11DepthStencilView* depthStensil, D3D11_VIEWPORT* viewport);
void SetAmbientLight(float amb) {
m_ambientLight = amb;
}
const float GetAmbientLight() {
return m_ambientLight;
}
private:
CShaderResource m_shaderResources;
ID3D11Device* m_pd3dDevice = NULL;
ID3D11DeviceContext* m_pd3dDeviceContext = NULL;
D3D_FEATURE_LEVEL m_featureLevel;
IDXGISwapChain* m_pSwapChain = NULL;
ID3D11RenderTargetView* m_backBuffer = NULL;
ID3D11RasterizerState* m_rasterizerState = NULL;
ID3D11Texture2D* m_depthStencil = NULL;
ID3D11DepthStencilView* m_depthStencilView = NULL;
std::unique_ptr<DirectX::SpriteBatch> m_spriteBatch;
std::unique_ptr<DirectX::SpriteFont> m_spriteFont;
std::unique_ptr<DirectX::SpriteFont> m_spriteFontJa;
std::unique_ptr<DirectX::SpriteFont> m_spriteFontJaBig;
std::unique_ptr<DirectX::SpriteFont> m_spriteFontJPLog;
CEffectEngine m_effectEngine;
int m_2dSpaceScreenWidth = 1280;
int m_2dSpaceScreenHeight = 720;
int m_frameBufferWidth = 0;
int m_frameBufferHeight = 0;
float m_ambientLight = 0.5f;
};
|
/*******************************************************************************
main.cpp - Shape-it
Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter,
and the Shape-it contributors
This file is part of Shape-it.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Shape-it can be linked against either OpenBabel version 3 or the RDKit.
OpenBabel is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
***********************************************************************/
// General
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <vector>
#ifndef USE_RDKIT
// OpenBabel
#include <openbabel/mol.h>
#include <openbabel/obconversion.h>
#else
#include <GraphMol/FileParsers/MolSupplier.h>
#include <GraphMol/FileParsers/MolWriters.h>
#include <GraphMol/ROMol.h>
#endif
// Pharao
#include <alignLib.h>
#include <alignmentInfo.h>
#include <atomGaussian.h>
#include <bestResults.h>
#include <gaussianVolume.h>
#include <mainErr.h>
#include <moleculeRotation.h>
#include <options.h>
#include <parseCommandLine.h>
#include <printHeader.h>
#include <printUsage.h>
#include <shapeAlignment.h>
//*--------------------------------------------------------------------------*//
//* MAIN MAIN
//*//
//*--------------------------------------------------------------------------*//
int main(int argc, char *argv[]) {
// Initialise random number generator
srandom(time(nullptr));
clock_t t0 = clock();
// Print header
printHeader();
// Read options
Options uo = parseCommandLine(argc, argv);
if (uo.version) {
printHeader();
exit(0);
}
if (uo.help) {
printUsage();
exit(0);
}
std::cerr << uo.print();
// Files
if (uo.dbInpFile.empty()) {
mainErr("Missing database file. This is a required option (-d).");
}
if (uo.refInpFile.empty()) {
mainErr("Missing ref file. This is a required option (-r).");
}
if (uo.molOutFile.empty() && uo.scoreOutFile.empty()) {
mainErr("At least one of the -o or -s option should be used.");
}
// Create a list to store the best results
BestResults *bestHits = nullptr;
if (uo.bestHits != 0) {
bestHits = new BestResults(uo.bestHits);
}
// Print header line to score output file
if (!uo.scoreOutFile.empty()) {
*(uo.scoreOutStream) << "dbName"
<< "\t"
<< "refName"
<< "\t" << tanimoto << "\t" << tversky_ref << "\t"
<< tversky_db << "\t"
<< "overlap"
<< "\t"
<< "refVolume"
<< "\t"
<< "dbVolume" << std::endl;
}
// Create reference molecule
std::string refName;
#ifndef USE_RDKIT
OpenBabel::OBMol refMol;
OpenBabel::OBConversion refInpReader;
if (uo.format.empty()) {
refInpReader.SetInFormat(refInpReader.FormatFromExt(uo.refInpFile));
} else {
refInpReader.SetInFormat(refInpReader.FindFormat(uo.format));
}
refInpReader.Read(&refMol, uo.refInpStream);
refName = refMol.GetTitle();
#else
bool takeOwnership = false;
bool sanitize = true;
bool removeHs = false;
RDKit::ForwardSDMolSupplier refsuppl(uo.refInpStream, takeOwnership, sanitize,
removeHs);
std::unique_ptr<RDKit::ROMol> refmptr(refsuppl.next());
if (!refmptr) {
mainErr("Could not parse reference molecule");
}
RDKit::ROMol &refMol = *refmptr;
refMol.getPropIfPresent("_Name", refName);
#endif
if (refName == "") {
refName = "Unnamed_ref";
}
// Create the refence set of Gaussians
GaussianVolume refVolume;
// List all Gaussians and their respective intersections
listAtomVolumes(refMol, refVolume);
// Move the Gaussian towards its center of geometry and align with principal
// axes
if (!uo.scoreOnly) {
initOrientation(refVolume);
}
// Write reference molecule to output
#ifndef USE_RDKIT
std::unique_ptr<OpenBabel::OBConversion> dbOutWriter(
new OpenBabel::OBConversion());
if (uo.format.empty()) {
dbOutWriter->SetOutFormat(dbOutWriter->FormatFromExt(uo.molOutFile));
} else {
dbOutWriter->SetOutFormat(dbOutWriter->FindFormat(uo.format));
}
if (uo.showRef && !uo.molOutFile.empty()) {
dbOutWriter->Write(&refMol, uo.molOutStream);
}
#else
std::unique_ptr<RDKit::SDWriter> dbOutWriter;
if (uo.molOutStream != nullptr) {
dbOutWriter.reset(new RDKit::SDWriter(uo.molOutStream, false));
dbOutWriter->write(refMol);
}
#endif
// Open database stream
unsigned molCount(0);
std::ostringstream ss;
#ifndef USE_RDKIT
OpenBabel::OBMol dbMol;
OpenBabel::OBConversion dbInpReader;
if (uo.format.empty()) {
dbInpReader.SetInFormat(dbInpReader.FormatFromExt(uo.dbInpFile));
} else {
dbInpReader.SetInFormat(dbInpReader.FindFormat(uo.format));
}
dbInpReader.SetInStream(uo.dbInpStream);
while (dbInpReader.Read(&dbMol)) {
#else
RDKit::ForwardSDMolSupplier dbsuppl(uo.dbInpStream, takeOwnership, sanitize,
removeHs);
while (!dbsuppl.atEnd()) {
std::unique_ptr<RDKit::ROMol> dbmptr(dbsuppl.next());
if (!dbmptr) {
continue;
}
RDKit::ROMol &dbMol = *dbmptr;
#endif
++molCount;
// Keep track of the number of molecules processed so far
if ((molCount % 10) == 0) {
std::cerr << ".";
if ((molCount % 500) == 0) {
std::cerr << " " << molCount << " molecules" << std::endl;
}
}
std::string dbName;
#ifndef USE_RDKIT
dbName = dbMol.GetTitle();
#else
dbMol.getPropIfPresent("_Name", dbName);
#endif
if (dbName == "") {
ss.str("");
ss << "MOL_" << molCount;
dbName = ss.str();
#ifndef USE_RDKIT
dbMol.SetTitle(dbName);
#else
dbMol.setProp("_Name", dbName);
#endif
}
// Create the set of Gaussians of database molecule
GaussianVolume dbVolume;
listAtomVolumes(dbMol, dbVolume);
// Overlap with reference
AlignmentInfo res;
double bestScore(0.0);
SolutionInfo bestSolution;
if (uo.scoreOnly) {
res.overlap = atomOverlap(refVolume, dbVolume);
res.rotor[0] = 1.0;
bestScore = getScore(uo.whichScore, res.overlap, refVolume.overlap,
dbVolume.overlap);
} else {
initOrientation(dbVolume);
bestSolution = std::move(shapeit::alignVolumes(
refVolume, dbVolume, uo.whichScore, uo.maxIter));
}
#ifndef USE_RDKIT
bestSolution.dbMol = dbMol;
#else
bestSolution.dbMol = dbMol;
#endif
bestSolution.refName = refName;
bestSolution.dbName = dbName;
// Cleanup local pointers to atom-gaussians
dbVolume.gaussians.clear();
dbVolume.levels.clear();
for (auto &childOverlap : dbVolume.childOverlaps) {
delete childOverlap;
childOverlap = nullptr;
}
dbVolume.childOverlaps.clear();
// At this point the information of the solution is stored in bestSolution
// Check if the result is better than the cutoff
if (bestSolution.score < uo.cutOff) {
continue;
}
// Post-process molecules
if (uo.bestHits || !uo.molOutFile.empty()) {
// Add the score properties
setAllScores(bestSolution);
if (!uo.scoreOnly) {
// Translate and rotate the molecule towards its centroid and inertia
// axes
positionMolecule(bestSolution.dbMol, bestSolution.dbCenter,
bestSolution.dbRotation);
// Rotate molecule with the optimal
rotateMolecule(bestSolution.dbMol, bestSolution.rotor);
// Rotate and translate the molecule with the inverse rotation and
// translation of the reference molecule
repositionMolecule(bestSolution.dbMol, refVolume.rotation,
refVolume.centroid);
}
if (uo.bestHits) {
bestHits->add(bestSolution);
} else if (!uo.molOutFile.empty() && dbOutWriter != nullptr) {
#ifndef USE_RDKIT
dbOutWriter->Write(&(bestSolution.dbMol), uo.molOutStream);
#else
dbOutWriter->write(bestSolution.dbMol);
#endif
}
}
if ((uo.bestHits == 0) && !uo.scoreOutFile.empty()) {
bestSolution.printScores(uo);
}
#ifndef USE_RDKIT
// Clear current molecule
dbMol.Clear();
#endif
}
if (uo.bestHits) {
if (!uo.molOutFile.empty()) {
for (const auto molptr : bestHits->getBestList()) {
if (molptr != nullptr && dbOutWriter != nullptr) {
#ifndef USE_RDKIT
dbOutWriter->Write(&(molptr->dbMol), uo.molOutStream);
#else
dbOutWriter->write(molptr->dbMol);
#endif
}
}
delete uo.molOutStream;
uo.molOutStream = nullptr;
}
if (!uo.scoreOutFile.empty()) {
bestHits->writeScores(&uo);
delete uo.scoreOutStream;
uo.scoreOutStream = nullptr;
}
}
// Clear current streams
if (uo.dbInpStream != nullptr) {
delete uo.dbInpStream;
uo.dbInpStream = nullptr;
}
if (uo.refInpStream != nullptr) {
delete uo.refInpStream;
uo.refInpStream = nullptr;
}
// Done processing database
std::cerr << std::endl;
std::cerr << "Processed " << molCount << " molecules" << std::endl;
double tt = (double)(clock() - t0) / CLOCKS_PER_SEC;
std::cerr << molCount << " molecules in " << tt << " seconds (";
std::cerr << molCount / tt << " molecules per second)" << std::endl;
// Cleanup local db volume
refVolume.gaussians.clear();
for (auto &childOverlap : refVolume.childOverlaps) {
delete childOverlap;
childOverlap = nullptr;
}
exit(0);
}
|
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
struct p{
int a, b, c;
};
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::vector<int> list(3);
bool FLAG = false;
std::queue<p> q;
bool visited[501][501];
std::memset(visited, 0, sizeof(visited));
std::cin >> list[0] >> list[1] >> list[2];
std::sort(list.begin(), list.end());
q.push({list[0], list[1], list[2]});
visited[list[0]][list[1]] = 1;
while(!q.empty())
{
auto [a, b, c] = q.front();
q.pop();
if(a == b && a == c)
{
FLAG = true;
break;
}
list[0] = a + a;
list[1] = b;
list[2] = c - a;
std::sort(list.begin(), list.end());
if(!visited[list[0]][list[1]])
{
visited[list[0]][list[1]] = 1;
q.push({list[0], list[1], list[2]});
}
list[0] = a;
list[1] = b + b;
list[2] = c - b;
std::sort(list.begin(), list.end());
if(!visited[list[0]][list[1]])
{
visited[list[0]][list[1]] = 1;
q.push({list[0], list[1], list[2]});
}
}
std::cout << FLAG << '\n';
return 0;
}
|
int Solution::removeDuplicates(vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
for (int i = 0; i < A.size() - 1; i++)
{
int j = i + 1;
while (j < A.size() && A[i] == A[j])
j++;
if (j == i + 1 || j == i + 2)
continue;
A.erase(A.begin() + i, A.begin() + j - 2);
}
return A.size();
}
// or
// class Solution {
// public:
// int removeDuplicates(int A[], int n) {
// int count = 0;
// for (int i = 0; i < n; i++) {
// if (i < n - 2 && A[i] == A[i+1] && A[i] == A[i+2]) continue;
// else {
// A[count] = A[i];
// count++;
// }
// }
// return count;
// }
// };
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef OPLOCALE_H
#define OPLOCALE_H
/** @short Provider of information and operations that need to take the user's locale into account. */
class OpLocale
{
public:
/** Create an OpLocale object. */
static OP_STATUS Create(OpLocale** new_locale);
virtual ~OpLocale() {}
/** Compare two strings.
*
* This is a UTF-16 version of strcoll().
*
* @param str1 String to be compared with str2
* @param str2 String to be compared with str1
* @param len Number of characters to at most compare in each string. If
* -1, compare the entire strings.
* @param ignore_case If TRUE, upper/lower-case differences between the two
* strings will be ignored when doing the comparison.
* @return An integer less than, equal to, or greater than zero if str1 is
* found, respectively, to be less than, to match, or be greater than str2,
* when both are interpreted as appropriate for the current locale.
*/
virtual int CompareStringsL(const uni_char *str1, const uni_char *str2, long len=-1, BOOL ignore_case=FALSE) = 0;
#ifndef DOXYGEN_DOCUMENTATION
/** Compare two strings.
*
* @deprecated Call CompareStringsL() instead.
*/
DEPRECATED(int CompareStrings(const uni_char *str1, const uni_char *str2, long len=-1));
#endif // !DOXYGEN_DOCUMENTATION
/** Format date and time.
*
* This method formats the broken-down 'tm' according to the format
* specification 'fmt' and places the result in the character array 'dest'
* of size 'max'.
*
* This is a UTF-16 version of strftime() (C99 7.23.3.5).
*
* The implementation needs to support at least the following subset of
* the specifiers defined by the C99 standard:
*
* - %a is replaced by the locale's abbreviated weekday name.
* - %A is replaced by the locale's full weekday name.
* - %b is replaced by the locale's abbreviated month name.
* - %B is replaced by the locale's full month name.
* - %c is replaced by the locale's appropriate date and time
* representation.
* - %d is replaced by the day of the month as a decimal number (01-31).
* - %H is replaced by the hour (24-hour clock) as a decimal number (00-23).
* - %I is replaced by the hour (12-hour clock) as a decimal number (01-12).
* - %j is replaced by the day of the year as a decimal number (001-366).
* - %m is replaced by the month as a decimal number (01-12).
* - %M is replaced by the minute as a decimal number (00-61).
* - %p is replaced by the locale's equivalent of the AM/PM designations
* associated with a 12-hour clock.
* - %S is replaced by the second as a decimal number (00-59).
* - %U is replaced by the week number of the year (the first Sunday as the
* first day of week 1) as a decimal number (00-53).
* - %w is replaced by the weekday as a decimal number (0-6), where Sunday
* is 0.
* - %W is replaced by the week number of the year (the first Monday is the
* first day of week 1) as a decimal number (00-53).
* - %x is replaced by the locale's appropriate date representation.
* - %X is replaced by the locale's appropriate time representation.
* - %y is replaced by the year without century as a decimal number (00-99).
* - %Y is replaced by the year with century as a decimal number.
* - %z is replaced by the offset from UTC (+HHMM or -HHMM), or an empty
* string if no time zone information is available. Positive numbers are
* east of Greenwich (ahead of UTC).
* - %% is replaced by %.
*
* Core only requires support for the specifiers above. If any other
* conversion specifiers are supported, they should behave according to
* the POSIX specification of strftime; for specifiers not covered by
* the POSIX specification, the behavior is undefined.
*
* @param dest Destination buffer for formatted date/time
* @param max Maximum number of characters to put in 'dest', including
* terminating NUL byte
* @param fmt Format string. Refer to strftime() documentation for details
* @param tm Time stamp to present as a string
*
* @return The number of characters placed in the array 'dest', not
* including the terminating NUL byte, provided the string, including the
* terminating NUL byte, fits. Otherwise, it returns 0, and the contents of
* the array is undefined.
*/
virtual size_t op_strftime(uni_char *dest, size_t max, const uni_char *fmt, const struct tm *tm) = 0;
/** Check if the locale uses 24h or AM/PM clock.
*
* @return TRUE if locale is 24h, FALSE otherwise.
*/
virtual BOOL Use24HourClock() = 0;
/** Get the first day of week for current localization.
*
* @param day - The index of day in week: 0 - Sunday, 1 - Monday,
* 2 - Tuesday and so on.
* @return See OpStatus. The value of day is only defined on success.
*/
virtual OP_STATUS GetFirstDayOfWeek(int& day) = 0;
/** Represent a number as a string.
*
* @param[out] buffer destination buffer
* @param limit maximum number of characters to write to 'buffer',
* including NUL terminator
* @param number to be rendered localized
* @param with_thousands_sep TRUE if thousands shall be grouped according to locale
* @return Number of characters written, or -1 on failure, in which case
* the contents of 'buffer' are undefined.
*/
virtual int NumberFormat(uni_char *buffer, size_t limit, int number, BOOL with_thousands_sep) = 0;
/** Represent a number as a string.
*
* @param buffer (out) destination buffer
* @param limit maximum number of characters to write to 'buffer',
* including NUL terminator
* @param number to be rendered localized
* @param precision Number of digits after decimal point
* @param with_thousands_sep TRUE if thousands shall be grouped according to locale
* @return Number of characters written, or -1 on failure, in which case
* the contents of 'buffer' are undefined.
*/
virtual int NumberFormat(uni_char *buffer, size_t limit, double number, int precision, BOOL with_thousands_sep) = 0;
/** Represent a number as a string.
*
* @param buffer (out) destination buffer
* @param limit maximum number of characters to write to 'buffer',
* including NUL terminator
* @param number to be rendered localized
* @param with_thousands_sep TRUE if thousands shall be grouped according to locale
* @return Number of characters written, or -1 on failure, in which case
* the contents of 'buffer' are undefined.
*/
virtual int NumberFormat(uni_char *buffer, size_t limit, OpFileLength number, BOOL with_thousands_sep) = 0;
/** Convert a string from UTF-16 to the system's locale encoding.
*
* In some cases Opera needs to convert from its internal representation of
* character data (UTF-16) to the way the system's locale represents it.
*
* @param[out] locale_str Set to the string converted (in the locale encoding)
* @param utf16_str UTF-16 string that is to be converted
*
* @return OK on success, ERR_NO_MEMORY on OOM, ERR on other generic
* conversion failure.
*/
virtual OP_STATUS ConvertToLocaleEncoding(OpString8* locale_str, const uni_char* utf16_str) = 0;
/** Convert a string from the system's locale encoding to UTF-16.
*
* In some cases Opera needs to convert character data from the way the
* system's locale represents it to Opera's internal representation
* (UTF-16).
*
* @param[out] utf16_str Set to the string converted (in UTF-16)
* @param locale_str Locale-encoded string that is to be converted
*
* @return OK on success, ERR_NO_MEMORY on OOM, ERR on other generic
* conversion failure.
*/
virtual OP_STATUS ConvertFromLocaleEncoding(OpString* utf16_str, const char* locale_str) = 0;
};
#ifndef DOXYGEN_DOCUMENTATION
inline int OpLocale::CompareStrings(const uni_char *str1, const uni_char *str2, long len)
{
int retval = -1;
TRAPD(dummy, retval = CompareStringsL(str1, str2, len));
return retval;
}
#endif // !DOXYGEN_DOCUMENTATION
#endif // !OPLOCALE_H
|
#pragma once
#include<vector>
#include<set>
#include<cmath>
#include<cstdlib>
struct Base
{ //baza
int x;
int y;
Base(int xx, int yy) :x(xx), y(yy) {}
Base(){ x = 0; y = 0; }
bool operator==(const Base& rhs)const { return (this->x == rhs.x) && (this->y == rhs.y); }
bool operator<(const Base& rhs)const { return this->x < rhs.x ? true : (this->x > rhs.x ? false : this->y < rhs.y); }
};
|
void nextComb(int curr, vector<string> mp, string iAns, vector<string> &ans, string A) {
if (curr >= A.size()) {
ans.push_back(iAns);
return;
}
for (int i = 0; i < mp[A[curr] - '0'].size(); i++) {
iAns.push_back(mp[A[curr] - '0'][i]);
nextComb(curr + 1, mp, iAns, ans, A);
iAns.pop_back();
}
}
vector<string> Solution::letterCombinations(string A) {
vector<string> mp(10);
mp[0] = "0";
mp[1] = "1";
mp[2] = "abc";
mp[3] = "def";
mp[4] = "ghi";
mp[5] = "jkl";
mp[6] = "mno";
mp[7] = "pqrs";
mp[8] = "tuv";
mp[9] = "wxyz";
vector<string> ans;
string iAns;
nextComb(0, mp, iAns, ans, A);
return ans;
}
|
#ifndef MOVIE_H
#define MOVIE_H
#include <string>
#include <iostream>
#include <set>
#include <algorithm>
#include "product.h"
#include "util.h"
class Movie : public Product {
public:
Movie(const std::string category, const std::string name, double price, int qty, std::string genre, std::string rating);
~Movie();
std::set<std::string> keywords() const;
bool isMatch(std::vector<std::string>& searchTerms) const;
std::string displayString() const;
void dump(std::ostream& os) const;
std::string getGenre() const;
std::string getRating() const;
private:
std::string genre_;
std::string rating_;
};
#endif
|
#ifndef XYZ_H
#define XYZ_H
#include <iostream>
#include <cmath>
#include <random>
#include <string>
#include <sstream>
std::random_device generator;
std::uniform_real_distribution<float> unitInterval(0.0f,1.0f);
std::uniform_real_distribution<float> symmetricInterval(-1.0f,1.0f);
constexpr double PI =3.141592653589793238463;
class xyz {
public:
float x;
float y;
float z;
xyz();
xyz(float X, float Y, float Z);
float magnitude();
std::string print_xyz();
void set_xyz(float X, float Y, float Z);
friend xyz operator+(const xyz &v1, const xyz &v2);
friend xyz operator-(const xyz &v1, const xyz &v2);
friend float operator*(const xyz &v1, const xyz &v2);
friend xyz operator*(const float &c1, const xyz &v1);
friend xyz operator*(const xyz &v1, const float &c1);
friend xyz operator/(const xyz &v1, const float &c1);
};
xyz::xyz(){
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
xyz::xyz(float X,float Y, float Z){
x = X;
y = Y;
z = Z;
}
void xyz::set_xyz(float X,float Y, float Z){
x = X;
y = Y;
z = Z;
}
float xyz::magnitude(){
return sqrt((x*x+y*y+z*z));
}
std::string xyz::print_xyz(){
std::stringstream result;
result << "(" << x << "," << y << "," << z << ")" ;
return result.str();
}
//Define vector addition
xyz operator+(const xyz &v1, const xyz &v2){
xyz result;
result.set_xyz(v1.x+v2.x,v1.y+v2.y,v1.z+v2.z);
return result;
}
//Define vector subtraction
xyz operator-(const xyz &v1, const xyz &v2){
xyz result;
result.set_xyz(v1.x-v2.x,v1.y-v2.y,v1.z-v2.z);
return result;
}
//Dot product
float operator*(const xyz &v1, const xyz &v2){
return (v1.x*v2.x)+(v1.y*v2.y)+(v1.z*v2.z);
}
//Vector scaling
xyz operator*(const float &c1, const xyz &v1){
xyz result;
result.set_xyz(c1*v1.x,c1*v1.y,c1*v1.z);
return result;
}
xyz operator*(const xyz &v1, const float &c1){
xyz result;
result.set_xyz(c1*v1.x,c1*v1.y,c1*v1.z);
return result;
}
//Vector division by constant
xyz operator/(const xyz &v1, const float &c1){
xyz result;
result.set_xyz(v1.x/c1, v1.y/c1, v1.z/c1);
return result;
}
//Random vector generation for unit interval 0-1.
xyz xyz_unit_interval(){
xyz result;
result.set_xyz(unitInterval(generator),unitInterval(generator),unitInterval(generator));
return result;
}
//Random vector generation for interval -1 to 1.
xyz xyz_symm_interval(){
xyz result;
result.set_xyz(symmetricInterval(generator),symmetricInterval(generator),symmetricInterval(generator));
return result;
}
//Choose random unit vector from surface of sphere.
xyz rand_direction(){
float theta = unitInterval(generator) * 2.0f * PI;
float u = symmetricInterval(generator);
xyz result;
result.set_xyz(sqrt(1-(u*u))*cos(theta),sqrt(1-(u*u))*sin(theta),u);
return result;
}
#endif
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Navalny.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Kwillum <daniilxod@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/22 01:43:56 by Kwillum #+# #+# */
/* Updated: 2021/01/22 01:44:46 by Kwillum ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef NAVALNY_HPP
# define NAVALNY_HPP
# include <iostream>
# include <string>
# include "Victim.hpp"
class Navalny : public Victim
{
private:
Navalny();
protected:
public:
Navalny(const std::string &name);
Navalny(const Navalny &toCopy);
virtual void getPolymorphed() const;
Navalny &operator=(const Navalny &toCopy);
virtual ~Navalny();
};
#endif
|
#pragma once
#include "Seaquence.h"
class State;
class SeaquenceController;
class GameSeaquence;
class GameSeaquenceController:public Seaquence
{
public:
typedef SeaquenceController GrandController;
enum NextSeaquence{
NEXT_ENDING,
NEXT_GAMEOVER,
NEXT_TITLE,
NEXT_NONE,
};
GameSeaquenceController();
~GameSeaquenceController();
Boot* Update(GrandController*);
State* GetState();
void DrawStateGame()const;//ゲームを描画する
bool HasFinalStageCleard()const;
void StartLoading();
void GotoNextStage();
int LifeNumber();
void ReduceLife();
private:
State* mState;
int mStageID;
int mLife;
//最終ステージ面定義
static const int FINALSTAGE = 2;
NextSeaquence mNextSeaquence;
GameSeaquence* mGameSeaquence;
};
|
#include "Shader.h"
#include <glm/gtc/type_ptr.hpp>
#include <fstream>
#include <sstream>
#include <iostream>
#include "OpenGLDebug.h"
ShaderBase::~ShaderBase()
{
if (_id)
{
glDeleteProgram(_id); glCheckError();
}
}
void ShaderBase::Start()
{
glUseProgram(_id); glCheckError();
}
void ShaderBase::End()
{
glUseProgram(0); glCheckError();
}
void ShaderBase::Set(const char* varName, bool value)
{
glUniform1i(glGetUniformLocation(_id, varName), (int)value); glCheckError();
}
void ShaderBase::Set(const char* varName, int value)
{
glUniform1i(glGetUniformLocation(_id, varName), value); glCheckError();
}
void ShaderBase::Set(const char* varName, float value)
{
glUniform1f(glGetUniformLocation(_id, varName), value); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::vec2 & value)
{
glUniform2fv(glGetUniformLocation(_id, varName), 1, &value[0]); glCheckError();
}
void ShaderBase::Set(const char* varName, float x, float y)
{
glUniform2f(glGetUniformLocation(_id, varName), x, y); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::vec3 & value)
{
glUniform3fv(glGetUniformLocation(_id, varName), 1, &value[0]); glCheckError();
}
void ShaderBase::Set(const char* varName, float x, float y, float z)
{
glUniform3f(glGetUniformLocation(_id, varName), x, y, z); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::vec4 & value)
{
glUniform4fv(glGetUniformLocation(_id, varName), 1, &value[0]); glCheckError();
}
void ShaderBase::Set(const char* varName, float x, float y, float z, float w)
{
glUniform4f(glGetUniformLocation(_id, varName), x, y, z, w); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::mat2 & mat)
{
glUniformMatrix2fv(glGetUniformLocation(_id, varName), 1, GL_FALSE, &mat[0][0]); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::mat3 & mat)
{
glUniformMatrix3fv(glGetUniformLocation(_id, varName), 1, GL_FALSE, &mat[0][0]); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::mat4 & mat)
{
glUniformMatrix4fv(glGetUniformLocation(_id, varName), 1, GL_FALSE, &mat[0][0]); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::ivec2& value)
{
glUniform2iv(glGetUniformLocation(_id, varName), 1, &value[0]); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::ivec3& value)
{
glUniform3iv(glGetUniformLocation(_id, varName), 1, &value[0]); glCheckError();
}
void ShaderBase::Set(const char* varName, const glm::ivec4& value)
{
glUniform4iv(glGetUniformLocation(_id, varName), 1, &value[0]); glCheckError();
}
|
/*
* Roller.h
*
* Created on: Apr 6, 2015
* Author: eddy
*/
#ifndef ROLLER_H_
#define ROLLER_H_
#include <thread>
#include <mutex>
class Roller{
public:
void start_cycle(int size);
void stop_cycle(void);
int get_number(void);
private:
void cycle(void);
int sides;
int number;
bool keep_cycling;
};
#endif /* ROLLER_H_ */
|
/*
TouchKeys: multi-touch musical keyboard control software
Copyright (c) 2013 Andrew McPherson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=====================================================================
MidiKeyboardSegment.cpp: handles incoming MIDI data and certain input-output
mappings for one segment of a keyboard. The keyboard may be divided up into
any number of segments with different behaviors. An important role of this
class is to manage the output channel allocation when using one MIDI channel
per note (for example, to handle polyphonic pitch bend).
*/
#include "MidiKeyboardSegment.h"
#include "MidiOutputController.h"
#include "../Mappings/MappingFactory.h"
#include "../Mappings/Vibrato/TouchkeyVibratoMappingFactory.h"
#include "../Mappings/PitchBend/TouchkeyPitchBendMappingFactory.h"
#include "../Mappings/Control/TouchkeyControlMappingFactory.h"
#include "../Mappings/ReleaseAngle/TouchkeyReleaseAngleMappingFactory.h"
#include "../Mappings/OnsetAngle/TouchkeyOnsetAngleMappingFactory.h"
#include "../Mappings/MultiFingerTrigger/TouchkeyMultiFingerTriggerMappingFactory.h"
//#include "../Mappings/KeyDivision/TouchkeyKeyDivisionMappingFactory.h"
#include "OscMidiConverter.h"
#include <algorithm>
#include <string>
#include <sstream>
#undef DEBUG_MIDI_KEYBOARD_SEGMENT
const int MidiKeyboardSegment::kMidiControllerDamperPedal = 64;
const int MidiKeyboardSegment::kMidiControllerSostenutoPedal = 66;
const int MidiKeyboardSegment::kPedalActiveValue = 64;
// Factores to use
const int kNumMappingFactoryTypes = 7;
const char* kMappingFactoryNames[kNumMappingFactoryTypes] = {"Control", "Vibrato", "Pitch Bend", "Split Key", "Multi-Finger Trigger", "Onset Angle", "Release Angle"};
// Constructor
MidiKeyboardSegment::MidiKeyboardSegment(PianoKeyboard& keyboard)
: keyboard_(keyboard), outputPortNumber_(0), mappingFactorySplitter_(keyboard),
mappingFactoryUniqueIdentifier_(0),
mode_(ModeOff), channelMask_(0),
noteMin_(0), noteMax_(127), outputChannelLowest_(0), outputTransposition_(0),
damperPedalEnabled_(true), touchkeyStandaloneMode_(false),
usesKeyboardChannelPressure_(false), usesKeyboardPitchWheel_(false),
usesKeyboardModWheel_(false), usesKeyboardPedals_(true),
usesKeyboardMidiControllers_(false),
pitchWheelRange_(2.0), useVoiceStealing_(false)
{
// Register for OSC messages from the internal keyboard source
setOscController(&keyboard_);
keyboard_.setMappingFactory(this, &mappingFactorySplitter_);
setAllControllerActionsTo(kControlActionBlock);
resetControllerValues();
for(int i = 0; i < 128; i++)
noteOnsetTimestamps_[i] = 0;
}
// Destructor
MidiKeyboardSegment::~MidiKeyboardSegment() {
removeAllMappingFactories();
keyboard_.removeMappingFactory(this);
}
bool MidiKeyboardSegment::respondsToMessage(const MidiMessage& message) {
int channel = message.getChannel();
// If the message is not something universal, check if it matches our channel
if(channel > 0) {
if(!(channelMask_ && (1 << (channel - 1))))
return false;
}
// If the message has a note number, see if it's in range
if(message.isNoteOn() || message.isNoteOff() || message.isAftertouch()) {
int noteNumber = message.getNoteNumber();
if(noteNumber < noteMin_ || noteNumber > noteMax_)
return false;
}
return true;
}
bool MidiKeyboardSegment::respondsToNote(int noteNumber) {
if(noteNumber < noteMin_ || noteNumber > noteMax_)
return false;
return true;
}
// Listen on a given MIDI channel
void MidiKeyboardSegment::enableChannel(int channelNumber) {
if(channelNumber >= 0 && channelNumber < 16)
channelMask_ |= (1 << channelNumber);
}
// Listen on all MIDI channels
void MidiKeyboardSegment::enableAllChannels() {
channelMask_ = 0xFFFF;
}
// Disable listening to a specific MIDI channel
void MidiKeyboardSegment::disableChannel(int channelNumber) {
if(channelNumber >= 0 && channelNumber < 16)
channelMask_ &= ~(1 << channelNumber);
}
// Disable all MIDI channels
void MidiKeyboardSegment::disableAllChanels() {
channelMask_ = 0;
}
// Set the range of notes we listen to. Sets the range to between
// minNote and maxNote, inclusive.
void MidiKeyboardSegment::setNoteRange(int minNote, int maxNote) {
// Sanity check
if(minNote > maxNote)
return;
if(minNote < 0)
noteMin_ = 0;
else if(minNote > 127)
noteMin_ = 127;
else
noteMin_ = minNote;
if(maxNote < 0)
noteMax_ = 0;
else if(maxNote > 127)
noteMax_ = 127;
else
noteMax_ = maxNote;
}
// Set the MIDI pitch wheel range
void MidiKeyboardSegment::setMidiPitchWheelRange(float semitones, bool send) {
if(semitones < 0)
pitchWheelRange_ = 0;
else if(semitones > 48.0)
pitchWheelRange_ = 48.0;
else
pitchWheelRange_ = semitones;
if(send)
sendMidiPitchWheelRange();
}
// Send the MIDI pitch wheel range RPN
// If in polyphonic mode, send to all channels; otherwise send only
// to the channel in question.
void MidiKeyboardSegment::sendMidiPitchWheelRange() {
// MPE-TODO
if(mode_ == ModePolyphonic) {
for(int i = outputChannelLowest_; i < outputChannelLowest_ + retransmitMaxPolyphony_; i++)
sendMidiPitchWheelRangeHelper(i);
}
else
sendMidiPitchWheelRangeHelper(outputChannelLowest_);
}
// Enable TouchKeys standalone mode (no MIDI input, touch triggers note)
void MidiKeyboardSegment::enableTouchkeyStandaloneMode() {
if(touchkeyStandaloneMode_)
return;
addOscListener("/touchkeys/on");
addOscListener("/touchkeys/off");
touchkeyStandaloneMode_ = true;
}
// Disable TouchKeys standalone mode (no MIDI input, touch triggers note)
void MidiKeyboardSegment::disableTouchkeyStandaloneMode() {
if(!touchkeyStandaloneMode_)
return;
removeOscListener("/touchkeys/on");
removeOscListener("/touchkeys/off");
touchkeyStandaloneMode_ = false;
}
// Disable any currently active notes
void MidiKeyboardSegment::allNotesOff() {
// TODO: implement me
}
// Reset controller values to defaults
void MidiKeyboardSegment::resetControllerValues() {
// Most controls default to 0
for(int i = 0; i < kControlMax; i++)
controllerValues_[i] = 0;
// ...except pitch wheel, which defaults to center
controllerValues_[kControlPitchWheel] = 8192;
}
// Set the operating mode of the controller. The mode determines the behavior in
// response to incoming MIDI data.
void MidiKeyboardSegment::setMode(int mode) {
if(mode == ModePassThrough)
setModePassThrough();
else if(mode == ModeMonophonic)
setModeMonophonic();
else if(mode == ModePolyphonic)
setModePolyphonic();
else if(mode == ModeMPE)
setModeMPE();
else
setModeOff();
}
void MidiKeyboardSegment::setModeOff() {
allNotesOff();
removeOscListener("/midi/noteon");
setAllControllerActionsTo(kControlActionBlock);
mode_ = ModeOff;
}
void MidiKeyboardSegment::setModePassThrough() {
allNotesOff();
removeOscListener("/midi/noteon");
setAllControllerActionsTo(kControlActionPassthrough);
mode_ = ModePassThrough;
}
void MidiKeyboardSegment::setModeMonophonic() {
allNotesOff();
removeOscListener("/midi/noteon");
setAllControllerActionsTo(kControlActionPassthrough);
mode_ = ModeMonophonic;
}
void MidiKeyboardSegment::setModePolyphonic() {
// First turn off any notes in the current mode
allNotesOff();
setAllControllerActionsTo(kControlActionBroadcast);
// Register a callback for touchkey data. When we get a note-on message,
// we request this callback occur once touch data is available. In this mode,
// we know the eventual channel before any touch data ever occurs: thus, we
// only listen to the MIDI onset itself, which happens after all the touch
// data is sent out.
addOscListener("/midi/noteon");
mode_ = ModePolyphonic;
if(retransmitMaxPolyphony_ < 1)
retransmitMaxPolyphony_ = 1;
modePolyphonicSetupHelper();
}
void MidiKeyboardSegment::setModeMPE() {
// First turn off any notes in the current mode
allNotesOff();
// MPE-TODO some things need to be set to master-zone retransmit
// also reset pitch wheel value to 0 since it's sent separately
setAllControllerActionsTo(kControlActionBroadcast);
// Register a callback for touchkey data. When we get a note-on message,
// we request this callback occur once touch data is available. In this mode,
// we know the eventual channel before any touch data ever occurs: thus, we
// only listen to the MIDI onset itself, which happens after all the touch
// data is sent out.
addOscListener("/midi/noteon");
mode_ = ModeMPE;
// MPE-TODO
// Set RPN 6 to enable MPE with the appropriate zone
}
// Set the maximum polyphony, affecting polyphonic mode only
void MidiKeyboardSegment::setPolyphony(int polyphony) {
// First turn off any notes if this affects current polyphonic mode
// (other modes unaffected so we can make these changes in background)
if(mode_ == ModePolyphonic)
allNotesOff();
if(polyphony < 1)
retransmitMaxPolyphony_ = 1;
else if(polyphony > 16)
retransmitMaxPolyphony_ = 16;
else
retransmitMaxPolyphony_ = polyphony;
// MPE-TODO
// Send RPN 6 to change the zone configuration
// -- maybe in modePolyphonicSetupHelper()
if(mode_ == ModePolyphonic)
modePolyphonicSetupHelper();
}
// Set whether the damper pedal is enabled or not
void MidiKeyboardSegment::setDamperPedalEnabled(bool enable) {
if(damperPedalEnabled_ && !enable) {
// Pedal was enabled before, now it isn't. Clear out any notes
// currently in the pedal so they can be retaken.
damperPedalWentOff();
}
damperPedalEnabled_ = enable;
}
// Set the lowest output channel
void MidiKeyboardSegment::setOutputChannelLowest(int ch) {
// FIXME this is probably broken for polyphonic mode!
// MPE-TODO: send new RPN 6 for disabling old zone and creating new one
outputChannelLowest_ = ch;
}
// Handle an incoming MIDI message
void MidiKeyboardSegment::midiHandlerMethod(MidiInput* source, const MidiMessage& message) {
// Log the timestamps of note onsets and releases, regardless of the mode
// of processing
if(message.isNoteOn()) {
if(message.getNoteNumber() >= 0 && message.getNoteNumber() < 128)
noteOnsetTimestamps_[message.getNoteNumber()] = keyboard_.schedulerCurrentTimestamp();
}
else if(message.isNoteOff()) {
// Remove the onset timestamp unless we have the specific condition:
// (damper pedal enabled) && (pedal is down) && (polyphonic mode)
// In this condition, onsets will be removed when note goes off
if(message.getNoteNumber() >= 0 && message.getNoteNumber() < 128) {
if(!damperPedalEnabled_ || controllerValues_[kMidiControllerDamperPedal] < kPedalActiveValue ||
(mode_ != ModePolyphonic && mode_ != ModeMPE)) {
noteOnsetTimestamps_[message.getNoteNumber()] = 0;
}
}
}
else if(message.isAllNotesOff() || message.isAllSoundOff()) {
for(int i = 0; i < 128; i++)
noteOnsetTimestamps_[i] = 0;
}
// Log the values of incoming control changes in case mappings need to use them later
if(message.isController() && !(message.isAllNotesOff() || message.isAllSoundOff())) {
// Handle damper pedal specially: it may affect note allocation
if(message.getControllerNumber() == kMidiControllerDamperPedal) {
if(message.getControllerValue() < kPedalActiveValue &&
controllerValues_[kMidiControllerDamperPedal] >= kPedalActiveValue) {
damperPedalWentOff();
}
}
if(message.getControllerNumber() >= 0 && message.getControllerNumber() < 128) {
if(message.getControllerNumber() == 1 && usesKeyboardModWheel_) {
controllerValues_[message.getControllerNumber()] = message.getControllerValue();
handleControlChangeRetransit(message.getControllerNumber(), message);
}
else if(message.getControllerNumber() >= 64 && message.getControllerNumber() <= 69
&& usesKeyboardPedals_) {
// MPE-TODO send this on master zone
controllerValues_[message.getControllerNumber()] = message.getControllerValue();
handleControlChangeRetransit(message.getControllerNumber(), message);
}
else if(usesKeyboardMidiControllers_) {
controllerValues_[message.getControllerNumber()] = message.getControllerValue();
handleControlChangeRetransit(message.getControllerNumber(), message);
}
}
}
else if(message.isChannelPressure()) {
if(usesKeyboardChannelPressure_) {
controllerValues_[kControlChannelAftertouch] = message.getChannelPressureValue();
handleControlChangeRetransit(kControlChannelAftertouch, message);
}
}
else if(message.isPitchWheel()) {
if(usesKeyboardPitchWheel_) {
if(mode_ == ModeMPE) {
// MPE-TODO send this on master zone instead of putting it into the calculations
}
else {
controllerValues_[kControlPitchWheel] = message.getPitchWheelValue();
handleControlChangeRetransit(kControlPitchWheel, message);
}
}
}
else {
// Process the message differently depending on the current mode
switch(mode_) {
case ModePassThrough:
modePassThroughHandler(source, message);
break;
case ModeMonophonic:
modeMonophonicHandler(source, message);
break;
case ModePolyphonic:
modePolyphonicHandler(source, message);
break;
case ModeMPE:
modeMPEHandler(source, message);
break;
case ModeOff:
default:
// Ignore message
break;
}
}
}
// OscHandler method which parses incoming OSC messages we've registered for. In this case,
// we use OSC callbacks to find out about touch data for notes we want to trigger.
bool MidiKeyboardSegment::oscHandlerMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data) {
if(touchkeyStandaloneMode_) {
if(!strcmp(path, "/touchkeys/on") && numValues > 0) {
int noteNumber = values[0]->i;
if(!respondsToNote(noteNumber))
return true;
if(noteNumber >= 0 && noteNumber < 128) {
// Generate MIDI note on for this message
MidiMessage msg(MidiMessage::noteOn(1, noteNumber, (uint8_t)64));
midiHandlerMethod(0, msg);
}
return true;
}
else if(!strcmp(path, "/touchkeys/off") && numValues > 0) {
int noteNumber = values[0]->i;
if(!respondsToNote(noteNumber))
return true;
if(noteNumber >= 0 && noteNumber < 128) {
// Generate MIDI note off for this message
MidiMessage msg(MidiMessage::noteOff(1, noteNumber));
midiHandlerMethod(0, msg);
}
return true;
}
}
if(mode_ == ModePolyphonic || mode_ == ModeMPE) {
modePolyphonicMPENoteOnCallback(path, types, numValues, values);
}
return true;
}
// Control method via OSC. This comes in via MainApplicationController to MidiInputController
// and is used specifically for querying and modifying the status of the zone and its mappings,
// as opposed to the more frequent OSC messages to oscHandlerMethod() which provide touch and
// MIDI data. Return true if message was successfully handled.
OscMessage* MidiKeyboardSegment::oscControlMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data) {
// First check if this message is destined for a mapping within the segment
// e.g. /mapping/my_mapping_name/message_for_mapping
if(!strncmp(path, "/mapping/", 9) && strlen(path) > 9) {
std::string subpath(&path[9]);
int separatorLoc = subpath.find_first_of('/');
if(separatorLoc == (int) std::string::npos || separatorLoc == (int) subpath.length() - 1) {
// Malformed input (no slash or it's the last character): ignore
return 0;
}
// Find the name of the mapping in the nextsegment
std::string mappingName = subpath.substr(0, separatorLoc);
// Look for a matching factory. TODO: this should probably be mutex-protected
vector<MappingFactory*>::iterator it;
for(it = mappingFactories_.begin(); it != mappingFactories_.end(); ++it) {
if((*it)->getShortName() == mappingName) {
std::string mappingAction = subpath.substr(separatorLoc);
if(mappingAction == "/delete") {
removeMappingFactory(*it);
return OscTransmitter::createSuccessMessage();
}
else {
// Pass message to mapping factory here
OscMessage *response = (*it)->oscControlMethod(mappingAction.c_str(), types, numValues, values, data);
// Prepend the mapping name to the response except in case of simple status response
if(response == 0)
return 0;
else if(!strcmp(response->path(), "/result"))
return response;
response->prependPath(mappingName.c_str());
response->prependPath("/mapping/");
return response;
}
}
}
}
else if(!strcmp(path, "/list-mappings")) {
// Return a list of mapping names and types
// TODO: this should be mutex-protected
OscMessage *response = OscTransmitter::createMessage("/list-mappings/result", "i", mappingFactories_.size(), LO_ARGS_END);
vector<MappingFactory*>::iterator it;
for(it = mappingFactories_.begin(); it != mappingFactories_.end(); ++it) {
lo_message_add_string(response->message(), (*it)->getShortName().c_str());
}
return response;
}
else if(!strcmp(path, "/add-mapping")) {
// Add a new mapping of a given type
if(numValues >= 1) {
if(types[0] == 'i') {
int type = values[0]->i;
if(type < 0 || type >= kNumMappingFactoryTypes)
return OscTransmitter::createFailureMessage();
// Create mapping factory of the requested type
MappingFactory *newFactory = createMappingFactoryForIndex(type);
if(newFactory == 0)
return OscTransmitter::createFailureMessage();
// Add the mapping factory to this segment, autogenerating the
// name unless it is specified
if(numValues >= 2) {
if(types[1] == 's') {
// Set the name as it was passed in
newFactory->setName(&values[1]->s);
addMappingFactory(newFactory, false);
}
else
addMappingFactory(newFactory, true);
}
else
addMappingFactory(newFactory, true);
return OscTransmitter::createSuccessMessage();
}
}
}
else if(!strcmp(path, "/set-range")) {
// Set the MIDI note range
if(numValues >= 2) {
if(types[0] == 'i' && types[1] == 'i') {
int rangeLow = values[0]->i;
int rangeHigh = values[1]->i;
if(rangeLow < 0 || rangeLow > 127 || rangeHigh < 0 || rangeHigh > 127)
return OscTransmitter::createFailureMessage();
if(rangeLow > rangeHigh) {
// Swap values so lowest one is always first
int temp = rangeLow;
rangeLow = rangeHigh;
rangeHigh = temp;
}
setNoteRange(rangeLow, rangeHigh);
return OscTransmitter::createSuccessMessage();
}
}
}
else if(!strcmp(path, "/set-transpose")) {
// Set the transposition of the output
if(numValues >= 1) {
if(types[0] == 'i') {
int transpose = values[0]->i;
if(transpose < -48 || transpose > 48)
return OscTransmitter::createFailureMessage();
setOutputTransposition(transpose);
return OscTransmitter::createSuccessMessage();
}
}
}
else if(!strcmp(path, "/set-transpose-octave-up")) {
// Set the transposition of the output
int transpose = outputTransposition() + 12;
if(transpose > 48)
transpose = 48;
setOutputTransposition(transpose);
return OscTransmitter::createSuccessMessage();
}
else if(!strcmp(path, "/set-transpose-octave-down")) {
// Set the transposition of the output
int transpose = outputTransposition() - 12;
if(transpose < -48)
transpose = -48;
setOutputTransposition(transpose);
return OscTransmitter::createSuccessMessage();
}
else if(!strcmp(path, "/set-controller-pass")) {
// Set which controllers to pass through
// Arguments: (channel pressure), (pitch wheel), (mod wheel), (pedals), (other CCs)
if(numValues >= 5) {
if(types[0] == 'i' && types[1] == 'i' && types[2] == 'i' && types[3] == 'i' && types[4] == 'i') {
setUsesKeyboardChannelPressure(values[0]->i != 0);
setUsesKeyboardPitchWheel(values[1]->i != 0);
setUsesKeyboardModWheel(values[2]->i != 0);
setUsesKeyboardPedals(values[3]->i != 0);
setUsesKeyboardMIDIControllers(values[4]->i != 0);
return OscTransmitter::createSuccessMessage();
}
}
}
else if(!strcmp(path, "/set-pitchwheel-range")) {
// Set the MIDI pitchwheel range in semitones
if(numValues >= 1) {
if(types[0] == 'i') {
int range = values[0]->i;
setMidiPitchWheelRange(range);
return OscTransmitter::createSuccessMessage();
}
else if(types[0] == 'f') {
float range = values[0]->f;
setMidiPitchWheelRange(range);
return OscTransmitter::createSuccessMessage();
}
}
}
else if(!strcmp(path, "/send-pitchwheel-range")) {
// Send an RPN value with the current pitchwheel range
sendMidiPitchWheelRange();
return OscTransmitter::createSuccessMessage();
}
else if(!strcmp(path, "/set-midi-mode")) {
// Set the MIDI mode (mono, poly etc.)
if(numValues >= 1) {
if(types[0] == 's') {
char *mode = &values[0]->s;
if(!strcmp(mode, "off"))
setModeOff();
else if(!strncmp(mode, "pass", 4))
setModePassThrough();
else if(!strncmp(mode, "mono", 4))
setModeMonophonic();
else if(!strncmp(mode, "poly", 4))
setModePolyphonic();
else if(!strncmp(mode, "mpe", 3))
setModeMPE();
else
return OscTransmitter::createFailureMessage();
return OscTransmitter::createSuccessMessage();
}
}
}
else if(!strcmp(path, "/set-midi-channels")) {
// Set the MIDI channels
if(numValues >= 2) {
if(types[0] == 'i' && types[1] == 'i') {
int channelLow = values[0]->i;
int channelHigh = values[1]->i;
if(channelLow < 1 || channelLow > 16 || channelHigh < 1 || channelHigh > 16)
return OscTransmitter::createFailureMessage();
if(channelLow > channelHigh) {
// Swap values so lowest one is always first
int temp = channelLow;
channelLow = channelHigh;
channelHigh = temp;
}
setOutputChannelLowest(channelLow - 1); // 1-16 --> 0-15 indexing
int polyphony = channelHigh - channelLow + 1;
if(polyphony < 1)
polyphony = 1;
setPolyphony(polyphony);
return OscTransmitter::createSuccessMessage();
}
}
}
else if(!strcmp(path, "/set-midi-stealing")) {
// Set whether MIDI voice stealing is enabled
if(numValues >= 1) {
if(types[0] == 'i') {
setVoiceStealingEnabled(values[0]->i != 0);
return OscTransmitter::createSuccessMessage();
}
}
}
// No match
return 0;
}
// Acquire an OSC-MIDI converter. If a converter for this control already exists,
// return it. If not, create it. This method keeps track of how many objects have
// acquired the converter. When all acquirers have released ihe converter, it is
// destroyed.
OscMidiConverter* MidiKeyboardSegment::acquireOscMidiConverter(int controlId) {
OscMidiConverter *converter;
if(oscMidiConverters_.count(controlId) == 0) {
converter = new OscMidiConverter(keyboard_, *this, controlId);
converter->setMidiOutputController(midiOutputController_);
oscMidiConverters_[controlId] = converter;
oscMidiConverterReferenceCounts_[controlId] = 1;
}
else {
if(oscMidiConverterReferenceCounts_.count(controlId) == 0) {
cerr << "BUG: found a converter with missing reference counter\n";
}
else if(oscMidiConverterReferenceCounts_[controlId] <= 0) {
cerr << "BUG: found a converter with no references\n";
oscMidiConverterReferenceCounts_[controlId] = 1;
}
else
oscMidiConverterReferenceCounts_[controlId]++;
converter = oscMidiConverters_[controlId];
}
return converter;
}
// Release a previously acquired OSC-MIDI converter. This call must be paired with
// acquireOscMidiConverter.
void MidiKeyboardSegment::releaseOscMidiConverter(int controlId) {
if(oscMidiConverters_.count(controlId) == 0 ||
oscMidiConverterReferenceCounts_.count(controlId) == 0) {
cerr << "BUG: releasing a missing OSC-MIDI converter\n";
return;
}
oscMidiConverterReferenceCounts_[controlId]--;
if(oscMidiConverterReferenceCounts_[controlId] == 0) {
// This was the last release of this converter. Delete it.
OscMidiConverter *converter = oscMidiConverters_[controlId];
delete converter;
oscMidiConverters_.erase(controlId);
oscMidiConverterReferenceCounts_.erase(controlId);
}
}
// Helper predicate function for filtering strings
inline bool char_is_not_alphanumeric(int c) {
#ifdef _MSC_VER
return !isalnum(c);
#else
return !std::isalnum(c);
#endif
}
// Return the number of mapping factory types available
int MidiKeyboardSegment::numberOfMappingFactories() {
return kNumMappingFactoryTypes;
}
// Return the name of the given mapping factory type
std::string MidiKeyboardSegment::mappingFactoryNameForIndex(int index) {
if(index < 0 || index >= kNumMappingFactoryTypes)
return std::string();
return kMappingFactoryNames[index];
}
// Return a new object of the given mapping factory type
MappingFactory* MidiKeyboardSegment::createMappingFactoryForIndex(int index) {
// switch(index) {
// case 0:
// return new TouchkeyControlMappingFactory(keyboard_, *this);
// case 1:
// return new TouchkeyVibratoMappingFactory(keyboard_, *this);
// case 2:
// return new TouchkeyPitchBendMappingFactory(keyboard_, *this);
// case 3:
//// return new TouchkeyKeyDivisionMappingFactory(keyboard_, *this);
// case 4:
// return new TouchkeyMultiFingerTriggerMappingFactory(keyboard_, *this);
// case 5:
// return new TouchkeyOnsetAngleMappingFactory(keyboard_, *this);
// case 6:
// return new TouchkeyReleaseAngleMappingFactory(keyboard_, *this);
// default:
// return 0;
// }
return NULL;
}
// Return whethera given mapping is experimental or not
bool MidiKeyboardSegment::mappingIsExperimental(int index) {
if(index == 5)
return true;
return false;
}
// Create a new mapping factory for this segment. A pointer should be passed in
// of a newly-allocated object. It will be released upon removal.
void MidiKeyboardSegment::addMappingFactory(MappingFactory* factory, bool autoGenerateName) {
// Check for duplicates-- can't add the same factory twice
vector<MappingFactory*>::iterator it;
for(it = mappingFactories_.begin(); it != mappingFactories_.end(); ++it) {
if(*it == factory)
return;
}
// If the name should autogenerate, find a unique name for this factory
if(autoGenerateName) {
std::string baseName = factory->factoryTypeName();
// Remove spaces, newlines, other invalid characters, leaving only alphanumerics
baseName.erase(std::remove_if(baseName.begin(), baseName.end(), char_is_not_alphanumeric),
baseName.end());
std::transform(baseName.begin(), baseName.end(), baseName.begin(), ::tolower);
// Now look for an OSC path with this name. If found, add a number to the end, incrementing
// it until a unique name is found
std::string name = baseName;
bool isUnique = false;
int appendDigit = 2;
while(!isUnique) {
isUnique = true;
for(unsigned int i = 0; i < mappingFactories_.size(); i++) {
std::string compareName = mappingFactories_[i]->getName();
int lastSeparator = compareName.find_last_of('/');
if((lastSeparator != (int) std::string::npos) && (lastSeparator < (int) compareName.size() - 1))
compareName = compareName.substr(lastSeparator + 1);
if(name == compareName) {
isUnique = false;
// Try a new name with a new digit at the end...
std::stringstream ss;
ss << baseName << appendDigit;
name = ss.str();
appendDigit++;
break;
}
}
}
factory->setName(name);
}
// Add factory to internal vector, and add it to splitter class
mappingFactories_.push_back(factory);
mappingFactorySplitter_.addFactory(factory);
mappingFactoryUniqueIdentifier_++;
}
// Remove a mapping factory, releasing the associated object.
void MidiKeyboardSegment::removeMappingFactory(MappingFactory* factory) {
vector<MappingFactory*>::iterator it;
for(it = mappingFactories_.begin(); it != mappingFactories_.end(); ++it) {
if(*it == factory) {
mappingFactorySplitter_.removeFactory(factory);
delete factory;
mappingFactories_.erase(it);
break;
}
}
mappingFactoryUniqueIdentifier_++;
}
// Remove all mapping factories, releasing each one
void MidiKeyboardSegment::removeAllMappingFactories() {
vector<MappingFactory*>::iterator it;
mappingFactorySplitter_.removeAllFactories();
for(it = mappingFactories_.begin(); it != mappingFactories_.end(); ++it) {
delete *it;
}
mappingFactories_.clear();
mappingFactoryUniqueIdentifier_++;
}
// Return a list of current mapping factories.
vector<MappingFactory*> const& MidiKeyboardSegment::mappingFactories(){
return mappingFactories_;
}
// Return the specific index of a mapping factory for this segment
int MidiKeyboardSegment::indexOfMappingFactory(MappingFactory *factory) {
vector<MappingFactory*>::iterator it;
int i = 0;
for(it = mappingFactories_.begin(); it != mappingFactories_.end(); ++it) {
if(*it == factory)
return i;
i++;
}
return -1;
}
// Get an XML element describing current settings (for saving presets)
// This element will need to be released (or added to another XML element
// that is released) by the caller
XmlElement* MidiKeyboardSegment::getPreset() {
XmlElement* segmentElement = new XmlElement("Segment");
// Add segment settings
PropertySet properties;
properties.setValue("outputPort", outputPortNumber_);
properties.setValue("mode", mode_);
properties.setValue("channelMask", (int)channelMask_);
properties.setValue("noteMin", noteMin_);
properties.setValue("noteMax", noteMax_);
properties.setValue("outputChannelLowest", outputChannelLowest_);
properties.setValue("outputTransposition", outputTransposition_);
properties.setValue("damperPedalEnabled", damperPedalEnabled_);
// Don't set standalone mode; that's an input parameter
properties.setValue("usesKeyboardChannelPressure", usesKeyboardChannelPressure_);
properties.setValue("usesKeyboardPitchWheel", usesKeyboardPitchWheel_);
properties.setValue("usesKeyboardModWheel", usesKeyboardModWheel_);
properties.setValue("usesKeyboardPedals", usesKeyboardPedals_);
properties.setValue("usesKeyboardMidiControllers", usesKeyboardMidiControllers_);
properties.setValue("pitchWheelRange", pitchWheelRange_);
properties.setValue("retransmitMaxPolyphony", retransmitMaxPolyphony_);
properties.setValue("useVoiceStealing", useVoiceStealing_);
segmentElement->addChildElement(properties.createXml("Properties"));
// Go through mapping factories and add their settings
vector<MappingFactory*>::iterator it;
for(it = mappingFactories_.begin(); it != mappingFactories_.end(); ++it) {
XmlElement* factoryElement = (*it)->getPreset();
segmentElement->addChildElement(factoryElement);
}
return segmentElement;
}
// Load settings from an XML element
bool MidiKeyboardSegment::loadPreset(XmlElement const* preset) {
removeAllMappingFactories();
XmlElement *propertiesElement = preset->getChildByName("Properties");
if(propertiesElement == 0)
return false;
// Load segment settings
PropertySet properties;
properties.restoreFromXml(*propertiesElement);
if(!properties.containsKey("outputPort"))
return false;
outputPortNumber_ = properties.getIntValue("outputPort");
if(!properties.containsKey("mode"))
return false;
int mode = properties.getIntValue("mode");
// Setting the mode affects a few other variables so use the
// functions rather than setting mode_ directly
if(mode == ModePassThrough)
setModePassThrough();
else if(mode == ModeMonophonic)
setModeMonophonic();
else if(mode == ModePolyphonic)
setModePolyphonic();
else if(mode == ModeMPE)
setModeMPE();
else // Off or unknown
setModeOff();
if(!properties.containsKey("channelMask"))
return false;
channelMask_ = properties.getIntValue("channelMask");
if(!properties.containsKey("noteMin"))
return false;
noteMin_ = properties.getIntValue("noteMin");
if(!properties.containsKey("noteMax"))
return false;
noteMax_ = properties.getIntValue("noteMax");
if(!properties.containsKey("outputChannelLowest"))
return false;
outputChannelLowest_ = properties.getIntValue("outputChannelLowest");
if(!properties.containsKey("outputTransposition"))
return false;
outputTransposition_ = properties.getIntValue("outputTransposition");
if(!properties.containsKey("damperPedalEnabled"))
return false;
damperPedalEnabled_ = properties.getBoolValue("damperPedalEnabled");
if(!properties.containsKey("usesKeyboardChannelPressure"))
return false;
usesKeyboardChannelPressure_ = properties.getBoolValue("usesKeyboardChannelPressure");
if(!properties.containsKey("usesKeyboardPitchWheel"))
return false;
usesKeyboardPitchWheel_ = properties.getBoolValue("usesKeyboardPitchWheel");
if(!properties.containsKey("usesKeyboardModWheel"))
return false;
usesKeyboardModWheel_ = properties.getBoolValue("usesKeyboardModWheel");
if(properties.containsKey("usesKeyboardPedals"))
usesKeyboardPedals_ = properties.getBoolValue("usesKeyboardPedals");
else
usesKeyboardPedals_ = false; // For backwards compatibility with older versions
if(!properties.containsKey("usesKeyboardMidiControllers"))
return false;
usesKeyboardMidiControllers_ = properties.getBoolValue("usesKeyboardMidiControllers");
if(!properties.containsKey("pitchWheelRange"))
return false;
pitchWheelRange_ = properties.getDoubleValue("pitchWheelRange");
if(!properties.containsKey("retransmitMaxPolyphony"))
return false;
setPolyphony(properties.getIntValue("retransmitMaxPolyphony"));
if(!properties.containsKey("useVoiceStealing"))
return false;
useVoiceStealing_ = properties.getBoolValue("useVoiceStealing");
// Load each mapping factory
XmlElement *element = preset->getChildByName("MappingFactory");
while(element != 0) {
if(!element->hasAttribute("type"))
return false;
// Create a new factory whose type depends on the XML tag
MappingFactory *factory;
std::string const& factoryType = element->getStringAttribute("type");
// if(factoryType == "Control")
// factory = new TouchkeyControlMappingFactory(keyboard_, *this);
// else if(factoryType == "Vibrato")
// factory = new TouchkeyVibratoMappingFactory(keyboard_, *this);
// else if(factoryType == "PitchBend")
// factory = new TouchkeyPitchBendMappingFactory(keyboard_, *this);
//// else if(factoryType == "KeyDivision")
//// factory = new TouchkeyKeyDivisionMappingFactory(keyboard_, *this);
// else if(factoryType == "MultiFingerTrigger")
// factory = new TouchkeyMultiFingerTriggerMappingFactory(keyboard_, *this);
// else if(factoryType == "OnsetAngle")
// factory = new TouchkeyOnsetAngleMappingFactory(keyboard_, *this);
// else if(factoryType == "ReleaseAngle")
// factory = new TouchkeyReleaseAngleMappingFactory(keyboard_, *this);
// else {
// // Type unknown or unsupported; ignore and continue
// element = element->getNextElementWithTagName("MappingFactory");
// continue;
// }
// Tell factory to load its settings from this element
if(!factory->loadPreset(element)) {
delete factory;
return false;
}
// Add factory; don't autogenerate name as it will be saved
addMappingFactory(factory, false);
element = element->getNextElementWithTagName("MappingFactory");
}
return true;
}
// Mode-specific MIDI handlers. These methods handle incoming MIDI data according to the rules
// defined by a particular mode of operation.
// Pass-Through: Retransmit any input data to the output unmodified.
void MidiKeyboardSegment::modePassThroughHandler(MidiInput* source, const MidiMessage& message) {
// Check if there is a note on or off, and update the keyboard class accordingly
if(message.isNoteOn()) {
int note = message.getNoteNumber();
if(keyboard_.key(note) != 0)
keyboard_.key(note)->midiNoteOn(this, message.getVelocity(), message.getChannel() - 1,
keyboard_.schedulerCurrentTimestamp());
// Retransmit, possibly with transposition
if(midiOutputController_ != 0) {
MidiMessage newMessage = MidiMessage::noteOn(message.getChannel(), message.getNoteNumber() + outputTransposition_, message.getVelocity());
midiOutputController_->sendMessage(outputPortNumber_, newMessage);
}
}
else if(message.isNoteOff()) {
int note = message.getNoteNumber();
if(keyboard_.key(note) != 0)
keyboard_.key(note)->midiNoteOff(this, keyboard_.schedulerCurrentTimestamp());
// Retransmit, possibly with transposition
if(midiOutputController_ != 0) {
MidiMessage newMessage = MidiMessage::noteOff(message.getChannel(), message.getNoteNumber() + outputTransposition_);
midiOutputController_->sendMessage(outputPortNumber_, newMessage);
}
}
else if(message.isAftertouch()) { // Polyphonic aftertouch: adjust to transposition
if(midiOutputController_ != 0) {
MidiMessage newMessage = MidiMessage::aftertouchChange(message.getChannel(), message.getNoteNumber() + outputTransposition_, message.getAfterTouchValue());
midiOutputController_->sendMessage(outputPortNumber_, newMessage);
}
}
else if(midiOutputController_ != 0) // Anything else goes through unchanged
midiOutputController_->sendMessage(outputPortNumber_, message);
}
// Monophonic: all MIDI messages pass through to the output, which is assumed to be a monosynth.
// However the most recent key which determines the currently sounding note will have its mapping
// active; all others are suspended.
void MidiKeyboardSegment::modeMonophonicHandler(MidiInput* source, const MidiMessage& message) {
if(message.isNoteOn()) {
// First suspend any other mappings. This might include the current note if the touch
// data has caused a mapping to be created.
if(keyboard_.mappingFactory(this) != 0) {
keyboard_.mappingFactory(this)->suspendAllMappings();
}
// And turn on note on MIDI controller
if(midiOutputController_ != 0) {
MidiMessage newMessage = MidiMessage::noteOn(message.getChannel(), message.getNoteNumber() + outputTransposition_, message.getVelocity());
midiOutputController_->sendMessage(outputPortNumber_, newMessage);
}
// Now start the next one
int note = message.getNoteNumber();
if(keyboard_.key(note) != 0)
keyboard_.key(note)->midiNoteOn(this, message.getVelocity(),
message.getChannel() - 1, keyboard_.schedulerCurrentTimestamp());
// Now resume the current note's mapping
if(keyboard_.mappingFactory(this) != 0) {
keyboard_.mappingFactory(this)->resumeMapping(note, true);
}
}
else if(message.isNoteOff()) {
// First stop this note
int note = message.getNoteNumber();
if(keyboard_.key(note) != 0)
keyboard_.key(note)->midiNoteOff(this, keyboard_.schedulerCurrentTimestamp());
// Then reactivate the most recent note's mappings
if(keyboard_.mappingFactory(this) != 0) {
int newest = newestNote();
if(newest >= 0)
keyboard_.mappingFactory(this)->resumeMapping(newest, true);
}
// And turn off note on MIDI controller
if(midiOutputController_ != 0) {
MidiMessage newMessage = MidiMessage::noteOff(message.getChannel(), message.getNoteNumber() + outputTransposition_, message.getVelocity());
midiOutputController_->sendMessage(outputPortNumber_, newMessage);
}
}
}
// Polyphonic: Each incoming note gets its own unique MIDI channel so its controllers
// can be manipulated separately (e.g. by touchkey data). Keep track of available channels
// and currently active notes.
void MidiKeyboardSegment::modePolyphonicHandler(MidiInput* source, const MidiMessage& message) {
if(message.getRawDataSize() <= 0)
return;
const unsigned char *rawData = message.getRawData();
if(rawData[0] == kMidiMessageReset) {
// Reset state and pass along to all relevant channels
retransmitChannelForNote_.clear(); // Clear current note information
retransmitChannelsAvailable_.clear();
retransmitNotesHeldInPedal_.clear();
for(int i = 0; i < retransmitMaxPolyphony_; i++) {
retransmitChannelsAvailable_.insert(i);
}
if(midiOutputController_ != 0)
midiOutputController_->sendReset(outputPortNumber_);
}
else if(message.isNoteOn()) {
if(retransmitChannelForNote_.count(message.getNoteNumber()) > 0
&& retransmitNotesHeldInPedal_.count(message.getNoteNumber()) == 0) {
// Case (2)-- retrigger an existing note
if(midiOutputController_ != 0) {
midiOutputController_->sendNoteOn(outputPortNumber_, retransmitChannelForNote_[message.getNoteNumber()],
message.getNoteNumber() + outputTransposition_, message.getVelocity());
}
}
else {
// New note
modePolyphonicNoteOn(message.getNoteNumber(), message.getVelocity());
}
}
else if(message.isNoteOff()) {
modePolyphonicNoteOff(message.getNoteNumber());
}
else if(message.isAllNotesOff() || message.isAllSoundOff()) {
retransmitChannelForNote_.clear(); // Clear current note information
retransmitChannelsAvailable_.clear();
retransmitNotesHeldInPedal_.clear();
for(int i = 0; i < retransmitMaxPolyphony_; i++)
retransmitChannelsAvailable_.insert(i);
}
else if(message.isAftertouch()) { // polyphonic aftertouch
if(retransmitChannelForNote_.count(message.getNoteNumber()) > 0) {
int retransmitChannel = retransmitChannelForNote_[message.getNoteNumber()];
if(midiOutputController_ != 0) {
midiOutputController_->sendAftertouchPoly(outputPortNumber_, retransmitChannel,
message.getNoteNumber() + outputTransposition_, message.getAfterTouchValue());
}
}
}
}
// Handle note on message in polyphonic mode. Allocate a new channel
// for this note and rebroadcast it.
void MidiKeyboardSegment::modePolyphonicNoteOn(unsigned char note, unsigned char velocity) {
int newChannel = -1;
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "Channels available: ";
for(set<int>::iterator it = retransmitChannelsAvailable_.begin();
it != retransmitChannelsAvailable_.end(); ++it) {
cout << *it << " ";
}
cout << endl;
cout << "Channels allocated: ";
for(map<int, int>::iterator it = retransmitChannelForNote_.begin();
it != retransmitChannelForNote_.end(); ++it) {
cout << it->second << "(" << it->first << ") ";
}
cout << endl;
#endif
if(retransmitNotesHeldInPedal_.count(note) > 0) {
// For notes that are still sounding in the pedal, reuse the same MIDI channel
// they had before.
if(retransmitChannelForNote_.count(note) > 0)
newChannel = retransmitChannelForNote_[note];
else {
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "BUG: note " << note << " held in pedal but has no channel\n";
#endif
retransmitNotesHeldInPedal_.erase(note);
return;
}
// No longer held in pedal: it will be an active note again with the same channel
retransmitNotesHeldInPedal_.erase(note);
}
else {
// Otherwise, allocate a new channel to this note
if(retransmitChannelsAvailable_.size() == 0) {
if(damperPedalEnabled_) {
// First priority is always to take a note that is being sustained
// in the pedal but not actively held. This is true whether or not
// voice stealing is enabled.
int oldNote = oldestNoteInPedal();
// int oldChannel = -1;
// if(retransmitChannelForNote_.count(oldNote) > 0)
// oldChannel = retransmitChannelForNote_[oldNote];
if(oldNote >= 0) {
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "Stealing note " << oldNote << " from pedal for note " << (int)note << endl;
#endif
modePolyphonicNoteOff(oldNote, true);
}
}
// Now try again...
if(retransmitChannelsAvailable_.size() == 0) {
if(useVoiceStealing_) {
// Find the voice with the oldest timestamp and turn it off
int oldNote = oldestNote();
// int oldChannel = -1;
// if(retransmitChannelForNote_.count(oldNote) > 0)
// oldChannel = retransmitChannelForNote_[oldNote];
if(oldNote < 0) {
// Shouldn't happen...
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "No notes present, but no MIDI output channel available for note " << (int)note << endl;
#endif
return;
}
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "Stealing note " << oldNote << " for note " << (int)note << endl;
#endif
modePolyphonicNoteOff(oldNote, true);
}
else {
// No channels available. Print a warning and finish
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "No MIDI output channel available for note " << (int)note << endl;
#endif
return;
}
}
}
// Request the first available channel
newChannel = *retransmitChannelsAvailable_.begin();
retransmitChannelsAvailable_.erase(newChannel);
retransmitChannelForNote_[note] = newChannel;
}
if(keyboard_.key(note) != 0) {
keyboard_.key(note)->midiNoteOn(this, velocity, newChannel, keyboard_.schedulerCurrentTimestamp());
}
// The above function will cause a callback to be generated, which in turn will generate
// the Note On message.
}
// Handle note off message in polyphonic mode. Release any channel
// associated with this note.
void MidiKeyboardSegment::modePolyphonicNoteOff(unsigned char note, bool forceOff) {
// If no channel associated with this note, ignore it
if(retransmitChannelForNote_.count(note) == 0) {
if(note >= 0 && note < 128)
noteOnsetTimestamps_[note] = 0;
return;
}
if(keyboard_.key(note) != 0) {
keyboard_.key(note)->midiNoteOff(this, keyboard_.schedulerCurrentTimestamp());
}
int oldNoteChannel = retransmitChannelForNote_[note];
if(midiOutputController_ != 0) {
if(forceOff) {
// To silence a note, we need to clear any pedals that might be holding it
if(controllerValues_[kMidiControllerDamperPedal] >= kPedalActiveValue) {
midiOutputController_->sendControlChange(outputPortNumber_, oldNoteChannel,
kMidiControllerDamperPedal, 0);
}
if(controllerValues_[kMidiControllerSostenutoPedal] >= kPedalActiveValue) {
midiOutputController_->sendControlChange(outputPortNumber_, oldNoteChannel,
kMidiControllerSostenutoPedal, 0);
}
// Send All Notes Off and All Sound Off
midiOutputController_->sendControlChange(outputPortNumber_, oldNoteChannel, kMidiControlAllNotesOff, 0);
midiOutputController_->sendControlChange(outputPortNumber_, oldNoteChannel, kMidiControlAllSoundOff, 0);
}
else {
// Send a Note Off message to the appropriate channel
midiOutputController_->sendNoteOff(outputPortNumber_, oldNoteChannel, note + outputTransposition_);
}
}
// If the pedal is enabled and currently active, don't re-enable this channel
// just yet. Instead, let the note continue ringing until we have to steal it later.
if(damperPedalEnabled_ && controllerValues_[kMidiControllerDamperPedal] >= kPedalActiveValue && !forceOff) {
retransmitNotesHeldInPedal_.insert(note);
}
else {
// Otherwise release the channel mapping associated with this note
if(retransmitNotesHeldInPedal_.count(note) > 0)
retransmitNotesHeldInPedal_.erase(note);
retransmitChannelsAvailable_.insert(retransmitChannelForNote_[note]);
retransmitChannelForNote_.erase(note);
if(note >= 0 && note < 128)
noteOnsetTimestamps_[note] = 0;
}
if(forceOff) {
// Now re-enable any pedals that we might have temporarily lifted on this channel
if(controllerValues_[kMidiControllerDamperPedal] >= kPedalActiveValue) {
midiOutputController_->sendControlChange(outputPortNumber_, oldNoteChannel,
kMidiControllerDamperPedal,
controllerValues_[kMidiControllerDamperPedal]);
}
if(controllerValues_[kMidiControllerSostenutoPedal] >= kPedalActiveValue) {
midiOutputController_->sendControlChange(outputPortNumber_, oldNoteChannel,
kMidiControllerSostenutoPedal,
controllerValues_[kMidiControllerSostenutoPedal]);
}
}
}
// Callback function after we request a note on. PianoKey class will respond
// with touch data (if available within a specified timeout), or with a frame
// indicating an absence of touch data. Once we receive this, we can send the
// MIDI note on message.
void MidiKeyboardSegment::modePolyphonicMPENoteOnCallback(const char *path, const char *types, int numValues, lo_arg **values) {
if(numValues < 3) // Sanity check: first 3 values hold MIDI information
return;
if(types[0] != 'i' || types[1] != 'i' || types[2] != 'i')
return;
int midiNote = values[0]->i;
int midiChannel = values[1]->i;
int midiVelocity = values[2]->i;
if(midiNote < 0 || midiNote > 127)
return;
// If there are multiple segments of the keyboard active, there may be OSC
// messages generated from keys that didn't come from us. Don't grab them by mistake.
// FIXME: the real fix here is to include a source ID with the OSC message
if(!respondsToNote(midiNote)) {
return;
}
// Send the Note On message to the correct channel
if(midiOutputController_ != 0) {
midiOutputController_->sendNoteOn(outputPortNumber_, midiChannel, midiNote + outputTransposition_, midiVelocity);
}
}
// MPE (Multidimensional Polyphonic Expression): Each incoming note gets its own unique MIDI channel.
// Like polyphonic mode but implementing the details of the MPE specification which differ subtly
// from a straightforward polyphonic allocation
void MidiKeyboardSegment::modeMPEHandler(MidiInput* source, const MidiMessage& message) {
// MPE-TODO
}
// Handle note on message in MPE mode. Allocate a new channel
// for this note and rebroadcast it.
void MidiKeyboardSegment::modeMPENoteOn(unsigned char note, unsigned char velocity) {
// MPE-TODO
// allocate notes to channels like polyphonic mode, with certain changes:
// -- round-robin as default rather than first available
// -- different stealing behaviour:
// ---- when no channels are available, add to an existing one with the fewest sounding notes
// ---- old note doesn't need to be turned off, but it could(?) have its mappings disabled
}
// Private helper method to handle changes in polyphony
void MidiKeyboardSegment::modePolyphonicSetupHelper() {
// Limit polyphony to 16 (number of MIDI channels) or fewer if starting above channel 1
if(retransmitMaxPolyphony_ + outputChannelLowest_ > 16)
retransmitMaxPolyphony_ = 16 - outputChannelLowest_;
retransmitChannelsAvailable_.clear();
for(int i = outputChannelLowest_; i < outputChannelLowest_ + retransmitMaxPolyphony_; i++)
retransmitChannelsAvailable_.insert(i);
retransmitChannelForNote_.clear();
retransmitNotesHeldInPedal_.clear();
}
// Find the oldest onset of the currently playing notes. Used for voice stealing.
// Returns -1 if no notes are playing.
int MidiKeyboardSegment::oldestNote() {
int oldestNoteNumber = -1;
timestamp_type oldestTimestamp = missing_value<timestamp_type>::missing();
for(int i = 0; i < 128; i++) {
if(missing_value<timestamp_type>::isMissing(oldestTimestamp) && noteOnsetTimestamps_[i] != 0) {
oldestNoteNumber = i;
oldestTimestamp = noteOnsetTimestamps_[i];
}
else if(noteOnsetTimestamps_[i] < oldestTimestamp && noteOnsetTimestamps_[i] != 0) {
oldestNoteNumber = i;
oldestTimestamp = noteOnsetTimestamps_[i];
}
}
return oldestNoteNumber;
}
// Finds the oldest onset of the notes currently finished but sustaining in the pedal.
// Used for voice stealing. Returns -1 if no notes are held in the pedal.
int MidiKeyboardSegment::oldestNoteInPedal() {
if(!damperPedalEnabled_ || retransmitNotesHeldInPedal_.empty())
return -1;
set<int>::iterator it;
int oldestNoteNumber = -1;
timestamp_type oldestTimestamp = missing_value<timestamp_type>::missing();
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "notes in pedal: ";
#endif
for(it = retransmitNotesHeldInPedal_.begin(); it != retransmitNotesHeldInPedal_.end(); ++it) {
int note = *it;
timestamp_type timestamp;
if(noteOnsetTimestamps_[note] != 0)
timestamp = noteOnsetTimestamps_[note];
else
timestamp = 0; // Why is there a note held in pedal with no onset? Steal it!
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << note << " (" << timestamp << ") ";
#endif
if(missing_value<timestamp_type>::isMissing(oldestTimestamp)) {
oldestNoteNumber = note;
oldestTimestamp = timestamp;
}
else if(timestamp < oldestTimestamp) {
oldestNoteNumber = note;
oldestTimestamp = timestamp;
}
}
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << endl;
#endif
return oldestNoteNumber;
}
// Find the newest onset of the currently playing notes. Used for monophonic mode.
// Returns -1 if no notes are playing.
int MidiKeyboardSegment::newestNote() {
int newestNoteNumber = -1;
timestamp_type newestTimestamp = missing_value<timestamp_type>::missing();
for(int i = 0; i < 128; i++) {
if(missing_value<timestamp_type>::isMissing(newestTimestamp) && noteOnsetTimestamps_[i] != 0) {
newestNoteNumber = i;
newestTimestamp = noteOnsetTimestamps_[i];
}
else if(noteOnsetTimestamps_[i] > newestTimestamp && noteOnsetTimestamps_[i] != 0) {
newestNoteNumber = i;
newestTimestamp = noteOnsetTimestamps_[i];
}
}
return newestNoteNumber;
}
// Given a controller number (including special "controllers" channel-pressure and pitch-wheel),
// retransit or not to outgoing MIDI channels depending on the current behaviour defined in
// controllerActions_.
void MidiKeyboardSegment::handleControlChangeRetransit(int controllerNumber, const MidiMessage& message) {
// MPE-TODO need a new mode for sending on master zone, e.g. for pitch wheel
if(midiOutputController_ == 0)
return;
if(controllerActions_[controllerNumber] == kControlActionPassthrough) {
// Tell OSC-MIDI converter to resend if present, otherwise pass through
if(oscMidiConverters_.count(controllerNumber) != 0) {
oscMidiConverters_[controllerNumber]->resend(message.getChannel() - 1);
}
else {
// Send this control change through unchanged
midiOutputController_->sendMessage(outputPortNumber_, message);
}
}
else if(controllerActions_[controllerNumber] == kControlActionBroadcast) {
// Send this control change to all active channels
MidiMessage newMessage(message); // Modifiable copy of the original message
if(oscMidiConverters_.count(controllerNumber) != 0) {
for(int i = 0; i < retransmitMaxPolyphony_; i++)
oscMidiConverters_[controllerNumber]->resend(i);
}
else {
for(int i = 0; i < retransmitMaxPolyphony_; i++) {
newMessage.setChannel(i + 1); // Juce uses 1-16, we use 0-15
midiOutputController_->sendMessage(outputPortNumber_, newMessage);
}
}
}
else if(controllerActions_[controllerNumber] == kControlActionSendToLatest) {
// Send this control change to the channel of the most recent note
int noteNumber = newestNote();
if(noteNumber < 0)
return;
if(keyboard_.key(noteNumber) != 0) {
int channel = keyboard_.key(noteNumber)->midiChannel();
if(oscMidiConverters_.count(controllerNumber) != 0)
oscMidiConverters_[controllerNumber]->resend(channel);
else {
MidiMessage newMessage(message); // Modifiable copy of the original message
newMessage.setChannel(channel + 1); // Juce uses 1-16, we use 0-15
midiOutputController_->sendMessage(outputPortNumber_, newMessage);
}
}
}
else {} // Block or unknown action
}
// Set all controllers to behave a particular way when messages received
void MidiKeyboardSegment::setAllControllerActionsTo(int action) {
for(int i = 0; i < kControlMax; i++)
controllerActions_[i] = action;
}
// Pedal went off. If we're saving notes in the pedal, release them
void MidiKeyboardSegment::damperPedalWentOff() {
if(!damperPedalEnabled_)
return;
// Go through a list of any notes currently in the damper pedal and release them
set<int>::iterator it;
for(it = retransmitNotesHeldInPedal_.begin(); it != retransmitNotesHeldInPedal_.end(); ++it) {
int note = *it;
#ifdef DEBUG_MIDI_KEYBOARD_SEGMENT
cout << "releasing note " << note << " on channel " << retransmitChannelForNote_[note] << endl;
#endif
retransmitChannelsAvailable_.insert(retransmitChannelForNote_[note]);
retransmitChannelForNote_.erase(note);
noteOnsetTimestamps_[note] = 0;
}
retransmitNotesHeldInPedal_.clear();
}
// Handle the actual sending of the pitch wheel range RPN to a specific channel
void MidiKeyboardSegment::sendMidiPitchWheelRangeHelper(int channel) {
if(midiOutputController_ == 0)
return;
// Find number of semitones and cents
int majorRange = (int)floorf(pitchWheelRange_);
int minorRange = (int)(100.0 * (pitchWheelRange_ - floorf(pitchWheelRange_)));
// Set RPN controller = 0
midiOutputController_->sendControlChange(outputPortNumber_, channel, 101, 0);
midiOutputController_->sendControlChange(outputPortNumber_, channel, 100, 0);
// Set data value MSB/LSB for bend range in semitones
midiOutputController_->sendControlChange(outputPortNumber_, channel, 6, majorRange);
midiOutputController_->sendControlChange(outputPortNumber_, channel, 38, minorRange);
// Set RPN controller back to 16383
midiOutputController_->sendControlChange(outputPortNumber_, channel, 101, 127);
midiOutputController_->sendControlChange(outputPortNumber_, channel, 100, 127);
}
|
#include <Windows.h>
#define button1 1
int CALLBACK wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR szCmdLine, int nCmdShow)
{
MSG msg{};
HWND hwnd{};
WNDCLASSEX wc{ sizeof(WNDCLASSEX) };
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.hInstance = hInstance;
wc.lpfnWndProc = [](HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)->LRESULT
{
switch (uMsg)
{
case WM_CREATE:
{
CreateWindow(TEXT("STATIC"), TEXT("Привет!!! Здесь оформление как в WIN98 наверное :D"), // Label tipo
WS_VISIBLE | WS_CHILD,
80, 100, 250, 50,
hwnd, (HMENU)3, NULL, NULL);
CreateWindow(TEXT("button"), TEXT("Обычная кнопка"),
WS_VISIBLE | WS_CHILD,
100, 250, 200, 30,
hwnd, (HMENU)button1, NULL, NULL);
CreateWindow(TEXT("edit"), TEXT("Типо лайнэдит"),
WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL,
100, 400, 200, 30, hwnd, (HMENU)2, NULL, NULL);
}
return 0;
case WM_COMMAND:
{
if (LOWORD(wParam) == button1) {
MessageBox(0, L"Кнопка сработала", L"Сообщение", MB_OK | MB_ICONINFORMATION);
}
}
return 0;
case WM_DESTROY:
{
PostQuitMessage(EXIT_FAILURE);
}
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
};
wc.lpszClassName = L"MyAppClass";
wc.lpszMenuName = nullptr;
wc.style = CS_VREDRAW | CS_HREDRAW;
if (!RegisterClassEx(&wc))
return EXIT_FAILURE;
if (hwnd = CreateWindow(
wc.lpszClassName,
L"Лабораторная работа №1 Дочерный процесс \"Привет\"", WS_OVERLAPPEDWINDOW,
600, 200, 400, 600, nullptr, nullptr, hInstance, nullptr);
hwnd == INVALID_HANDLE_VALUE)
return EXIT_FAILURE;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
|
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#include "scheduler.hh"
#include <iomanip>
#include <sstream>
#include <iostream>
#include <cmath>
#include <numeric>
#include <chrono>
#include "thunk/ggutils.hh"
#include "thunk/thunk_reader.hh"
#include "net/s3.hh"
#include "tui/status_bar.hh"
#include "util/optional.hh"
#include "util/iterator.hh"
#include "util/exception.hh"
#include "util/timeit.hh"
#include "util/path.hh"
#include "util/digest.hh"
using namespace std;
using namespace gg;
using namespace gg::thunk;
using namespace std::chrono;
using ReductionResult = gg::cache::ReductionResult;
size_t Scheduler::remaining_jobs() const
{
size_t jobs = 0;
for (auto & tracker : pending_dags_)
{
jobs += tracker->dep_graph_.size();
}
return jobs;
}
void Scheduler::print_status() const
{
if (not status_bar_)
return;
static time_point<steady_clock> last_display = steady_clock::now();
const auto this_display = steady_clock::now();
if ( duration_cast<milliseconds>( this_display - last_display ).count() > 33 ) {
last_display = this_display;
stringstream data;
data << "dags: " << setw( 5 ) << left << pending_dags_.size();
data << "in queue: " << setw( 5 ) << left << job_queue_.size();
for ( auto & ee : exec_engines_ ) {
data << " " << ee->label() << " (" << ee->max_jobs() << "): "
<< setw( 5 ) << left << ee->job_count();
}
data << " done: " << setw( 5 ) << left
<< finished_jobs_
<< " remaining: " << remaining_jobs();
data << " | cost: " << "~$" << setw( 8 ) << fixed
<< setprecision( 2 ) << estimated_cost_;
/* Print to STDOUT */
cout << data.str() << endl;
}
}
static void print_gg_message( const string & tag, const string & message )
{
cerr << "[" << tag << "] " << message << endl;
}
Scheduler::Scheduler( ExecutionLoop & loop,
std::vector<std::unique_ptr<ExecutionEngine>> && execution_engines,
std::vector<std::unique_ptr<ExecutionEngine>> && fallback_engines,
std::unique_ptr<StorageBackend> && storage_backend,
const std::chrono::milliseconds default_timeout,
const size_t timeout_multiplier,
const bool status_bar,
const size_t queue_lookahead,
const PlacementHeuristic heuristic)
: exec_loop_( loop ),
status_bar_( status_bar ),
lookahead_( queue_lookahead ),
heuristic_( heuristic ),
default_timeout_( default_timeout ),
timeout_multiplier_( timeout_multiplier ),
exec_engines_( move( execution_engines ) ),
fallback_engines_( move( fallback_engines ) ),
storage_backend_( move( storage_backend ) )
{
auto success_callback =
[this] ( const string & old_hash, vector<ThunkOutput> && outputs, const float cost )
{ finalize_execution( old_hash, move( outputs ), cost ); };
auto failure_callback =
[this] ( const string & old_hash, const JobStatus failure_reason )
{
switch ( failure_reason ) {
/* this is the only fatal failure */
case JobStatus::ExecutionFailure:
throw runtime_error( "execution failed: " + old_hash );
/* for all of the following cases, except default, we will push the failed
job back into the queue */
case JobStatus::InvocationFailure:
print_gg_message( "warning", "invocation failed: " + old_hash );
break;
case JobStatus::RateLimit:
print_gg_message( "warning", "rate limited: " + old_hash );
break;
case JobStatus::FetchDependenciesFailure:
print_gg_message( "warning", "fetching the dependencies failed: " + old_hash );
break;
case JobStatus::UploadOutputFailure:
print_gg_message( "warning", "uploading the output failed: " + old_hash );
break;
case JobStatus::OperationalFailure:
print_gg_message( "warning", "operational failure: " + old_hash );
break;
case JobStatus::SocketFailure:
print_gg_message( "warning", "socket failure: " + old_hash );
break;
case JobStatus::ChildProcessFailure:
print_gg_message( "warning", "child process failure: " + old_hash );
break;
default:
throw runtime_error( "execution failed for an unknown reason: " + old_hash );
}
/* let's retry */
auto it = running_jobs_.find(old_hash);
if (it == running_jobs_.end())
throw runtime_error( "inconsistent state" );
std::shared_ptr<Tracker> tracker = it->second.tracker_;
tracker->job_queue_.push_front(old_hash);
};
if ( exec_engines_.size() == 0 ) {
throw runtime_error( "no execution engines are available" );
}
for ( auto & ee : exec_engines_ ) {
ee->set_success_callback( success_callback );
ee->set_failure_callback( failure_callback );
ee->init( exec_loop_ );
}
for ( auto & fe : fallback_engines_ ) {
fe->set_success_callback( success_callback );
fe->set_failure_callback( failure_callback );
fe->init( exec_loop_ );
}
}
void Scheduler::finalize_execution( const string & old_hash,
vector<ThunkOutput> && outputs,
const float cost )
{
auto it = running_jobs_.find( old_hash );
if (it == running_jobs_.end())
throw runtime_error( "inconsistent state" );
std::shared_ptr<Tracker> tracker = it->second.tracker_;
tracker->finalize_execution(old_hash, move(outputs), cost);
running_jobs_.erase(old_hash);
}
void Scheduler::add_dag( const std::vector<std::string> & target_hashes )
{
for (auto & hash : target_hashes)
{
shared_ptr<Tracker> dag = make_shared<Tracker>(hash);
pending_dags_.push_back(dag);
}
}
void Scheduler::add_dag( shared_ptr<Tracker> tracker )
{
pending_dags_.push_back(tracker);
}
vector<shared_ptr<Tracker>> Scheduler::run_once()
{
const auto poll_result = exec_loop_.loop_once( timeout_check_interval_ == 0s
? -1
: timeout_check_interval_.count() );
/* Process updated DAGs */
vector<shared_ptr<Tracker>> finished_dags;
for (auto it = pending_dags_.begin(); it != pending_dags_.end();)
{
shared_ptr<Tracker> dag = *it;
if (dag->is_finished()) {
finished_dags.push_back(dag);
it = pending_dags_.erase(it);
} else {
while (true) {
string hash = dag->next();
if (hash.empty())
break;
job_queue_.emplace_back(hash, dag);
}
it++;
}
}
/* Issue retries */
const auto clock_now = Clock::now();
if ( timeout_check_interval_ != 0s and clock_now >= next_timeout_check_ ) {
size_t count = 0;
for ( auto & job : running_jobs_ ) {
if ( job.second.timeout != 0ms and
( clock_now - job.second.start ) > job.second.timeout ) {
job_queue_.emplace_back( job.first, job.second.tracker_ );
job.second.start = clock_now;
job.second.timeout += job.second.restarts * job.second.timeout;
job.second.restarts++;
count ++;
}
}
next_timeout_check_ += timeout_check_interval_;
if ( count > 0 ) {
print_gg_message( "info", "duplicating " + to_string( count ) +
" job" + ( ( count == 1 ) ? "" : "s" ) );
}
}
if ( status_interval_ != 0s and clock_now >= next_status_print_ ) {
print_status();
next_status_print_ += status_interval_;
}
if (poll_result.result == Poller::Result::Type::Exit) {
throw runtime_error( "unhandled poller failure happened, job is not finished" );
}
if (job_queue_.empty())
return finished_dags;
/* Issue new jobs */
while (true) {
auto result = pick_job();
if (!result.initialized()) {
return finished_dags;
}
auto schedule_info = result.get();
string thunk_hash = schedule_info.first->first;
std::shared_ptr<Tracker> dag = schedule_info.first->second;
job_queue_.erase(schedule_info.first);
/* don't bother executing gg-execute if it's in the cache */
Optional<ReductionResult> cache_entry;
while ( true ) {
auto temp_cache_entry = gg::cache::check( cache_entry.initialized() ? cache_entry->hash
: thunk_hash );
if ( temp_cache_entry.initialized() ) {
cache_entry = move( temp_cache_entry );
}
else {
break;
}
}
if (cache_entry.initialized()) {
Thunk thunk { ThunkReader::read( gg::paths::blob( thunk_hash ), thunk_hash ) };
vector<ThunkOutput> new_outputs;
for ( const auto & tag : thunk.outputs() ) {
Optional<cache::ReductionResult> result = cache::check( gg::hash::for_output( thunk_hash, tag ) );
if ( not result.initialized() ) {
throw runtime_error( "inconsistent cache entries" );
}
new_outputs.emplace_back( result->hash, tag );
}
finalize_execution( thunk_hash, move( new_outputs ), 0 );
}
else {
const Thunk & thunk = dag->dep_graph_.get_thunk( thunk_hash );
std::unique_ptr<ExecutionEngine> &engine = schedule_info.second;
engine->force_thunk( thunk, exec_loop_ );
auto it = running_jobs_.find( thunk_hash );
if (it == running_jobs_.end()) {
JobInfo job_info(dag);
job_info.start = Clock::now();
job_info.timeout = thunk.timeout() * timeout_multiplier_;
job_info.restarts++;
if ( job_info.timeout == 0s ) {
job_info.timeout = default_timeout_;
}
running_jobs_.insert( make_pair(thunk_hash, move(job_info) ) );
} else {
JobInfo & job_info = it->second;
job_info.start = Clock::now();
job_info.timeout = thunk.timeout() * timeout_multiplier_;
job_info.restarts++;
if ( job_info.timeout == 0s ) {
job_info.timeout = default_timeout_;
}
}
}
}
return finished_dags;
}
typedef std::list<std::pair<std::string, std::shared_ptr<Tracker>>>::iterator job_iterator;
Optional<pair<job_iterator, std::unique_ptr<ExecutionEngine>&>> Scheduler::pick_job()
{
Optional<pair<job_iterator, std::unique_ptr<ExecutionEngine>&>> result;
int max_value = -1;
int try_fallback = 1;
size_t ahead = 0;
switch (heuristic_)
{
case PlacementHeuristic::First:
for (auto thunk_it = job_queue_.begin(); thunk_it != job_queue_.end(); thunk_it++)
{
std::shared_ptr<Tracker> dag = thunk_it->second;
const Thunk& thunk = dag->dep_graph_.get_thunk(thunk_it->first);
for (auto & exec_engine : exec_engines_)
{
if (exec_engine->is_remote() && thunk.is_localonly())
continue;
if (exec_engine->can_execute(thunk)) {
try_fallback = 0;
if (exec_engine->job_count() >= exec_engine->max_jobs())
continue;
result.initialize(thunk_it, exec_engine);
return result;
}
}
}
break;
case PlacementHeuristic::Random:
throw runtime_error("not yet implemented");
break;
case PlacementHeuristic::MostObjects:
for (auto thunk_it = job_queue_.begin(); thunk_it != job_queue_.end(); thunk_it++)
{
if (ahead >= lookahead_)
break;
std::shared_ptr<Tracker> dag = thunk_it->second;
const Thunk& thunk = dag->dep_graph_.get_thunk(thunk_it->first);
for (auto & exec_engine : exec_engines_)
{
if (exec_engine->is_remote() && thunk.is_localonly())
continue;
if (!exec_engine->can_execute(thunk))
continue;
try_fallback = 0;
if (exec_engine->job_count() >= exec_engine->max_jobs())
continue;
int metric = 0;
for (const auto & item : join_containers( thunk.values(), thunk.executables())) {
if (exec_engine->in_cache(item.first)) {
metric++;
}
}
if (metric > max_value or !result.initialized()) {
max_value = metric;
Optional<pair<job_iterator, std::unique_ptr<ExecutionEngine>&>> new_result;
new_result.initialize(thunk_it, exec_engine);
result = move(new_result);
}
}
ahead++;
}
break;
case PlacementHeuristic::MostObjectsSize:
for (auto thunk_it = job_queue_.begin(); thunk_it != job_queue_.end(); thunk_it++)
{
if (ahead >= lookahead_)
break;
std::shared_ptr<Tracker> dag = thunk_it->second;
const Thunk& thunk = dag->dep_graph_.get_thunk(thunk_it->first);
for (auto & exec_engine : exec_engines_)
{
if (exec_engine->is_remote() && thunk.is_localonly())
continue;
if (!exec_engine->can_execute(thunk))
continue;
try_fallback = 0;
if (exec_engine->job_count() >= exec_engine->max_jobs())
continue;
int metric = 0;
for (const auto & item : join_containers( thunk.values(), thunk.executables())) {
if (exec_engine->in_cache(item.first)) {
metric += gg::hash::size(item.first);
}
}
if (metric > max_value or !result.initialized()) {
max_value = metric;
Optional<pair<job_iterator, std::unique_ptr<ExecutionEngine>&>> new_result;
new_result.initialize(thunk_it, exec_engine);
result = move(new_result);
}
}
ahead++;
}
break;
case PlacementHeuristic::LargestObject:
for (auto thunk_it = job_queue_.begin(); thunk_it != job_queue_.end(); thunk_it++)
{
if (ahead >= lookahead_)
break;
std::shared_ptr<Tracker> dag = thunk_it->second;
const Thunk& thunk = dag->dep_graph_.get_thunk(thunk_it->first);
for (auto & exec_engine : exec_engines_)
{
if (exec_engine->is_remote() && thunk.is_localonly())
continue;
if (!exec_engine->can_execute(thunk))
continue;
try_fallback = 0;
if (exec_engine->job_count() >= exec_engine->max_jobs())
continue;
int metric = 0;
for (const auto & item : join_containers( thunk.values(), thunk.executables())) {
if (exec_engine->in_cache(item.first)) {
metric = max(metric, (int) gg::hash::size(item.first));
}
}
if (metric > max_value or !result.initialized()) {
max_value = metric;
Optional<pair<job_iterator, std::unique_ptr<ExecutionEngine>&>> new_result;
new_result.initialize(thunk_it, exec_engine);
result = move(new_result);
}
}
ahead++;
}
break;
case PlacementHeuristic::LRU:
throw runtime_error("not yet implemented");
break;
default:
throw runtime_error("invalid placement heuristic");
}
/* try fallback engines! */
if (!result.initialized() && try_fallback) {
/* Try fallback engines! */
for (auto thunk_it = job_queue_.begin(); thunk_it != job_queue_.end(); thunk_it++)
{
std::shared_ptr<Tracker> dag = thunk_it->second;
const Thunk& thunk = dag->dep_graph_.get_thunk(thunk_it->first);
for (auto & exec_engine : fallback_engines_)
{
if (exec_engine->is_remote() && thunk.is_localonly())
continue;
if (exec_engine->can_execute(thunk)) {
if (exec_engine->job_count() >= exec_engine->max_jobs())
continue;
result.initialize(thunk_it, exec_engine);
return result;
}
}
}
}
return result;
}
|
#ifndef __VIVADO_SYNTH__
#include <fstream>
using namespace std;
// Debug utility
ofstream* global_debug_handle;
#endif //__VIVADO_SYNTH__
#include "gp_4_opt_compute_units.h"
#include "hw_classes.h"
struct in_in_update_0_write0_merged_banks_6_cache {
// RAM Box: {[0, 80], [0, 78]}
// Capacity: 44
// # of read delays: 6
hw_uint<16> f0;
hw_uint<16> f2;
fifo<hw_uint<16>, 19> f3;
hw_uint<16> f4;
hw_uint<16> f6;
fifo<hw_uint<16>, 19> f7;
hw_uint<16> f8;
hw_uint<16> f10;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_20() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_21() {
return f4;
}
inline hw_uint<16> peek_22() {
return f6;
}
inline hw_uint<16> peek_41() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f7.back();
}
inline hw_uint<16> peek_42() {
return f8;
}
inline hw_uint<16> peek_43() {
return f10;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f10 = f8;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 19
f8 = f7.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 19 reading from capacity: 1
f7.push(f6);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f6 = f4;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 19
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 19 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct in_in_update_0_write1_merged_banks_3_cache {
// RAM Box: {[1, 81], [0, 78]}
// Capacity: 44
// # of read delays: 4
hw_uint<16> f0;
hw_uint<16> f2;
fifo<hw_uint<16>, 20> f3;
hw_uint<16> f4;
fifo<hw_uint<16>, 20> f5;
hw_uint<16> f6;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_21() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_22() {
return f4;
}
inline hw_uint<16> peek_42() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f5.back();
}
inline hw_uint<16> peek_43() {
return f6;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 20
f6 = f5.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 20 reading from capacity: 1
f5.push(f4);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 20
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 20 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct in_in_update_0_write2_merged_banks_6_cache {
// RAM Box: {[2, 82], [0, 78]}
// Capacity: 44
// # of read delays: 4
hw_uint<16> f0;
hw_uint<16> f2;
fifo<hw_uint<16>, 20> f3;
hw_uint<16> f4;
fifo<hw_uint<16>, 20> f5;
hw_uint<16> f6;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_21() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_22() {
return f4;
}
inline hw_uint<16> peek_42() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f5.back();
}
inline hw_uint<16> peek_43() {
return f6;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 20
f6 = f5.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 20 reading from capacity: 1
f5.push(f4);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 20
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 20 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct in_in_update_0_write3_merged_banks_3_cache {
// RAM Box: {[3, 83], [0, 78]}
// Capacity: 44
// # of read delays: 4
hw_uint<16> f0;
hw_uint<16> f2;
fifo<hw_uint<16>, 20> f3;
hw_uint<16> f4;
fifo<hw_uint<16>, 20> f5;
hw_uint<16> f6;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_21() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_22() {
return f4;
}
inline hw_uint<16> peek_42() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f5.back();
}
inline hw_uint<16> peek_43() {
return f6;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 20
f6 = f5.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 20 reading from capacity: 1
f5.push(f4);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 20
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 20 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct in_cache {
in_in_update_0_write0_merged_banks_6_cache in_in_update_0_write0_merged_banks_6;
in_in_update_0_write1_merged_banks_3_cache in_in_update_0_write1_merged_banks_3;
in_in_update_0_write2_merged_banks_6_cache in_in_update_0_write2_merged_banks_6;
in_in_update_0_write3_merged_banks_3_cache in_in_update_0_write3_merged_banks_3;
};
inline void in_in_update_0_write0_write(hw_uint<16>& in_in_update_0_write0, in_cache& in, int d0, int d1) {
in.in_in_update_0_write0_merged_banks_6.push(in_in_update_0_write0);
}
inline void in_in_update_0_write1_write(hw_uint<16>& in_in_update_0_write1, in_cache& in, int d0, int d1) {
in.in_in_update_0_write1_merged_banks_3.push(in_in_update_0_write1);
}
inline void in_in_update_0_write2_write(hw_uint<16>& in_in_update_0_write2, in_cache& in, int d0, int d1) {
in.in_in_update_0_write2_merged_banks_6.push(in_in_update_0_write2);
}
inline void in_in_update_0_write3_write(hw_uint<16>& in_in_update_0_write3, in_cache& in, int d0, int d1) {
in.in_in_update_0_write3_merged_banks_3.push(in_in_update_0_write3);
}
inline hw_uint<16> level_0_rd0_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd0 read pattern: { level_0_update_0[d0, d1] -> in[4d0, 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 43 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_6.peek_43();
return value_in_in_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd1_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd1 read pattern: { level_0_update_0[d0, d1] -> in[4d0, 1 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 22 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_6.peek_22();
return value_in_in_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd10_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd10 read pattern: { level_0_update_0[d0, d1] -> in[2 + 4d0, 1 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 22 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write2 = in.in_in_update_0_write2_merged_banks_6.peek_22();
return value_in_in_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd11_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd11 read pattern: { level_0_update_0[d0, d1] -> in[2 + 4d0, 2 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 1 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write2 = in.in_in_update_0_write2_merged_banks_6.peek_1();
return value_in_in_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd12_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd12 read pattern: { level_0_update_0[d0, d1] -> in[3 + 4d0, 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 43 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write3 = in.in_in_update_0_write3_merged_banks_3.peek_43();
return value_in_in_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd13_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd13 read pattern: { level_0_update_0[d0, d1] -> in[3 + 4d0, 1 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 22 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write3 = in.in_in_update_0_write3_merged_banks_3.peek_22();
return value_in_in_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd14_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd14 read pattern: { level_0_update_0[d0, d1] -> in[3 + 4d0, 2 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 1 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write3 = in.in_in_update_0_write3_merged_banks_3.peek_1();
return value_in_in_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd15_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd15 read pattern: { level_0_update_0[d0, d1] -> in[4 + 4d0, 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 42 : 0 <= d0 <= 18 and 0 <= d1 <= 38; level_0_update_0[d0, d1] -> (23 + d0) : d0 = 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_6.peek_42();
return value_in_in_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd16_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd16 read pattern: { level_0_update_0[d0, d1] -> in[4 + 4d0, 1 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 21 : 0 <= d0 <= 18 and 0 <= d1 <= 38; level_0_update_0[d0, d1] -> (2 + d0) : d0 = 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_6.peek_21();
return value_in_in_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd17_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd17 read pattern: { level_0_update_0[d0, d1] -> in[4 + 4d0, 2 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { }
auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_6.peek_0();
return value_in_in_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd2_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd2 read pattern: { level_0_update_0[d0, d1] -> in[4d0, 2 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 1 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_6.peek_1();
return value_in_in_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd3_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd3 read pattern: { level_0_update_0[d0, d1] -> in[1 + 4d0, 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 43 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write1 = in.in_in_update_0_write1_merged_banks_3.peek_43();
return value_in_in_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd4_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd4 read pattern: { level_0_update_0[d0, d1] -> in[1 + 4d0, 1 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 22 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write1 = in.in_in_update_0_write1_merged_banks_3.peek_22();
return value_in_in_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd5_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd5 read pattern: { level_0_update_0[d0, d1] -> in[1 + 4d0, 2 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 1 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write1 = in.in_in_update_0_write1_merged_banks_3.peek_1();
return value_in_in_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd6_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd6 read pattern: { level_0_update_0[d0, d1] -> in[2 + 4d0, 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 43 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write2 = in.in_in_update_0_write2_merged_banks_6.peek_43();
return value_in_in_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd7_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd7 read pattern: { level_0_update_0[d0, d1] -> in[2 + 4d0, 1 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 22 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write2 = in.in_in_update_0_write2_merged_banks_6.peek_22();
return value_in_in_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd8_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd8 read pattern: { level_0_update_0[d0, d1] -> in[2 + 4d0, 2 + 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 1 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write2 = in.in_in_update_0_write2_merged_banks_6.peek_1();
return value_in_in_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_0_rd9_select(in_cache& in, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_0_rd9 read pattern: { level_0_update_0[d0, d1] -> in[2 + 4d0, 2d1] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Read schedule : { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// Write schedule: { in_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 20 and 0 <= d1 <= 78 }
// DD fold: { level_0_update_0[d0, d1] -> 43 : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
auto value_in_in_update_0_write2 = in.in_in_update_0_write2_merged_banks_6.peek_43();
return value_in_in_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// in_update_0_write
// in_in_update_0_write0
// in_in_update_0_write1
// in_in_update_0_write2
// in_in_update_0_write3
inline void in_in_update_0_write_bundle_write(hw_uint<64>& in_update_0_write, in_cache& in, int d0, int d1) {
hw_uint<16> in_in_update_0_write0_res = in_update_0_write.extract<0, 15>();
in_in_update_0_write0_write(in_in_update_0_write0_res, in, d0, d1);
hw_uint<16> in_in_update_0_write1_res = in_update_0_write.extract<16, 31>();
in_in_update_0_write1_write(in_in_update_0_write1_res, in, d0, d1);
hw_uint<16> in_in_update_0_write2_res = in_update_0_write.extract<32, 47>();
in_in_update_0_write2_write(in_in_update_0_write2_res, in, d0, d1);
hw_uint<16> in_in_update_0_write3_res = in_update_0_write.extract<48, 63>();
in_in_update_0_write3_write(in_in_update_0_write3_res, in, d0, d1);
}
// level_0_update_0_read
// level_0_rd0
// level_0_rd1
// level_0_rd2
// level_0_rd3
// level_0_rd4
// level_0_rd5
// level_0_rd6
// level_0_rd7
// level_0_rd8
// level_0_rd9
// level_0_rd10
// level_0_rd11
// level_0_rd12
// level_0_rd13
// level_0_rd14
// level_0_rd15
// level_0_rd16
// level_0_rd17
inline hw_uint<288> in_level_0_update_0_read_bundle_read(in_cache& in, int d0, int d1) {
// # of ports in bundle: 18
// level_0_rd0
// level_0_rd1
// level_0_rd2
// level_0_rd3
// level_0_rd4
// level_0_rd5
// level_0_rd6
// level_0_rd7
// level_0_rd8
// level_0_rd9
// level_0_rd10
// level_0_rd11
// level_0_rd12
// level_0_rd13
// level_0_rd14
// level_0_rd15
// level_0_rd16
// level_0_rd17
hw_uint<288> result;
hw_uint<16> level_0_rd0_res = level_0_rd0_select(in, d0, d1);
set_at<0, 288>(result, level_0_rd0_res);
hw_uint<16> level_0_rd1_res = level_0_rd1_select(in, d0, d1);
set_at<16, 288>(result, level_0_rd1_res);
hw_uint<16> level_0_rd2_res = level_0_rd2_select(in, d0, d1);
set_at<32, 288>(result, level_0_rd2_res);
hw_uint<16> level_0_rd3_res = level_0_rd3_select(in, d0, d1);
set_at<48, 288>(result, level_0_rd3_res);
hw_uint<16> level_0_rd4_res = level_0_rd4_select(in, d0, d1);
set_at<64, 288>(result, level_0_rd4_res);
hw_uint<16> level_0_rd5_res = level_0_rd5_select(in, d0, d1);
set_at<80, 288>(result, level_0_rd5_res);
hw_uint<16> level_0_rd6_res = level_0_rd6_select(in, d0, d1);
set_at<96, 288>(result, level_0_rd6_res);
hw_uint<16> level_0_rd7_res = level_0_rd7_select(in, d0, d1);
set_at<112, 288>(result, level_0_rd7_res);
hw_uint<16> level_0_rd8_res = level_0_rd8_select(in, d0, d1);
set_at<128, 288>(result, level_0_rd8_res);
hw_uint<16> level_0_rd9_res = level_0_rd9_select(in, d0, d1);
set_at<144, 288>(result, level_0_rd9_res);
hw_uint<16> level_0_rd10_res = level_0_rd10_select(in, d0, d1);
set_at<160, 288>(result, level_0_rd10_res);
hw_uint<16> level_0_rd11_res = level_0_rd11_select(in, d0, d1);
set_at<176, 288>(result, level_0_rd11_res);
hw_uint<16> level_0_rd12_res = level_0_rd12_select(in, d0, d1);
set_at<192, 288>(result, level_0_rd12_res);
hw_uint<16> level_0_rd13_res = level_0_rd13_select(in, d0, d1);
set_at<208, 288>(result, level_0_rd13_res);
hw_uint<16> level_0_rd14_res = level_0_rd14_select(in, d0, d1);
set_at<224, 288>(result, level_0_rd14_res);
hw_uint<16> level_0_rd15_res = level_0_rd15_select(in, d0, d1);
set_at<240, 288>(result, level_0_rd15_res);
hw_uint<16> level_0_rd16_res = level_0_rd16_select(in, d0, d1);
set_at<256, 288>(result, level_0_rd16_res);
hw_uint<16> level_0_rd17_res = level_0_rd17_select(in, d0, d1);
set_at<272, 288>(result, level_0_rd17_res);
return result;
}
#include "hw_classes.h"
struct level_0_level_0_update_0_write0_merged_banks_6_cache {
// RAM Box: {[0, 38], [0, 38]}
// Capacity: 42
// # of read delays: 6
hw_uint<16> f0;
hw_uint<16> f2;
fifo<hw_uint<16>, 18> f3;
hw_uint<16> f4;
hw_uint<16> f6;
fifo<hw_uint<16>, 18> f7;
hw_uint<16> f8;
hw_uint<16> f10;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_19() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_20() {
return f4;
}
inline hw_uint<16> peek_21() {
return f6;
}
inline hw_uint<16> peek_39() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f7.back();
}
inline hw_uint<16> peek_40() {
return f8;
}
inline hw_uint<16> peek_41() {
return f10;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f10 = f8;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 18
f8 = f7.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 18 reading from capacity: 1
f7.push(f6);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f6 = f4;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 18
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 18 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct level_0_level_0_update_0_write1_merged_banks_3_cache {
// RAM Box: {[1, 39], [0, 38]}
// Capacity: 42
// # of read delays: 4
hw_uint<16> f0;
hw_uint<16> f2;
fifo<hw_uint<16>, 19> f3;
hw_uint<16> f4;
fifo<hw_uint<16>, 19> f5;
hw_uint<16> f6;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_20() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_21() {
return f4;
}
inline hw_uint<16> peek_40() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f5.back();
}
inline hw_uint<16> peek_41() {
return f6;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 19
f6 = f5.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 19 reading from capacity: 1
f5.push(f4);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 19
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 19 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct level_0_cache {
level_0_level_0_update_0_write0_merged_banks_6_cache level_0_level_0_update_0_write0_merged_banks_6;
level_0_level_0_update_0_write1_merged_banks_3_cache level_0_level_0_update_0_write1_merged_banks_3;
};
inline void level_0_level_0_update_0_write0_write(hw_uint<16>& level_0_level_0_update_0_write0, level_0_cache& level_0, int d0, int d1) {
level_0.level_0_level_0_update_0_write0_merged_banks_6.push(level_0_level_0_update_0_write0);
}
inline void level_0_level_0_update_0_write1_write(hw_uint<16>& level_0_level_0_update_0_write1, level_0_cache& level_0, int d0, int d1) {
level_0.level_0_level_0_update_0_write1_merged_banks_3.push(level_0_level_0_update_0_write1);
}
inline hw_uint<16> level_1_rd0_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd0 read pattern: { level_1_update_0[d0, d1] -> level_0[2d0, 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 41 : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write0 = level_0.level_0_level_0_update_0_write0_merged_banks_6.peek_41();
return value_level_0_level_0_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd1_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd1 read pattern: { level_1_update_0[d0, d1] -> level_0[2d0, 1 + 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 21 : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write0 = level_0.level_0_level_0_update_0_write0_merged_banks_6.peek_21();
return value_level_0_level_0_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd2_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd2 read pattern: { level_1_update_0[d0, d1] -> level_0[2d0, 2 + 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 1 : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write0 = level_0.level_0_level_0_update_0_write0_merged_banks_6.peek_1();
return value_level_0_level_0_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd3_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd3 read pattern: { level_1_update_0[d0, d1] -> level_0[1 + 2d0, 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 41 : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write1 = level_0.level_0_level_0_update_0_write1_merged_banks_3.peek_41();
return value_level_0_level_0_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd4_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd4 read pattern: { level_1_update_0[d0, d1] -> level_0[1 + 2d0, 1 + 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 21 : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write1 = level_0.level_0_level_0_update_0_write1_merged_banks_3.peek_21();
return value_level_0_level_0_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd5_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd5 read pattern: { level_1_update_0[d0, d1] -> level_0[1 + 2d0, 2 + 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 1 : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write1 = level_0.level_0_level_0_update_0_write1_merged_banks_3.peek_1();
return value_level_0_level_0_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd6_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd6 read pattern: { level_1_update_0[d0, d1] -> level_0[2 + 2d0, 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 40 : 0 <= d0 <= 17 and 0 <= d1 <= 18; level_1_update_0[d0, d1] -> (22 + d0) : d0 = 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write0 = level_0.level_0_level_0_update_0_write0_merged_banks_6.peek_40();
return value_level_0_level_0_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd7_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd7 read pattern: { level_1_update_0[d0, d1] -> level_0[2 + 2d0, 1 + 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { level_1_update_0[d0, d1] -> 20 : 0 <= d0 <= 17 and 0 <= d1 <= 18; level_1_update_0[d0, d1] -> (2 + d0) : d0 = 18 and 0 <= d1 <= 18 }
auto value_level_0_level_0_update_0_write0 = level_0.level_0_level_0_update_0_write0_merged_banks_6.peek_20();
return value_level_0_level_0_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_1_rd8_select(level_0_cache& level_0, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_1_rd8 read pattern: { level_1_update_0[d0, d1] -> level_0[2 + 2d0, 2 + 2d1] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Read schedule : { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// Write schedule: { level_0_update_0[d0, d1] -> [2 + 2d1, 1 + d0, 2] : 0 <= d0 <= 19 and 0 <= d1 <= 38 }
// DD fold: { }
auto value_level_0_level_0_update_0_write0 = level_0.level_0_level_0_update_0_write0_merged_banks_6.peek_0();
return value_level_0_level_0_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// level_0_update_0_write
// level_0_level_0_update_0_write0
// level_0_level_0_update_0_write1
inline void level_0_level_0_update_0_write_bundle_write(hw_uint<32>& level_0_update_0_write, level_0_cache& level_0, int d0, int d1) {
hw_uint<16> level_0_level_0_update_0_write0_res = level_0_update_0_write.extract<0, 15>();
level_0_level_0_update_0_write0_write(level_0_level_0_update_0_write0_res, level_0, d0, d1);
hw_uint<16> level_0_level_0_update_0_write1_res = level_0_update_0_write.extract<16, 31>();
level_0_level_0_update_0_write1_write(level_0_level_0_update_0_write1_res, level_0, d0, d1);
}
// level_1_update_0_read
// level_1_rd0
// level_1_rd1
// level_1_rd2
// level_1_rd3
// level_1_rd4
// level_1_rd5
// level_1_rd6
// level_1_rd7
// level_1_rd8
inline hw_uint<144> level_0_level_1_update_0_read_bundle_read(level_0_cache& level_0, int d0, int d1) {
// # of ports in bundle: 9
// level_1_rd0
// level_1_rd1
// level_1_rd2
// level_1_rd3
// level_1_rd4
// level_1_rd5
// level_1_rd6
// level_1_rd7
// level_1_rd8
hw_uint<144> result;
hw_uint<16> level_1_rd0_res = level_1_rd0_select(level_0, d0, d1);
set_at<0, 144>(result, level_1_rd0_res);
hw_uint<16> level_1_rd1_res = level_1_rd1_select(level_0, d0, d1);
set_at<16, 144>(result, level_1_rd1_res);
hw_uint<16> level_1_rd2_res = level_1_rd2_select(level_0, d0, d1);
set_at<32, 144>(result, level_1_rd2_res);
hw_uint<16> level_1_rd3_res = level_1_rd3_select(level_0, d0, d1);
set_at<48, 144>(result, level_1_rd3_res);
hw_uint<16> level_1_rd4_res = level_1_rd4_select(level_0, d0, d1);
set_at<64, 144>(result, level_1_rd4_res);
hw_uint<16> level_1_rd5_res = level_1_rd5_select(level_0, d0, d1);
set_at<80, 144>(result, level_1_rd5_res);
hw_uint<16> level_1_rd6_res = level_1_rd6_select(level_0, d0, d1);
set_at<96, 144>(result, level_1_rd6_res);
hw_uint<16> level_1_rd7_res = level_1_rd7_select(level_0, d0, d1);
set_at<112, 144>(result, level_1_rd7_res);
hw_uint<16> level_1_rd8_res = level_1_rd8_select(level_0, d0, d1);
set_at<128, 144>(result, level_1_rd8_res);
return result;
}
#include "hw_classes.h"
struct level_1_level_1_update_0_write0_merged_banks_9_cache {
// RAM Box: {[0, 18], [0, 18]}
// Capacity: 41
// # of read delays: 9
hw_uint<16> f0;
hw_uint<16> f2;
hw_uint<16> f4;
fifo<hw_uint<16>, 16> f5;
hw_uint<16> f6;
hw_uint<16> f8;
hw_uint<16> f10;
fifo<hw_uint<16>, 16> f11;
hw_uint<16> f12;
hw_uint<16> f14;
hw_uint<16> f16;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_2() {
return f4;
}
inline hw_uint<16> peek_18() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f5.back();
}
inline hw_uint<16> peek_19() {
return f6;
}
inline hw_uint<16> peek_20() {
return f8;
}
inline hw_uint<16> peek_21() {
return f10;
}
inline hw_uint<16> peek_37() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f11.back();
}
inline hw_uint<16> peek_38() {
return f12;
}
inline hw_uint<16> peek_39() {
return f14;
}
inline hw_uint<16> peek_40() {
return f16;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f16 = f14;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f14 = f12;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 16
f12 = f11.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 16 reading from capacity: 1
f11.push(f10);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f10 = f8;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f8 = f6;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 16
f6 = f5.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 16 reading from capacity: 1
f5.push(f4);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f4 = f2;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct level_1_cache {
level_1_level_1_update_0_write0_merged_banks_9_cache level_1_level_1_update_0_write0_merged_banks_9;
};
inline void level_1_level_1_update_0_write0_write(hw_uint<16>& level_1_level_1_update_0_write0, level_1_cache& level_1, int d0, int d1) {
level_1.level_1_level_1_update_0_write0_merged_banks_9.push(level_1_level_1_update_0_write0);
}
inline hw_uint<16> level_2_rd0_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd0 read pattern: { level_2_update_0[d0, d1] -> level_1[2d0, 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 40 : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_40();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd1_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd1 read pattern: { level_2_update_0[d0, d1] -> level_1[2d0, 1 + 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 21 : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_21();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd2_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd2 read pattern: { level_2_update_0[d0, d1] -> level_1[2d0, 2 + 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 2 : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_2();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd3_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd3 read pattern: { level_2_update_0[d0, d1] -> level_1[1 + 2d0, 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 39 : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_39();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd4_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd4 read pattern: { level_2_update_0[d0, d1] -> level_1[1 + 2d0, 1 + 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 20 : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_20();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd5_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd5 read pattern: { level_2_update_0[d0, d1] -> level_1[1 + 2d0, 2 + 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 1 : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_1();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd6_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd6 read pattern: { level_2_update_0[d0, d1] -> level_1[2 + 2d0, 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 38 : 0 <= d0 <= 7 and 0 <= d1 <= 8; level_2_update_0[d0, d1] -> (22 + 2 * d0) : d0 = 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_38();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd7_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd7 read pattern: { level_2_update_0[d0, d1] -> level_1[2 + 2d0, 1 + 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { level_2_update_0[d0, d1] -> 19 : 0 <= d0 <= 7 and 0 <= d1 <= 8; level_2_update_0[d0, d1] -> (3 + 2 * d0) : d0 = 8 and 0 <= d1 <= 8 }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_19();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_2_rd8_select(level_1_cache& level_1, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_2_rd8 read pattern: { level_2_update_0[d0, d1] -> level_1[2 + 2d0, 2 + 2d1] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Read schedule : { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// Write schedule: { level_1_update_0[d0, d1] -> [6 + 4d1, 2 + d0, 3] : 0 <= d0 <= 18 and 0 <= d1 <= 18 }
// DD fold: { }
auto value_level_1_level_1_update_0_write0 = level_1.level_1_level_1_update_0_write0_merged_banks_9.peek_0();
return value_level_1_level_1_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// level_1_update_0_write
// level_1_level_1_update_0_write0
inline void level_1_level_1_update_0_write_bundle_write(hw_uint<16>& level_1_update_0_write, level_1_cache& level_1, int d0, int d1) {
hw_uint<16> level_1_level_1_update_0_write0_res = level_1_update_0_write.extract<0, 15>();
level_1_level_1_update_0_write0_write(level_1_level_1_update_0_write0_res, level_1, d0, d1);
}
// level_2_update_0_read
// level_2_rd0
// level_2_rd1
// level_2_rd2
// level_2_rd3
// level_2_rd4
// level_2_rd5
// level_2_rd6
// level_2_rd7
// level_2_rd8
inline hw_uint<144> level_1_level_2_update_0_read_bundle_read(level_1_cache& level_1, int d0, int d1) {
// # of ports in bundle: 9
// level_2_rd0
// level_2_rd1
// level_2_rd2
// level_2_rd3
// level_2_rd4
// level_2_rd5
// level_2_rd6
// level_2_rd7
// level_2_rd8
hw_uint<144> result;
hw_uint<16> level_2_rd0_res = level_2_rd0_select(level_1, d0, d1);
set_at<0, 144>(result, level_2_rd0_res);
hw_uint<16> level_2_rd1_res = level_2_rd1_select(level_1, d0, d1);
set_at<16, 144>(result, level_2_rd1_res);
hw_uint<16> level_2_rd2_res = level_2_rd2_select(level_1, d0, d1);
set_at<32, 144>(result, level_2_rd2_res);
hw_uint<16> level_2_rd3_res = level_2_rd3_select(level_1, d0, d1);
set_at<48, 144>(result, level_2_rd3_res);
hw_uint<16> level_2_rd4_res = level_2_rd4_select(level_1, d0, d1);
set_at<64, 144>(result, level_2_rd4_res);
hw_uint<16> level_2_rd5_res = level_2_rd5_select(level_1, d0, d1);
set_at<80, 144>(result, level_2_rd5_res);
hw_uint<16> level_2_rd6_res = level_2_rd6_select(level_1, d0, d1);
set_at<96, 144>(result, level_2_rd6_res);
hw_uint<16> level_2_rd7_res = level_2_rd7_select(level_1, d0, d1);
set_at<112, 144>(result, level_2_rd7_res);
hw_uint<16> level_2_rd8_res = level_2_rd8_select(level_1, d0, d1);
set_at<128, 144>(result, level_2_rd8_res);
return result;
}
#include "hw_classes.h"
struct level_2_level_2_update_0_write0_merged_banks_9_cache {
// RAM Box: {[0, 8], [0, 8]}
// Capacity: 21
// # of read delays: 9
hw_uint<16> f0;
hw_uint<16> f2;
hw_uint<16> f4;
fifo<hw_uint<16>, 6> f5;
hw_uint<16> f6;
hw_uint<16> f8;
hw_uint<16> f10;
fifo<hw_uint<16>, 6> f11;
hw_uint<16> f12;
hw_uint<16> f14;
hw_uint<16> f16;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_2() {
return f4;
}
inline hw_uint<16> peek_8() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f5.back();
}
inline hw_uint<16> peek_9() {
return f6;
}
inline hw_uint<16> peek_10() {
return f8;
}
inline hw_uint<16> peek_11() {
return f10;
}
inline hw_uint<16> peek_17() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f11.back();
}
inline hw_uint<16> peek_18() {
return f12;
}
inline hw_uint<16> peek_19() {
return f14;
}
inline hw_uint<16> peek_20() {
return f16;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f16 = f14;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f14 = f12;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 6
f12 = f11.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 6 reading from capacity: 1
f11.push(f10);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f10 = f8;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f8 = f6;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 6
f6 = f5.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 6 reading from capacity: 1
f5.push(f4);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f4 = f2;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct level_2_cache {
level_2_level_2_update_0_write0_merged_banks_9_cache level_2_level_2_update_0_write0_merged_banks_9;
};
inline void level_2_level_2_update_0_write0_write(hw_uint<16>& level_2_level_2_update_0_write0, level_2_cache& level_2, int d0, int d1) {
level_2.level_2_level_2_update_0_write0_merged_banks_9.push(level_2_level_2_update_0_write0);
}
inline hw_uint<16> level_3_rd0_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd0 read pattern: { level_3_update_0[d0, d1] -> level_2[2d0, 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 20 : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_20();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd1_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd1 read pattern: { level_3_update_0[d0, d1] -> level_2[2d0, 1 + 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 11 : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_11();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd2_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd2 read pattern: { level_3_update_0[d0, d1] -> level_2[2d0, 2 + 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 2 : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_2();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd3_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd3 read pattern: { level_3_update_0[d0, d1] -> level_2[1 + 2d0, 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 19 : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_19();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd4_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd4 read pattern: { level_3_update_0[d0, d1] -> level_2[1 + 2d0, 1 + 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 10 : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_10();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd5_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd5 read pattern: { level_3_update_0[d0, d1] -> level_2[1 + 2d0, 2 + 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 1 : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_1();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd6_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd6 read pattern: { level_3_update_0[d0, d1] -> level_2[2 + 2d0, 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 18 : 0 <= d0 <= 2 and 0 <= d1 <= 3; level_3_update_0[d0, d1] -> (12 + 2 * d0) : d0 = 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_18();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd7_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd7 read pattern: { level_3_update_0[d0, d1] -> level_2[2 + 2d0, 1 + 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { level_3_update_0[d0, d1] -> 9 : 0 <= d0 <= 2 and 0 <= d1 <= 3; level_3_update_0[d0, d1] -> (3 + 2 * d0) : d0 = 3 and 0 <= d1 <= 3 }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_9();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> level_3_rd8_select(level_2_cache& level_2, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// level_3_rd8 read pattern: { level_3_update_0[d0, d1] -> level_2[2 + 2d0, 2 + 2d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_2_update_0[d0, d1] -> [14 + 8d1, 4 + 2d0, 4] : 0 <= d0 <= 8 and 0 <= d1 <= 8 }
// DD fold: { }
auto value_level_2_level_2_update_0_write0 = level_2.level_2_level_2_update_0_write0_merged_banks_9.peek_0();
return value_level_2_level_2_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// level_2_update_0_write
// level_2_level_2_update_0_write0
inline void level_2_level_2_update_0_write_bundle_write(hw_uint<16>& level_2_update_0_write, level_2_cache& level_2, int d0, int d1) {
hw_uint<16> level_2_level_2_update_0_write0_res = level_2_update_0_write.extract<0, 15>();
level_2_level_2_update_0_write0_write(level_2_level_2_update_0_write0_res, level_2, d0, d1);
}
// level_3_update_0_read
// level_3_rd0
// level_3_rd1
// level_3_rd2
// level_3_rd3
// level_3_rd4
// level_3_rd5
// level_3_rd6
// level_3_rd7
// level_3_rd8
inline hw_uint<144> level_2_level_3_update_0_read_bundle_read(level_2_cache& level_2, int d0, int d1) {
// # of ports in bundle: 9
// level_3_rd0
// level_3_rd1
// level_3_rd2
// level_3_rd3
// level_3_rd4
// level_3_rd5
// level_3_rd6
// level_3_rd7
// level_3_rd8
hw_uint<144> result;
hw_uint<16> level_3_rd0_res = level_3_rd0_select(level_2, d0, d1);
set_at<0, 144>(result, level_3_rd0_res);
hw_uint<16> level_3_rd1_res = level_3_rd1_select(level_2, d0, d1);
set_at<16, 144>(result, level_3_rd1_res);
hw_uint<16> level_3_rd2_res = level_3_rd2_select(level_2, d0, d1);
set_at<32, 144>(result, level_3_rd2_res);
hw_uint<16> level_3_rd3_res = level_3_rd3_select(level_2, d0, d1);
set_at<48, 144>(result, level_3_rd3_res);
hw_uint<16> level_3_rd4_res = level_3_rd4_select(level_2, d0, d1);
set_at<64, 144>(result, level_3_rd4_res);
hw_uint<16> level_3_rd5_res = level_3_rd5_select(level_2, d0, d1);
set_at<80, 144>(result, level_3_rd5_res);
hw_uint<16> level_3_rd6_res = level_3_rd6_select(level_2, d0, d1);
set_at<96, 144>(result, level_3_rd6_res);
hw_uint<16> level_3_rd7_res = level_3_rd7_select(level_2, d0, d1);
set_at<112, 144>(result, level_3_rd7_res);
hw_uint<16> level_3_rd8_res = level_3_rd8_select(level_2, d0, d1);
set_at<128, 144>(result, level_3_rd8_res);
return result;
}
#include "hw_classes.h"
struct level_3_level_3_update_0_write0_merged_banks_1_cache {
// RAM Box: {[0, 3], [0, 3]}
// Capacity: 1
// # of read delays: 1
fifo<hw_uint<16>, 1> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(0 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct level_3_cache {
level_3_level_3_update_0_write0_merged_banks_1_cache level_3_level_3_update_0_write0_merged_banks_1;
};
inline void level_3_level_3_update_0_write0_write(hw_uint<16>& level_3_level_3_update_0_write0, level_3_cache& level_3, int d0, int d1) {
level_3.level_3_level_3_update_0_write0_merged_banks_1.push(level_3_level_3_update_0_write0);
}
inline hw_uint<16> gp_4_rd0_select(level_3_cache& level_3, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// gp_4_rd0 read pattern: { gp_4_update_0[d0, d1] -> level_3[d0, d1] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Read schedule : { gp_4_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 6] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// Write schedule: { level_3_update_0[d0, d1] -> [30 + 16d1, 8 + 4d0, 5] : 0 <= d0 <= 3 and 0 <= d1 <= 3 }
// DD fold: { }
auto value_level_3_level_3_update_0_write0 = level_3.level_3_level_3_update_0_write0_merged_banks_1.peek(/* one reader or all rams */ 0);
return value_level_3_level_3_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// gp_4_update_0_read
// gp_4_rd0
inline hw_uint<16> level_3_gp_4_update_0_read_bundle_read(level_3_cache& level_3, int d0, int d1) {
// # of ports in bundle: 1
// gp_4_rd0
hw_uint<16> result;
hw_uint<16> gp_4_rd0_res = gp_4_rd0_select(level_3, d0, d1);
set_at<0, 16>(result, gp_4_rd0_res);
return result;
}
// level_3_update_0_write
// level_3_level_3_update_0_write0
inline void level_3_level_3_update_0_write_bundle_write(hw_uint<16>& level_3_update_0_write, level_3_cache& level_3, int d0, int d1) {
hw_uint<16> level_3_level_3_update_0_write0_res = level_3_update_0_write.extract<0, 15>();
level_3_level_3_update_0_write0_write(level_3_level_3_update_0_write0_res, level_3, d0, d1);
}
// Operation logic
inline void level_1_update_0(level_0_cache& level_0, level_1_cache& level_1, int d0, int d1) {
// Consume: level_0
auto level_0_0_c__0_value = level_0_level_1_update_0_read_bundle_read(level_0/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
auto compute_result = reduce_gauss_unrolled_1(level_0_0_c__0_value);
// Produce: level_1
level_1_level_1_update_0_write_bundle_write(compute_result, level_1, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
}
inline void level_3_update_0(level_2_cache& level_2, level_3_cache& level_3, int d0, int d1) {
// Consume: level_2
auto level_2_0_c__0_value = level_2_level_3_update_0_read_bundle_read(level_2/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
auto compute_result = reduce_gauss_unrolled_1(level_2_0_c__0_value);
// Produce: level_3
level_3_level_3_update_0_write_bundle_write(compute_result, level_3, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
}
inline void level_2_update_0(level_1_cache& level_1, level_2_cache& level_2, int d0, int d1) {
// Consume: level_1
auto level_1_0_c__0_value = level_1_level_2_update_0_read_bundle_read(level_1/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
auto compute_result = reduce_gauss_unrolled_1(level_1_0_c__0_value);
// Produce: level_2
level_2_level_2_update_0_write_bundle_write(compute_result, level_2, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
}
inline void gp_4_update_0(level_3_cache& level_3, HWStream<hw_uint<16> >& /* buffer_args num ports = 1 */gp_4, int d0, int d1) {
// Consume: level_3
auto level_3_0_c__0_value = level_3_gp_4_update_0_read_bundle_read(level_3/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
auto compute_result = id_unrolled_1(level_3_0_c__0_value);
// Produce: gp_4
gp_4.write(compute_result);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
}
inline void level_0_update_0(in_cache& in, level_0_cache& level_0, int d0, int d1) {
// Consume: in
auto in_0_c__0_value = in_level_0_update_0_read_bundle_read(in/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
auto compute_result = reduce_gauss_unrolled_2(in_0_c__0_value);
// Produce: level_0
level_0_level_0_update_0_write_bundle_write(compute_result, level_0, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
}
inline void in_update_0(HWStream<hw_uint<64> >& /* buffer_args num ports = 4 */in_off_chip, in_cache& in, int d0, int d1) {
// Consume: in_off_chip
auto in_off_chip_0_c__0_value = in_off_chip.read();
auto compute_result = id_unrolled_4(in_off_chip_0_c__0_value);
// Produce: in
in_in_update_0_write_bundle_write(compute_result, in, d0, d1);
#ifndef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
}
// Driver function
void gp_4_opt(HWStream<hw_uint<64> >& /* get_args num ports = 4 */in_off_chip, HWStream<hw_uint<16> >& /* get_args num ports = 1 */gp_4, int num_epochs) {
#ifndef __VIVADO_SYNTH__
ofstream debug_file("gp_4_opt_debug.csv");
global_debug_handle = &debug_file;
#endif //__VIVADO_SYNTH__
in_cache in;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
level_0_cache level_0;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
level_1_cache level_1;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
level_2_cache level_2;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
level_3_cache level_3;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
#ifdef __VIVADO_SYNTH__
#pragma HLS inline recursive
#endif // __VIVADO_SYNTH__
for (int epoch = 0; epoch < num_epochs; epoch++) {
// Schedules...
// gp_4_update_0 -> [1*d1*1*16 + 1*30,1*d0*1*4 + 1*8,1*6]
// in_off_chip_update_0 -> [1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*0]
// in_update_0 -> [1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*1]
// level_0_update_0 -> [1*d1*1*2 + 1*2,1*d0*1*1 + 1*1,1*2]
// level_1_update_0 -> [1*d1*1*4 + 1*6,1*d0*1*1 + 1*2,1*3]
// level_2_update_0 -> [1*d1*1*8 + 1*14,1*d0*1*2 + 1*4,1*4]
// level_3_update_0 -> [1*d1*1*16 + 1*30,1*d0*1*4 + 1*8,1*5]
for (int c0 = 0; c0 <= 78; c0++) {
for (int c1 = 0; c1 <= 20; c1++) {
#ifdef __VIVADO_SYNTH__
#pragma HLS pipeline II=1
#endif // __VIVADO_SYNTH__
if ((0 <= c1 && c1 <= 20) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 78) && ((c0 - 0) % 1 == 0)) {
in_update_0(in_off_chip, in, (c1 - 0) / 1, (c0 - 0) / 1);
}
if ((1 <= c1 && c1 <= 20) && ((c1 - 1) % 1 == 0) && (2 <= c0 && c0 <= 78) && ((c0 - 2) % 2 == 0)) {
level_0_update_0(in, level_0, (c1 - 1) / 1, (c0 - 2) / 2);
}
if ((2 <= c1 && c1 <= 20) && ((c1 - 2) % 1 == 0) && (6 <= c0 && c0 <= 78) && ((c0 - 6) % 4 == 0)) {
level_1_update_0(level_0, level_1, (c1 - 2) / 1, (c0 - 6) / 4);
}
if ((4 <= c1 && c1 <= 20) && ((c1 - 4) % 2 == 0) && (14 <= c0 && c0 <= 78) && ((c0 - 14) % 8 == 0)) {
level_2_update_0(level_1, level_2, (c1 - 4) / 2, (c0 - 14) / 8);
}
if ((8 <= c1 && c1 <= 20) && ((c1 - 8) % 4 == 0) && (30 <= c0 && c0 <= 78) && ((c0 - 30) % 16 == 0)) {
level_3_update_0(level_2, level_3, (c1 - 8) / 4, (c0 - 30) / 16);
}
if ((8 <= c1 && c1 <= 20) && ((c1 - 8) % 4 == 0) && (30 <= c0 && c0 <= 78) && ((c0 - 30) % 16 == 0)) {
gp_4_update_0(level_3, gp_4, (c1 - 8) / 4, (c0 - 30) / 16);
}
}
}
}
#ifndef __VIVADO_SYNTH__
debug_file.close();
#endif //__VIVADO_SYNTH__
}
void gp_4_opt(HWStream<hw_uint<64> >& /* get_args num ports = 4 */in_off_chip, HWStream<hw_uint<16> >& /* get_args num ports = 1 */gp_4) {
gp_4_opt(in_off_chip, gp_4, 1);
}
#ifdef __VIVADO_SYNTH__
#include "gp_4_opt.h"
const int gp_4_update_0_write_num_transfers = 16;
const int in_update_0_read_num_transfers = 1659;
extern "C" {
static void read_in_update_0_read(hw_uint<64>* input, HWStream<hw_uint<64> >& v, const int size) {
hw_uint<64> burst_reg;
int num_transfers = in_update_0_read_num_transfers*size;
for (int i = 0; i < num_transfers; i++) {
#pragma HLS pipeline II=1
burst_reg = input[i];
v.write(burst_reg);
}
}
static void write_gp_4_update_0_write(hw_uint<16>* output, HWStream<hw_uint<16> >& v, const int size) {
hw_uint<16> burst_reg;
int num_transfers = gp_4_update_0_write_num_transfers*size;
for (int i = 0; i < num_transfers; i++) {
#pragma HLS pipeline II=1
burst_reg = v.read();
output[i] = burst_reg;
}
}
void gp_4_opt_accel(hw_uint<64>* in_update_0_read, hw_uint<16>* gp_4_update_0_write, const int size) {
#pragma HLS dataflow
#pragma HLS INTERFACE m_axi port = in_update_0_read offset = slave depth = 65536 bundle = gmem0
#pragma HLS INTERFACE m_axi port = gp_4_update_0_write offset = slave depth = 65536 bundle = gmem1
#pragma HLS INTERFACE s_axilite port = in_update_0_read bundle = control
#pragma HLS INTERFACE s_axilite port = gp_4_update_0_write bundle = control
#pragma HLS INTERFACE s_axilite port = size bundle = control
#pragma HLS INTERFACE s_axilite port = return bundle = control
static HWStream<hw_uint<64> > in_update_0_read_channel;
static HWStream<hw_uint<16> > gp_4_update_0_write_channel;
read_in_update_0_read(in_update_0_read, in_update_0_read_channel, size);
gp_4_opt(in_update_0_read_channel, gp_4_update_0_write_channel, size);
write_gp_4_update_0_write(gp_4_update_0_write, gp_4_update_0_write_channel, size);
}
}
#endif //__VIVADO_SYNTH__
|
#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 <map>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define MOD 1000000007
inline int Add(int x, int y) {
return (x + y) % MOD;
}
inline int Sub(int x, int y) {
return (x - y + MOD) % MOD;
}
inline int Mul(int x, int y) {
return (LL(x) * y) % MOD;
}
inline int Pow(int x, int y) {
int res = 1;
while (y) {
if (y&1) res = Mul(res, x);
x = Mul(x, x);
y >>= 1;
}
return res;
}
inline int Div(int x, int y) {
return Mul(x, Pow(y, MOD - 2));
}
int n, d[111], fact[111], pow10[111], C[111][111], f[111][111];
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
cin >> n;
for (int i = 0; i< 10; i++) cin >> d[i];
fact[0] = 1;
for (int i = 1; i <= 100; i++) fact[i] = Mul(fact[i - 1], i);
pow10[0] = 1;
for (int i = 1; i <= 100; i++) pow10[i] = Mul(pow10[i - 1], 10);
for (int i = 0; i <= 100; i++) {
C[i][0] = 1;
for (int j = 1; j <= i; j++) C[i][j] = Add(C[i - 1][j], C[i - 1][j - 1]);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int fd = 1; fd < 10; fd++) {
bool noadd = false;
if (d[fd]) d[fd]--;else noadd = true;
int l = i - 1;
int sum = 0;
for (int j = 0; j < 10; j++) sum += d[j];
if (sum > l) {
if (!noadd) d[fd]++;
continue;
}
memset(f, 0, sizeof(f));
for (int k = d[9]; k <= l; k++) f[9][k] = 1;
for (int k = 8; k >= 0; k--) {
for (int j = d[k]; j <= l; j++) {
for (int jj = d[k]; jj <= j; jj++) {
f[k][j] = Add(f[k][j], Mul(C[j][jj], f[k + 1][j - jj]) );
}
}
}
ans = Add(ans, f[0][l]);
if (!noadd) d[fd]++;
}
}
cout << ans << endl;
return 0;
}
|
class PZombie_VB: Citizen1
{
side = 1;
glassesEnabled = 0;
moves = "CfgMovesZombie";
gestures = "CfgGesturesMale";
weapons[] = {};
weaponSlots = "";
backpack = "";
magazines[] = {};
respawnWeapons[] = {};
respawnMagazines[] = {};
faceType = "PZombieFace1";
identityTypes[] = {"PZombie1"};
extCameraPosition[] = {0,1.5,-9};
canHideBodies = 0;
};
class pz_policeman: PZombie_VB
{
model = "\ca\characters2\civil\Policeman\Policeman";
class Wounds
{
tex[] = {};
mat[] = {"ca\characters2\civil\policeman\data\policeman.rvmat","ca\characters2\civil\policeman\data\w1_policeman.rvmat","ca\characters2\civil\policeman\data\w2_policeman.rvmat","ca\characters\heads\male\defaulthead\data\hhl.rvmat","ca\characters\heads\male\defaulthead\data\hhl_wounds.rvmat","ca\characters\heads\male\defaulthead\data\hhl_wounds.rvmat"};
};
};
class pz_suit1: PZombie_VB
{
model = "\ca\characters2\civil\Functionary\Functionary";
hiddenSelections[] = {"Camo"};
hiddenSelectionsTextures[] = {"\ca\characters2\civil\functionary\data\functionary_co.paa"};
class Wounds
{
tex[] = {};
mat[] = {"ca\characters2\civil\Functionary\data\Functionary.rvmat","ca\characters2\civil\Functionary\data\W1_Functionary.rvmat","ca\characters2\civil\Functionary\data\W2_Functionary.rvmat","ca\characters\heads\male\defaulthead\data\hhl.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat"};
};
};
class pz_suit2: pz_suit1
{
hiddenSelectionsTextures[] = {"\ca\characters2\civil\functionary\data\functionary2_co.paa"};
};
class pz_worker1: PZombie_VB
{
model = "\Ca\characters_E\Overall\Overall";
hiddenSelections[] = {"Camo"};
class Wounds
{
tex[] = {};
mat[] = {"Ca\characters_E\Overall\Data\Overall.rvmat","Ca\characters_E\Overall\Data\W1_Overall.rvmat","Ca\characters_E\Overall\Data\W2_Overall.rvmat"};
};
hiddenSelectionsTextures[] = {"z\addons\dayz_communityassets\zeds\overall\Overall_4_co.paa"};
};
class pz_worker2: pz_worker1
{
hiddenSelectionsTextures[] = {"z\addons\dayz_communityassets\zeds\overall\overall_2_co.paa"};
};
class pz_worker3: pz_worker1
{
hiddenSelectionsTextures[] = {"z\addons\dayz_communityassets\zeds\overall\Overall_3_co.paa"};
};
class pz_doctor: PZombie_VB
{
model = "\ca\characters2\civil\Doctor\Doctor";
hiddenSelections[] = {"Camo"};
hiddenSelectionsTextures[] = {"\dayz\textures\clothes\doctor_co.paa"};
class Wounds
{
tex[] = {};
mat[] = {"ca\characters2\civil\doctor\data\doctor.rvmat","ca\characters2\civil\doctor\data\W1_doctor.rvmat","ca\characters2\civil\doctor\data\W2_doctor.rvmat","ca\characters\heads\male\defaulthead\data\hhl.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat"};
};
};
class pz_teacher: pz_doctor
{
hiddenSelectionsTextures[] = {"\dayz\textures\clothes\teacher_co.paa"};
};
class pz_hunter: PZombie_VB
{
model = "\ca\characters2\civil\Woodlander\Woodlander";
hiddenSelections[] = {"Camo"};
hiddenSelectionsTextures[] = {"\ca\characters2\civil\woodlander\data\woodlander_v3_co.paa"};
class Wounds
{
tex[] = {};
mat[] = {"ca\characters2\civil\Woodlander\data\Woodlander.rvmat","ca\characters2\civil\Woodlander\data\W1_Woodlander.rvmat","ca\characters2\civil\Woodlander\data\W2_Woodlander.rvmat","ca\characters\heads\male\defaulthead\data\hhl.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat"};
};
};
class pz_villager1: PZombie_VB
{
model = "\ca\characters2\civil\Villager\Villager";
hiddenSelections[] = {"Camo"};
hiddenSelectionsTextures[] = {"z\addons\dayz_communityassets\zeds\villager\villager_v4_co.paa"};
class Wounds
{
tex[] = {};
mat[] = {"ca\characters\heads\male\defaulthead\data\hhl.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat","ca\characters2\Civil\Villager\Data\villager.RVmat","ca\characters2\Civil\Villager\Data\villager_w1.RVmat","ca\characters2\Civil\Villager\Data\villager_w2.RVmat"};
};
};
class pz_villager2: pz_villager1
{
hiddenSelectionsTextures[] = {"z\addons\dayz_communityassets\zeds\villager\villager_v2_co.paa"};
};
class pz_villager3: pz_villager1
{
hiddenSelectionsTextures[] = {"z\addons\dayz_communityassets\zeds\villager\villager_v3_co.paa"};
};
class pz_priest: PZombie_VB
{
model = "\ca\characters2\civil\Priest\Priest";
class Wounds
{
tex[] = {};
mat[] = {"ca\characters2\civil\priest\data\priest.rvmat","ca\characters2\civil\priest\data\W1_priest.rvmat","ca\characters2\civil\priest\data\W2_priest.rvmat","ca\characters\heads\male\defaulthead\data\hhl.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat","ca\characters\heads\male\defaulthead\data\hhl_Wounds.rvmat"};
};
};
|
/*
* SDEV340 Week 2 Problem 1
* Convert an integer x: 0 <= x <= 9999 into its English string representation
* Benjamin Lovy
*/
#include <iostream>
#include <string>
using std::string;
// Class for pretty-printing a number 0-9999
class Numbers
{
unsigned int number;
static string hundred;
static string lessThan20[];
static string tensFromTwenty[];
static string thousand;
public:
Numbers(unsigned int value); // Constructor
void print() const; // Write the english representation to stdout
// Static helper functions to print portions of numbers
static void printLessThan20(unsigned int n);
static void printLessThan100(unsigned int n);
static void printLessThan1000(unsigned int n);
};
// Statics
string Numbers::hundred = "hundred";
string Numbers::lessThan20[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
string Numbers::tensFromTwenty[] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
string Numbers::thousand = "thousand";
void Numbers::printLessThan20(unsigned int n)
{
std::cout << lessThan20[n];
}
void Numbers::printLessThan100(unsigned int n)
{
if (n >= 20)
{
// get tens place and ones place
unsigned int ones = n % 10;
unsigned int tens = n / 10; // interger division will truncate the ones
std::cout << tensFromTwenty[tens - 2];
// Only display ones if not zero
if (ones > 0)
std::cout << " " << lessThan20[ones];
}
else
printLessThan20(n);
}
void Numbers::printLessThan1000(unsigned int n)
{
if (n == 0)
std::cout << lessThan20[n];
else
{
unsigned int hundreds = n / 100;
std::cout << lessThan20[hundreds] << " " << hundred;
unsigned int rest = n - (100 * hundreds);
if (rest > 0)
{
std::cout << " ";
printLessThan100(rest);
}
}
}
// Constructor
Numbers::Numbers(unsigned int value)
{
number = value;
}
// Write the english representation to stdout
void Numbers::print() const
{
using std::cout;
if (number >= 1000)
{
unsigned int thousands = number / 1000;
std::cout << lessThan20[thousands] << " " << thousand;
unsigned int rest = number - (1000 * thousands);
if (rest > 0)
{
std::cout << " ";
printLessThan1000(rest);
}
}
else
printLessThan1000(number);
}
int main()
{
using std::cin;
using std::cout;
// Collect number in range
unsigned int userVal;
do
{
cout << "Enter number 0 - 9999> ";
cin >> userVal;
} while (userVal > 9999);
// Instantiate object
Numbers userNum(userVal);
// Print output
userNum.print();
return 0;
}
|
//////////////////////////////////////////////////////////////////////////
// ExpandCollapseControl.cpp - Provides expand and collapse functionality//
// to hide and unhide data on web browser //
// //
// Language: Visual C++ 2015 //
// Platform: MicroSoft Surface Pro, Windows 10 //
// Application: Code Publisher - CSE 687 Project 3 //
// Author: Manasa Malali Nagabhushana SUID:845368670 //
//////////////////////////////////////////////////////////////////////////
#include "ExpandCollapseControl.h"
ExpandCollapse::ExpandCollapse() :node(Repository::getInstance()->AST()) {}
// function that walks through the AST to retrieve the type
void ExpandCollapse::TreeWalkDemo(ASTNode* root)
{
std::pair<int, int> lcount;
CheckType(root, lcount);
for (auto children : root->children_)
{
newType = root->type_;
TreeWalkDemo(children);
newType = root->type_;
}
}
// function that checks for the type
void ExpandCollapse::CheckType(ASTNode* root, std::pair<int, int> lcount)
{
if ((root->type_ == "function") || (root->type_ == "struct") || (root->type_ == "class") || (root->type_ == "enum"))
{
lcount = std::make_pair(int(root->startLineCount_), int(root->endLineCount_));
FileLength[root->path_].push_back(lcount);
}
}
// function to retrieve the length of function, struct or class
std::unordered_map<std::string, std::vector<std::pair<int, int>>> ExpandCollapse::RetrieveFileLength()
{
ASTNode *root = node.root();
TreeWalkDemo(root);
return FileLength;
}
// test stub
#ifdef Expand
int main()
{
ExpandCollapse ex;
ASTNode *Root;
ex.TreeWalkDemo(Root);
ex.RetrieceFileLength();
return 0;
}
#endif
|
//
// Created by Dawid Szymański on 2019-05-18.
//
#include <iostream>
int exercise04() {
int mnoznik = 2, nadgodziny = 0, liczbagodzin, stawka, brutto, podatek, netto;
int prog = 28 , prog20 = 19, prog2030 = 21, prog30 = 28;
int var20, var2030, var30;
std::cout << "Podaj liczbe godzin\nLiczba godzin: " << std::endl;
std::cin >> liczbagodzin;
std::cout << "Podaj stawke\nStawka: " << std::endl;
std::cin >> stawka;
nadgodziny = liczbagodzin - 40;
if (nadgodziny > 0) {
liczbagodzin = 40;
} else {
nadgodziny = 0;
}
brutto = (nadgodziny * mnoznik + liczbagodzin) * stawka * 52;
char proceed;
do {
std::cout << "Wyliczyć podatek? [Y]es / [N]o";
std::cin >> proceed;
} while (proceed != 'y' && proceed != 'Y' && proceed != 'n' && proceed != 'N');
if (proceed == 'n' || proceed == 'N') {
std::cout << "W ciagu roku zarobi: " << brutto << std::endl;
return 0;
}
if ((var30 = brutto - 30000) < 0) {
var30 = 0;
prog = 21;
}
if ((var2030 = brutto - 20000 - var30) < 0) {
var2030 = 0;
prog = 19;
}
if ((var20 = brutto - var2030 - var30) < 0) {
var20 = 0;
}
podatek = (var30 * prog30 + var2030 * prog2030 + var20 * prog20) / 100;
netto = brutto - podatek;
std::cout << "\nProg podatkowy: " << prog<< "%, Podatek: " << podatek << " + netto: " << netto << " = Brutto: " << brutto;
};
|
#include "BulletObject.h"
#include "BulletTransform.h"
namespace Game
{
BulletObject::BulletObject(Transform transform) : mTransform(transform)
{
}
BulletObject::~BulletObject()
{
}
PhysicsTransform& BulletObject::transform(){
return mTransform;
}
BulletTransform& BulletObject::nativeTransform()
{
return mTransform;
}
void BulletObject::setShape(CollisionShapes shape)
{
mCollisionShape = shape;
}
void BulletObject::setMass(float mass)
{
mMass = mass;
}
CollisionShapes BulletObject::getShape()
{
return mCollisionShape;
}
float BulletObject::getMass()
{
return mMass;
}
void BulletObject::setMesh(MeshTransform *meshTransform)
{
mMeshTransform = meshTransform;
}
MeshTransform *BulletObject::getMesh()
{
return mMeshTransform;
}
}
|
class Solution {
public:
double myPow(double x, int n) {
if (n<0) return 1.0/power(x,n);
return power(x,n);
}
private:
// 采用分治法
double power(double x, int n) {
if (0==n) return 1.0;
double val = power(x, n/2);
return (n%2==0)? val*val: val*val*x;
}
};
|
#pragma once
#include "widgets/widget.hpp"
namespace OptimExplorer
{
class TrainWidget : public Widget
{
public:
TrainWidget() : Widget("Train") {}
void render() override;
private:
float m_lr = 1e-3;
float m_wd = 5e-4;
int m_epochs = 10;
};
} // namespace OptimExplorer
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 2007-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 COMMON_SOCKET_ADDRESS_H
#define COMMON_SOCKET_ADDRESS_H __FILE__
#include "modules/pi/network/OpSocketAddress.h"
/** A re-usable base-class for OpSocketAddress implementations.
*
* This base-class implements the obvious management of the port number and
* provides the implementation-neutral implementation of Copy(), needed for
* TWEAK_POSIX_MIXED_SOCKADDR (q.v.). It also provides for being able to use
* const OpSocketAddress* wherever reasonable, unlike the PI.
*/
class CommonSocketAddress : public OpSocketAddress
{
// Ideally in_port_t, but requires #include <netinet/in.h>, which declares it 16-bit.
UINT16 m_port;
protected:
CommonSocketAddress() : m_port(0) {}
// Let const instances of derived classes know m_port:
UINT16 GetPort() const { return m_port; }
public:
virtual void SetPort(UINT port)
{ OP_ASSERT(port < 0x10000); m_port = static_cast<UINT16>(port); }
virtual UINT Port() { return static_cast<UINT>(m_port); }
virtual BOOL IsEqual(OpSocketAddress* socket_address)
{ return Port() == socket_address->Port() && IsHostEqual(socket_address); }
#ifdef MIXED_SOCKETRY
OP_STATUS Import(const OpSocketAddress* socket_address)
{
OpString text;
RETURN_IF_ERROR(socket_address->ToString(&text)); // doesn't include port
RETURN_IF_ERROR(FromString(&text)); // does not set port
SetPort(socket_address->Port());
return OpStatus::OK;
}
virtual OP_STATUS Copy(OpSocketAddress* socket_address)
{ return Import(static_cast<const OpSocketAddress*>(socket_address)); }
#endif
};
#endif // COMMON_SOCKET_ADDRESS_H
|
// Created on: 1995-07-18
// Created by: Modelistation
// Copyright (c) 1995-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 _Extrema_GenExtPS_HeaderFile
#define _Extrema_GenExtPS_HeaderFile
#include <Bnd_HArray1OfSphere.hxx>
#include <Extrema_Array2OfPOnSurfParams.hxx>
#include <Extrema_POnSurfParams.hxx>
#include <Extrema_HUBTreeOfSphere.hxx>
#include <Extrema_FuncPSNorm.hxx>
#include <Extrema_ExtFlag.hxx>
#include <Extrema_ExtAlgo.hxx>
#include <TColStd_HArray1OfReal.hxx>
class Adaptor3d_Surface;
//! It calculates all the extremum distances
//! between a point and a surface.
//! These distances can be minimum or maximum.
class Extrema_GenExtPS
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor.
Standard_EXPORT Extrema_GenExtPS();
//! Destructor.
Standard_EXPORT ~Extrema_GenExtPS();
//! It calculates all the distances.
//! The function F(u,v)=distance(P,S(u,v)) has an
//! extremum when gradient(F)=0. The algorithm searches
//! all the zeros inside the definition ranges of the
//! surface.
//! NbU and NbV are used to locate the close points
//! to find the zeros. They must be great enough
//! such that if there is N extrema, there will
//! be N extrema between P and the grid.
//! TolU et TolV are used to determine the conditions
//! to stop the iterations; at the iteration number n:
//! (Un - Un-1) < TolU and (Vn - Vn-1) < TolV .
Standard_EXPORT Extrema_GenExtPS(const gp_Pnt& P, const Adaptor3d_Surface& S, const Standard_Integer NbU, const Standard_Integer NbV, const Standard_Real TolU, const Standard_Real TolV, const Extrema_ExtFlag F = Extrema_ExtFlag_MINMAX, const Extrema_ExtAlgo A = Extrema_ExtAlgo_Grad);
//! It calculates all the distances.
//! The function F(u,v)=distance(P,S(u,v)) has an
//! extremum when gradient(F)=0. The algorithm searches
//! all the zeros inside the definition ranges of the
//! surface.
//! NbU and NbV are used to locate the close points
//! to find the zeros. They must be great enough
//! such that if there is N extrema, there will
//! be N extrema between P and the grid.
//! TolU et TolV are used to determine the conditions
//! to stop the iterations; at the iteration number n:
//! (Un - Un-1) < TolU and (Vn - Vn-1) < TolV .
Standard_EXPORT Extrema_GenExtPS(const gp_Pnt& P, const Adaptor3d_Surface& S, const Standard_Integer NbU, const Standard_Integer NbV, const Standard_Real Umin, const Standard_Real Usup, const Standard_Real Vmin, const Standard_Real Vsup, const Standard_Real TolU, const Standard_Real TolV, const Extrema_ExtFlag F = Extrema_ExtFlag_MINMAX, const Extrema_ExtAlgo A = Extrema_ExtAlgo_Grad);
Standard_EXPORT void Initialize (const Adaptor3d_Surface& S, const Standard_Integer NbU, const Standard_Integer NbV, const Standard_Real TolU, const Standard_Real TolV);
Standard_EXPORT void Initialize (const Adaptor3d_Surface& S, const Standard_Integer NbU, const Standard_Integer NbV, const Standard_Real Umin, const Standard_Real Usup, const Standard_Real Vmin, const Standard_Real Vsup, const Standard_Real TolU, const Standard_Real TolV);
//! the algorithm is done with the point P.
//! An exception is raised if the fields have not
//! been initialized.
Standard_EXPORT void Perform (const gp_Pnt& P);
Standard_EXPORT void SetFlag (const Extrema_ExtFlag F);
Standard_EXPORT void SetAlgo (const Extrema_ExtAlgo A);
//! Returns True if the distances are found.
Standard_EXPORT Standard_Boolean IsDone() const;
//! Returns the number of extremum distances.
Standard_EXPORT Standard_Integer NbExt() const;
//! Returns the value of the Nth resulting square distance.
Standard_EXPORT Standard_Real SquareDistance (const Standard_Integer N) const;
//! Returns the point of the Nth resulting distance.
Standard_EXPORT const Extrema_POnSurf& Point (const Standard_Integer N) const;
private:
Standard_EXPORT void BuildTree();
Standard_EXPORT void FindSolution (const gp_Pnt& P, const Extrema_POnSurfParams& theParams);
//! Selection of points to build grid, depending on the type of surface
Standard_EXPORT void GetGridPoints (const Adaptor3d_Surface& theSurf);
//! Creation of grid of parametric points
Standard_EXPORT void BuildGrid (const gp_Pnt& thePoint);
//! Compute new edge parameters.
Standard_EXPORT const Extrema_POnSurfParams& ComputeEdgeParameters (const Standard_Boolean IsUEdge, const Extrema_POnSurfParams& theParam0, const Extrema_POnSurfParams& theParam1, const gp_Pnt& thePoints, const Standard_Real theDiffTol);
private:
// disallow copies
Extrema_GenExtPS (const Extrema_GenExtPS& ) Standard_DELETE;
Extrema_GenExtPS& operator= (const Extrema_GenExtPS& ) Standard_DELETE;
private:
Standard_Boolean myDone;
Standard_Boolean myInit;
Standard_Real myumin;
Standard_Real myusup;
Standard_Real myvmin;
Standard_Real myvsup;
Standard_Integer myusample;
Standard_Integer myvsample;
Standard_Real mytolu;
Standard_Real mytolv;
Extrema_Array2OfPOnSurfParams myPoints;
Extrema_HUBTreeOfSphere mySphereUBTree;
Handle(Bnd_HArray1OfSphere) mySphereArray;
Extrema_FuncPSNorm myF;
const Adaptor3d_Surface* myS;
Extrema_ExtFlag myFlag;
Extrema_ExtAlgo myAlgo;
Handle(TColStd_HArray1OfReal) myUParams;
Handle(TColStd_HArray1OfReal) myVParams;
Extrema_Array2OfPOnSurfParams myFacePntParams;
Extrema_Array2OfPOnSurfParams myUEdgePntParams;
Extrema_Array2OfPOnSurfParams myVEdgePntParams;
Extrema_POnSurfParams myGridParam;
};
#endif // _Extrema_GenExtPS_HeaderFile
|
#include "singl_motion.h"
#include "ui_singl_motion.h"
Singl_Motion::Singl_Motion(QWidget *parent) :
QDialog(parent),
ui(new Ui::Singl_Motion)
{
ui->setupUi(this);
ui->Motion_Number->addItem("M1");
ui->Motion_Number->addItem("M2");
ui->Motion_Number->addItem("M3");
}
Singl_Motion::~Singl_Motion()
{
delete ui;
}
void Singl_Motion::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
|
#include "Region.h"
#include "..\Util.h"
using namespace BroodWar;
namespace BroodWar
{
namespace Api
{
Region^ ConvertRegion(BWAPI::Region region)
{
if(region == NULL)
return nullptr;
return gcnew Region(region);
}
Region::Region(BWAPI::Region region)
{
instance = region;
}
int Region::Id::get()
{
return instance->getID();
}
int Region::RegionGroupId::get()
{
return instance->getRegionGroupID();
}
Position^ Region::Center::get()
{
return ConvertPosition(instance->getCenter());
}
bool Region::IsHigherGround::get()
{
return instance->isHigherGround();
}
int Region::DefensePriority::get()
{
return instance->getDefensePriority();
}
bool Region::IsAccessible::get()
{
return instance->isAccessible();
}
HashSet<Region^>^ Region::Neighbours::get()
{
return ToHashSet<BWAPI::Region, Region^>(instance->getNeighbors(), &ConvertRegion);
}
Rectangle Region::Bounds::get()
{
return System::Drawing::Rectangle(
instance->getBoundsLeft(),
instance->getBoundsTop(),
instance->getBoundsRight() - instance->getBoundsLeft(),
instance->getBoundsBottom() - instance->getBoundsTop());
}
Region^ Region::ClosestAccessibleRegion::get()
{
return ConvertRegion(instance->getClosestAccessibleRegion());
}
Region^ Region::ClosestInaccessibleRegion::get()
{
return ConvertRegion(instance->getClosestInaccessibleRegion());
}
int Region::DistanceTo(Region^ region)
{
return instance->getDistance(region->instance);
}
int Region::GetHashCode()
{
return instance->getID();
}
bool Region::Equals(Object^ o)
{
Region^ other = dynamic_cast<Region^>(o);
return this->Equals(other);
}
bool Region::Equals(Region^ other)
{
if(ReferenceEquals(nullptr, other))
return false;
if(ReferenceEquals(this, other))
return true;
return this->instance->getID() == other->instance->getID();
}
bool Region::operator == (Region^ first, Region^ second)
{
if(ReferenceEquals(first, second))
return true;
if(ReferenceEquals(nullptr, first))
return false;
return first->Equals(second);
}
bool Region::operator != (Region^ first, Region^ second)
{
return !(first == second);
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
**
** Peter Krefting
*/
/** @file ua.cpp
*
* Contains functions for handling the User-Agent string.
*/
#include "core/pch.h"
#include "modules/about/operaversion.h"
#include "modules/url/uamanager/ua.h"
#include "modules/pi/OpUAComponentManager.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/url/url2.h"
#include "modules/url/url_man.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/dochand/win.h"
#include "modules/windowcommander/src/WindowCommander.h"
#if defined SC_UA_CONTEXT_COMPONENTS && defined COMPONENT_IN_UASTRING_SUPPORT
# error "Cannot combine TWEAK_URL_UA_COMPONENTS_CONTEXT and TWEAK_URL_UA_COMPONENTS"
#endif
#if defined SC_UA_CONTEXT_COMPONENTS && defined TOKEN_IN_UASTRING_SUPPORT
# error "Cannot combine TWEAK_URL_UA_COMPONENTS_CONTEXT and TWEAK_URL_UA_TOKENS"
#endif
UAManager::UAManager()
: m_component_manager(NULL)
, m_UA_SelectedStringId(UA_MSIE)
{}
void UAManager::ConstructL()
{
// Create the component manager
LEAVE_IF_ERROR(OpUAComponentManager::Create(&m_component_manager));
// Read setting from PrefsManager
PrefChanged(OpPrefsCollection::Network, PrefsCollectionNetwork::UABaseId,
g_pcnet->GetIntegerPref(PrefsCollectionNetwork::UABaseId));
// Register as a listener
g_pcnet->RegisterListenerL(this);
#ifdef UA_CAN_CHANGE_LANGUAGE
g_pcfiles->RegisterFilesListenerL(this);
#endif
}
UAManager::~UAManager()
{
// Unregister as a listener
g_pcnet->UnregisterListener(this);
#ifdef UA_CAN_CHANGE_LANGUAGE
g_pcfiles->UnregisterFilesListener(this);
#endif
// Deallocate the component manager
OP_DELETE(m_component_manager);
}
// ___________________________________________________________________________
//
// GetUserAgentStr
//
// ___________________________________________________________________________
//
//
#ifndef SC_UA_EXTERNAL
int UAManager::GetUserAgentStr(BOOL full, char *buffer, int buf_len, const uni_char *host, Window *win, UA_BaseStringId force_ua, BOOL use_ua_utn)
{
//Yes compiler, we declare and possibly do not use these variables..
(void)use_ua_utn;
int len = 0;
UA_BaseStringId identify_as;
if (force_ua == UA_NotOverridden)
{
// Optimization when host override handling is taken care of outside
// UAManager (as in ServerManager).
if (host)
{
identify_as = static_cast<UA_BaseStringId>
(g_pcnet->GetIntegerPref(PrefsCollectionNetwork::UABaseId, host));
}
else
{
identify_as = m_UA_SelectedStringId;
}
}
else
{
identify_as = force_ua;
}
// Set up parameters for OpUAComponentManager.
OpUAComponentManager::Args ua_args =
{
identify_as
, host
, win ? win->GetWindowCommander() : NULL
# ifdef IMODE_EXTENSIONS
, use_ua_utn
# endif
};
if (m_language.IsEmpty())
{
OP_STATUS rc;
if (OpStatus::IsError(rc = m_language.Set(g_languageManager->GetLanguage().CStr())))
{
m_language.Set("und"); // Undetermined, cf. RFC 5646
if (OpStatus::IsMemoryError(rc))
g_memory_manager->RaiseCondition(rc);
}
}
#if defined SOFTCORE_CUSTOM_UA && defined PREFS_HAVE_CUSTOM_UA
OpStringC customua(g_pccore->GetStringPref(PrefsCollectionCore::CustomUAString, host));
if (!customua.IsEmpty())
{
uni_cstrlcpy(buffer, customua.CStr(), buf_len);
return op_strlen(buffer);
}
#endif
if (buf_len > 0)
{
#ifdef COMPONENT_IN_UASTRING_SUPPORT
// Get the extended comment string
if (m_comment_string.IsEmpty()
# ifdef IMODE_EXTENSIONS
|| m_comment_string_utn.IsEmpty()
# endif
)
{
// First call or components changed - need to build our
// comments string.
OP_STATUS rc = AssembleComponents();
if (OpStatus::IsMemoryError(rc))
{
g_memory_manager->RaiseCondition(rc);
}
}
const char *comment_trailer =
# ifdef IMODE_EXTENSIONS
use_ua_utn ? m_comment_string_utn.CStr() :
# endif
# ifdef SC_UA_COMPONENT_FOR_OPERA_ONLY
(identify_as == UA_Opera) ? m_comment_string.CStr() : NULL;
# else
m_comment_string.CStr();
# endif // SC_UA_COMPONEN_FOR_OPERA_ONLY
#elif defined SC_UA_CONTEXT_COMPONENTS
// Get the context-dependent comment string
const char *comment_trailer =
m_component_manager->GetCommentString(ua_args, m_language.CStr());
#else
// No comment
const char *comment_trailer = NULL;
#endif
char* buf_p = buffer;
int remaining_buf = buf_len;
#if defined TOKEN_IN_UASTRING_SUPPORT || defined SC_UA_CONTEXT_COMPONENTS
// Add the prefix
# ifdef SC_UA_CONTEXT_COMPONENTS
// Get the context-dependent prefix string
const char *prefix = m_component_manager->GetPrefixString(ua_args);
if (full && prefix && *prefix)
# else
if (full && !m_prefix.IsEmpty())
# endif
{
// There is a prefix, add it and advance the buffer pointer
# ifdef SC_UA_CONTEXT_COMPONENTS
len = op_snprintf(buf_p, remaining_buf, "%s ", prefix);
# else
len = op_snprintf(buf_p, remaining_buf, "%s ", m_prefix.CStr());
# endif
if (len >= remaining_buf)
return buf_len - 1;
buf_p += len;
remaining_buf -= len;
}
#endif
const char *osstr = m_component_manager->GetOSString(ua_args);
len = op_snprintf(buf_p, remaining_buf, GetUserAgent(identify_as, full),
osstr, comment_trailer ? "; " : "", comment_trailer ? comment_trailer : "");
if (len >= remaining_buf)
return buf_len - 1;
buf_p += len;
remaining_buf -= len;
#ifdef SOFTCORE_UA_CORE_VERSION
// Core version is non-NULL, and we're identifying as Opera
if (full && SOFTCORE_UA_CORE_VERSION && IsOperaUA(identify_as))
{
len = op_snprintf(buf_p, remaining_buf, " %s/%s", SOFTCORE_UA_CORE_VERSION, CORE_VERSION_STRING);
if (len >= remaining_buf)
return buf_len - 1;
buf_p += len;
remaining_buf -= len;
}
#endif
#ifdef SC_UA_VERSION_TAG
// Core version is non-NULL, and we're identifying as Opera
if (full && IsOperaUA(identify_as))
{
len = op_snprintf(buf_p, remaining_buf, " Version/%s", VER_NUM_STR);
if (len >= remaining_buf)
return buf_len - 1;
buf_p += len;
remaining_buf -= len;
}
#endif // SC_UA_VERSION_TAG
#if defined TOKEN_IN_UASTRING_SUPPORT || defined SC_UA_CONTEXT_COMPONENTS
// Add the suffix
# ifdef SC_UA_CONTEXT_COMPONENTS
// Get the context-dependent suffix string
const char *suffix = m_component_manager->GetSuffixString(ua_args);
if (full && suffix && *suffix)
# else
if (full && !m_suffix.IsEmpty())
# endif
{
# ifdef SC_UA_CONTEXT_COMPONENTS
op_snprintf(buf_p, remaining_buf, " %s", suffix);
# else
op_snprintf(buf_p, remaining_buf, " %s", m_suffix.CStr());
# endif
}
#endif
len = op_strlen(buffer);
}
return len;
}
#endif // SC_UA_EXTERNAL
void UAManager::PrefChanged(OpPrefsCollection::Collections id, int pref, int newvalue)
{
if (OpPrefsCollection::Network == id &&
PrefsCollectionNetwork::UABaseId == pref)
{
m_UA_SelectedStringId =
(newvalue > 0 && (newvalue < UA_MozillaOnly || IsOperaUA(static_cast<enum UA_BaseStringId>(newvalue)))
? (UA_BaseStringId) newvalue
: UA_MSIE);
if (urlManager)
{
urlManager->UpdateUAOverrides();
}
}
}
#ifdef PREFS_HOSTOVERRIDE
void UAManager::HostOverrideChanged(OpPrefsCollection::Collections /* id */,
const uni_char *hostname)
{
ServerName *sn = g_url_api->GetServerName(hostname);
if (sn)
sn->UpdateUAOverrides();
}
#endif
#ifdef UA_CAN_CHANGE_LANGUAGE
void UAManager::FileChangedL(PrefsCollectionFiles::filepref pref, const OpFile *newvalue)
{
if (pref == PrefsCollectionFiles::LanguageFile)
{
// Forget the current language. The new language isn't loaded yet,
// so we postpone reading the language until the next call.
m_language.Empty();
# ifdef COMPONENT_IN_UASTRING_SUPPORT
// We need to re-assemble the comment string next time.
m_comment_string.Empty();
# endif
}
}
#endif
const char *UAManager::GetUserAgent(UA_BaseStringId identify_as, BOOL full)
{
switch (identify_as)
{
case UA_Opera:
default:
#ifdef VER_NUM_FORCE_STR
return "Opera/" VER_NUM_FORCE_STR " (%s%s%s)" + (full ? 0 : 6);
#else
return "Opera/" VER_NUM_STR " (%s%s%s)" + (full ? 0 : 6);
#endif // VER_NUM_FORCE_STR
case UA_Mozilla:
if (full)
return "Mozilla/" SOFTCORE_UA_MOZILLA_SPOOF_VERSION " (%s%s%s; rv:"
SOFTCORE_UA_MOZILLA_REVISION ") Gecko/" SOFTCORE_UA_MOZILLA_GECKO_DATE
" Firefox/" SOFTCORE_UA_FIREFOX_VERSION " Opera " VER_NUM_STR;
else
return SOFTCORE_UA_MOZILLA_SPOOF_VERSION " (%s%s%s; rv:"
SOFTCORE_UA_MOZILLA_REVISION ")";
case UA_MSIE:
if (full)
return "Mozilla/5.0 (compatible; MSIE " SOFTCORE_UA_MSIE_SPOOF_VERSION "; %s%s%s) Opera " VER_NUM_STR;
else
return "5.0 (compatible; MSIE " SOFTCORE_UA_MSIE_SPOOF_VERSION "; %s%s%s)";
#ifdef URL_TVSTORE_UA
case UA_TVStore:
#ifdef VER_NUM_FORCE_STR
return "Opera/" VER_NUM_FORCE_STR " (%s; Opera TV Store/" VER_BUILD_IDENTIFIER "%s%s)" + (full ? 0 : 6);
#else
return "Opera/" VER_NUM_STR " (%s; Opera TV Store/" VER_BUILD_IDENTIFIER "%s%s)" + (full ? 0 : 6);
#endif // VER_NUM_FORCE_STR
#endif // URL_TVSTORE_UA
#ifdef IMODE_EXTENSIONS
case UA_IMODE:
return "DoCoMo/1.0/Opera" VER_NUM_STR "/c20/TB/W10H10" + (full ? 0 : 8);
#endif
case UA_MozillaOnly:
if (full)
return "Mozilla/" SOFTCORE_UA_MOZILLA_SPOOF_VERSION " (%s%s%s; rv:"
SOFTCORE_UA_MOZILLA_REVISION ") Gecko/" SOFTCORE_UA_MOZILLA_GECKO_DATE
" Firefox/" SOFTCORE_UA_FIREFOX_VERSION;
else
return SOFTCORE_UA_MOZILLA_SPOOF_VERSION " (%s%s%s; rv:"
SOFTCORE_UA_MOZILLA_REVISION ")";
case UA_MSIE_Only:
return "Mozilla/5.0 (compatible; MSIE " SOFTCORE_UA_MSIE_SPOOF_VERSION "; %s; "
"Trident/" SOFTCORE_UA_MSIE_TRIDENT "%s%s)"
+ (full ? 0 : 8);
case UA_Mozilla_478:
if (full)
return "Mozilla/4.78 (%s%s%s) Opera " VER_NUM_STR;
else
return "4.78 (%s%s%s)";
}
}
#ifdef UA_NEED_GET_VERSION_CODE
/*static*/
OP_STATUS UAManager::PickSpoofVersionString(UA_BaseStringId use_id, int, OpString8 &target)
{
const char *verstr;
switch(use_id)
{
case UA_MozillaOnly:
case UA_Mozilla:
verstr = SOFTCORE_UA_MOZILLA_SPOOF_VERSION; /* "5.0" */
break;
case UA_MSIE:
case UA_MSIE_Only:
verstr = SOFTCORE_UA_MSIE_SPOOF_VERSION; /* "6.0" */
break;
case UA_Opera:
verstr = VER_NUM_STR;
break;
default:
verstr = "";
}
return target.Set(verstr);
}
#endif // UA_NEED_GET_VERSION_CODE
/* static */
UA_BaseStringId UAManager::OverrideUserAgent(const ServerName *host)
{
(void)host; //Yes compiler, we declare and possibly do not use this variable..
#ifdef PREFS_HOSTOVERRIDE
if (host && host->UniName() != NULL)
{
UA_BaseStringId current_id = g_uaManager->GetUABaseId();
// Check if User-Agent string is overridden for this host by the
// preferences.
HostOverrideStatus is_overridden =
g_pcnet->IsHostOverridden(host->UniName(), FALSE);
if (is_overridden == HostOverrideActive
#ifdef PREFSFILE_WRITE_GLOBAL
|| is_overridden == HostOverrideDownloadedActive
#endif
)
{
UA_BaseStringId overridden_id =
UA_BaseStringId(g_pcnet->GetIntegerPref(PrefsCollectionNetwork::UABaseId, host));
if (overridden_id != current_id)
return overridden_id;
}
}
#endif
return UA_NotOverridden;
}
#ifdef COMPONENT_IN_UASTRING_SUPPORT
OP_STATUS UAManager::AddComponent(const char * component_string, BOOL only_utn)
{
#ifndef IMODE_EXTENSIONS
OP_ASSERT(!only_utn);
if (only_utn)
{
return OpStatus::ERR_NOT_SUPPORTED;
}
#endif
// Recompose comment string next time
m_comment_string.Empty();
// Add the component if it isn't already there
OP_STATUS status = OpStatus::OK;
if (FindComponent(component_string) == -1)
{
ua_component * newitem = OP_NEW(ua_component, ());
if (newitem)
{
status = newitem->m_componentstring.Set(component_string);
if (OpStatus::IsSuccess(status))
{
#ifdef IMODE_EXTENSIONS
newitem->m_only_utn = only_utn;
#endif
status = m_components.Add(newitem);
}
}
else
status = OpStatus::ERR_NO_MEMORY;
} // else,.. duplicates ignored
return status;
}
#endif // COMPONENT_IN_UASTRING_SUPPORT
#ifdef COMPONENT_IN_UASTRING_SUPPORT
void UAManager::RemoveComponent(const char * component_string)
{
// Recompose comment string next time
m_comment_string.Empty();
// Delete the component if we can find it
int entry = FindComponent(component_string);
if (entry >= 0)
m_components.Delete(entry);
}
#endif // COMPONENT_IN_UASTRING_SUPPORT
#ifdef COMPONENT_IN_UASTRING_SUPPORT
/**
* Find a component in the comment string.
*
* @param component_string String to locat
* @return Index, or -1 if not found
*/
int UAManager::FindComponent(const char * component_string)
{
int entry = -1;
int maxcomponents = m_components.GetCount();
for (int i = 0; i < maxcomponents; i ++)
{
if (op_strcmp(m_components.Get(i)->m_componentstring.CStr(), component_string) == 0)
{
entry = i;
break;
}
}
return entry;
}
#endif // COMPONENT_IN_UASTRING_SUPPORT
#ifdef COMPONENT_IN_UASTRING_SUPPORT
/**
* Assemble the components for the comment string. The last component
* is always the language file, so given that we have enough memory
* to perform our work, m_comment_string should never be empty after
* this function is called.
*
* @return Status of the operation
*/
OP_STATUS UAManager::AssembleComponents()
{
m_comment_string.Empty();
BOOL first = TRUE;
#ifdef IMODE_EXTENSIONS
m_comment_string_utn.Empty();
BOOL imodeFirst = TRUE;
#endif
if (g_pccore->GetIntegerPref(PrefsCollectionCore::AllowComponentsInUAStringComment))
{
int maxcomponents = m_components.GetCount();
for (int i = 0; i < maxcomponents; i ++)
{
ua_component *p = m_components.Get(i);
#ifdef IMODE_EXTENSIONS
if (!imodeFirst)
RETURN_IF_ERROR(m_comment_string_utn.Append("; "));
imodeFirst = FALSE;
RETURN_IF_ERROR(m_comment_string_utn.Append(p->m_componentstring));
if (!p->m_only_utn)
#endif
{
if (!first)
RETURN_IF_ERROR(m_comment_string.Append("; "));
first = FALSE;
RETURN_IF_ERROR(m_comment_string.Append(p->m_componentstring));
}
}
}
// Add the ISP id (dgisp) at the end of the component list, if one
// is listed in the ini file.
OpStringC isp_id =
g_pcnet->GetStringPref(PrefsCollectionNetwork::IspUserAgentId);
if (isp_id.Length())
{
OpString8 isp_id8;
RETURN_IF_ERROR(isp_id8.SetUTF8FromUTF16(isp_id.CStr()));
if (!first)
RETURN_IF_ERROR(m_comment_string.Append("; "));
RETURN_IF_ERROR(m_comment_string.Append(isp_id8));
#ifdef IMODE_EXTENSIONS
if (!imodeFirst)
RETURN_IF_ERROR(m_comment_string_utn.Append("; "));
RETURN_IF_ERROR(m_comment_string_utn.Append(isp_id8));
#endif
}
return OpStatus::OK;
}
#endif // COMPONENT_IN_UASTRING_SUPPORT
|
#include "classes/particle.h"
void Particle::integrate(float duration)
{
asert(duration > 0.0);
//Update using Verlet integration
Vector3 lastAcc = acceleration;
Vector3 newAcc = force*inverseMass
Vector3 avgAcc = (lastAcc + newAcc)*.5;
position.addScaledVector(velocity, duration);
position.addScaledVector(lastAcc, duration*duration*.5);
velocity *= powf(damping, duration);
velocity.addScaledVector(avgAcc, duration);
}
|
#pragma once
#include<cocos2d.h>
#include<ctime>
USING_NS_CC;
class WorldTime : public Sprite
{
public:
CREATE_FUNC(WorldTime);
virtual bool init();
static WorldTime* getInstance();
clock_t getTime();
DWORD DelayBegin, DelayEnd, DelayTime;
private:
static WorldTime* _instance;
};
|
/*
* Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com>
* Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com>
* Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com>
* Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com>
* Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net>
* Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com>
* Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "gtests/dtoin/TestDtoinHelper.hh"
#include "dtoin/BalanceCostDtoin.hh"
#include "dtoin/MachineDtoin.hh"
#include "dtoin/PoidsDtoin.hh"
#include "dtoin/ProcessDtoin.hh"
#include "dtoin/RessourceDtoin.hh"
#include "dtoin/ServiceDtoin.hh"
#include "dtoin/SolutionDtoin.hh"
#include <sstream>
using namespace std;
void TestDtoinHelper::loadTestDataRessource(ContextBO* pContextBO_p){
RessourceDtoin reader_l;
istringstream iss_l(getRessourceTestData());
reader_l.read(iss_l, pContextBO_p);
}
void TestDtoinHelper::loadTestDataMachine(ContextBO* pContextBO_p){
MachineDtoin reader_l;
istringstream iss_l(getMachineTestData());
reader_l.read(iss_l, pContextBO_p);
}
void TestDtoinHelper::loadTestDataService(ContextBO* pContextBO_p){
ServiceDtoin reader_l;
istringstream iss_l(getServiceTestData());
reader_l.read(iss_l, pContextBO_p);
}
void TestDtoinHelper::loadTestDataProcess(ContextBO* pContextBO_p){
ProcessDtoin reader_l;
istringstream iss_l(getProcessTestData());
reader_l.read(iss_l, pContextBO_p);
}
void TestDtoinHelper::loadTestDataBalanceCost(ContextBO* pContextBO_p){
BalanceCostDtoin reader_l;
istringstream iss_l(getBalanceCostTestData());
reader_l.read(iss_l, pContextBO_p);
}
void TestDtoinHelper::loadTestDataPoids(ContextBO* pContextBO_p){
PoidsDtoin reader_l;
istringstream iss_l(getPoidsTestData());
reader_l.read(iss_l, pContextBO_p);
}
void TestDtoinHelper::loadTestDataSolInit(ContextBO* pContextBO_p){
SolutionDtoin reader_l;
istringstream iss_l(getSolInitTestData());
reader_l.read(iss_l, pContextBO_p);
}
string TestDtoinHelper::getMachineTestData(){
return string("4 \
\
0 \
0 \
30 400 \
16 80 \
0 1 4 5 \
\
0 \
0 \
10 240 \
8 160 \
1 0 3 4 \
\
1 \
1 \
15 100 \
12 80 \
4 3 0 2 \
\
1 \
2 \
10 100 \
8 80 \
5 4 2 0");
}
string TestDtoinHelper::getRessourceTestData(){
return string("2 \
\
1 \
100 \
\
0 \
10");
}
string TestDtoinHelper::getServiceTestData(){
return string("2 \
\
2 \
0 \
\
1 \
1 \
0 \
\
3 \
0 \
12 10 \
1000 \
\
0 \
10 20 \
100 \
\
1 \
6 200 \
1");
}
string TestDtoinHelper::getProcessTestData(){
return string("3 \
0 \
12 10 \
1000 \
\
0 \
10 20 \
100 \
\
1 \
6 200 \
1");
}
string TestDtoinHelper::getBalanceCostTestData(){
return string("1 \
0 1 20 \
10");
}
string TestDtoinHelper::getPoidsTestData(){
return string("1 \
10 \
100");
}
string TestDtoinHelper::getSolInitTestData(){
return string("0 3 0");
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2007-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef MEMORY_REPORTING_H
#define MEMORY_REPORTING_H
#ifdef ENABLE_MEMORY_DEBUGGING
#include "modules/memory/src/memory_events.h"
class OpMemReporting : public OpMemEventListener
{
public:
OpMemReporting(void);
virtual void MemoryEvent(OpMemEvent* event);
void PrintStatistics(void);
void SetMemoryMaxErrorCount(int value) { memory_max_error_count = value; }
//
// This will avoid getting leak-errors for this object. We don't want
// to destroy this object too early or else we will miss memory events.
// FIXME: Actually destroy this object somewhere.
//
void* operator new(size_t size) OP_NOTHROW { return op_lowlevel_malloc(size); }
void operator delete(void* ptr) { op_lowlevel_free(ptr); }
private:
int event_count;
int suppressed_event_count;
int memory_max_error_count;
void EventKeywords(char* buffer, OpMemEvent* event);
void LogAllocate(OpMemEvent* event);
void LogFree(OpMemEvent* event);
};
#endif // ENABLE_MEMORY_DEBUGGING
#endif // MEMORY_REPORTING_H
|
#ifndef HWMEDIADECODER_H
#define HWMEDIADECODER_H
#include <android/native_window_jni.h>
struct StreamDecodedataParameter
{
char *minetype;
int width;
int height;
ANativeWindow *window;
int channels;
int samplerate;
};
class CHwMediaDecoder
{
public:
CHwMediaDecoder() { m_codecid = -1;}
virtual ~CHwMediaDecoder() {}
public: //音频输出: aac, 视频输出: yuv
virtual int Decode(unsigned char *pktBuf, int pktLen, int64_t presentationTimeUs, unsigned char *outBuf) = 0;
public:
int m_codecid; //输出编码格式
int m_param1;
int m_param2;
int m_videow;
int m_videoh;
};
#endif
|
#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>
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;
struct Tp {
int x, y;
} a[33];
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
int T;
scanf("%d", &T);
for (int __it = 0; __it < T; ++__it) {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &a[i].x, &a[i].y);
}
int cnt = 0, ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int A1 = (- a[i].x + a[j].x) * 2;
int B1 = (a[j].y - a[i].y) * 2;
int C1 = - A1 * (a[i].x + a[j].x) / 2 - B1 * (a[i].y + a[j].y) / 2;
for (int k = j + 1; k < n; ++k) {
int A2 = (- a[i].x + a[k].x) * 2;
int B2 = (a[k].y - a[i].y) * 2;
int C2 = - A2 * (a[i].x + a[k].x) / 2 - B2 * (a[i].y + a[k].y) / 2;
cnt += n - 3;
if (A1 * B2 == A2 * B1) continue;
int d = A1 * B2 - A2 * B1;
double cx = double(-C1 * B2 + C2 * B1) / d;
double cy = double(-A1 * C2 + C1 * A2) / d;
double R = sqr(a[i].x - cx) + sqr(a[i].y - cy);
for (int ai = 0; ai < n; ++ai)
if (ai != i && ai != j && ai != k) {
if (sqr(a[ai].x - cx) + sqr(a[ai].y - cy) <= R + 1e-6) {
++ans;
}
}
}
}
}
if (cnt == 0) cnt = 1;
cout.precision(12);
cout << fixed << double(ans) / cnt << endl;
}
return 0;
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
bool asc = true, des = true;
for (int i = 1; i <= 8; ++i)
{
int a;
std::cin >> a;
asc = asc && a == i;
des = des && a == (9 - i);
}
std::cout << (asc ? "ascending" : (des ? "descending" : "mixed")) << '\n';
return 0;
}
|
/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.14.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFrame>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *open;
QAction *save;
QAction *actionExit;
QWidget *centralWidget;
QHBoxLayout *horizontalLayout;
QWidget *working_widget;
QHBoxLayout *horizontalLayout_9;
QWidget *utils;
QVBoxLayout *verticalLayout;
QWidget *widget;
QVBoxLayout *button_layout;
QVBoxLayout *verticalLayout_2;
QWidget *verticalWidget_2;
QVBoxLayout *verticalLayout_3;
QLabel *label_4;
QHBoxLayout *horizontalLayout_2;
QPushButton *pushButton_4;
QPushButton *pushButton_2;
QHBoxLayout *horizontalLayout_5;
QPushButton *pushButton;
QPushButton *pushButton_3;
QVBoxLayout *verticalLayout_5;
QWidget *verticalWidget_3;
QVBoxLayout *verticalLayout_4;
QLabel *label_5;
QHBoxLayout *horizontalLayout_3;
QLabel *label_3;
QSpinBox *som;
QHBoxLayout *horizontalLayout_4;
QLabel *label_2;
QSpinBox *are;
QVBoxLayout *verticalLayout_14;
QHBoxLayout *horizontalLayout_20;
QHBoxLayout *horizontalLayout_21;
QPushButton *reset;
QPushButton *Generate;
QLabel *label_6;
QVBoxLayout *verticalLayout_11;
QHBoxLayout *horizontalLayout_15;
QPushButton *pushButton_9;
QHBoxLayout *horizontalLayout_16;
QPushButton *pushButton_5;
QVBoxLayout *verticalLayout_12;
QHBoxLayout *horizontalLayout_17;
QHBoxLayout *horizontalLayout_18;
QPushButton *pushButton_7;
QPushButton *pushButton_8;
QVBoxLayout *verticalLayout_15;
QHBoxLayout *horizontalLayout_22;
QLabel *label;
QLabel *label_9;
QLabel *label_8;
QLabel *label_7;
QTextEdit *textEdit;
QFrame *pushButton_6;
QSpacerItem *verticalSpacer;
QWidget *graphLayout_2;
QVBoxLayout *graphLayout;
QMenuBar *menuBar;
QMenu *menuFile;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(1024, 792);
MainWindow->setMinimumSize(QSize(720, 540));
MainWindow->setMaximumSize(QSize(16777215, 16777215));
MainWindow->setStyleSheet(QString::fromUtf8("selection-color: rgb(255, 255, 255);"));
open = new QAction(MainWindow);
open->setObjectName(QString::fromUtf8("open"));
QIcon icon;
icon.addFile(QString::fromUtf8(":/new/prefix1/open.png"), QSize(), QIcon::Normal, QIcon::Off);
open->setIcon(icon);
open->setIconVisibleInMenu(true);
save = new QAction(MainWindow);
save->setObjectName(QString::fromUtf8("save"));
QIcon icon1;
icon1.addFile(QString::fromUtf8(":/new/prefix1/save.png"), QSize(), QIcon::Normal, QIcon::Off);
save->setIcon(icon1);
actionExit = new QAction(MainWindow);
actionExit->setObjectName(QString::fromUtf8("actionExit"));
actionExit->setEnabled(true);
QIcon icon2;
icon2.addFile(QString::fromUtf8(":/new/prefix1/exit.png"), QSize(), QIcon::Normal, QIcon::Off);
actionExit->setIcon(icon2);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
centralWidget->setStyleSheet(QString::fromUtf8("background-color: rgb(0, 0, 0);"));
horizontalLayout = new QHBoxLayout(centralWidget);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
working_widget = new QWidget(centralWidget);
working_widget->setObjectName(QString::fromUtf8("working_widget"));
working_widget->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 255);"));
horizontalLayout_9 = new QHBoxLayout(working_widget);
horizontalLayout_9->setSpacing(6);
horizontalLayout_9->setContentsMargins(11, 11, 11, 11);
horizontalLayout_9->setObjectName(QString::fromUtf8("horizontalLayout_9"));
horizontalLayout_9->setContentsMargins(0, 0, 0, 0);
utils = new QWidget(working_widget);
utils->setObjectName(QString::fromUtf8("utils"));
utils->setMaximumSize(QSize(270, 16777215));
verticalLayout = new QVBoxLayout(utils);
verticalLayout->setSpacing(0);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
widget = new QWidget(utils);
widget->setObjectName(QString::fromUtf8("widget"));
widget->setStyleSheet(QString::fromUtf8("background-color: rgb(0, 0, 0);"));
button_layout = new QVBoxLayout(widget);
button_layout->setSpacing(6);
button_layout->setContentsMargins(11, 11, 11, 11);
button_layout->setObjectName(QString::fromUtf8("button_layout"));
button_layout->setSizeConstraint(QLayout::SetMinimumSize);
verticalLayout_2 = new QVBoxLayout();
verticalLayout_2->setSpacing(6);
verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2"));
verticalWidget_2 = new QWidget(widget);
verticalWidget_2->setObjectName(QString::fromUtf8("verticalWidget_2"));
verticalWidget_2->setStyleSheet(QString::fromUtf8(""));
verticalLayout_3 = new QVBoxLayout(verticalWidget_2);
verticalLayout_3->setSpacing(6);
verticalLayout_3->setContentsMargins(11, 11, 11, 11);
verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3"));
label_4 = new QLabel(verticalWidget_2);
label_4->setObjectName(QString::fromUtf8("label_4"));
label_4->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));
verticalLayout_3->addWidget(label_4);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
horizontalLayout_2->setContentsMargins(-1, 0, -1, -1);
pushButton_4 = new QPushButton(verticalWidget_2);
pushButton_4->setObjectName(QString::fromUtf8("pushButton_4"));
pushButton_4->setMinimumSize(QSize(0, 20));
pushButton_4->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);\n"
"background-color: rgb(255, 0, 127);"));
horizontalLayout_2->addWidget(pushButton_4);
pushButton_2 = new QPushButton(verticalWidget_2);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
pushButton_2->setEnabled(true);
pushButton_2->setMinimumSize(QSize(0, 20));
pushButton_2->setStyleSheet(QString::fromUtf8("color: rgb(0, 0, 0);\n"
"background-color: rgb(170, 255, 127);"));
pushButton_2->setAutoDefault(false);
horizontalLayout_2->addWidget(pushButton_2);
verticalLayout_3->addLayout(horizontalLayout_2);
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setSpacing(6);
horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5"));
horizontalLayout_5->setSizeConstraint(QLayout::SetDefaultConstraint);
horizontalLayout_5->setContentsMargins(-1, 0, -1, -1);
pushButton = new QPushButton(verticalWidget_2);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
pushButton->setMinimumSize(QSize(0, 20));
pushButton->setStyleSheet(QString::fromUtf8("color: rgb(0, 0, 0);\n"
"background-color: rgb(170, 255, 255);"));
horizontalLayout_5->addWidget(pushButton);
pushButton_3 = new QPushButton(verticalWidget_2);
pushButton_3->setObjectName(QString::fromUtf8("pushButton_3"));
pushButton_3->setMinimumSize(QSize(0, 20));
pushButton_3->setStyleSheet(QString::fromUtf8("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 255, 127);"));
horizontalLayout_5->addWidget(pushButton_3);
verticalLayout_3->addLayout(horizontalLayout_5);
verticalLayout_2->addWidget(verticalWidget_2);
button_layout->addLayout(verticalLayout_2);
verticalLayout_5 = new QVBoxLayout();
verticalLayout_5->setSpacing(6);
verticalLayout_5->setObjectName(QString::fromUtf8("verticalLayout_5"));
verticalWidget_3 = new QWidget(widget);
verticalWidget_3->setObjectName(QString::fromUtf8("verticalWidget_3"));
verticalWidget_3->setStyleSheet(QString::fromUtf8(""));
verticalLayout_4 = new QVBoxLayout(verticalWidget_3);
verticalLayout_4->setSpacing(6);
verticalLayout_4->setContentsMargins(11, 11, 11, 11);
verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4"));
label_5 = new QLabel(verticalWidget_3);
label_5->setObjectName(QString::fromUtf8("label_5"));
label_5->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));
verticalLayout_4->addWidget(label_5);
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setSpacing(6);
horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3"));
label_3 = new QLabel(verticalWidget_3);
label_3->setObjectName(QString::fromUtf8("label_3"));
label_3->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));
horizontalLayout_3->addWidget(label_3);
som = new QSpinBox(verticalWidget_3);
som->setObjectName(QString::fromUtf8("som"));
som->setStyleSheet(QString::fromUtf8("\n"
"background-color: rgb(255, 255, 255);"));
som->setMaximum(100);
horizontalLayout_3->addWidget(som);
verticalLayout_4->addLayout(horizontalLayout_3);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setSpacing(6);
horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4"));
label_2 = new QLabel(verticalWidget_3);
label_2->setObjectName(QString::fromUtf8("label_2"));
label_2->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));
horizontalLayout_4->addWidget(label_2);
are = new QSpinBox(verticalWidget_3);
are->setObjectName(QString::fromUtf8("are"));
are->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 255);"));
are->setMaximum(300);
horizontalLayout_4->addWidget(are);
verticalLayout_4->addLayout(horizontalLayout_4);
verticalLayout_14 = new QVBoxLayout();
verticalLayout_14->setSpacing(6);
verticalLayout_14->setObjectName(QString::fromUtf8("verticalLayout_14"));
horizontalLayout_20 = new QHBoxLayout();
horizontalLayout_20->setSpacing(6);
horizontalLayout_20->setObjectName(QString::fromUtf8("horizontalLayout_20"));
horizontalLayout_21 = new QHBoxLayout();
horizontalLayout_21->setSpacing(6);
horizontalLayout_21->setObjectName(QString::fromUtf8("horizontalLayout_21"));
reset = new QPushButton(verticalWidget_3);
reset->setObjectName(QString::fromUtf8("reset"));
reset->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);\n"
"background-color: rgb(255, 0, 127);"));
horizontalLayout_21->addWidget(reset);
Generate = new QPushButton(verticalWidget_3);
Generate->setObjectName(QString::fromUtf8("Generate"));
Generate->setEnabled(true);
Generate->setStyleSheet(QString::fromUtf8("background-color: rgb(170, 255, 127);\n"
"color: rgb(0, 0, 0);"));
horizontalLayout_21->addWidget(Generate);
horizontalLayout_20->addLayout(horizontalLayout_21);
verticalLayout_14->addLayout(horizontalLayout_20);
verticalLayout_4->addLayout(verticalLayout_14);
verticalLayout_5->addWidget(verticalWidget_3);
label_6 = new QLabel(widget);
label_6->setObjectName(QString::fromUtf8("label_6"));
label_6->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);\n"
"background-color: rgb(255 255, 255);"));
verticalLayout_5->addWidget(label_6);
button_layout->addLayout(verticalLayout_5);
verticalLayout_11 = new QVBoxLayout();
verticalLayout_11->setSpacing(6);
verticalLayout_11->setObjectName(QString::fromUtf8("verticalLayout_11"));
horizontalLayout_15 = new QHBoxLayout();
horizontalLayout_15->setSpacing(6);
horizontalLayout_15->setObjectName(QString::fromUtf8("horizontalLayout_15"));
pushButton_9 = new QPushButton(widget);
pushButton_9->setObjectName(QString::fromUtf8("pushButton_9"));
pushButton_9->setMinimumSize(QSize(0, 20));
pushButton_9->setStyleSheet(QString::fromUtf8("background-color: rgb(170, 255, 255);\n"
"color: rgb(0, 0, 0);"));
horizontalLayout_15->addWidget(pushButton_9);
horizontalLayout_16 = new QHBoxLayout();
horizontalLayout_16->setSpacing(6);
horizontalLayout_16->setObjectName(QString::fromUtf8("horizontalLayout_16"));
pushButton_5 = new QPushButton(widget);
pushButton_5->setObjectName(QString::fromUtf8("pushButton_5"));
pushButton_5->setStyleSheet(QString::fromUtf8("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 255, 127);"));
horizontalLayout_16->addWidget(pushButton_5);
horizontalLayout_15->addLayout(horizontalLayout_16);
verticalLayout_11->addLayout(horizontalLayout_15);
verticalLayout_12 = new QVBoxLayout();
verticalLayout_12->setSpacing(6);
verticalLayout_12->setObjectName(QString::fromUtf8("verticalLayout_12"));
horizontalLayout_17 = new QHBoxLayout();
horizontalLayout_17->setSpacing(6);
horizontalLayout_17->setObjectName(QString::fromUtf8("horizontalLayout_17"));
horizontalLayout_18 = new QHBoxLayout();
horizontalLayout_18->setSpacing(6);
horizontalLayout_18->setObjectName(QString::fromUtf8("horizontalLayout_18"));
pushButton_7 = new QPushButton(widget);
pushButton_7->setObjectName(QString::fromUtf8("pushButton_7"));
pushButton_7->setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);\n"
"background-color: rgb(255, 0, 127);"));
horizontalLayout_18->addWidget(pushButton_7);
horizontalLayout_17->addLayout(horizontalLayout_18);
pushButton_8 = new QPushButton(widget);
pushButton_8->setObjectName(QString::fromUtf8("pushButton_8"));
pushButton_8->setStyleSheet(QString::fromUtf8("color: rgb(0, 0, 0);\n"
"background-color: rgb(170, 255, 127);"));
horizontalLayout_17->addWidget(pushButton_8);
verticalLayout_12->addLayout(horizontalLayout_17);
verticalLayout_11->addLayout(verticalLayout_12);
verticalLayout_15 = new QVBoxLayout();
verticalLayout_15->setSpacing(6);
verticalLayout_15->setObjectName(QString::fromUtf8("verticalLayout_15"));
horizontalLayout_22 = new QHBoxLayout();
horizontalLayout_22->setSpacing(6);
horizontalLayout_22->setObjectName(QString::fromUtf8("horizontalLayout_22"));
label = new QLabel(widget);
label->setObjectName(QString::fromUtf8("label"));
label->setEnabled(true);
label->setMinimumSize(QSize(10, 10));
label->setMaximumSize(QSize(50, 16));
label->setStyleSheet(QString::fromUtf8("background-color: rgb(0, 0, 0);"));
label->setPixmap(QPixmap(QString::fromUtf8(":/new/Qrc/Capture2.PNG")));
label->setScaledContents(false);
label->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
label->setWordWrap(false);
horizontalLayout_22->addWidget(label);
label_9 = new QLabel(widget);
label_9->setObjectName(QString::fromUtf8("label_9"));
label_9->setStyleSheet(QString::fromUtf8("background-color: rgb(0, 0, 0);\n"
"color: rgb(255, 255, 255);"));
horizontalLayout_22->addWidget(label_9);
label_8 = new QLabel(widget);
label_8->setObjectName(QString::fromUtf8("label_8"));
label_8->setStyleSheet(QString::fromUtf8("\n"
"background-color: rgb(0, 0, 0);"));
label_8->setPixmap(QPixmap(QString::fromUtf8(":/new/Qrc/Capture1.PNG")));
label_8->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
horizontalLayout_22->addWidget(label_8);
label_7 = new QLabel(widget);
label_7->setObjectName(QString::fromUtf8("label_7"));
label_7->setStyleSheet(QString::fromUtf8("background-color: rgb(0, 0, 0);\n"
"color: rgb(255, 255, 255);"));
horizontalLayout_22->addWidget(label_7);
verticalLayout_15->addLayout(horizontalLayout_22);
verticalLayout_11->addLayout(verticalLayout_15);
textEdit = new QTextEdit(widget);
textEdit->setObjectName(QString::fromUtf8("textEdit"));
textEdit->setEnabled(true);
textEdit->viewport()->setProperty("cursor", QVariant(QCursor(Qt::IBeamCursor)));
textEdit->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 255);\n"
"font: 87 9pt \"Arial Black\";"));
textEdit->setReadOnly(true);
verticalLayout_11->addWidget(textEdit);
button_layout->addLayout(verticalLayout_11);
pushButton_6 = new QFrame(widget);
pushButton_6->setObjectName(QString::fromUtf8("pushButton_6"));
pushButton_6->setFrameShape(QFrame::HLine);
pushButton_6->setFrameShadow(QFrame::Sunken);
button_layout->addWidget(pushButton_6);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
button_layout->addItem(verticalSpacer);
verticalLayout->addWidget(widget);
horizontalLayout_9->addWidget(utils);
graphLayout_2 = new QWidget(working_widget);
graphLayout_2->setObjectName(QString::fromUtf8("graphLayout_2"));
graphLayout_2->setStyleSheet(QString::fromUtf8(""));
graphLayout = new QVBoxLayout(graphLayout_2);
graphLayout->setSpacing(6);
graphLayout->setContentsMargins(11, 11, 11, 11);
graphLayout->setObjectName(QString::fromUtf8("graphLayout"));
graphLayout->setContentsMargins(6, -1, -1, -1);
horizontalLayout_9->addWidget(graphLayout_2);
horizontalLayout->addWidget(working_widget);
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
menuBar->setGeometry(QRect(0, 0, 1024, 21));
menuBar->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 255);\n"
"selection-color: rgb(170, 255, 255);\n"
"selection-background-color: rgb(170, 255, 255);\n"
"\n"
""));
menuBar->setDefaultUp(false);
menuBar->setNativeMenuBar(true);
menuFile = new QMenu(menuBar);
menuFile->setObjectName(QString::fromUtf8("menuFile"));
menuFile->setStyleSheet(QString::fromUtf8("selection-background-color: rgb(255, 255, 127);\n"
"selection-color: rgb(170, 255, 255);\n"
"color: rgb(0, 0, 0);"));
menuFile->setTearOffEnabled(false);
MainWindow->setMenuBar(menuBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QString::fromUtf8("statusBar"));
statusBar->setStyleSheet(QString::fromUtf8("background-color: rgb(0, 0, 0);"));
MainWindow->setStatusBar(statusBar);
menuBar->addAction(menuFile->menuAction());
menuFile->addAction(open);
menuFile->addAction(save);
menuFile->addAction(actionExit);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QCoreApplication::translate("MainWindow", "MainWindow", nullptr));
open->setText(QCoreApplication::translate("MainWindow", "&Open Graph", nullptr));
#if QT_CONFIG(shortcut)
open->setShortcut(QCoreApplication::translate("MainWindow", "Ctrl+O", nullptr));
#endif // QT_CONFIG(shortcut)
save->setText(QCoreApplication::translate("MainWindow", "&Save", nullptr));
#if QT_CONFIG(shortcut)
save->setShortcut(QCoreApplication::translate("MainWindow", "Ctrl+S", nullptr));
#endif // QT_CONFIG(shortcut)
actionExit->setText(QCoreApplication::translate("MainWindow", "&Exit", nullptr));
#if QT_CONFIG(shortcut)
actionExit->setShortcut(QCoreApplication::translate("MainWindow", "Alt+X", nullptr));
#endif // QT_CONFIG(shortcut)
label_4->setText(QCoreApplication::translate("MainWindow", "Construction manuelle :", nullptr));
pushButton_4->setText(QCoreApplication::translate("MainWindow", "Select", nullptr));
pushButton_2->setText(QCoreApplication::translate("MainWindow", "Add Node", nullptr));
pushButton->setText(QCoreApplication::translate("MainWindow", "Remove Item ", nullptr));
pushButton_3->setText(QCoreApplication::translate("MainWindow", "Add Edge", nullptr));
label_5->setText(QCoreApplication::translate("MainWindow", "Contruction Al\303\251atoire :", nullptr));
label_3->setText(QCoreApplication::translate("MainWindow", " Node", nullptr));
label_2->setText(QCoreApplication::translate("MainWindow", " Edge", nullptr));
reset->setText(QCoreApplication::translate("MainWindow", "Reset", nullptr));
Generate->setText(QCoreApplication::translate("MainWindow", "Generate", nullptr));
label_6->setText(QCoreApplication::translate("MainWindow", "Algorithmes :", nullptr));
pushButton_9->setText(QCoreApplication::translate("MainWindow", "Steiner Tree", nullptr));
pushButton_5->setText(QCoreApplication::translate("MainWindow", "Terminals", nullptr));
pushButton_7->setText(QCoreApplication::translate("MainWindow", "Kruskal", nullptr));
pushButton_8->setText(QCoreApplication::translate("MainWindow", "Dijkstra", nullptr));
label->setText(QString());
label_9->setText(QCoreApplication::translate("MainWindow", "Terminals", nullptr));
label_8->setText(QString());
label_7->setText(QCoreApplication::translate("MainWindow", "Steiner vertices", nullptr));
menuFile->setTitle(QCoreApplication::translate("MainWindow", "&File", nullptr));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
|
#include<cstdio>
using namespace std;
int n,L,G;
int main()
{
scanf("%d%d%d",&n,&L,&G);
for(int i=1;i<=n;i++)
{
int w,h;
scanf("%d%d",&w,&h);
while(w>G || h>G)
w/=2,h/=2;
if(w<L || h<L) printf("Too Young\n");
if(w>=L && h>=L && w!=h) printf("Too Simple\n");
if(w>=L && h>=L && w==h) printf("Sometimes Naive\n");
}
}
|
//
// Created by 송지원 on 2019-10-31.
#include "iostream"
#include <string.h>
using namespace std;
int main () {
char input[101];
int ch;
int i, len;
cin.getline(input, 101);
len = strlen(input);
for (i=0; i<len; i++) {
ch = input[i];
if ((ch-'A') * (ch-'M') <= 0) ch += 13;
else if ((ch-'a') * (ch-'m') <= 0) ch += 13;
else if ((ch-'N') * (ch-'Z') <= 0) ch = ch + 12 - 'Z' + 'A';
else if ((ch-'n') * (ch-'z') <= 0) ch = ch + 12 - 'z' + 'a';
printf("%c", ch);
}
return 0;
}
|
/*
ID: stevenh6
TASK: agrinet
LANG: C++
*/
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
ofstream fout("agrinet.out");
ifstream fin("agrinet.in");
int main()
{
int sol = 0;
int connect[100] = {1};
int web[100][100];
int n;
fin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
fin >> web[i][j];
}
}
for (int i = 1; i < n; i++)// n - i, i-j, j, k
{
int indiv = 0;
int shortest;
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++)
{
if ((indiv == 0 || web[j][k] < indiv) && web[j][k] && connect[j] && !connect[k])
{
indiv = web[j][k];
shortest = k;
}
}
}
sol += indiv;
connect[shortest] = 1;
}
fout << sol << endl;
}
|
#include <SDL/SDL.h>
#include <Arduino.h>
#include <avr/io.h>
#include "component/sdcard.h"
#include "component/adc.h"
#include "component/heater.h"
#include "component/serial.h"
#include "component/display_SSD1309.h"
#include "component/display_HD44780.h"
#include "component/led_PCA9632.h"
#include "component/arduinoIO.h"
#include "component/stepper.h"
#include "../Marlin/preferences.h"
#include "../Marlin/UltiLCD2.h"
#include "../Marlin/temperature.h"
#include "../Marlin/stepper.h"
SDL_Surface *screen;
extern int8_t lcd_lib_encoder_pos_interrupt;
extern int8_t encoderDiff;
extern uint8_t __eeprom__storage[4096];
bool cardInserted = true;
int stoppedValue;
void setupGui()
{
if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
screen = SDL_SetVideoMode(1024, 600, 32, SDL_SWSURFACE);
}
unsigned long lastUpdate = SDL_GetTicks();
int key_delay;
#define KEY_REPEAT_DELAY 3
#define SCALE 3
void guiUpdate()
{
for(unsigned int n=0; n<simComponentList.size(); n++)
simComponentList[n]->tick();
if (SDL_GetTicks() - lastUpdate < 25)
return;
lastUpdate = SDL_GetTicks();
int clickX = -1, clickY = -1;
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
key_delay = 0;
break;
case SDL_KEYUP:
// If escape is pressed, quit
if (event.key.keysym.sym == SDLK_ESCAPE)
{
FILE* f = fopen("eeprom.save", "wb");
fwrite(__eeprom__storage, sizeof(__eeprom__storage), 1, f);
fclose(f);
exit(0);
}
if (event.key.keysym.sym == SDLK_p)
{
SDL_Surface* tmpSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, 128*SCALE,64*SCALE,32, 0, 0, 0, 0);
SDL_Rect src = {SCALE, SCALE, 128*SCALE,64*SCALE};
SDL_Rect dst = {0, 0, 128*SCALE,64*SCALE};
SDL_BlitSurface(screen, &src, tmpSurface, &dst);
char filename[128];
static int screenshotNr = 0;
sprintf(filename, "screen%i.bmp", screenshotNr);
screenshotNr++;
SDL_SaveBMP(tmpSurface, filename);
SDL_FreeSurface(tmpSurface);
}
break;
case SDL_MOUSEMOTION:
if (event.motion.state)
{
#ifdef ENABLE_ULTILCD2
lcd_lib_encoder_pos_interrupt += event.motion.xrel / 2;
#endif
}
break;
case SDL_MOUSEBUTTONDOWN:
clickX = event.button.x;
clickY = event.button.y;
break;
case SDL_QUIT:
{
FILE* f = fopen("eeprom.save", "wb");
fwrite(__eeprom__storage, sizeof(__eeprom__storage), 1, f);
fclose(f);
exit(0);
}
}
}
Uint8* keys = SDL_GetKeyState(NULL);
writeInput(BTN_ENC, !keys[SDLK_RETURN]);
if (keys[SDLK_RIGHT])
{
if (key_delay == 0)
{
#ifdef ENABLE_ULTILCD2
lcd_lib_encoder_pos_interrupt+=2;
#endif
#ifdef ULTIPANEL
encoderDiff+=2;
#endif
key_delay = KEY_REPEAT_DELAY;
}else
key_delay--;
}
if (keys[SDLK_LEFT])
{
if (key_delay == 0)
{
#ifdef ENABLE_ULTILCD2
lcd_lib_encoder_pos_interrupt-=2;
#endif
#ifdef ULTIPANEL
encoderDiff-=2;
#endif
key_delay = KEY_REPEAT_DELAY;
}else
key_delay--;
}
SDL_FillRect(screen, NULL, 0x000000);
for(unsigned int n=0; n<simComponentList.size(); n++)
simComponentList[n]->doDraw();
SDL_Rect rect;
rect.w = 32;
rect.h = 32;
rect.x = 128 * SCALE + 32;
rect.y = 32;
if (clickX >= rect.x && clickX <= rect.x + rect.w && clickY >= rect.y && clickY <= rect.y + rect.h)
cardInserted = !cardInserted;
SDL_FillRect(screen, &rect, cardInserted ? 0x00FF00 : 0xFF0000);
rect.y += 48;
writeInput(SDCARDDETECT, !cardInserted);
if (clickX >= rect.x && clickX <= rect.x + rect.w && clickY >= rect.y && clickY <= rect.y + rect.h)
stoppedValue = !stoppedValue;
writeInput(SAFETY_TRIGGERED_PIN, stoppedValue);
SDL_FillRect(screen, &rect, stoppedValue ? 0x00FF00 : 0xFF0000);
rect.y += 48;
SDL_Flip(screen);
}
#define PRINTER_DOWN_SCALE 2
class printerSim : public simBaseComponent
{
private:
stepperSim* x;
stepperSim* y;
stepperSim* z;
stepperSim* e0;
stepperSim* e1;
int e0stepPos, e1stepPos;
int map[X_MAX_LENGTH/PRINTER_DOWN_SCALE+1][Y_MAX_LENGTH/PRINTER_DOWN_SCALE+1];
public:
printerSim(stepperSim* x, stepperSim* y, stepperSim* z, stepperSim* e0, stepperSim* e1)
: x(x), y(y), z(z), e0(e0), e1(e1)
{
e0stepPos = e0->getPosition();
e1stepPos = e1->getPosition();
memset(map, 0, sizeof(map));
}
virtual ~printerSim()
{
}
void draw(int _x, int _y)
{
drawRect(_x, _y, X_MAX_LENGTH / PRINTER_DOWN_SCALE + 1, Y_MAX_LENGTH / PRINTER_DOWN_SCALE + 1, 0x202020);
for(unsigned int py=0; py<Y_MAX_LENGTH/PRINTER_DOWN_SCALE; py++)
for(unsigned int px=0; px<X_MAX_LENGTH/PRINTER_DOWN_SCALE; px++)
drawRect(_x+px, _y+py, 1, 1, map[px][py] + 0x202020);
drawRect(_x + X_MAX_LENGTH / PRINTER_DOWN_SCALE + 2, _y, 1, Z_MAX_LENGTH / PRINTER_DOWN_SCALE + 1, 0x202020);
float pos[3];
float stepsPerUnit[4] = DEFAULT_AXIS_STEPS_PER_UNIT;
pos[0] = x->getPosition() / stepsPerUnit[X_AXIS];
pos[1] = Y_MAX_POS - y->getPosition() / stepsPerUnit[Y_AXIS];
pos[2] = z->getPosition() / stepsPerUnit[Z_AXIS];
map[int(pos[0]/PRINTER_DOWN_SCALE)][int(pos[1]/PRINTER_DOWN_SCALE)] += e0->getPosition() - e0stepPos;
map[int(pos[0]/PRINTER_DOWN_SCALE)][int(pos[1]/PRINTER_DOWN_SCALE)] += e1->getPosition() - e1stepPos;
e0stepPos = e0->getPosition();
e1stepPos = e1->getPosition();
drawRect(_x + pos[0] / PRINTER_DOWN_SCALE, _y + pos[1] / PRINTER_DOWN_SCALE, 1, 1, 0xFFFFFF);
drawRect(_x + X_MAX_LENGTH / PRINTER_DOWN_SCALE + 2, _y + pos[2] / PRINTER_DOWN_SCALE, 1, 1, 0xFFFFFF);
}
};
void sim_setup_main()
{
setupGui();
sim_setup(guiUpdate);
adcSim* adc = new adcSim();
arduinoIOSim* arduinoIO = new arduinoIOSim();
stepperSim* xStep = new stepperSim(arduinoIO, X_ENABLE_PIN, X_STEP_PIN, X_DIR_PIN, INVERT_X_DIR);
stepperSim* yStep = new stepperSim(arduinoIO, Y_ENABLE_PIN, Y_STEP_PIN, Y_DIR_PIN, INVERT_Y_DIR);
stepperSim* zStep = new stepperSim(arduinoIO, Z_ENABLE_PIN, Z_STEP_PIN, Z_DIR_PIN, INVERT_Z_DIR);
stepperSim* e0Step = new stepperSim(arduinoIO, E0_ENABLE_PIN, E0_STEP_PIN, E0_DIR_PIN, INVERT_E0_DIR);
stepperSim* e1Step = new stepperSim(arduinoIO, E1_ENABLE_PIN, E1_STEP_PIN, E1_DIR_PIN, INVERT_E1_DIR);
float stepsPerUnit[4] = DEFAULT_AXIS_STEPS_PER_UNIT;
xStep->setRange(0, X_MAX_POS * stepsPerUnit[X_AXIS]);
yStep->setRange(0, Y_MAX_POS * stepsPerUnit[Y_AXIS]);
zStep->setRange(0, Z_MAX_POS * stepsPerUnit[Z_AXIS]);
xStep->setEndstops(X_MIN_PIN, X_MAX_PIN);
yStep->setEndstops(Y_MIN_PIN, Y_MAX_PIN);
zStep->setEndstops(Z_MIN_PIN, Z_MAX_PIN);
(new printerSim(xStep, yStep, zStep, e0Step, e1Step))->setDrawPosition(5, 70);
e0Step->setDrawPosition(130, 100);
e1Step->setDrawPosition(130, 110);
(new heaterSim(HEATER_0_PIN, adc, TEMP_0_PIN))->setDrawPosition(130, 70);
(new heaterSim(HEATER_1_PIN, adc, TEMP_1_PIN))->setDrawPosition(130, 80);
(new heaterSim(HEATER_BED_PIN, adc, TEMP_BED_PIN, 0.2))->setDrawPosition(130, 90);
new sdcardSimulation("c:/models/", 5000);
(new serialSim())->setDrawPosition(150, 0);
#if defined(ULTIBOARD_V2_CONTROLLER) || defined(ENABLE_ULTILCD2)
i2cSim* i2c = new i2cSim();
(new displaySDD1309Sim(i2c))->setDrawPosition(0, 0);
(new ledPCA9632Sim(i2c))->setDrawPosition(1, 66);
#endif
#if defined(ULTIPANEL) && !defined(ULTIBOARD_V2_CONTROLLER)
(new displayHD44780Sim(arduinoIO, LCD_PINS_RS, LCD_PINS_ENABLE, LCD_PINS_D4, LCD_PINS_D5,LCD_PINS_D6,LCD_PINS_D7))->setDrawPosition(0, 0);
#endif
}
|
//
// Created by manout on 18-1-18.
//
#include <vector>
#include <algorithm>
using std::upper_bound;
using std::lower_bound;
using std::vector;
void insert_sort(vector<int>& data)
{
for (auto it = data.begin() + 1; it not_eq data.end(); ++it)
{
auto const insertion_point = std::upper_bound(data.begin(), it, *it);
std::rotate(insertion_point, it, it+1);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.