{"text":"#include \n#include \n#include \"libgobgp.h\"\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid DecodePath(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.Length() < 1) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n\n if (!args[0]->IsObject()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument\")));\n return;\n }\n Local path_arg = args[0]->ToObject();\n Local nlri_arg = path_arg->Get(String::NewFromUtf8(isolate, \"nlri\"));\n Local pattrs_val = path_arg->Get(String::NewFromUtf8(isolate, \"pattrs\"));\n\n if (!pattrs_val->IsArray()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument\")));\n return;\n }\n Local pattrs_arg = Local::Cast(pattrs_val);\n\n buf nlri;\n nlri.value = node::Buffer::Data(nlri_arg);\n nlri.len = node::Buffer::Length(nlri_arg);\n\n buf* pattrs[pattrs_arg->Length()];\n for (int i = 0; i < (int)pattrs_arg->Length(); i++) {\n pattrs[i] = (buf*) malloc(sizeof(buf));\n pattrs[i]->value = node::Buffer::Data(pattrs_arg->Get(i));\n pattrs[i]->len = node::Buffer::Length(pattrs_arg->Get(i));\n }\n\n path path;\n path.nlri = nlri;\n path.path_attributes = pattrs;\n path.path_attributes_len = pattrs_arg->Length();\n\n args.GetReturnValue().Set(String::NewFromUtf8(isolate, decode_path(&path)));\n\n for (int i = 0; i < (int)pattrs_arg->Length(); i++)\n free(pattrs[i]);\n}\n\nvoid SerializePath(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.Length() < 2) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n\n if (!args[0]->IsNumber()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument\")));\n return;\n }\n if (!args[1]->IsString()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument\")));\n return;\n }\n\n path* serialized = serialize_path(args[0]->NumberValue(), *String::Utf8Value(args[1]));\n\n Local path = Object::New(isolate);\n path->Set(String::NewFromUtf8(isolate, \"nlri\"), node::Buffer::New(isolate, serialized->nlri.value, serialized->nlri.len).ToLocalChecked());\n\n Local pattrs = Array::New(isolate);\n for (int i = 0; i < serialized->path_attributes_len; i++) {\n pattrs->Set(i, node::Buffer::New(isolate, serialized->path_attributes[i]->value, serialized->path_attributes[i]->len).ToLocalChecked());\n }\n path->Set(String::NewFromUtf8(isolate, \"pattrs\"), pattrs);\n\n args.GetReturnValue().Set(path);\n}\n\nvoid init(Local exports) {\n NODE_SET_METHOD(exports, \"decode_path\", DecodePath);\n NODE_SET_METHOD(exports, \"serialize_path\", SerializePath);\n}\n\nNODE_MODULE(addon, init)\nError message should describe the situation in more detail#include \n#include \n#include \"libgobgp.h\"\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid DecodePath(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.Length() < 1) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n\n if (!args[0]->IsObject()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument: Must be an Object\")));\n return;\n }\n Local path_arg = args[0]->ToObject();\n Local nlri_arg = path_arg->Get(String::NewFromUtf8(isolate, \"nlri\"));\n Local pattrs_val = path_arg->Get(String::NewFromUtf8(isolate, \"pattrs\"));\n\n if (!pattrs_val->IsArray()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument: Value of \\\"pattrs\\\" must be an Array\")));\n return;\n }\n Local pattrs_arg = Local::Cast(pattrs_val);\n\n buf nlri;\n nlri.value = node::Buffer::Data(nlri_arg);\n nlri.len = node::Buffer::Length(nlri_arg);\n\n buf* pattrs[pattrs_arg->Length()];\n for (int i = 0; i < (int)pattrs_arg->Length(); i++) {\n pattrs[i] = (buf*) malloc(sizeof(buf));\n pattrs[i]->value = node::Buffer::Data(pattrs_arg->Get(i));\n pattrs[i]->len = node::Buffer::Length(pattrs_arg->Get(i));\n }\n\n path path;\n path.nlri = nlri;\n path.path_attributes = pattrs;\n path.path_attributes_len = pattrs_arg->Length();\n\n args.GetReturnValue().Set(String::NewFromUtf8(isolate, decode_path(&path)));\n\n for (int i = 0; i < (int)pattrs_arg->Length(); i++)\n free(pattrs[i]);\n}\n\nvoid SerializePath(const FunctionCallbackInfo& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.Length() < 2) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n return;\n }\n\n if (!args[0]->IsNumber()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument: Must be a Number\")));\n return;\n }\n if (!args[1]->IsString()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"Invalid argument: Must be a String\")));\n return;\n }\n\n path* serialized = serialize_path(args[0]->NumberValue(), *String::Utf8Value(args[1]));\n\n Local path = Object::New(isolate);\n path->Set(String::NewFromUtf8(isolate, \"nlri\"), node::Buffer::New(isolate, serialized->nlri.value, serialized->nlri.len).ToLocalChecked());\n\n Local pattrs = Array::New(isolate);\n for (int i = 0; i < serialized->path_attributes_len; i++) {\n pattrs->Set(i, node::Buffer::New(isolate, serialized->path_attributes[i]->value, serialized->path_attributes[i]->len).ToLocalChecked());\n }\n path->Set(String::NewFromUtf8(isolate, \"pattrs\"), pattrs);\n\n args.GetReturnValue().Set(path);\n}\n\nvoid init(Local exports) {\n NODE_SET_METHOD(exports, \"decode_path\", DecodePath);\n NODE_SET_METHOD(exports, \"serialize_path\", SerializePath);\n}\n\nNODE_MODULE(addon, init)\n<|endoftext|>"} {"text":"\n#include \"nmranet\/GlobalEventHandler.hxx\"\n#include \"nmranet\/NMRAnetEventRegistry.hxx\"\n#include \"if\/nmranet_if.h\"\n#include \"core\/nmranet_event.h\"\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n\n\/*static*\/\nGlobalEventFlow* GlobalEventFlow::instance = nullptr;\n\nstruct GlobalEventFlow::Impl {\n Impl(int max_event_slots) : pending_sem_(max_event_slots) {}\n\n \/\/ This is the queue of events that are coming from the read thread to the\n \/\/ handler thread. Every \"released\" event is a new incoming event message.\n TypedAllocator event_queue_;\n\n \/\/ Statically allocated structure for calling the event handlers from the\n \/\/ main event queue.\n EventReport main_event_report_;\n\n \/\/ Each allocated GlobalEventMessage holds one value in this semaphore.\n OSSem pending_sem_;\n};\n\nclass EventIterator {\n public:\n\n\n};\n\nGlobalEventFlow::GlobalEventFlow(Executor* executor, int max_event_slots)\n : ControlFlow(executor, CrashNotifiable::DefaultInstance()), impl_(new Impl(max_event_slots)) {\n StartFlowAt(ST(WaitForEvent));\n}\n\nControlFlow::ControlFlowAction GlobalEventFlow::WaitForEvent() {\n return Allocate(&impl_->event_queue_, ST(HandleEvent));\n}\n\nvoid DecodeRange(EventReport* r) {\n uint64_t e = r->event;\n if (e&1) {\n r->mask = (e ^ (e+1)) >> 1;\n } else {\n r->mask = (e ^ (e-1)) >> 1;\n }\n r->event &= ~r->mask;\n}\n\nControlFlow::ControlFlowAction GlobalEventFlow::HandleEvent() {\n GlobalEventMessage* m;\n GetAllocationResult(&m);\n EventReport* rep = &impl_->main_event_report_;\n rep->src_node = m->src_node;\n rep->dst_node = m->dst_node;\n rep->event = m->event;\n rep->mask = EVENT_EXACT_MASK;\n FreeMessage(m);\n\n EventHandlerFunction fn;\n switch (m->mti) {\n case MTI_EVENT_REPORT:\n fn = &NMRAnetEventHandler::HandleEventReport;\n break;\n case MTI_CONSUMER_IDENTIFY:\n fn = &NMRAnetEventHandler::HandleIdentifyConsumer;\n break;\n case MTI_CONSUMER_IDENTIFIED_RANGE:\n DecodeRange(rep);\n fn = &NMRAnetEventHandler::HandleConsumerRangeIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_UNKNOWN:\n rep->state = UNKNOWN;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_VALID:\n rep->state = VALID;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_INVALID:\n rep->state = INVALID;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_RESERVED:\n rep->state = RESERVED;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFY:\n fn = &NMRAnetEventHandler::HandleIdentifyProducer;\n break;\n case MTI_PRODUCER_IDENTIFIED_RANGE:\n DecodeRange(rep);\n fn = &NMRAnetEventHandler::HandleProducerRangeIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_UNKNOWN:\n rep->state = UNKNOWN;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_VALID:\n rep->state = VALID;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_INVALID:\n rep->state = INVALID;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_RESERVED:\n rep->state = RESERVED;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_EVENTS_IDENTIFY_ADDRESSED:\n case MTI_EVENTS_IDENTIFY_GLOBAL:\n fn = &NMRAnetEventHandler::HandleIdentifyGlobal;\n break;\n default:\n DIE(\"Unexpected message arrived at the global event handler.\");\n } \/\/ case\n NMRAnetEventHandler* h = nullptr;\n (h->*fn)(rep, this);\n return YieldAndCall(ST(WaitForEvent));\n}\n\nGlobalEventMessage* GlobalEventFlow::AllocateMessage() {\n impl_->pending_sem_.wait();\n return new GlobalEventMessage();\n}\n\nvoid GlobalEventFlow::PostEvent(GlobalEventMessage* message) {\n impl_->event_queue_.TypedRelease(message);\n}\n\nvoid GlobalEventFlow::FreeMessage(GlobalEventMessage* m) {\n delete m;\n impl_->pending_sem_.post();\n}\n\n\/** Process an event packet.\n * @param mti Message Type Indicator\n * @param node node that the packet is addressed to\n * @param data NMRAnet packet data\n *\/\nextern \"C\" void nmranet_event_packet_addressed(uint16_t mti,\n node_handle_t src,\n node_t node,\n const void* data) {\n \/*struct id_node* id_node = node;\n if (id_node->priv->state == NODE_UNINITIALIZED) {\n return;\n }*\/\n\n GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage();\n m->mti = mti;\n m->dst_node = node;\n m->event = 0;\n if (data) {\n memcpy(&m->event, data, sizeof(uint64_t));\n m->event = be64toh(m->event);\n }\n GlobalEventFlow::instance->PostEvent(m);\n\n switch (mti) {\n default:\n break;\n case MTI_CONSUMER_IDENTIFY:\n \/\/nmranet_identify_consumers(node, event, EVENT_EXACT_MASK);\n break;\n case MTI_CONSUMER_IDENTIFIED_RANGE:\n \/\/nmranet_identify_consumers(node, event, identify_range_mask(event));\n break;\n case MTI_CONSUMER_IDENTIFIED_UNKNOWN: \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_VALID: \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_INVALID: \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_RESERVED:\n break;\n case MTI_PRODUCER_IDENTIFY:\n \/\/nmranet_identify_producers(node, event, EVENT_EXACT_MASK);\n break;\n case MTI_PRODUCER_IDENTIFIED_RANGE:\n \/\/nmranet_identify_producers(node, event, identify_range_mask(event));\n break;\n case MTI_PRODUCER_IDENTIFIED_UNKNOWN: \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_VALID: \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_INVALID: \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_RESERVED:\n break;\n case MTI_EVENTS_IDENTIFY_ADDRESSED: \/* fall through *\/\n case MTI_EVENTS_IDENTIFY_GLOBAL:\n \/\/nmranet_identify_consumers(node, 0, EVENT_ALL_MASK);\n \/\/nmranet_identify_producers(node, 0, EVENT_ALL_MASK);\n break;\n }\n}\n\n\/** Process an event packet.\n * @param mti Message Type Indicator\n * @param src source Node ID\n * @param data NMRAnet packet data\n *\/\nvoid nmranet_event_packet_global(uint16_t mti,\n node_handle_t src,\n const void* data) {\n GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage();\n m->mti = mti;\n m->dst_node = nullptr;\n m->src_node = src;\n m->event = 0;\n if (data) {\n memcpy(&m->event, data, sizeof(uint64_t));\n m->event = be64toh(m->event);\n }\n GlobalEventFlow::instance->PostEvent(m);\n\n switch (mti) {\n default:\n break;\n case MTI_EVENT_REPORT: {\n \/* to save processing time in instantiations that include a large\n * number of nodes, consumers are sorted at the event level and\n * not at the node level.\n *\/\n \/*struct event_node* event_node;\n struct event_node event_lookup;\n\n uint64_t event;\n memcpy(&event, data, sizeof(uint64_t));\n\n event = be64toh(event);\n event_lookup.event = event;\n\n event_node = RB_FIND(event_tree, &eventHead, &event_lookup);\n if (event_node) {\n for (EventPriv* current = event_node->priv; current != NULL;\n current = current->next) {\n event_post(current->node, src, event);\n }\n }*\/\n break;\n }\n case MTI_CONSUMER_IDENTIFY:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_RANGE:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_UNKNOWN:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_VALID:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_INVALID:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_RESERVED:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFY:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_RANGE:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_UNKNOWN:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_VALID:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_INVALID:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_RESERVED:\n \/* fall through *\/\n case MTI_EVENTS_IDENTIFY_GLOBAL:\n \/\/ os_mutex_lock(&nodeMutex);\n \/* global message, deliver all, non-subscribe *\/\n \/* for (node_t node = nmranet_node_next(NULL); node != NULL;\n node = nmranet_node_next(node)) {\n nmranet_event_packet_addressed(mti, node, data);\n }\n os_mutex_unlock(&nodeMutex);*\/\n break;\n }\n}\nAdds an implementation for doing dual iterations in event handler registries; one high-priority for standard events and one low-priority for global identify events. Adds a vector-based event registry implementation.#include \n\n#include \"nmranet\/GlobalEventHandler.hxx\"\n#include \"nmranet\/NMRAnetEventRegistry.hxx\"\n#include \"if\/nmranet_if.h\"\n#include \"core\/nmranet_event.h\"\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n\n\/*static*\/\nGlobalEventFlow* GlobalEventFlow::instance = nullptr;\n\nstruct GlobalEventFlow::Impl {\n Impl(int max_event_slots) : pending_sem_(max_event_slots) {}\n\n \/\/ This is the queue of events that are coming from the read thread to the\n \/\/ handler thread. Every \"released\" event is a new incoming event message.\n TypedAllocator event_queue_;\n\n \/\/ Statically allocated structure for calling the event handlers from the\n \/\/ main event queue.\n EventReport main_event_report_;\n\n \/\/ Each allocated GlobalEventMessage holds one value in this semaphore.\n OSSem pending_sem_;\n};\n\n\/\/ Abstract class for representing iteration through a container for event\n\/\/ handlers.\nclass EventIterator : public Notifiable {\n public:\n EventIterator(Notifiable* parent)\n : event_(nullptr), done_(nullptr), parent_(parent), was_notified_(true) {}\n\n virtual NMRAnetEventHandler* NextEntry() = 0;\n\n void InitIterator(EventReport* event, Notifiable* done) {\n HASSERT(event_ == nullptr);\n HASSERT(done_ == nullptr);\n event_ = event;\n done_ = done;\n }\n void ClearIteration() {\n event_ = nullptr;\n done_ = nullptr;\n }\n EventReport* event() { return event_; }\n Notifiable* done() { return done_; }\n Notifiable* NewCallback() {\n HASSERT(was_notified_);\n was_notified_ = false;\n return this;\n }\n virtual void Notify() {\n was_notified_ = true;\n parent_->Notify();\n }\n bool HasBeenNotified() { return was_notified_; }\n\n private:\n \/\/ Stores iteration arguments.\n EventReport* event_;\n \/\/ Stores the iteration completion callback.\n Notifiable* done_;\n \/\/ Proxies incoming notifications to this parent.\n Notifiable* parent_;\n \/\/ When there is an incoming notification, this is set to true.\n bool was_notified_;\n};\n\ntemplate \nclass StlIterator : public EventIterator {\n public:\n StlIterator(Notifiable* parent) : EventIterator(parent) {}\n\n void Set(IT begin, IT end) {\n it_ = begin;\n end_ = end;\n }\n\n virtual NMRAnetEventHandler* NextEntry() {\n if (it_ == end_)\n return NULL;\n else\n return *it_++;\n }\n\n private:\n IT it_;\n IT end_;\n};\n\nclass DualIteratorFlow : public ControlFlow, public ProxyEventHandler {\n public:\n DualIteratorFlow(Executor* executor,\n EventIterator* standard_iterator,\n EventIterator* global_iterator)\n : ControlFlow(executor, NULL),\n standard_iterator_(standard_iterator),\n global_iterator_(global_iterator) {\n StartFlowAt(ST(StateInIteration));\n }\n\n virtual void InitStandardIterator() = 0;\n\n virtual void HandlerFn(EventHandlerFunction fn,\n EventReport* event,\n Notifiable* done) {\n event_handler_mutex.AssertLocked();\n proxy_fn_ = fn;\n standard_iterator_->InitIterator(event, done);\n InitStandardIterator();\n this->Notify();\n }\n\n virtual void InitGlobalIterator() = 0;\n\n virtual void HandleIdentifyGlobal(EventReport* event, Notifiable* done) {\n event_handler_mutex.AssertLocked();\n \/\/ We immediately release the global iterator mutex and will acquire it\n \/\/ inside when we try to call children.\n event_handler_mutex.Unlock();\n global_iterator_->InitIterator(event, done);\n InitGlobalIterator();\n this->Notify();\n }\n\n protected:\n ControlFlowAction StateInIteration() {\n \/\/ We first try a standard iteration.\n if (!standard_iterator_->done())\n return CallImmediately(ST(TryStandardIteration));\n \/\/ Then a global iteration.\n if (!global_iterator_->done())\n return CallImmediately(ST(GetGlobalIterationLock));\n \/\/ Give up and wait for incoming messages.\n return WaitForNotification();\n }\n\n ControlFlowAction TryStandardIteration() {\n NMRAnetEventHandler* handler = standard_iterator_->NextEntry();\n if (!handler) {\n \/\/ Iteration done.\n standard_iterator_->done()->Notify();\n standard_iterator_->ClearIteration();\n return YieldAndCall(ST(StateInIteration));\n }\n (handler->*proxy_fn_)(standard_iterator_->event(),\n standard_iterator_->NewCallback());\n return CallImmediately(ST(WaitForStandardReturn));\n }\n\n ControlFlowAction WaitForStandardReturn() {\n if (!standard_iterator_->HasBeenNotified())\n return WaitForNotification();\n return CallImmediately(ST(TryStandardIteration));\n }\n\n ControlFlowAction GetGlobalIterationLock() {\n return Allocate(&event_handler_mutex, ST(CallGlobalIteration));\n }\n\n ControlFlowAction CallGlobalIteration() {\n NMRAnetEventHandler* handler = global_iterator_->NextEntry();\n if (!handler) {\n \/\/ Iteration done. We hand back the iterator lock.\n global_iterator_->done()->Notify();\n global_iterator_->ClearIteration();\n return YieldAndCall(ST(StateInIteration));\n }\n handler->HandleIdentifyGlobal(global_iterator_->event(),\n global_iterator_->NewCallback());\n return CallImmediately(ST(WaitForGlobalReturn));\n }\n\n ControlFlowAction WaitForGlobalReturn() {\n if (!global_iterator_->HasBeenNotified())\n return WaitForNotification();\n \/\/ Releases the iteration lock and yields to other control flows that might\n \/\/ want it.\n event_handler_mutex.Unlock();\n return YieldAndCall(ST(StateInIteration));\n }\n\n private:\n EventHandlerFunction proxy_fn_;\n EventIterator* standard_iterator_;\n EventIterator* global_iterator_;\n};\n\nclass VectorEventHandlers : public DualIteratorFlow {\n public:\n VectorEventHandlers(Executor* executor)\n : DualIteratorFlow(executor,\n &standard_iterator_impl_,\n &global_iterator_impl_),\n standard_iterator_impl_(this),\n global_iterator_impl_(this) {}\n\n virtual void InitStandardIterator() {\n standard_iterator_impl_.Set(handlers_.begin(), handlers_.end());\n }\n\n virtual void InitGlobalIterator() {\n global_iterator_impl_.Set(handlers_.begin(), handlers_.end());\n }\n\n private:\n typedef std::vector HandlersList;\n HandlersList handlers_;\n StlIterator standard_iterator_impl_;\n StlIterator global_iterator_impl_;\n};\n\nGlobalEventFlow::GlobalEventFlow(Executor* executor, int max_event_slots)\n : ControlFlow(executor, CrashNotifiable::DefaultInstance()),\n impl_(new Impl(max_event_slots)) {\n StartFlowAt(ST(WaitForEvent));\n}\n\nControlFlow::ControlFlowAction GlobalEventFlow::WaitForEvent() {\n return Allocate(&impl_->event_queue_, ST(HandleEvent));\n}\n\nvoid DecodeRange(EventReport* r) {\n uint64_t e = r->event;\n if (e & 1) {\n r->mask = (e ^ (e + 1)) >> 1;\n } else {\n r->mask = (e ^ (e - 1)) >> 1;\n }\n r->event &= ~r->mask;\n}\n\nControlFlow::ControlFlowAction GlobalEventFlow::HandleEvent() {\n GlobalEventMessage* m;\n GetAllocationResult(&m);\n EventReport* rep = &impl_->main_event_report_;\n rep->src_node = m->src_node;\n rep->dst_node = m->dst_node;\n rep->event = m->event;\n rep->mask = EVENT_EXACT_MASK;\n FreeMessage(m);\n\n EventHandlerFunction fn;\n switch (m->mti) {\n case MTI_EVENT_REPORT:\n fn = &NMRAnetEventHandler::HandleEventReport;\n break;\n case MTI_CONSUMER_IDENTIFY:\n fn = &NMRAnetEventHandler::HandleIdentifyConsumer;\n break;\n case MTI_CONSUMER_IDENTIFIED_RANGE:\n DecodeRange(rep);\n fn = &NMRAnetEventHandler::HandleConsumerRangeIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_UNKNOWN:\n rep->state = UNKNOWN;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_VALID:\n rep->state = VALID;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_INVALID:\n rep->state = INVALID;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_CONSUMER_IDENTIFIED_RESERVED:\n rep->state = RESERVED;\n fn = &NMRAnetEventHandler::HandleConsumerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFY:\n fn = &NMRAnetEventHandler::HandleIdentifyProducer;\n break;\n case MTI_PRODUCER_IDENTIFIED_RANGE:\n DecodeRange(rep);\n fn = &NMRAnetEventHandler::HandleProducerRangeIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_UNKNOWN:\n rep->state = UNKNOWN;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_VALID:\n rep->state = VALID;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_INVALID:\n rep->state = INVALID;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_PRODUCER_IDENTIFIED_RESERVED:\n rep->state = RESERVED;\n fn = &NMRAnetEventHandler::HandleProducerIdentified;\n break;\n case MTI_EVENTS_IDENTIFY_ADDRESSED:\n case MTI_EVENTS_IDENTIFY_GLOBAL:\n fn = &NMRAnetEventHandler::HandleIdentifyGlobal;\n break;\n default:\n DIE(\"Unexpected message arrived at the global event handler.\");\n } \/\/ case\n NMRAnetEventHandler* h = nullptr;\n (h->*fn)(rep, this);\n return YieldAndCall(ST(WaitForEvent));\n}\n\nGlobalEventMessage* GlobalEventFlow::AllocateMessage() {\n impl_->pending_sem_.wait();\n return new GlobalEventMessage();\n}\n\nvoid GlobalEventFlow::PostEvent(GlobalEventMessage* message) {\n impl_->event_queue_.TypedRelease(message);\n}\n\nvoid GlobalEventFlow::FreeMessage(GlobalEventMessage* m) {\n delete m;\n impl_->pending_sem_.post();\n}\n\n\/** Process an event packet.\n * @param mti Message Type Indicator\n * @param node node that the packet is addressed to\n * @param data NMRAnet packet data\n *\/\nextern \"C\" void nmranet_event_packet_addressed(uint16_t mti,\n node_handle_t src,\n node_t node,\n const void* data) {\n \/*struct id_node* id_node = node;\n if (id_node->priv->state == NODE_UNINITIALIZED) {\n return;\n }*\/\n\n GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage();\n m->mti = mti;\n m->dst_node = node;\n m->event = 0;\n if (data) {\n memcpy(&m->event, data, sizeof(uint64_t));\n m->event = be64toh(m->event);\n }\n GlobalEventFlow::instance->PostEvent(m);\n\n switch (mti) {\n default:\n break;\n case MTI_CONSUMER_IDENTIFY:\n \/\/ nmranet_identify_consumers(node, event, EVENT_EXACT_MASK);\n break;\n case MTI_CONSUMER_IDENTIFIED_RANGE:\n \/\/ nmranet_identify_consumers(node, event, identify_range_mask(event));\n break;\n case MTI_CONSUMER_IDENTIFIED_UNKNOWN: \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_VALID: \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_INVALID: \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_RESERVED:\n break;\n case MTI_PRODUCER_IDENTIFY:\n \/\/ nmranet_identify_producers(node, event, EVENT_EXACT_MASK);\n break;\n case MTI_PRODUCER_IDENTIFIED_RANGE:\n \/\/ nmranet_identify_producers(node, event, identify_range_mask(event));\n break;\n case MTI_PRODUCER_IDENTIFIED_UNKNOWN: \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_VALID: \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_INVALID: \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_RESERVED:\n break;\n case MTI_EVENTS_IDENTIFY_ADDRESSED: \/* fall through *\/\n case MTI_EVENTS_IDENTIFY_GLOBAL:\n \/\/ nmranet_identify_consumers(node, 0, EVENT_ALL_MASK);\n \/\/ nmranet_identify_producers(node, 0, EVENT_ALL_MASK);\n break;\n }\n}\n\n\/** Process an event packet.\n * @param mti Message Type Indicator\n * @param src source Node ID\n * @param data NMRAnet packet data\n *\/\nvoid nmranet_event_packet_global(uint16_t mti,\n node_handle_t src,\n const void* data) {\n GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage();\n m->mti = mti;\n m->dst_node = nullptr;\n m->src_node = src;\n m->event = 0;\n if (data) {\n memcpy(&m->event, data, sizeof(uint64_t));\n m->event = be64toh(m->event);\n }\n GlobalEventFlow::instance->PostEvent(m);\n\n switch (mti) {\n default:\n break;\n case MTI_EVENT_REPORT: {\n \/* to save processing time in instantiations that include a large\n * number of nodes, consumers are sorted at the event level and\n * not at the node level.\n *\/\n \/*struct event_node* event_node;\n struct event_node event_lookup;\n\n uint64_t event;\n memcpy(&event, data, sizeof(uint64_t));\n\n event = be64toh(event);\n event_lookup.event = event;\n\n event_node = RB_FIND(event_tree, &eventHead, &event_lookup);\n if (event_node) {\n for (EventPriv* current = event_node->priv; current != NULL;\n current = current->next) {\n event_post(current->node, src, event);\n }\n }*\/\n break;\n }\n case MTI_CONSUMER_IDENTIFY:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_RANGE:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_UNKNOWN:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_VALID:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_INVALID:\n \/* fall through *\/\n case MTI_CONSUMER_IDENTIFIED_RESERVED:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFY:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_RANGE:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_UNKNOWN:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_VALID:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_INVALID:\n \/* fall through *\/\n case MTI_PRODUCER_IDENTIFIED_RESERVED:\n \/* fall through *\/\n case MTI_EVENTS_IDENTIFY_GLOBAL:\n \/\/ os_mutex_lock(&nodeMutex);\n \/* global message, deliver all, non-subscribe *\/\n \/* for (node_t node = nmranet_node_next(NULL); node != NULL;\n node = nmranet_node_next(node)) {\n nmranet_event_packet_addressed(mti, node, data);\n }\n os_mutex_unlock(&nodeMutex);*\/\n break;\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"zmsg_types.hpp\"\n\nnamespace {\n\ntemplate<>\nstruct zmsg {\n}:\n\n}补充<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Functional programming\n\n\/\/ Function that returns a callable in the form of a lambda\nstd::function make_adder(int x)\n{\n return ([=](int a) -> int{ return x + a; });\n}\n\nvoid do_functional()\n{\n \/\/ Lambda with no capture\n auto simple_lambda = [](int a){ return a + 3; };\n assert(simple_lambda(5) == 8);\n\n \/\/ Capture by value\n int x = 5;\n auto by_value = [x](int a){ return a + x; };\n assert(by_value(1) == 6);\n x = 7; \/\/ change not seen by lambda\n assert(by_value(1) == 6);\n \/\/ Also >> at end of template\n assert((std::is_convertible>::value));\n\n \/\/ Capture by reference\n auto by_reference = [&x](int a){ return a + x; };\n assert(by_reference(1) == 8);\n x = 8; \/\/ change seen my lambda\n assert(by_reference(1) == 9);\n\n \/\/ Get a callable from a function\n auto add3 = make_adder(3);\n assert(add3(5) == 8);\n\n auto make_addr_lambda = [](int a) {\n return [a](int b) { return a + b; };\n };\n\n assert(make_addr_lambda(6)(8) == 14);\n}\n\n\/\/ Integer types, type traits\n\ntemplate \nvoid check_size(size_t size, bool is_signed)\n{\n assert(sizeof(T) == size);\n assert(std::is_signed::value == is_signed);\n}\n\nvoid do_inttypes()\n{\n \/\/ static_assert is a compile-time check\n static_assert(1 == sizeof(int8_t), \"int8_t check\");\n check_size(1, true);\n check_size(1, false);\n check_size(2, true);\n check_size(2, false);\n check_size(4, true);\n check_size(4, false);\n check_size(8, true);\n check_size(8, false);\n\n \/\/ auto, decltype\n auto x = 5LL;\n check_size(8, true);\n assert((std::is_same::value));\n}\n\nclass A\n{\n public:\n static constexpr auto def_value = 5;\n A(int x) :\n x(x)\n {\n }\n \/\/ Constructor delegation\n A() : A(def_value)\n {\n }\n int getX() const\n {\n return x;\n }\n\n private:\n int x;\n};\n\nvoid do_iteration()\n{\n \/\/ Initializers, foreach syntax, auto for iterators\n std::vector v = { 1, 2, 3, 4 };\n assert(v.size() == 4);\n int sum = 0;\n for (auto i: v)\n {\n sum += i;\n }\n assert(10 == sum);\n for (auto i = v.begin(); i != v.end(); ++i)\n {\n sum += *i;\n }\n assert(20 == sum);\n\n std::vector v2 = { A(), A(3) };\n assert(5 == v2.at(0).getX());\n assert(3 == v2.at(1).getX());\n}\n\n\/\/ Variadic template\n\ntemplate\nvoid variadic1(A1 const& a1)\n{\n assert(a1 == 12);\n}\n\ntemplate\nvoid variadic1(A1 const& a1, A2 const& a2)\n{\n assert(a1 == a2);\n}\n\ntemplate\nvoid variadic(Args... args)\n{\n variadic1(args...);\n}\n\ntemplate\nbool pairwise_equal(A const& a, A const& b)\n{\n return (a == b);\n}\n\ntemplate\nbool pairwise_equal(T const& a, T const& b, Rest... rest)\n{\n return pairwise_equal(a, b) && pairwise_equal(rest...);\n}\n\nvoid do_variadic()\n{\n variadic(15, 15);\n variadic(12);\n assert(pairwise_equal(5, 5, 2.0, 2.0, std::string(\"a\"), std::string(\"a\")));\n assert(! pairwise_equal(5, 5, 2.0, 3.0));\n}\n\n\/\/ deleted, default\n\nclass B\n{\n public:\n B(int x) :\n x(x)\n {\n }\n B() : B(5)\n {\n }\n int getX() const\n {\n return x;\n }\n\n virtual ~B() = default;\n B(B const&) = delete;\n B& operator=(B const&) = delete;\n\n private:\n int x;\n};\n\nvoid do_default_deleted()\n{\n B b1;\n assert(5 == b1.getX());\n assert(std::is_copy_constructible::value);\n assert(! std::is_copy_constructible::value);\n}\n\n\/\/ smart pointers\n\nclass C\n{\n public:\n C(int id = 0) :\n id(id)\n {\n incr(id);\n }\n ~C()\n {\n decr(id);\n }\n C(C const& rhs) : C(rhs.id)\n {\n }\n C& operator=(C const& rhs)\n {\n if (&rhs != this)\n {\n decr(id);\n id = rhs.id;\n incr(id);\n }\n return *this;\n }\n static void check(size_t size, int v, int count)\n {\n assert(m.size() == size);\n auto p = m.find(v);\n if (p != m.end())\n {\n assert(p->second == count);\n }\n }\n\n private:\n void incr(int i)\n {\n ++m[i];\n }\n void decr(int i)\n {\n if (--m[i] == 0)\n {\n m.erase(i);\n }\n }\n\n static std::map m;\n int id;\n};\n\nstd::map C::m;\n\nstd::shared_ptr make_c(int id)\n{\n return std::make_shared(id);\n}\n\nstd::shared_ptr make_c_array(std::vector const& is)\n{\n auto p = std::shared_ptr(new C[is.size()], std::default_delete());\n C* pp = p.get();\n for (size_t i = 0; i < is.size(); ++i)\n {\n pp[i] = C(is.at(i));\n }\n return p;\n}\n\nvoid do_smart_pointers()\n{\n auto p1 = make_c(1);\n C::check(1, 1, 1);\n auto p2 = make_c_array({2, 3, 4, 5});\n for (auto i: {1, 2, 3, 4, 5})\n {\n C::check(5, i, 1);\n }\n {\n C::check(5, 1, 1);\n C c3(*p1);\n C::check(5, 1, 2);\n }\n C::check(5, 1, 1);\n p1 = nullptr;\n C::check(4, 1, 0);\n p2 = nullptr;\n C::check(0, 0, 0);\n {\n std::unique_ptr p3(new C(6));\n C::check(1, 6, 1);\n }\n C::check(0, 0, 0);\n}\n\n\/\/ Regular expressions\n\nvoid do_regex()\n{\n \/\/ Basic match\/search. Match matches whole string; search searches\n \/\/ within string. Use std::smatch for matching std::string and\n \/\/ std::cmatch for matching char const*.\n\n std::regex expr1(\"([0-9]+)\");\n std::regex expr2(\"([0-9]+)\\\\s*([a-z]+)[[:space:]]*([0-9]+)\");\n std::string str1(\"one 234 fifth 678 nine\");\n std::string str2(\"234 five 678 nine\");\n std::string str3(\"one 234 five 678\");\n std::string str4(\"234\");\n std::string str5(\"234 five 678\");\n std::smatch match1;\n assert(! std::regex_match(str1, match1, expr1));\n assert(! std::regex_match(str2, match1, expr1));\n assert(! std::regex_match(str3, match1, expr1));\n assert(std::regex_match(str4, match1, expr1));\n assert(match1[0].first == match1[1].first);\n assert(match1[0].second == match1[1].second);\n std::string s;\n s.assign(match1[1].first, match1[1].second);\n assert(\"234\" == s);\n assert(s == match1[1].str());\n assert(std::regex_match(str5, match1, expr2));\n assert(\"234 five 678\" == match1[0].str());\n assert(\"234\" == match1[1].str());\n assert(\"five\" == match1[2].str());\n assert(\"678\" == match1[3].str());\n assert(std::regex_search(str1, match1, expr2));\n assert(\"234 fifth 678\" == match1[0].str());\n assert(\"234\" == match1[1].str());\n assert(\"fifth\" == match1[2].str());\n assert(\"678\" == match1[3].str());\n\n \/\/ Iterator\n std::regex expr3(\"[[:digit:]]+\");\n std::string str6 = \"asdf234erasdf9453.kgdl423asdf\";\n std::sregex_iterator m1(str6.begin(), str6.end(), expr3);\n std::sregex_iterator m2;\n s.clear();\n for (std::sregex_iterator iter = m1; iter != m2; ++iter)\n {\n\tstd::smatch const& match2 = *iter;\n s += match2[0].str() + \"|\";\n }\n assert(\"234|9453|423|\" == s);\n\n \/\/ Submatches\n std::regex expr4(\"(?:(asdf)|(qwer))\");\n char const* str7 = \"0asdf1qwer2\";\n std::cregex_iterator m3(str7, str7 + std::strlen(str7), expr4);\n assert(\"asdf\" == (*m3)[0].str());\n assert((*m3)[1].matched);\n assert(! (*m3)[2].matched);\n ++m3;\n assert(\"qwer\" == (*m3)[0].str());\n assert(! (*m3)[1].matched);\n assert((*m3)[2].matched);\n}\n\nint main()\n{\n do_functional();\n do_inttypes();\n do_iteration();\n do_variadic();\n do_default_deleted();\n do_smart_pointers();\n do_regex();\n std::cout << \"assertions passed\\n\";\n return 0;\n}\nlibtests\/cxx11.cc: fix build with gcc 4.8#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Functional programming\n\n\/\/ Function that returns a callable in the form of a lambda\nstd::function make_adder(int x)\n{\n return ([=](int a) -> int{ return x + a; });\n}\n\nvoid do_functional()\n{\n \/\/ Lambda with no capture\n auto simple_lambda = [](int a){ return a + 3; };\n assert(simple_lambda(5) == 8);\n\n \/\/ Capture by value\n int x = 5;\n auto by_value = [x](int a){ return a + x; };\n assert(by_value(1) == 6);\n x = 7; \/\/ change not seen by lambda\n assert(by_value(1) == 6);\n \/\/ Also >> at end of template\n assert((std::is_convertible>::value));\n\n \/\/ Capture by reference\n auto by_reference = [&x](int a){ return a + x; };\n assert(by_reference(1) == 8);\n x = 8; \/\/ change seen my lambda\n assert(by_reference(1) == 9);\n\n \/\/ Get a callable from a function\n auto add3 = make_adder(3);\n assert(add3(5) == 8);\n\n auto make_addr_lambda = [](int a) {\n return [a](int b) { return a + b; };\n };\n\n assert(make_addr_lambda(6)(8) == 14);\n}\n\n\/\/ Integer types, type traits\n\ntemplate \nvoid check_size(size_t size, bool is_signed)\n{\n assert(sizeof(T) == size);\n assert(std::is_signed::value == is_signed);\n}\n\nvoid do_inttypes()\n{\n \/\/ static_assert is a compile-time check\n static_assert(1 == sizeof(int8_t), \"int8_t check\");\n check_size(1, true);\n check_size(1, false);\n check_size(2, true);\n check_size(2, false);\n check_size(4, true);\n check_size(4, false);\n check_size(8, true);\n check_size(8, false);\n\n \/\/ auto, decltype\n auto x = 5LL;\n check_size(8, true);\n assert((std::is_same::value));\n}\n\nclass A\n{\n public:\n static constexpr auto def_value = 5;\n A(int x) :\n x(x)\n {\n }\n \/\/ Constructor delegation\n A() : A(def_value)\n {\n }\n int getX() const\n {\n return x;\n }\n\n private:\n int x;\n};\n\nvoid do_iteration()\n{\n \/\/ Initializers, foreach syntax, auto for iterators\n std::vector v = { 1, 2, 3, 4 };\n assert(v.size() == 4);\n int sum = 0;\n for (auto i: v)\n {\n sum += i;\n }\n assert(10 == sum);\n for (auto i = v.begin(); i != v.end(); ++i)\n {\n sum += *i;\n }\n assert(20 == sum);\n\n std::vector v2 = { A(), A(3) };\n assert(5 == v2.at(0).getX());\n assert(3 == v2.at(1).getX());\n}\n\n\/\/ Variadic template\n\ntemplate\nvoid variadic1(A1 const& a1)\n{\n assert(a1 == 12);\n}\n\ntemplate\nvoid variadic1(A1 const& a1, A2 const& a2)\n{\n assert(a1 == a2);\n}\n\ntemplate\nvoid variadic(Args... args)\n{\n variadic1(args...);\n}\n\ntemplate\nbool pairwise_equal(A const& a, A const& b)\n{\n return (a == b);\n}\n\ntemplate\nbool pairwise_equal(T const& a, T const& b, Rest... rest)\n{\n return pairwise_equal(a, b) && pairwise_equal(rest...);\n}\n\nvoid do_variadic()\n{\n variadic(15, 15);\n variadic(12);\n assert(pairwise_equal(5, 5, 2.0, 2.0, std::string(\"a\"), std::string(\"a\")));\n assert(! pairwise_equal(5, 5, 2.0, 3.0));\n}\n\n\/\/ deleted, default\n\nclass B\n{\n public:\n B(int x) :\n x(x)\n {\n }\n B() : B(5)\n {\n }\n int getX() const\n {\n return x;\n }\n\n virtual ~B() = default;\n B(B const&) = delete;\n B& operator=(B const&) = delete;\n\n private:\n int x;\n};\n\nvoid do_default_deleted()\n{\n B b1;\n assert(5 == b1.getX());\n assert(std::is_copy_constructible::value);\n assert(! std::is_copy_constructible::value);\n}\n\n\/\/ smart pointers\n\nclass C\n{\n public:\n C(int id = 0) :\n id(id)\n {\n incr(id);\n }\n ~C()\n {\n decr(id);\n }\n C(C const& rhs) : C(rhs.id)\n {\n }\n C& operator=(C const& rhs)\n {\n if (&rhs != this)\n {\n decr(id);\n id = rhs.id;\n incr(id);\n }\n return *this;\n }\n static void check(size_t size, int v, int count)\n {\n assert(m.size() == size);\n auto p = m.find(v);\n if (p != m.end())\n {\n assert(p->second == count);\n }\n }\n\n private:\n void incr(int i)\n {\n ++m[i];\n }\n void decr(int i)\n {\n if (--m[i] == 0)\n {\n m.erase(i);\n }\n }\n\n static std::map m;\n int id;\n};\n\nstd::map C::m;\n\nstd::shared_ptr make_c(int id)\n{\n return std::make_shared(id);\n}\n\nstd::shared_ptr make_c_array(std::vector const& is)\n{\n auto p = std::shared_ptr(new C[is.size()], std::default_delete());\n C* pp = p.get();\n for (size_t i = 0; i < is.size(); ++i)\n {\n pp[i] = C(is.at(i));\n }\n return p;\n}\n\nvoid do_smart_pointers()\n{\n auto p1 = make_c(1);\n C::check(1, 1, 1);\n auto p2 = make_c_array({2, 3, 4, 5});\n for (auto i: {1, 2, 3, 4, 5})\n {\n C::check(5, i, 1);\n }\n {\n C::check(5, 1, 1);\n C c3(*p1);\n C::check(5, 1, 2);\n }\n C::check(5, 1, 1);\n p1 = nullptr;\n C::check(4, 1, 0);\n p2 = nullptr;\n C::check(0, 0, 0);\n {\n std::unique_ptr p3(new C(6));\n C::check(1, 6, 1);\n }\n C::check(0, 0, 0);\n}\n\n\/\/ Regular expressions\n\nvoid do_regex()\n{\n \/\/ Basic match\/search. Match matches whole string; search searches\n \/\/ within string. Use std::smatch for matching std::string and\n \/\/ std::cmatch for matching char const*.\n\n std::regex expr1(\"([0-9]+)\");\n std::regex expr2(\"([0-9]+)\\\\s*([a-z]+)[[:space:]]*([0-9]+)\");\n std::string str1(\"one 234 fifth 678 nine\");\n std::string str2(\"234 five 678 nine\");\n std::string str3(\"one 234 five 678\");\n std::string str4(\"234\");\n std::string str5(\"234 five 678\");\n std::smatch match1;\n assert(! std::regex_match(str1, match1, expr1));\n assert(! std::regex_match(str2, match1, expr1));\n assert(! std::regex_match(str3, match1, expr1));\n assert(std::regex_match(str4, match1, expr1));\n assert(match1[0].first == match1[1].first);\n assert(match1[0].second == match1[1].second);\n std::string s;\n s.assign(match1[1].first, match1[1].second);\n assert(\"234\" == s);\n assert(s == match1[1].str());\n assert(std::regex_match(str5, match1, expr2));\n assert(\"234 five 678\" == match1[0].str());\n assert(\"234\" == match1[1].str());\n assert(\"five\" == match1[2].str());\n assert(\"678\" == match1[3].str());\n assert(std::regex_search(str1, match1, expr2));\n assert(\"234 fifth 678\" == match1[0].str());\n assert(\"234\" == match1[1].str());\n assert(\"fifth\" == match1[2].str());\n assert(\"678\" == match1[3].str());\n\n \/\/ Iterator\n std::regex expr3(\"[[:digit:]]+\");\n std::string str6 = \"asdf234erasdf9453.kgdl423asdf\";\n std::sregex_iterator m1(str6.begin(), str6.end(), expr3);\n std::sregex_iterator m2;\n s.clear();\n for (std::sregex_iterator iter = m1; iter != m2; ++iter)\n {\n\tstd::smatch const& match2 = *iter;\n s += match2[0].str() + \"|\";\n }\n assert(\"234|9453|423|\" == s);\n\n \/\/ Submatches\n std::regex expr4(\"(?:(asdf)|(qwer))\");\n char const* str7 = \"0asdf1qwer2\";\n std::cregex_iterator m3(str7, str7 + std::strlen(str7), expr4);\n assert(\"asdf\" == (*m3)[0].str());\n assert((*m3)[1].matched);\n assert(! (*m3)[2].matched);\n ++m3;\n assert(\"qwer\" == (*m3)[0].str());\n assert(! (*m3)[1].matched);\n assert((*m3)[2].matched);\n}\n\nint main()\n{\n do_functional();\n do_inttypes();\n do_iteration();\n do_variadic();\n do_default_deleted();\n do_smart_pointers();\n do_regex();\n std::cout << \"assertions passed\\n\";\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * guard.cc: Functions for thread-safe static initialisation.\n *\n * Static values in C++ can be initialised lazily their first use. This file\n * contains functions that are used to ensure that two threads attempting to\n * initialize the same static do not call the constructor twice. This is\n * important because constructors can have side effects, so calling the\n * constructor twice may be very bad.\n *\n * Statics that require initialisation are protected by a 64-bit value. Any\n * platform that can do 32-bit atomic test and set operations can use this\n * value as a low-overhead lock. Because statics (in most sane code) are\n * accessed far more times than they are initialised, this lock implementation\n * is heavily optimised towards the case where the static has already been\n * initialised. \n *\/\n#include \n#include \n#include \n\n#ifdef __arm__\n\/\/ ARM ABI - 32-bit guards.\n\n\/**\n * Acquires a lock on a guard, returning 0 if the object has already been\n * initialised, and 1 if it has not. If the object is already constructed then\n * this function just needs to read a byte from memory and return.\n *\/\nextern \"C\" int __cxa_guard_acquire(volatile int32_t *guard_object)\n{\n\tif ((1<<31) == *guard_object) { return 0; }\n\t\/\/ If we can atomically move the value from 0 -> 1, then this is\n\t\/\/ uninitialised.\n\tif (__sync_bool_compare_and_swap(guard_object, 0, 1))\n\t{\n\t\treturn 1;\n\t}\n\t\/\/ If the value is not 0, some other thread was initialising this. Spin\n\t\/\/ until it's finished.\n\twhile (__sync_bool_compare_and_swap(guard_object, (1<<31), (1<<31)))\n\t{\n\t\t\/\/ If the other thread aborted, then we grab the lock\n\t\tif (__sync_bool_compare_and_swap(guard_object, 0, 1))\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t\tsched_yield();\n\t}\n\treturn 0;\n}\n\n\/**\n * Releases the lock without marking the object as initialised. This function\n * is called if initialising a static causes an exception to be thrown.\n *\/\nextern \"C\" void __cxa_guard_abort(int32_t *guard_object)\n{\n\tassert(__sync_bool_compare_and_swap(guard_object, 1, 0));\n}\n\/**\n * Releases the guard and marks the object as initialised. This function is\n * called after successful initialisation of a static.\n *\/\nextern \"C\" void __cxa_guard_release(int32_t *guard_object)\n{\n\tassert(__sync_bool_compare_and_swap(guard_object, 1, (1<<31)));\n}\n\n\n#else\n\/\/ Itanium ABI: 64-bit guards\n\n\/**\n * Returns a pointer to the low 32 bits in a 64-bit value, respecting the\n * platform's byte order.\n *\/\nstatic int32_t *low_32_bits(volatile int64_t *ptr)\n{\n\tint32_t *low= (int32_t*)ptr;\n\t\/\/ Test if the machine is big endian - constant propagation at compile time\n\t\/\/ should eliminate this completely.\n\tint one = 1;\n\tif (*(char*)&one != 1)\n\t{\n\t\tlow++;\n\t}\n\treturn low;\n}\n\n\/**\n * Acquires a lock on a guard, returning 0 if the object has already been\n * initialised, and 1 if it has not. If the object is already constructed then\n * this function just needs to read a byte from memory and return.\n *\/\nextern \"C\" int __cxa_guard_acquire(volatile int64_t *guard_object)\n{\n\tchar first_byte = (*guard_object) >> 56;\n\tif (1 == first_byte) { return 0; }\n\tint32_t *lock = low_32_bits(guard_object);\n\t\/\/ Simple spin lock using the low 32 bits. We assume that concurrent\n\t\/\/ attempts to initialize statics are very rare, so we don't need to\n\t\/\/ optimise for the case where we have lots of threads trying to acquire\n\t\/\/ the lock at the same time.\n\twhile (!__sync_bool_compare_and_swap_4(lock, 0, 1))\n\t{\n\t\tsched_yield();\n\t}\n\t\/\/ We have to test the guard again, in case another thread has performed\n\t\/\/ the initialisation while we were trying to acquire the lock.\n\tfirst_byte = (*guard_object) >> 56;\n\treturn (1 != first_byte);\n}\n\n\/**\n * Releases the lock without marking the object as initialised. This function\n * is called if initialising a static causes an exception to be thrown.\n *\/\nextern \"C\" void __cxa_guard_abort(int64_t *guard_object)\n{\n\tint32_t *lock = low_32_bits(guard_object);\n\t*lock = 0;\n}\n\/**\n * Releases the guard and marks the object as initialised. This function is\n * called after successful initialisation of a static.\n *\/\nextern \"C\" void __cxa_guard_release(int64_t *guard_object)\n{\n\t\/\/ Set the first byte to 1\n\t*guard_object |= ((int64_t)1) << 56;\n\t__cxa_guard_abort(guard_object);\n}\n\n#endif\nFix a potential race in guard logic.\/**\n * guard.cc: Functions for thread-safe static initialisation.\n *\n * Static values in C++ can be initialised lazily their first use. This file\n * contains functions that are used to ensure that two threads attempting to\n * initialize the same static do not call the constructor twice. This is\n * important because constructors can have side effects, so calling the\n * constructor twice may be very bad.\n *\n * Statics that require initialisation are protected by a 64-bit value. Any\n * platform that can do 32-bit atomic test and set operations can use this\n * value as a low-overhead lock. Because statics (in most sane code) are\n * accessed far more times than they are initialised, this lock implementation\n * is heavily optimised towards the case where the static has already been\n * initialised. \n *\/\n#include \n#include \n#include \n\n#ifdef __arm__\n\/\/ ARM ABI - 32-bit guards.\n\n\/**\n * Acquires a lock on a guard, returning 0 if the object has already been\n * initialised, and 1 if it has not. If the object is already constructed then\n * this function just needs to read a byte from memory and return.\n *\/\nextern \"C\" int __cxa_guard_acquire(volatile int32_t *guard_object)\n{\n\tif ((1<<31) == *guard_object) { return 0; }\n\t\/\/ If we can atomically move the value from 0 -> 1, then this is\n\t\/\/ uninitialised.\n\tif (__sync_bool_compare_and_swap(guard_object, 0, 1))\n\t{\n\t\treturn 1;\n\t}\n\t\/\/ If the value is not 0, some other thread was initialising this. Spin\n\t\/\/ until it's finished.\n\twhile (__sync_bool_compare_and_swap(guard_object, (1<<31), (1<<31)))\n\t{\n\t\t\/\/ If the other thread aborted, then we grab the lock\n\t\tif (__sync_bool_compare_and_swap(guard_object, 0, 1))\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t\tsched_yield();\n\t}\n\treturn 0;\n}\n\n\/**\n * Releases the lock without marking the object as initialised. This function\n * is called if initialising a static causes an exception to be thrown.\n *\/\nextern \"C\" void __cxa_guard_abort(int32_t *guard_object)\n{\n\tassert(__sync_bool_compare_and_swap(guard_object, 1, 0));\n}\n\/**\n * Releases the guard and marks the object as initialised. This function is\n * called after successful initialisation of a static.\n *\/\nextern \"C\" void __cxa_guard_release(int32_t *guard_object)\n{\n\tassert(__sync_bool_compare_and_swap(guard_object, 1, (1<<31)));\n}\n\n\n#else\n\/\/ Itanium ABI: 64-bit guards\n\n\/**\n * Returns a pointer to the low 32 bits in a 64-bit value, respecting the\n * platform's byte order.\n *\/\nstatic int32_t *low_32_bits(volatile int64_t *ptr)\n{\n\tint32_t *low= (int32_t*)ptr;\n\t\/\/ Test if the machine is big endian - constant propagation at compile time\n\t\/\/ should eliminate this completely.\n\tint one = 1;\n\tif (*(char*)&one != 1)\n\t{\n\t\tlow++;\n\t}\n\treturn low;\n}\n\n\/**\n * Acquires a lock on a guard, returning 0 if the object has already been\n * initialised, and 1 if it has not. If the object is already constructed then\n * this function just needs to read a byte from memory and return.\n *\/\nextern \"C\" int __cxa_guard_acquire(volatile int64_t *guard_object)\n{\n\tchar first_byte = (*guard_object) >> 56;\n\tif (1 == first_byte) { return 0; }\n\tint32_t *lock = low_32_bits(guard_object);\n\t\/\/ Simple spin lock using the low 32 bits. We assume that concurrent\n\t\/\/ attempts to initialize statics are very rare, so we don't need to\n\t\/\/ optimise for the case where we have lots of threads trying to acquire\n\t\/\/ the lock at the same time.\n\twhile (!__sync_bool_compare_and_swap_4(lock, 0, 1))\n\t{\n\t\tif (1 == ((*guard_object) >> 56))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tsched_yield();\n\t}\n\t\/\/ We have to test the guard again, in case another thread has performed\n\t\/\/ the initialisation while we were trying to acquire the lock.\n\tfirst_byte = (*guard_object) >> 56;\n\treturn (1 != first_byte);\n}\n\n\/**\n * Releases the lock without marking the object as initialised. This function\n * is called if initialising a static causes an exception to be thrown.\n *\/\nextern \"C\" void __cxa_guard_abort(int64_t *guard_object)\n{\n\tint32_t *lock = low_32_bits(guard_object);\n\t*lock = 0;\n}\n\/**\n * Releases the guard and marks the object as initialised. This function is\n * called after successful initialisation of a static.\n *\/\nextern \"C\" void __cxa_guard_release(int64_t *guard_object)\n{\n\t\/\/ Set the first byte to 1\n\t*guard_object |= ((int64_t)1) << 56;\n\t__cxa_guard_abort(guard_object);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2014, Stefan Kohlbrecher, TU Darmstadt\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of TU Darmstadt, nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\n#include \n#include \n\n#include \n#include \n\nmove_group::OctomapRaycastCapability::OctomapRaycastCapability():\n MoveGroupCapability(\"OctomapRaycastCapability\")\n{\n}\n\nvoid move_group::OctomapRaycastCapability::initialize()\n{\n\n node_handle_.param(\"octomap_min_distance_to_obstacle\", octo_min_distance_ ,0.05);\n\n ros::AdvertiseServiceOptions ops=ros::AdvertiseServiceOptions::create(\"get_distance_to_obstacle\", boost::bind(&move_group::OctomapRaycastCapability::lookupServiceCallback, this,_1,_2),ros::VoidConstPtr(),&service_queue_);\n dist_lookup_srv_server_ = node_handle_.advertiseService(ops);\n\n service_thread_=boost::thread(boost::bind(&move_group::OctomapRaycastCapability::serviceThread,this));\n\n m_markerPub = node_handle_.advertise(\"distance_to_obstacle_debug_markers\", 1, false);\n\n\n tf_ = this->context_->planning_scene_monitor_->getTFClient();\n}\n\nvoid move_group::OctomapRaycastCapability::serviceThread(){\n ros::Rate rate(100.0);\n while (ros::ok()){\n service_queue_.callAvailable(ros::WallDuration(1.0));\n rate.sleep();\n }\n}\n\nbool move_group::OctomapRaycastCapability::lookupServiceCallback(hector_nav_msgs::GetDistanceToObstacle::Request &req,\n hector_nav_msgs::GetDistanceToObstacle::Response &res )\n{\n\n ROS_DEBUG(\"Octomap distance lookup service called\");\n tf::StampedTransform camera_transform;\n\n const std::string target_frame = context_->planning_scene_monitor_->getPlanningScene()->getPlanningFrame();\n\n try{\n tf_->waitForTransform(target_frame ,req.point.header.frame_id, req.point.header.stamp, ros::Duration(1.0));\n tf_->lookupTransform(target_frame, req.point.header.frame_id, req.point.header.stamp, camera_transform);\n }catch(tf::TransformException e){\n ROS_ERROR(\"Transform failed in lookup distance service call: %s\",e.what());\n return false;\n }\n\n bool useOutliers = true;\n\n\n const octomap::point3d origin = octomap::pointTfToOctomap(camera_transform.getOrigin());\n\n tf::Point end_point = camera_transform * tf::Point(req.point.point.x, req.point.point.y, req.point.point.z);\n tf::Vector3 direction = end_point - camera_transform.getOrigin();\n\n const octomap::point3d directionOc = octomap::pointTfToOctomap(direction);\n std::vector endPoints;\n std::vector distances;\n int n=3;\n endPoints.resize(1);\n std::vector directions;\n directions.push_back(directionOc);\n\n planning_scene_monitor::LockedPlanningSceneRO ls (context_->planning_scene_monitor_);\n\n \/\/ Below is inspired by\n \/\/ https:\/\/github.com\/ros-planning\/moveit_core\/blob\/jade-devel\/planning_scene\/src\/planning_scene.cpp#L850\n \/\/ and quite hacky. There should be a better way to access the octomap (at least read-only)?\n collision_detection::CollisionWorld::ObjectConstPtr map = ls.getPlanningSceneMonitor()->getPlanningScene()->getWorld()->getObject(\"\");\n const shapes::OcTree* octree_shape = static_cast(map->shapes_[0].get());\n const boost::shared_ptr octree_ = octree_shape->octree;\n\n if(octree_->castRay(origin,directions[0],endPoints[0],true,5.0)) {\n distances.push_back(origin.distance(endPoints[0]));\n }\n\n if (distances.size()!=0) {\n int count_outliers;\n endPoints.resize(1+(n*2));\n get_endpoints(origin, *octree_, distances[0], direction, directions, endPoints, n);\n if (useOutliers) {\n double distance_threshold=0.7;\n count_outliers=0;\n for (size_t i =1;idistance_threshold) {\n count_outliers++;\n }\n }\n ROS_DEBUG(\"corner case: number of outliers: %d \",count_outliers);\n }\n\n res.distance = distances[0];\n\n res.end_point.header.frame_id = target_frame;\n res.end_point.header.stamp = req.point.header.stamp;\n res.end_point.point.x = endPoints[0].x();\n res.end_point.point.y = endPoints[0].y();\n res.end_point.point.z = endPoints[0].z();\n\n if (res.distance < octo_min_distance_) {\n res.distance = -1.0;\n ROS_WARN(\"Octomap GetDistanceToObstacle got distance under min_Distance -> returning -1.0\");\n }\n\n if (useOutliers) {\n if (count_outliers>=n-1) {\n res.distance=-1.0;\n ROS_DEBUG(\"Octomap GetDistanceToObstacle Corner Case\");\n }\n }\n } else {\n res.distance=-1.0;\n }\n\n ROS_DEBUG(\"Result: getDistanceObstacle_Octo: distance: %f\",res.distance);\n if (m_markerPub.getNumSubscribers() > 0){\n visualization_msgs::MarkerArray marker_array;\n visualization_msgs::Marker marker;\n marker.header.stamp = req.point.header.stamp;\n marker.header.frame_id = target_frame;\n marker.type = visualization_msgs::Marker::LINE_LIST;\n marker.action = visualization_msgs::Marker::ADD;\n marker.color.r= 1.0;\n marker.color.a = 1.0;\n marker.scale.x = 0.02;\n marker.ns =\"\";\n marker.action = visualization_msgs::Marker::ADD;\n marker.pose.orientation.w = 1.0;\n\n std::vector point_vector;\n for (size_t i = 0; i < endPoints.size(); ++i){\n geometry_msgs::Point tmp = octomap::pointOctomapToMsg(origin);\n point_vector.push_back(tmp);\n\n tmp = octomap::pointOctomapToMsg(endPoints[i]);\n point_vector.push_back(tmp);\n }\n marker.points=point_vector;\n marker_array.markers.push_back(marker);\n m_markerPub.publish(marker_array);\n }\n\n return true;\n\n}\n\nvoid move_group::OctomapRaycastCapability::get_endpoints(const octomap::point3d& origin,\n const octomap::OcTree& octree,\n const float reference_distance,\n const tf::Vector3& direction,\n std::vector& directions,\n std::vector& endPoints,\n int n){\n tf::Vector3 z_axis(0,0,1);\n\n double tolerance=octree.getResolution()*0.05;\n\n for (int i=1;i<=n;i++){\n double angle=std::atan2((octree.getResolution()*i)+tolerance,reference_distance);\n\n tf::Vector3 direction_z_plus = direction.rotate(z_axis, +angle);\n tf::Vector3 direction_z_minus = direction.rotate(z_axis, -angle);\n\n const octomap::point3d direction_z_plus_Oc = octomap::pointTfToOctomap(direction_z_plus);\n const octomap::point3d direction_z_minus_Oc = octomap::pointTfToOctomap(direction_z_minus);\n\n directions.push_back(direction_z_plus_Oc);\n directions.push_back(direction_z_minus_Oc);\n\n octree.castRay(origin,directions[2*i-1],endPoints[2*i-1],true,5.0);\n octree.castRay(origin,directions[2*i],endPoints[2*i],true,5.0);\n\n }\n}\n\n\/*\nvoid move_group::OctomapRaycastCapability::visTimerCallback(const ros::TimerEvent& event)\n{\n if (octomap_full_pub_.getNumSubscribers() > 0){\n\n moveit_msgs::PlanningScene tmp;\n moveit_msgs::PlanningSceneComponents comp;\n std::string octomap_frame_id;\n comp.components = moveit_msgs::PlanningSceneComponents::OCTOMAP;\n\n {\n planning_scene_monitor::LockedPlanningSceneRO ls (context_->planning_scene_monitor_);\n ls.getPlanningSceneMonitor()->getPlanningScene()->getPlanningSceneMsg(tmp, comp);\n octomap_frame_id = ls.getPlanningSceneMonitor()->getPlanningScene()->getPlanningFrame();\n }\n\n tmp.world.octomap.octomap.header.frame_id = octomap_frame_id;\n\n octomap_full_pub_.publish(tmp.world.octomap.octomap);\n }\n}\n*\/\n\n\/\/bool move_group::OctomapAccessCapability::clearOctomap(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res)\n\/\/{\n\/\/ if (!context_->planning_scene_monitor_)\n\/\/ {\n\/\/ ROS_ERROR(\"Cannot clear octomap since planning_scene_monitor_ does not exist.\");\n\/\/ return true;\n\/\/ }\n\n\/\/ ROS_INFO(\"Clearing octomap...\");\n\/\/ context_->planning_scene_monitor_->clearOctomap();\n\/\/ ROS_INFO(\"Octomap cleared.\");\n\/\/ return true;\n\/\/}\n\n\n#include \nCLASS_LOADER_REGISTER_CLASS(move_group::OctomapRaycastCapability, move_group::MoveGroupCapability)\nRemove obsolete code\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2014, Stefan Kohlbrecher, TU Darmstadt\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of TU Darmstadt, nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\n#include \n#include \n\n#include \n#include \n\nmove_group::OctomapRaycastCapability::OctomapRaycastCapability():\n MoveGroupCapability(\"OctomapRaycastCapability\")\n{\n}\n\nvoid move_group::OctomapRaycastCapability::initialize()\n{\n\n node_handle_.param(\"octomap_min_distance_to_obstacle\", octo_min_distance_ ,0.05);\n\n ros::AdvertiseServiceOptions ops=ros::AdvertiseServiceOptions::create(\"get_distance_to_obstacle\", boost::bind(&move_group::OctomapRaycastCapability::lookupServiceCallback, this,_1,_2),ros::VoidConstPtr(),&service_queue_);\n dist_lookup_srv_server_ = node_handle_.advertiseService(ops);\n\n service_thread_=boost::thread(boost::bind(&move_group::OctomapRaycastCapability::serviceThread,this));\n\n m_markerPub = node_handle_.advertise(\"distance_to_obstacle_debug_markers\", 1, false);\n\n\n tf_ = this->context_->planning_scene_monitor_->getTFClient();\n}\n\nvoid move_group::OctomapRaycastCapability::serviceThread(){\n ros::Rate rate(100.0);\n while (ros::ok()){\n service_queue_.callAvailable(ros::WallDuration(1.0));\n rate.sleep();\n }\n}\n\nbool move_group::OctomapRaycastCapability::lookupServiceCallback(hector_nav_msgs::GetDistanceToObstacle::Request &req,\n hector_nav_msgs::GetDistanceToObstacle::Response &res )\n{\n\n ROS_DEBUG(\"Octomap distance lookup service called\");\n tf::StampedTransform camera_transform;\n\n const std::string target_frame = context_->planning_scene_monitor_->getPlanningScene()->getPlanningFrame();\n\n try{\n tf_->waitForTransform(target_frame ,req.point.header.frame_id, req.point.header.stamp, ros::Duration(1.0));\n tf_->lookupTransform(target_frame, req.point.header.frame_id, req.point.header.stamp, camera_transform);\n }catch(tf::TransformException e){\n ROS_ERROR(\"Transform failed in lookup distance service call: %s\",e.what());\n return false;\n }\n\n bool useOutliers = true;\n\n\n const octomap::point3d origin = octomap::pointTfToOctomap(camera_transform.getOrigin());\n\n tf::Point end_point = camera_transform * tf::Point(req.point.point.x, req.point.point.y, req.point.point.z);\n tf::Vector3 direction = end_point - camera_transform.getOrigin();\n\n const octomap::point3d directionOc = octomap::pointTfToOctomap(direction);\n std::vector endPoints;\n std::vector distances;\n int n=3;\n endPoints.resize(1);\n std::vector directions;\n directions.push_back(directionOc);\n\n planning_scene_monitor::LockedPlanningSceneRO ls (context_->planning_scene_monitor_);\n\n \/\/ Below is inspired by\n \/\/ https:\/\/github.com\/ros-planning\/moveit_core\/blob\/jade-devel\/planning_scene\/src\/planning_scene.cpp#L850\n \/\/ and quite hacky. There should be a better way to access the octomap (at least read-only)?\n collision_detection::CollisionWorld::ObjectConstPtr map = ls.getPlanningSceneMonitor()->getPlanningScene()->getWorld()->getObject(\"\");\n const shapes::OcTree* octree_shape = static_cast(map->shapes_[0].get());\n const boost::shared_ptr octree_ = octree_shape->octree;\n\n if(octree_->castRay(origin,directions[0],endPoints[0],true,5.0)) {\n distances.push_back(origin.distance(endPoints[0]));\n }\n\n if (distances.size()!=0) {\n int count_outliers;\n endPoints.resize(1+(n*2));\n get_endpoints(origin, *octree_, distances[0], direction, directions, endPoints, n);\n if (useOutliers) {\n double distance_threshold=0.7;\n count_outliers=0;\n for (size_t i =1;idistance_threshold) {\n count_outliers++;\n }\n }\n ROS_DEBUG(\"corner case: number of outliers: %d \",count_outliers);\n }\n\n res.distance = distances[0];\n\n res.end_point.header.frame_id = target_frame;\n res.end_point.header.stamp = req.point.header.stamp;\n res.end_point.point.x = endPoints[0].x();\n res.end_point.point.y = endPoints[0].y();\n res.end_point.point.z = endPoints[0].z();\n\n if (res.distance < octo_min_distance_) {\n res.distance = -1.0;\n ROS_WARN(\"Octomap GetDistanceToObstacle got distance under min_Distance -> returning -1.0\");\n }\n\n if (useOutliers) {\n if (count_outliers>=n-1) {\n res.distance=-1.0;\n ROS_DEBUG(\"Octomap GetDistanceToObstacle Corner Case\");\n }\n }\n } else {\n res.distance=-1.0;\n }\n\n ROS_DEBUG(\"Result: getDistanceObstacle_Octo: distance: %f\",res.distance);\n if (m_markerPub.getNumSubscribers() > 0){\n visualization_msgs::MarkerArray marker_array;\n visualization_msgs::Marker marker;\n marker.header.stamp = req.point.header.stamp;\n marker.header.frame_id = target_frame;\n marker.type = visualization_msgs::Marker::LINE_LIST;\n marker.action = visualization_msgs::Marker::ADD;\n marker.color.r= 1.0;\n marker.color.a = 1.0;\n marker.scale.x = 0.02;\n marker.ns =\"\";\n marker.action = visualization_msgs::Marker::ADD;\n marker.pose.orientation.w = 1.0;\n\n std::vector point_vector;\n for (size_t i = 0; i < endPoints.size(); ++i){\n geometry_msgs::Point tmp = octomap::pointOctomapToMsg(origin);\n point_vector.push_back(tmp);\n\n tmp = octomap::pointOctomapToMsg(endPoints[i]);\n point_vector.push_back(tmp);\n }\n marker.points=point_vector;\n marker_array.markers.push_back(marker);\n m_markerPub.publish(marker_array);\n }\n\n return true;\n\n}\n\nvoid move_group::OctomapRaycastCapability::get_endpoints(const octomap::point3d& origin,\n const octomap::OcTree& octree,\n const float reference_distance,\n const tf::Vector3& direction,\n std::vector& directions,\n std::vector& endPoints,\n int n){\n tf::Vector3 z_axis(0,0,1);\n\n double tolerance=octree.getResolution()*0.05;\n\n for (int i=1;i<=n;i++){\n double angle=std::atan2((octree.getResolution()*i)+tolerance,reference_distance);\n\n tf::Vector3 direction_z_plus = direction.rotate(z_axis, +angle);\n tf::Vector3 direction_z_minus = direction.rotate(z_axis, -angle);\n\n const octomap::point3d direction_z_plus_Oc = octomap::pointTfToOctomap(direction_z_plus);\n const octomap::point3d direction_z_minus_Oc = octomap::pointTfToOctomap(direction_z_minus);\n\n directions.push_back(direction_z_plus_Oc);\n directions.push_back(direction_z_minus_Oc);\n\n octree.castRay(origin,directions[2*i-1],endPoints[2*i-1],true,5.0);\n octree.castRay(origin,directions[2*i],endPoints[2*i],true,5.0);\n\n }\n}\n\n#include \nCLASS_LOADER_REGISTER_CLASS(move_group::OctomapRaycastCapability, move_group::MoveGroupCapability)\n<|endoftext|>"} {"text":"#include \"hrwplayer.h\"\n\nQString moduleFileName;\n\nHrwPlayer::HrwPlayer()\n{\n setupUi(this);\n\n audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);\n mediaObject = new Phonon::MediaObject(this);\n metaInformationResolver = new Phonon::MediaObject(this);\n\n mediaObject->setTickInterval(1000); \/\/ for remaining time display\n\n Phonon::createPath(mediaObject, audioOutput);\n\n PlayButton->setIcon(QIcon::fromTheme(\"media-playback-start\"));\n StopButton->setIcon(QIcon::fromTheme(\"media-playback-stop\"));\n PauseButton->setIcon(QIcon::fromTheme(\"media-playback-pause\"));\n NextButton->setIcon(QIcon::fromTheme(\"media-skip-forward\"));\n PrevButton->setIcon(QIcon::fromTheme(\"media-skip-backward\"));\n FavoriteButton->setIcon(QIcon::fromTheme(\"bookmarks\"));\n\n progressBar->setVisible(false);\n DoConnects();\n InitializeSongsList();\n}\n\nvoid HrwPlayer::DoConnects()\n{\n connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));\n connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)),\n\t this, SLOT(StateChanged(Phonon::State,Phonon::State)));\n \/\/ connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)),\n \/\/ this, SLOT(metaStateChanged(Phonon::State,Phonon::State)));\n \/\/ connect(mediaObject, SIGNAL(currentSourceChanged(Phonon::MediaSource)),\n \/\/ this, SLOT(sourceChanged(Phonon::MediaSource)));\n connect(mediaObject, SIGNAL(finished()), this, SLOT(FinishedPlaying()));\n\n connect(SongsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PlaySelected(QListWidgetItem*)));\n connect(AuthorsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PopulateSongs(QListWidgetItem*)));\n connect(PlayButton, SIGNAL(clicked()), mediaObject, SLOT(play()));\n connect(PauseButton, SIGNAL(clicked()), mediaObject, SLOT(pause()) );\n connect(StopButton, SIGNAL(clicked()), mediaObject, SLOT(stop()));\n connect(NextButton, SIGNAL(clicked()), this, SLOT(FinishedPlaying()));\n connect(FavoriteButton, SIGNAL(clicked()), this, SLOT(handleFavorite()));\n\n seekSlider->setMediaObject(mediaObject);\n volumeSlider->setAudioOutput(audioOutput);\n}\n\nvoid HrwPlayer::InitializeSongsList()\n{\n QSqlDatabase db = QSqlDatabase::addDatabase(\"QSQLITE\");\n db.setDatabaseName(\"utwory.sqlite\");\n db.open();\n\n QSqlQuery query(\"SELECT DISTINCT(author) as author FROM songs ORDER BY author\");\n QStringList authors;\n while (query.next()) {\n\tauthors << query.value(0).toString();\n }\n AuthorsList->insertItems(0, authors);\n PopulateSongs(AuthorsList->item(0));\n};\n\nHrwPlayer::~HrwPlayer() {};\n\nvoid HrwPlayer::JustPlay(QString fileName)\n{\n mediaObject->setCurrentSource(fileName);\n QFileInfo fileinfo(fileName);\n TitleLabel->setText(\"Playing \\\"\" + fileinfo.baseName() + \"\\\" by \" + CurrentAuthor);\n TimeLabel->setText(\"00:00\");\n mediaObject->play();\n}\n\nvoid HrwPlayer::StateChanged(Phonon::State newState, Phonon::State \/* oldState *\/)\n{\n switch (newState)\n {\n\tcase Phonon::ErrorState:\n\t if (mediaObject->errorType() == Phonon::FatalError)\n\t {\n\t\tQMessageBox::warning(this, tr(\"Fatal Error\"),\n\t\t\tmediaObject->errorString());\n\t }\n\t else\n\t {\n\t\tQMessageBox::warning(this, tr(\"Error\"),\n\t\t\tmediaObject->errorString());\n\t }\n\t break;\n\tcase Phonon::PlayingState:\n\t PlayButton->setEnabled(false);\n\t PauseButton->setEnabled(true);\n\t StopButton->setEnabled(true);\n\t break;\n\tcase Phonon::StoppedState:\n\t StopButton->setEnabled(false);\n\t PlayButton->setEnabled(true);\n\t PauseButton->setEnabled(false);\n\t break;\n\tcase Phonon::PausedState:\n\t PauseButton->setEnabled(false);\n\t StopButton->setEnabled(true);\n\t PlayButton->setEnabled(true);\n\t break;\n\tcase Phonon::BufferingState:\n\t break;\n\tdefault:\n\t ;\n }\n}\n\nvoid HrwPlayer::PlaySelected(QListWidgetItem* selectedItem)\n{\n QString fileName = buildModuleName(selectedItem->text());\n\n qDebug() << \"PlaySelected - module to play: \" << fileName ;\n\n if(!QFile::exists(fileName))\n {\n\tqDebug() << \"PlaySelected - module not available\";\n\n\tFetchSong(buildModuleName(selectedItem->text(), false));\n }\n else\n {\n\tJustPlay(fileName);\n }\n}\n\nvoid HrwPlayer::PopulateSongs(QListWidgetItem* selectedItem)\n{\n CurrentAuthor = selectedItem->text();\n QSqlQuery query(\"SELECT title FROM songs WHERE author = '\" + CurrentAuthor + \"' ORDER BY title\");\n\n qDebug() << \"PopulateSongs - switching to author: \" << CurrentAuthor;\n\n QStringList songs;\n while (query.next()) {\n\tsongs << query.value(0).toString().remove(QRegExp(\".mod$\"));\n }\n\n SongsList->clear();\n SongsList->insertItems(0, songs);\n}\n\nvoid HrwPlayer::FinishedPlaying()\n{\n QListWidgetItem* selectedItem;\n\n if(SongsList->currentRow() == (SongsList->count() - 1))\n {\n\t\/\/ for looping over one author\n\/\/ selectedItem = SongsList->item(0);\n\/\/ SongsList->setCurrentRow(0);\n\tPopulateSongs(AuthorsList->item(AuthorsList->currentRow() + 1));\n\tselectedItem = SongsList->item(0);\n\tAuthorsList->setCurrentRow(AuthorsList->currentRow() + 1);\n\tSongsList->setCurrentRow(0);\n }\n else\n {\n\tselectedItem = SongsList->item(SongsList->currentRow() + 1);\n\tSongsList->setCurrentRow(SongsList->currentRow() + 1);\n }\n\n qDebug() << \"play?\";\n PlaySelected(selectedItem);\n}\n\nvoid HrwPlayer::tick(qint64 time)\n{\n QTime displayTime(0, (time \/ 60000) % 60, (time \/ 1000) % 60);\n\n TimeLabel->setText(displayTime.toString(\"mm:ss\"));\n}\n\nvoid HrwPlayer::FetchSong(QString fileName)\n{\n QNetworkAccessManager *manager = new QNetworkAccessManager(this);\n connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));\n\n QString urlSong = \"ftp:\/\/ftp.amigascne.org\/mirrors\/ftp.modland.com\/pub\/modules\/Protracker\/\" + fileName ;\n\n qDebug() << \"FetchSong - module to fetch: \" << urlSong ;\n\n QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(urlSong)));\n\n progressBar->reset();\n connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(handleProgressBar(qint64, qint64))); \n progressBar->setVisible(true);\n}\n\nvoid HrwPlayer::handleProgressBar(qint64 bytesfetched, qint64 bytestotal)\n{\n progressBar->setMaximum(bytestotal);\n progressBar->setValue(bytesfetched);\n}\n\nvoid HrwPlayer::downloadFinished(QNetworkReply *reply)\n{\n QUrl url = reply->url();\n\n if(reply->error())\n {\n\t\/\/TODO\n\tqDebug() << \"downloadFinished todo \";\n }\n else\n {\n\tQDir katalog(\"modules\/\");\n\tkatalog.mkpath(CurrentAuthor);\n\n\tQFileInfo fileinfo(url.path());\n\n\tQString fileName = buildModuleName(fileinfo.baseName());\n\n\tQFile file(fileName);\n\tif(file.open(QIODevice::WriteOnly))\n\t{\n\t file.write(reply->readAll());\n\t file.close();\n\n\t qDebug() << \"downloadFinished - module fetched\";\n\n\t JustPlay(fileName);\n\t}\n }\n progressBar->setVisible(false);\n}\n\nQString HrwPlayer::buildModuleName(QString title, bool localName)\n{\n QString fullName;\n\n if(localName)\n\tfullName.append(\"modules\/\");\n\n fullName += CurrentAuthor + \"\/\" + title + \".mod\";\n\n return fullName;\n}\n\nvoid HrwPlayer::handleFavorite()\n{\n}\nadded some debugs#include \"hrwplayer.h\"\n\nQString moduleFileName;\n\nHrwPlayer::HrwPlayer()\n{\n qDebug() << \"HrwPlayer::HrwPlayer()\";\n\n setupUi(this);\n\n audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);\n mediaObject = new Phonon::MediaObject(this);\n metaInformationResolver = new Phonon::MediaObject(this);\n\n mediaObject->setTickInterval(1000); \/\/ for remaining time display\n\n Phonon::createPath(mediaObject, audioOutput);\n\n PlayButton->setIcon(QIcon::fromTheme(\"media-playback-start\"));\n StopButton->setIcon(QIcon::fromTheme(\"media-playback-stop\"));\n PauseButton->setIcon(QIcon::fromTheme(\"media-playback-pause\"));\n NextButton->setIcon(QIcon::fromTheme(\"media-skip-forward\"));\n PrevButton->setIcon(QIcon::fromTheme(\"media-skip-backward\"));\n FavoriteButton->setIcon(QIcon::fromTheme(\"bookmarks\"));\n\n progressBar->setVisible(false);\n DoConnects();\n InitializeSongsList();\n}\n\nvoid HrwPlayer::DoConnects()\n{\n qDebug() << \"HrwPlayer::DoConnects()\";\n\n connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));\n connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)),\n\t this, SLOT(StateChanged(Phonon::State,Phonon::State)));\n \/\/ connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)),\n \/\/ this, SLOT(metaStateChanged(Phonon::State,Phonon::State)));\n \/\/ connect(mediaObject, SIGNAL(currentSourceChanged(Phonon::MediaSource)),\n \/\/ this, SLOT(sourceChanged(Phonon::MediaSource)));\n connect(mediaObject, SIGNAL(finished()), this, SLOT(FinishedPlaying()));\n\n connect(SongsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PlaySelected(QListWidgetItem*)));\n connect(AuthorsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PopulateSongs(QListWidgetItem*)));\n connect(PlayButton, SIGNAL(clicked()), mediaObject, SLOT(play()));\n connect(PauseButton, SIGNAL(clicked()), mediaObject, SLOT(pause()) );\n connect(StopButton, SIGNAL(clicked()), mediaObject, SLOT(stop()));\n connect(NextButton, SIGNAL(clicked()), this, SLOT(FinishedPlaying()));\n connect(FavoriteButton, SIGNAL(clicked()), this, SLOT(handleFavorite()));\n\n seekSlider->setMediaObject(mediaObject);\n volumeSlider->setAudioOutput(audioOutput);\n}\n\nvoid HrwPlayer::InitializeSongsList()\n{\n qDebug() << \"HrwPlayer::InitializeSongsList()\";\n\n QSqlDatabase db = QSqlDatabase::addDatabase(\"QSQLITE\");\n db.setDatabaseName(\"utwory.sqlite\");\n db.open();\n\n QSqlQuery query(\"SELECT DISTINCT(author) as author FROM songs ORDER BY author\");\n QStringList authors;\n while (query.next()) {\n\tauthors << query.value(0).toString();\n }\n AuthorsList->insertItems(0, authors);\n PopulateSongs(AuthorsList->item(0));\n};\n\nHrwPlayer::~HrwPlayer() {};\n\nvoid HrwPlayer::JustPlay(QString fileName)\n{\n qDebug() << \"HrwPlayer::JustPlay()\";\n\n mediaObject->setCurrentSource(fileName);\n QFileInfo fileinfo(fileName);\n TitleLabel->setText(\"Playing \\\"\" + fileinfo.baseName() + \"\\\" by \" + CurrentAuthor);\n TimeLabel->setText(\"00:00\");\n mediaObject->play();\n}\n\nvoid HrwPlayer::StateChanged(Phonon::State newState, Phonon::State \/* oldState *\/)\n{\n qDebug() << \"HrwPlayer::StateChanged()\";\n\n switch (newState)\n {\n\tcase Phonon::ErrorState:\n\t if (mediaObject->errorType() == Phonon::FatalError)\n\t {\n\t\tQMessageBox::warning(this, tr(\"Fatal Error\"),\n\t\t\tmediaObject->errorString());\n\t }\n\t else\n\t {\n\t\tQMessageBox::warning(this, tr(\"Error\"),\n\t\t\tmediaObject->errorString());\n\t }\n\t break;\n\tcase Phonon::PlayingState:\n\t PlayButton->setEnabled(false);\n\t PauseButton->setEnabled(true);\n\t StopButton->setEnabled(true);\n\t break;\n\tcase Phonon::StoppedState:\n\t StopButton->setEnabled(false);\n\t PlayButton->setEnabled(true);\n\t PauseButton->setEnabled(false);\n\t break;\n\tcase Phonon::PausedState:\n\t PauseButton->setEnabled(false);\n\t StopButton->setEnabled(true);\n\t PlayButton->setEnabled(true);\n\t break;\n\tcase Phonon::BufferingState:\n\t break;\n\tdefault:\n\t ;\n }\n}\n\nvoid HrwPlayer::PlaySelected(QListWidgetItem* selectedItem)\n{\n qDebug() << \"HrwPlayer::PlaySelected()\";\n\n QString fileName = buildModuleName(selectedItem->text());\n\n qDebug() << \"\\t\" << \"PlaySelected - module to play: \" << fileName ;\n\n if(!QFile::exists(fileName))\n {\n\tqDebug() << \"\\t\" << \"PlaySelected - module not available\";\n\n\tFetchSong(buildModuleName(selectedItem->text(), false));\n }\n else\n {\n\tJustPlay(fileName);\n }\n}\n\nvoid HrwPlayer::PopulateSongs(QListWidgetItem* selectedItem)\n{\n qDebug() << \"HrwPlayer::PopulateSongs()\";\n\n CurrentAuthor = selectedItem->text();\n QSqlQuery query(\"SELECT title FROM songs WHERE author = '\" + CurrentAuthor + \"' ORDER BY title\");\n\n qDebug() << \"\\t\" << \"PopulateSongs - switching to author: \" << CurrentAuthor;\n\n QStringList songs;\n while (query.next()) {\n\tsongs << query.value(0).toString().remove(QRegExp(\".mod$\"));\n }\n\n SongsList->clear();\n SongsList->insertItems(0, songs);\n}\n\nvoid HrwPlayer::FinishedPlaying()\n{\n qDebug() << \"HrwPlayer::FinishedPlaying()\";\n\n QListWidgetItem* selectedItem;\n\n if(SongsList->currentRow() == (SongsList->count() - 1))\n {\n\t\/\/ for looping over one author\n\/\/ selectedItem = SongsList->item(0);\n\/\/ SongsList->setCurrentRow(0);\n\tPopulateSongs(AuthorsList->item(AuthorsList->currentRow() + 1));\n\tselectedItem = SongsList->item(0);\n\tAuthorsList->setCurrentRow(AuthorsList->currentRow() + 1);\n\tSongsList->setCurrentRow(0);\n }\n else\n {\n\tselectedItem = SongsList->item(SongsList->currentRow() + 1);\n\tSongsList->setCurrentRow(SongsList->currentRow() + 1);\n }\n\n qDebug() << \"\\t\" << \"play?\";\n PlaySelected(selectedItem);\n}\n\nvoid HrwPlayer::tick(qint64 time)\n{\n qDebug() << \"HrwPlayer::tick()\";\n\n QTime displayTime(0, (time \/ 60000) % 60, (time \/ 1000) % 60);\n\n TimeLabel->setText(displayTime.toString(\"mm:ss\"));\n}\n\nvoid HrwPlayer::FetchSong(QString fileName)\n{\n qDebug() << \"HrwPlayer::FetchSong()\";\n\n QNetworkAccessManager *manager = new QNetworkAccessManager(this);\n connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));\n\n QString urlSong = \"ftp:\/\/ftp.amigascne.org\/mirrors\/ftp.modland.com\/pub\/modules\/Protracker\/\" + fileName ;\n\n qDebug() << \"\\t\" << \"FetchSong - module to fetch: \" << urlSong ;\n\n QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(urlSong)));\n\n progressBar->reset();\n connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(handleProgressBar(qint64, qint64))); \n progressBar->setVisible(true);\n}\n\nvoid HrwPlayer::handleProgressBar(qint64 bytesfetched, qint64 bytestotal)\n{\n qDebug() << \"HrwPlayer::handleProgressBar()\";\n\n progressBar->setMaximum(bytestotal);\n progressBar->setValue(bytesfetched);\n}\n\nvoid HrwPlayer::downloadFinished(QNetworkReply *reply)\n{\n qDebug() << \"HrwPlayer::downloadFinished()\";\n\n QUrl url = reply->url();\n\n if(reply->error())\n {\n\t\/\/TODO\n\tqDebug() << \"\\t\" << \"downloadFinished todo \";\n }\n else\n {\n\tQDir katalog(\"modules\/\");\n\tkatalog.mkpath(CurrentAuthor);\n\n\tQFileInfo fileinfo(url.path());\n\n\tQString fileName = buildModuleName(fileinfo.baseName());\n\n\tQFile file(fileName);\n\tif(file.open(QIODevice::WriteOnly))\n\t{\n\t file.write(reply->readAll());\n\t file.close();\n\n\t qDebug() << \"\\t\" << \"downloadFinished - module fetched\";\n\n\t JustPlay(fileName);\n\t}\n }\n progressBar->setVisible(false);\n}\n\nQString HrwPlayer::buildModuleName(QString title, bool localName)\n{\n QString fullName;\n\n if(localName)\n\tfullName.append(\"modules\/\");\n\n fullName += CurrentAuthor + \"\/\" + title + \".mod\";\n\n return fullName;\n}\n\nvoid HrwPlayer::handleFavorite()\n{\n qDebug() << \"HrwPlayer::handleFavorite()\";\n\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Paul Russo 30\/07\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/** \\class TClingTypedefInfo\nEmulation of the CINT TypedefInfo class.\n\nThe CINT C++ interpreter provides an interface to metadata about\na typedef through the TypedefInfo class. This class provides the\nsame functionality, using an interface as close as possible to\nTypedefInfo but the typedef metadata comes from the Clang C++\ncompiler, not CINT.\n*\/\n\n#include \"TClingTypedefInfo.h\"\n\n#include \"TDictionary.h\"\n#include \"TError.h\"\n#include \"TMetaUtils.h\"\n#include \"Rtypes.h\" \/\/ for gDebug\n#include \"ThreadLocalStorage.h\"\n\n#include \"cling\/Interpreter\/LookupHelper.h\"\n#include \"cling\/Utils\/AST.h\"\n#include \"clang\/AST\/Attr.h\"\n\nusing namespace clang;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Lookup named typedef and initialize the iterator to point to it.\n\/\/\/ Yields a non-iterable TClingTypedefInfo (fIter is invalid).\n\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const char *name)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle(\"\")\n{\n Init(name);\n}\n\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const clang::TypedefNameDecl *TdefD)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD),\n fTitle(\"\")\n{\n \/\/ Initialize with a clang::TypedefDecl.\n \/\/ fIter is invalid; cannot call Next().\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Get the current typedef declaration.\n\nconst clang::Decl *TClingTypedefInfo::GetDecl() const\n{\n return fDecl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Lookup named typedef and reset the iterator to point to it.\n\nvoid TClingTypedefInfo::Init(const char *name)\n{\n fDecl = 0;\n\n \/\/ Reset the iterator to invalid.\n fFirstTime = true;\n fDescend = false;\n fIter = clang::DeclContext::decl_iterator();\n fIterStack.clear();\n\n \/\/ Some trivial early exit, covering many cases in a cheap way.\n if (!name || !*name) return;\n const char lastChar = name[strlen(name) - 1];\n if (lastChar == '*' || lastChar == '&' || !strncmp(name, \"const \", 6))\n return;\n\n \/\/ Ask the cling interpreter to lookup the name for us.\n const cling::LookupHelper& lh = fInterp->getLookupHelper();\n clang::QualType QT = lh.findType(name,\n gDebug > 5 ? cling::LookupHelper::WithDiagnostics\n : cling::LookupHelper::NoDiagnostics);\n if (QT.isNull()) {\n std::string buf = TClassEdit::InsertStd(name);\n if (buf != name) {\n QT = lh.findType(buf,\n gDebug > 5 ? cling::LookupHelper::WithDiagnostics\n : cling::LookupHelper::NoDiagnostics);\n }\n if (QT.isNull()) {\n return;\n }\n }\n const clang::TypedefType *td = QT->getAs();\n \/\/ if (fDecl && !llvm::isa(fDecl)) {\n if (!td) {\n \/\/ If what the lookup found is not a typedef, ignore it.\n return;\n }\n fDecl = td->getDecl();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return true if the current iterator position is valid.\n\nbool TClingTypedefInfo::IsValid() const\n{\n return fDecl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Increment the iterator, return true if new position is valid.\n\nint TClingTypedefInfo::InternalNext()\n{\n if (!*fIter) {\n \/\/ Iterator is already invalid.\n if (fFirstTime && fDecl) {\n std::string buf;\n clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy());\n llvm::raw_string_ostream stream(buf);\n llvm::dyn_cast(fDecl)\n ->getNameForDiagnostic(stream, Policy, \/*Qualified=*\/false);\n stream.flush();\n Error(\"TClingTypedefInfo::InternalNext\",\"Next called but iteration not prepared for %s!\",buf.c_str());\n }\n return 0;\n }\n \/\/ Deserialization might happen during the iteration.\n cling::Interpreter::PushTransactionRAII pushedT(fInterp);\n while (true) {\n \/\/ Advance to next usable decl, or return if\n \/\/ there is no next usable decl.\n if (fFirstTime) {\n \/\/ The cint semantics are strange.\n fFirstTime = false;\n }\n else {\n \/\/ Advance the iterator one decl, descending into\n \/\/ the current decl context if necessary.\n if (!fDescend) {\n \/\/ Do not need to scan the decl context of the\n \/\/ current decl, move on to the next decl.\n ++fIter;\n }\n else {\n \/\/ Descend into the decl context of the current decl.\n fDescend = false;\n fIterStack.push_back(fIter);\n clang::DeclContext *dc = llvm::cast(*fIter);\n fIter = dc->decls_begin();\n }\n \/\/ Fix it if we went past the end.\n while (!*fIter && fIterStack.size()) {\n fIter = fIterStack.back();\n fIterStack.pop_back();\n ++fIter;\n }\n \/\/ Check for final termination.\n if (!*fIter) {\n \/\/ We have reached the end of the translation unit, all done.\n fDecl = 0;\n return 0;\n }\n }\n \/\/ Return if this decl is a typedef.\n if (llvm::isa(*fIter)) {\n fDecl = *fIter;\n return 1;\n }\n \/\/ Descend into namespaces and classes.\n clang::Decl::Kind dk = fIter->getKind();\n if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) ||\n (dk == clang::Decl::ClassTemplateSpecialization)) {\n fDescend = true;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Increment the iterator.\n\nint TClingTypedefInfo::Next()\n{\n return InternalNext();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return a bit mask of metadata about the current typedef.\n\nlong TClingTypedefInfo::Property() const\n{\n if (!IsValid()) {\n return 0L;\n }\n long property = 0L;\n property |= kIsTypedef;\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType().getCanonicalType();\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n while (1) {\n if (qt->isArrayType()) {\n qt = llvm::cast(qt)->getElementType();\n continue;\n }\n else if (qt->isReferenceType()) {\n property |= kIsReference;\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isPointerType()) {\n property |= kIsPointer;\n if (qt.isConstQualified()) {\n property |= kIsConstPointer;\n }\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isMemberPointerType()) {\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n break;\n }\n if (qt->isBuiltinType()) {\n property |= kIsFundamental;\n }\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n return property;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the size in bytes of the underlying type of the current typedef.\n\nint TClingTypedefInfo::Size() const\n{\n if (!IsValid()) {\n return 1;\n }\n clang::ASTContext &context = fDecl->getASTContext();\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType();\n if (qt->isDependentType()) {\n \/\/ The underlying type is dependent on a template parameter,\n \/\/ we have no idea what it is yet.\n return 0;\n }\n if (const clang::RecordType *rt = qt->getAs()) {\n if (!rt->getDecl()->getDefinition()) {\n \/\/ This is a typedef to a forward-declared type.\n return 0;\n }\n }\n \/\/ Note: This is an int64_t.\n clang::CharUnits::QuantityType quantity =\n context.getTypeSizeInChars(qt).getQuantity();\n \/\/ Truncate cast to fit the CINT interface.\n return static_cast(quantity);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Get the name of the underlying type of the current typedef.\n\nconst char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const\n{\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n TTHREAD_TLS_DECL( std::string, truename);\n truename.clear();\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType underlyingType = td->getUnderlyingType();\n if (underlyingType->isBooleanType()) {\n return \"bool\";\n }\n const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext();\n ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt);\n\n return truename.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Get the name of the current typedef.\n\nconst char *TClingTypedefInfo::Name() const\n{\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n TTHREAD_TLS_DECL( std::string, fullname);\n fullname.clear();\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n const clang::ASTContext &ctxt = fDecl->getASTContext();\n ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp);\n return fullname.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst char *TClingTypedefInfo::Title()\n{\n if (!IsValid()) {\n return 0;\n }\n \/\/NOTE: We can't use it as a cache due to the \"thoughtful\" self iterator\n \/\/if (fTitle.size())\n \/\/ return fTitle.c_str();\n\n \/\/ Try to get the comment either from the annotation or the header file if present\n\n \/\/ Iterate over the redeclarations, we can have multiple definitions in the\n \/\/ redecl chain (came from merging of pcms).\n if (const TypedefNameDecl *TND = llvm::dyn_cast(GetDecl())) {\n if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) {\n if (AnnotateAttr *A = TND->getAttr()) {\n fTitle = A->getAnnotation().str();\n return fTitle.c_str();\n }\n }\n }\n else if (!GetDecl()->isFromASTFile()) {\n \/\/ Try to get the comment from the header file if present\n \/\/ but not for decls from AST file, where rootcling would have\n \/\/ created an annotation\n fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();\n }\n return fTitle.c_str();\n}\n\nDecls might get deserialized (see future tutorials\/v7\/simple.py).\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Paul Russo 30\/07\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/** \\class TClingTypedefInfo\nEmulation of the CINT TypedefInfo class.\n\nThe CINT C++ interpreter provides an interface to metadata about\na typedef through the TypedefInfo class. This class provides the\nsame functionality, using an interface as close as possible to\nTypedefInfo but the typedef metadata comes from the Clang C++\ncompiler, not CINT.\n*\/\n\n#include \"TClingTypedefInfo.h\"\n\n#include \"TDictionary.h\"\n#include \"TError.h\"\n#include \"TMetaUtils.h\"\n#include \"Rtypes.h\" \/\/ for gDebug\n#include \"ThreadLocalStorage.h\"\n\n#include \"cling\/Interpreter\/LookupHelper.h\"\n#include \"cling\/Utils\/AST.h\"\n#include \"clang\/AST\/Attr.h\"\n\nusing namespace clang;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Lookup named typedef and initialize the iterator to point to it.\n\/\/\/ Yields a non-iterable TClingTypedefInfo (fIter is invalid).\n\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const char *name)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle(\"\")\n{\n Init(name);\n}\n\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const clang::TypedefNameDecl *TdefD)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD),\n fTitle(\"\")\n{\n \/\/ Initialize with a clang::TypedefDecl.\n \/\/ fIter is invalid; cannot call Next().\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Get the current typedef declaration.\n\nconst clang::Decl *TClingTypedefInfo::GetDecl() const\n{\n return fDecl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Lookup named typedef and reset the iterator to point to it.\n\nvoid TClingTypedefInfo::Init(const char *name)\n{\n fDecl = 0;\n\n \/\/ Reset the iterator to invalid.\n fFirstTime = true;\n fDescend = false;\n fIter = clang::DeclContext::decl_iterator();\n fIterStack.clear();\n\n \/\/ Some trivial early exit, covering many cases in a cheap way.\n if (!name || !*name) return;\n const char lastChar = name[strlen(name) - 1];\n if (lastChar == '*' || lastChar == '&' || !strncmp(name, \"const \", 6))\n return;\n\n \/\/ Ask the cling interpreter to lookup the name for us.\n const cling::LookupHelper& lh = fInterp->getLookupHelper();\n clang::QualType QT = lh.findType(name,\n gDebug > 5 ? cling::LookupHelper::WithDiagnostics\n : cling::LookupHelper::NoDiagnostics);\n if (QT.isNull()) {\n std::string buf = TClassEdit::InsertStd(name);\n if (buf != name) {\n QT = lh.findType(buf,\n gDebug > 5 ? cling::LookupHelper::WithDiagnostics\n : cling::LookupHelper::NoDiagnostics);\n }\n if (QT.isNull()) {\n return;\n }\n }\n const clang::TypedefType *td = QT->getAs();\n \/\/ if (fDecl && !llvm::isa(fDecl)) {\n if (!td) {\n \/\/ If what the lookup found is not a typedef, ignore it.\n return;\n }\n fDecl = td->getDecl();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return true if the current iterator position is valid.\n\nbool TClingTypedefInfo::IsValid() const\n{\n return fDecl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Increment the iterator, return true if new position is valid.\n\nint TClingTypedefInfo::InternalNext()\n{\n if (!*fIter) {\n \/\/ Iterator is already invalid.\n if (fFirstTime && fDecl) {\n std::string buf;\n clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy());\n llvm::raw_string_ostream stream(buf);\n llvm::dyn_cast(fDecl)\n ->getNameForDiagnostic(stream, Policy, \/*Qualified=*\/false);\n stream.flush();\n Error(\"TClingTypedefInfo::InternalNext\",\"Next called but iteration not prepared for %s!\",buf.c_str());\n }\n return 0;\n }\n \/\/ Deserialization might happen during the iteration.\n cling::Interpreter::PushTransactionRAII pushedT(fInterp);\n while (true) {\n \/\/ Advance to next usable decl, or return if\n \/\/ there is no next usable decl.\n if (fFirstTime) {\n \/\/ The cint semantics are strange.\n fFirstTime = false;\n }\n else {\n \/\/ Advance the iterator one decl, descending into\n \/\/ the current decl context if necessary.\n if (!fDescend) {\n \/\/ Do not need to scan the decl context of the\n \/\/ current decl, move on to the next decl.\n ++fIter;\n }\n else {\n \/\/ Descend into the decl context of the current decl.\n fDescend = false;\n fIterStack.push_back(fIter);\n clang::DeclContext *dc = llvm::cast(*fIter);\n fIter = dc->decls_begin();\n }\n \/\/ Fix it if we went past the end.\n while (!*fIter && fIterStack.size()) {\n fIter = fIterStack.back();\n fIterStack.pop_back();\n ++fIter;\n }\n \/\/ Check for final termination.\n if (!*fIter) {\n \/\/ We have reached the end of the translation unit, all done.\n fDecl = 0;\n return 0;\n }\n }\n \/\/ Return if this decl is a typedef.\n if (llvm::isa(*fIter)) {\n fDecl = *fIter;\n return 1;\n }\n \/\/ Descend into namespaces and classes.\n clang::Decl::Kind dk = fIter->getKind();\n if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) ||\n (dk == clang::Decl::ClassTemplateSpecialization)) {\n fDescend = true;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Increment the iterator.\n\nint TClingTypedefInfo::Next()\n{\n return InternalNext();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return a bit mask of metadata about the current typedef.\n\nlong TClingTypedefInfo::Property() const\n{\n if (!IsValid()) {\n return 0L;\n }\n long property = 0L;\n property |= kIsTypedef;\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType().getCanonicalType();\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n while (1) {\n if (qt->isArrayType()) {\n qt = llvm::cast(qt)->getElementType();\n continue;\n }\n else if (qt->isReferenceType()) {\n property |= kIsReference;\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isPointerType()) {\n property |= kIsPointer;\n if (qt.isConstQualified()) {\n property |= kIsConstPointer;\n }\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isMemberPointerType()) {\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n break;\n }\n if (qt->isBuiltinType()) {\n property |= kIsFundamental;\n }\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n return property;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the size in bytes of the underlying type of the current typedef.\n\nint TClingTypedefInfo::Size() const\n{\n if (!IsValid()) {\n return 1;\n }\n clang::ASTContext &context = fDecl->getASTContext();\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType();\n if (qt->isDependentType()) {\n \/\/ The underlying type is dependent on a template parameter,\n \/\/ we have no idea what it is yet.\n return 0;\n }\n if (const clang::RecordType *rt = qt->getAs()) {\n if (!rt->getDecl()->getDefinition()) {\n \/\/ This is a typedef to a forward-declared type.\n return 0;\n }\n }\n\n \/\/ Deserialization might happen during the size calculation.\n cling::Interpreter::PushTransactionRAII pushedT(fInterp);\n\n \/\/ Note: This is an int64_t.\n clang::CharUnits::QuantityType quantity =\n context.getTypeSizeInChars(qt).getQuantity();\n \/\/ Truncate cast to fit the CINT interface.\n return static_cast(quantity);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Get the name of the underlying type of the current typedef.\n\nconst char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const\n{\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n TTHREAD_TLS_DECL( std::string, truename);\n truename.clear();\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType underlyingType = td->getUnderlyingType();\n if (underlyingType->isBooleanType()) {\n return \"bool\";\n }\n const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext();\n ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt);\n\n return truename.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Get the name of the current typedef.\n\nconst char *TClingTypedefInfo::Name() const\n{\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n TTHREAD_TLS_DECL( std::string, fullname);\n fullname.clear();\n const clang::TypedefNameDecl *td = llvm::dyn_cast(fDecl);\n const clang::ASTContext &ctxt = fDecl->getASTContext();\n ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp);\n return fullname.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst char *TClingTypedefInfo::Title()\n{\n if (!IsValid()) {\n return 0;\n }\n \/\/NOTE: We can't use it as a cache due to the \"thoughtful\" self iterator\n \/\/if (fTitle.size())\n \/\/ return fTitle.c_str();\n\n \/\/ Try to get the comment either from the annotation or the header file if present\n\n \/\/ Iterate over the redeclarations, we can have multiple definitions in the\n \/\/ redecl chain (came from merging of pcms).\n if (const TypedefNameDecl *TND = llvm::dyn_cast(GetDecl())) {\n if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) {\n if (AnnotateAttr *A = TND->getAttr()) {\n fTitle = A->getAnnotation().str();\n return fTitle.c_str();\n }\n }\n }\n else if (!GetDecl()->isFromASTFile()) {\n \/\/ Try to get the comment from the header file if present\n \/\/ but not for decls from AST file, where rootcling would have\n \/\/ created an annotation\n fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();\n }\n return fTitle.c_str();\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\/*\n* Covariant Mozart Utility Library: Switcher\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n*\n* Copyright (C) 2016 Michael Lee(李登淳)\n* Email: China-LDC@outlook.com\n* Github: https:\/\/github.com\/mikecovlee\n* Website: http:\/\/ldc.atd3.cn\n*\n* Version: 17.1.0\n*\/\n#include \".\/base.hpp\"\n#include \".\/any.hpp\"\n#include \".\/function.hpp\"\n#include \".\/tuple.hpp\"\n#include \n\nnamespace cov {\n\tclass switcher final {\n\tpublic:\n\t\ttypedef cov::function case_type;\n\tprivate:\n\t\tstd::deque>> mCases;\n\t\tcov::function mDefault;\n\t\tconst cov::any mCondition;\n\tpublic:\n\t\tswitcher()=delete;\n\t\tswitcher(const cov::any& val):mCondition(val) {}\n\t\tswitcher(switcher&&) noexcept=delete;\n\t\tswitcher(const switcher&)=delete;\n\t\t~switcher()=default;\n\t\tvoid add_case(const cov::any& head,const case_type& body) {\n\t\t\tif(object::show_warning&&head.type()!=mCondition.type())\n\t\t\t\tthrow cov::warning(\"W0001\");\n\t\t\tbool exsist=false;\n\t\t\tfor(auto& it:mCases) {\n\t\t\t\tif(it.get<0>()==head) {\n\t\t\t\t\texsist=true;\n\t\t\t\t\tif(object::show_warning)\n\t\t\t\t\t\tthrow cov::warning(\"W0002\");\n\t\t\t\t\telse\n\t\t\t\t\t\tit.get<1>()=body;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!exsist)\n\t\t\t\tmCases.push_back(tuple>(head,body));\n\t\t}\n\t\tvoid add_default(const case_type& body) {\n\t\t\tif(mDefault.callable()&&object::show_warning)\n\t\t\t\tthrow cov::warning(\"W0002\");\n\t\t\tmDefault=body;\n\t\t}\n\t\tvoid perform() {\n\t\t\tfor(auto& it:mCases) {\n\t\t\t\tif(it.get<0>()==mCondition&&it.get<1>().callable()) {\n\t\t\t\t\tit.get<1>().call();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(mDefault.callable())\n\t\t\t\tmDefault.call();\n\t\t}\n\t};\n\tclass switcher_stack final {\n\t\tstd::deque mStack;\n\tpublic:\n\t\tswitcher_stack()=default;\n\t\tswitcher_stack(switcher_stack&&) noexcept=delete;\n\t\tswitcher_stack(const switcher_stack&)=delete;\n\t\t~switcher_stack() {\n\t\t\tfor(auto&it:mStack)\n\t\t\t\tdelete it;\n\t\t}\n\t\tswitcher& top() {\n\t\t\treturn *mStack.front();\n\t\t}\n\t\tvoid push(const cov::any& val) {\n\t\t\tmStack.push_front(new switcher(val));\n\t\t}\n\t\tvoid pop() {\n\t\t\tdelete mStack.front();\n\t\t\tmStack.pop_front();\n\t\t}\n\t};\n\tswitcher_stack cov_switchers;\n}\n\n#define Switch(obj) cov::cov_switchers.push(obj);\n#define EndSwitch cov::cov_switchers.top().perform();cov::cov_switchers.pop();\n#define Case(obj) cov::cov_switchers.top().add_case(obj,[&]{\n#define Default cov::cov_switchers.top().add_default([&]{\n#define EndCase });修复与Windows.h共存时名称冲突的问题#pragma once\n\/*\n* Covariant Mozart Utility Library: Switcher\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n*\n* Copyright (C) 2016 Michael Lee(李登淳)\n* Email: China-LDC@outlook.com\n* Github: https:\/\/github.com\/mikecovlee\n* Website: http:\/\/ldc.atd3.cn\n*\n* Version: 17.1.0\n*\/\n#include \".\/base.hpp\"\n#include \".\/any.hpp\"\n#include \".\/function.hpp\"\n#include \".\/tuple.hpp\"\n#include \n\nnamespace cov {\n\tclass switcher final {\n\tpublic:\n\t\ttypedef cov::function case_type;\n\tprivate:\n\t\tstd::deque>> mCases;\n\t\tcov::function mDefault;\n\t\tconst cov::any mCondition;\n\tpublic:\n\t\tswitcher()=delete;\n\t\tswitcher(const cov::any& val):mCondition(val) {}\n\t\tswitcher(switcher&&) noexcept=delete;\n\t\tswitcher(const switcher&)=delete;\n\t\t~switcher()=default;\n\t\tvoid add_case(const cov::any& head,const case_type& body) {\n\t\t\tif(object::show_warning&&head.type()!=mCondition.type())\n\t\t\t\tthrow cov::warning(\"W0001\");\n\t\t\tbool exsist=false;\n\t\t\tfor(auto& it:mCases) {\n\t\t\t\tif(it.get<0>()==head) {\n\t\t\t\t\texsist=true;\n\t\t\t\t\tif(object::show_warning)\n\t\t\t\t\t\tthrow cov::warning(\"W0002\");\n\t\t\t\t\telse\n\t\t\t\t\t\tit.get<1>()=body;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!exsist)\n\t\t\t\tmCases.push_back(tuple>(head,body));\n\t\t}\n\t\tvoid add_default(const case_type& body) {\n\t\t\tif(mDefault.callable()&&object::show_warning)\n\t\t\t\tthrow cov::warning(\"W0002\");\n\t\t\tmDefault=body;\n\t\t}\n\t\tvoid perform() {\n\t\t\tfor(auto& it:mCases) {\n\t\t\t\tif(it.get<0>()==mCondition&&it.get<1>().callable()) {\n\t\t\t\t\tit.get<1>().call();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(mDefault.callable())\n\t\t\t\tmDefault.call();\n\t\t}\n\t};\n\tclass switcher_stack final {\n\t\tstd::deque mStack;\n\tpublic:\n\t\tswitcher_stack()=default;\n\t\tswitcher_stack(switcher_stack&&) noexcept=delete;\n\t\tswitcher_stack(const switcher_stack&)=delete;\n\t\t~switcher_stack() {\n\t\t\tfor(auto&it:mStack)\n\t\t\t\tdelete it;\n\t\t}\n\t\tswitcher& top() {\n\t\t\treturn *mStack.front();\n\t\t}\n\t\tvoid push(const cov::any& val) {\n\t\t\tmStack.push_front(new switcher(val));\n\t\t}\n\t\tvoid pop() {\n\t\t\tdelete mStack.front();\n\t\t\tmStack.pop_front();\n\t\t}\n\t};\n\tswitcher_stack cov_switchers;\n}\n\n#define CovSwitch(obj) cov::cov_switchers.push(obj);\n#define EndCovSwitch cov::cov_switchers.top().perform();cov::cov_switchers.pop();\n#define CovCase(obj) cov::cov_switchers.top().add_case(obj,[&]{\n#define CovDefault cov::cov_switchers.top().add_default([&]{\n#define EndCovCase });<|endoftext|>"} {"text":"\/\/===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the AsmPrinter class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instruction.h\"\n#include \"llvm\/Support\/Mangler.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\nusing namespace llvm;\n\nbool AsmPrinter::doInitialization(Module &M) {\n Mang = new Mangler(M, GlobalPrefix);\n return false;\n}\n\nbool AsmPrinter::doFinalization(Module &M) {\n delete Mang; Mang = 0;\n return false;\n}\n\nvoid AsmPrinter::setupMachineFunction(MachineFunction &MF) {\n \/\/ What's my mangled name?\n CurrentFnName = Mang->getValueName((Value*)MF.getFunction());\n}\n\n\/\/ emitAlignment - Emit an alignment directive to the specified power of two.\nvoid AsmPrinter::emitAlignment(unsigned NumBits) const {\n if (AlignmentIsInBytes) NumBits = 1 << NumBits;\n O << AlignDirective << NumBits << \"\\n\";\n}\n\n\/\/\/ emitZeros - Emit a block of zeros.\n\/\/\/\nvoid AsmPrinter::emitZeros(uint64_t NumZeros) const {\n if (NumZeros) {\n if (ZeroDirective)\n O << ZeroDirective << NumZeros << \"\\n\";\n else {\n for (; NumZeros; --NumZeros)\n O << Data8bitsDirective << \"0\\n\";\n }\n }\n}\n\n\/\/ Print out the specified constant, without a storage class. Only the\n\/\/ constants valid in constant expressions can occur here.\nvoid AsmPrinter::emitConstantValueOnly(const Constant *CV) {\n if (CV->isNullValue() || isa(CV))\n O << \"0\";\n else if (const ConstantBool *CB = dyn_cast(CV)) {\n assert(CB == ConstantBool::True);\n O << \"1\";\n } else if (const ConstantSInt *CI = dyn_cast(CV))\n if (((CI->getValue() << 32) >> 32) == CI->getValue())\n O << CI->getValue();\n else\n O << (uint64_t)CI->getValue();\n else if (const ConstantUInt *CI = dyn_cast(CV))\n O << CI->getValue();\n else if (isa((Value*)CV)) {\n \/\/ This is a constant address for a global variable or function. Use the\n \/\/ name of the variable or function as the address value, possibly\n \/\/ decorating it with GlobalVarAddrPrefix\/Suffix or\n \/\/ FunctionAddrPrefix\/Suffix (these all default to \"\" )\n if (isa((Value*)CV))\n O << FunctionAddrPrefix << Mang->getValueName(CV) << FunctionAddrSuffix;\n else\n O << GlobalVarAddrPrefix << Mang->getValueName(CV) << GlobalVarAddrSuffix;\n } else if (const ConstantExpr *CE = dyn_cast(CV)) {\n const TargetData &TD = TM.getTargetData();\n switch(CE->getOpcode()) {\n case Instruction::GetElementPtr: {\n \/\/ generate a symbolic expression for the byte address\n const Constant *ptrVal = CE->getOperand(0);\n std::vector idxVec(CE->op_begin()+1, CE->op_end());\n if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {\n if (Offset)\n O << \"(\";\n emitConstantValueOnly(ptrVal);\n if (Offset > 0)\n O << \") + \" << Offset;\n else if (Offset < 0)\n O << \") - \" << -Offset;\n } else {\n emitConstantValueOnly(ptrVal);\n }\n break;\n }\n case Instruction::Cast: {\n \/\/ Support only non-converting or widening casts for now, that is, ones\n \/\/ that do not involve a change in value. This assertion is really gross,\n \/\/ and may not even be a complete check.\n Constant *Op = CE->getOperand(0);\n const Type *OpTy = Op->getType(), *Ty = CE->getType();\n\n \/\/ Remember, kids, pointers can be losslessly converted back and forth\n \/\/ into 32-bit or wider integers, regardless of signedness. :-P\n assert(((isa(OpTy)\n && (Ty == Type::LongTy || Ty == Type::ULongTy\n || Ty == Type::IntTy || Ty == Type::UIntTy))\n || (isa(Ty)\n && (OpTy == Type::LongTy || OpTy == Type::ULongTy\n || OpTy == Type::IntTy || OpTy == Type::UIntTy))\n || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))\n && OpTy->isLosslesslyConvertibleTo(Ty))))\n && \"FIXME: Don't yet support this kind of constant cast expr\");\n O << \"(\";\n emitConstantValueOnly(Op);\n O << \")\";\n break;\n }\n case Instruction::Add:\n O << \"(\";\n emitConstantValueOnly(CE->getOperand(0));\n O << \") + (\";\n emitConstantValueOnly(CE->getOperand(1));\n O << \")\";\n break;\n default:\n assert(0 && \"Unsupported operator!\");\n }\n } else {\n assert(0 && \"Unknown constant value!\");\n }\n}\n\n\/\/\/ toOctal - Convert the low order bits of X into an octal digit.\n\/\/\/\nstatic inline char toOctal(int X) {\n return (X&7)+'0';\n}\n\n\/\/\/ getAsCString - Return the specified array as a C compatible string, only if\n\/\/\/ the predicate isString is true.\n\/\/\/\nstatic void printAsCString(std::ostream &O, const ConstantArray *CVA) {\n assert(CVA->isString() && \"Array is not string compatible!\");\n\n O << \"\\\"\";\n for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {\n unsigned char C =\n (unsigned char)cast(CVA->getOperand(i))->getRawValue();\n\n if (C == '\"') {\n O << \"\\\\\\\"\";\n } else if (C == '\\\\') {\n O << \"\\\\\\\\\";\n } else if (isprint(C)) {\n O << C;\n } else {\n switch(C) {\n case '\\b': O << \"\\\\b\"; break;\n case '\\f': O << \"\\\\f\"; break;\n case '\\n': O << \"\\\\n\"; break;\n case '\\r': O << \"\\\\r\"; break;\n case '\\t': O << \"\\\\t\"; break;\n default:\n O << '\\\\';\n O << toOctal(C >> 6);\n O << toOctal(C >> 3);\n O << toOctal(C >> 0);\n break;\n }\n }\n }\n O << \"\\\"\";\n}\n\n\/\/\/ emitGlobalConstant - Print a general LLVM constant to the .s file.\n\/\/\/\nvoid AsmPrinter::emitGlobalConstant(const Constant *CV) {\n const TargetData &TD = TM.getTargetData();\n\n if (CV->isNullValue() || isa(CV)) {\n emitZeros(TD.getTypeSize(CV->getType()));\n return;\n } else if (const ConstantArray *CVA = dyn_cast(CV)) {\n if (CVA->isString()) {\n O << AsciiDirective;\n printAsCString(O, CVA);\n O << \"\\n\";\n } else { \/\/ Not a string. Print the values in successive locations\n for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)\n emitGlobalConstant(CVA->getOperand(i));\n }\n return;\n } else if (const ConstantStruct *CVS = dyn_cast(CV)) {\n \/\/ Print the fields in successive locations. Pad to align if needed!\n const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());\n uint64_t sizeSoFar = 0;\n for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {\n const Constant* field = CVS->getOperand(i);\n\n \/\/ Check if padding is needed and insert one or more 0s.\n uint64_t fieldSize = TD.getTypeSize(field->getType());\n uint64_t padSize = ((i == e-1? cvsLayout->StructSize\n : cvsLayout->MemberOffsets[i+1])\n - cvsLayout->MemberOffsets[i]) - fieldSize;\n sizeSoFar += fieldSize + padSize;\n\n \/\/ Now print the actual field value\n emitGlobalConstant(field);\n\n \/\/ Insert the field padding unless it's zero bytes...\n emitZeros(padSize);\n }\n assert(sizeSoFar == cvsLayout->StructSize &&\n \"Layout of constant struct may be incorrect!\");\n return;\n } else if (const ConstantFP *CFP = dyn_cast(CV)) {\n \/\/ FP Constants are printed as integer constants to avoid losing\n \/\/ precision...\n double Val = CFP->getValue();\n if (CFP->getType() == Type::DoubleTy) {\n if (Data64bitsDirective)\n O << Data64bitsDirective << DoubleToBits(Val) << \"\\t\" << CommentString\n << \" double value: \" << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \" << Val\n << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \" << Val\n << \"\\n\";\n }\n return;\n } else {\n O << Data32bitsDirective << FloatToBits(Val) << \"\\t\" << CommentString\n << \" float \" << Val << \"\\n\";\n return;\n }\n } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {\n if (const ConstantInt *CI = dyn_cast(CV)) {\n uint64_t Val = CI->getRawValue();\n\n if (Data64bitsDirective)\n O << Data64bitsDirective << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n }\n return;\n }\n }\n\n const Type *type = CV->getType();\n switch (type->getTypeID()) {\n case Type::BoolTyID:\n case Type::UByteTyID: case Type::SByteTyID:\n O << Data8bitsDirective;\n break;\n case Type::UShortTyID: case Type::ShortTyID:\n O << Data16bitsDirective;\n break;\n case Type::PointerTyID:\n if (TD.getPointerSize() == 8) {\n O << Data64bitsDirective;\n break;\n }\n \/\/Fall through for pointer size == int size\n case Type::UIntTyID: case Type::IntTyID:\n O << Data32bitsDirective;\n break;\n case Type::ULongTyID: case Type::LongTyID:\n assert(Data64bitsDirective &&\"Target cannot handle 64-bit constant exprs!\");\n O << Data64bitsDirective;\n break;\n case Type::FloatTyID: case Type::DoubleTyID:\n assert (0 && \"Should have already output floating point constant.\");\n default:\n assert (0 && \"Can't handle printing this type of thing\");\n break;\n }\n emitConstantValueOnly(CV);\n O << \"\\n\";\n}\nadd support for .asciz, and enable it by default. If your target assemblerdoesn't support .asciz, just set AscizDirective to null in your asmprinter. This compiles C strings to:\/\/===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the AsmPrinter class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instruction.h\"\n#include \"llvm\/Support\/Mangler.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\nusing namespace llvm;\n\nbool AsmPrinter::doInitialization(Module &M) {\n Mang = new Mangler(M, GlobalPrefix);\n return false;\n}\n\nbool AsmPrinter::doFinalization(Module &M) {\n delete Mang; Mang = 0;\n return false;\n}\n\nvoid AsmPrinter::setupMachineFunction(MachineFunction &MF) {\n \/\/ What's my mangled name?\n CurrentFnName = Mang->getValueName((Value*)MF.getFunction());\n}\n\n\/\/ emitAlignment - Emit an alignment directive to the specified power of two.\nvoid AsmPrinter::emitAlignment(unsigned NumBits) const {\n if (AlignmentIsInBytes) NumBits = 1 << NumBits;\n O << AlignDirective << NumBits << \"\\n\";\n}\n\n\/\/\/ emitZeros - Emit a block of zeros.\n\/\/\/\nvoid AsmPrinter::emitZeros(uint64_t NumZeros) const {\n if (NumZeros) {\n if (ZeroDirective)\n O << ZeroDirective << NumZeros << \"\\n\";\n else {\n for (; NumZeros; --NumZeros)\n O << Data8bitsDirective << \"0\\n\";\n }\n }\n}\n\n\/\/ Print out the specified constant, without a storage class. Only the\n\/\/ constants valid in constant expressions can occur here.\nvoid AsmPrinter::emitConstantValueOnly(const Constant *CV) {\n if (CV->isNullValue() || isa(CV))\n O << \"0\";\n else if (const ConstantBool *CB = dyn_cast(CV)) {\n assert(CB == ConstantBool::True);\n O << \"1\";\n } else if (const ConstantSInt *CI = dyn_cast(CV))\n if (((CI->getValue() << 32) >> 32) == CI->getValue())\n O << CI->getValue();\n else\n O << (uint64_t)CI->getValue();\n else if (const ConstantUInt *CI = dyn_cast(CV))\n O << CI->getValue();\n else if (isa((Value*)CV)) {\n \/\/ This is a constant address for a global variable or function. Use the\n \/\/ name of the variable or function as the address value, possibly\n \/\/ decorating it with GlobalVarAddrPrefix\/Suffix or\n \/\/ FunctionAddrPrefix\/Suffix (these all default to \"\" )\n if (isa((Value*)CV))\n O << FunctionAddrPrefix << Mang->getValueName(CV) << FunctionAddrSuffix;\n else\n O << GlobalVarAddrPrefix << Mang->getValueName(CV) << GlobalVarAddrSuffix;\n } else if (const ConstantExpr *CE = dyn_cast(CV)) {\n const TargetData &TD = TM.getTargetData();\n switch(CE->getOpcode()) {\n case Instruction::GetElementPtr: {\n \/\/ generate a symbolic expression for the byte address\n const Constant *ptrVal = CE->getOperand(0);\n std::vector idxVec(CE->op_begin()+1, CE->op_end());\n if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {\n if (Offset)\n O << \"(\";\n emitConstantValueOnly(ptrVal);\n if (Offset > 0)\n O << \") + \" << Offset;\n else if (Offset < 0)\n O << \") - \" << -Offset;\n } else {\n emitConstantValueOnly(ptrVal);\n }\n break;\n }\n case Instruction::Cast: {\n \/\/ Support only non-converting or widening casts for now, that is, ones\n \/\/ that do not involve a change in value. This assertion is really gross,\n \/\/ and may not even be a complete check.\n Constant *Op = CE->getOperand(0);\n const Type *OpTy = Op->getType(), *Ty = CE->getType();\n\n \/\/ Remember, kids, pointers can be losslessly converted back and forth\n \/\/ into 32-bit or wider integers, regardless of signedness. :-P\n assert(((isa(OpTy)\n && (Ty == Type::LongTy || Ty == Type::ULongTy\n || Ty == Type::IntTy || Ty == Type::UIntTy))\n || (isa(Ty)\n && (OpTy == Type::LongTy || OpTy == Type::ULongTy\n || OpTy == Type::IntTy || OpTy == Type::UIntTy))\n || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))\n && OpTy->isLosslesslyConvertibleTo(Ty))))\n && \"FIXME: Don't yet support this kind of constant cast expr\");\n O << \"(\";\n emitConstantValueOnly(Op);\n O << \")\";\n break;\n }\n case Instruction::Add:\n O << \"(\";\n emitConstantValueOnly(CE->getOperand(0));\n O << \") + (\";\n emitConstantValueOnly(CE->getOperand(1));\n O << \")\";\n break;\n default:\n assert(0 && \"Unsupported operator!\");\n }\n } else {\n assert(0 && \"Unknown constant value!\");\n }\n}\n\n\/\/\/ toOctal - Convert the low order bits of X into an octal digit.\n\/\/\/\nstatic inline char toOctal(int X) {\n return (X&7)+'0';\n}\n\n\/\/\/ printAsCString - Print the specified array as a C compatible string, only if\n\/\/\/ the predicate isString is true.\n\/\/\/\nstatic void printAsCString(std::ostream &O, const ConstantArray *CVA,\n unsigned LastElt) {\n assert(CVA->isString() && \"Array is not string compatible!\");\n\n O << \"\\\"\";\n for (unsigned i = 0; i != LastElt; ++i) {\n unsigned char C =\n (unsigned char)cast(CVA->getOperand(i))->getRawValue();\n\n if (C == '\"') {\n O << \"\\\\\\\"\";\n } else if (C == '\\\\') {\n O << \"\\\\\\\\\";\n } else if (isprint(C)) {\n O << C;\n } else {\n switch(C) {\n case '\\b': O << \"\\\\b\"; break;\n case '\\f': O << \"\\\\f\"; break;\n case '\\n': O << \"\\\\n\"; break;\n case '\\r': O << \"\\\\r\"; break;\n case '\\t': O << \"\\\\t\"; break;\n default:\n O << '\\\\';\n O << toOctal(C >> 6);\n O << toOctal(C >> 3);\n O << toOctal(C >> 0);\n break;\n }\n }\n }\n O << \"\\\"\";\n}\n\n\/\/\/ emitGlobalConstant - Print a general LLVM constant to the .s file.\n\/\/\/\nvoid AsmPrinter::emitGlobalConstant(const Constant *CV) {\n const TargetData &TD = TM.getTargetData();\n\n if (CV->isNullValue() || isa(CV)) {\n emitZeros(TD.getTypeSize(CV->getType()));\n return;\n } else if (const ConstantArray *CVA = dyn_cast(CV)) {\n if (CVA->isString()) {\n unsigned NumElts = CVA->getNumOperands();\n if (AscizDirective && NumElts && \n cast(CVA->getOperand(NumElts-1))->getRawValue() == 0) {\n O << AscizDirective;\n printAsCString(O, CVA, NumElts-1);\n } else {\n O << AsciiDirective;\n printAsCString(O, CVA, NumElts);\n }\n O << \"\\n\";\n } else { \/\/ Not a string. Print the values in successive locations\n for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)\n emitGlobalConstant(CVA->getOperand(i));\n }\n return;\n } else if (const ConstantStruct *CVS = dyn_cast(CV)) {\n \/\/ Print the fields in successive locations. Pad to align if needed!\n const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());\n uint64_t sizeSoFar = 0;\n for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {\n const Constant* field = CVS->getOperand(i);\n\n \/\/ Check if padding is needed and insert one or more 0s.\n uint64_t fieldSize = TD.getTypeSize(field->getType());\n uint64_t padSize = ((i == e-1? cvsLayout->StructSize\n : cvsLayout->MemberOffsets[i+1])\n - cvsLayout->MemberOffsets[i]) - fieldSize;\n sizeSoFar += fieldSize + padSize;\n\n \/\/ Now print the actual field value\n emitGlobalConstant(field);\n\n \/\/ Insert the field padding unless it's zero bytes...\n emitZeros(padSize);\n }\n assert(sizeSoFar == cvsLayout->StructSize &&\n \"Layout of constant struct may be incorrect!\");\n return;\n } else if (const ConstantFP *CFP = dyn_cast(CV)) {\n \/\/ FP Constants are printed as integer constants to avoid losing\n \/\/ precision...\n double Val = CFP->getValue();\n if (CFP->getType() == Type::DoubleTy) {\n if (Data64bitsDirective)\n O << Data64bitsDirective << DoubleToBits(Val) << \"\\t\" << CommentString\n << \" double value: \" << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \" << Val\n << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \" << Val\n << \"\\n\";\n }\n return;\n } else {\n O << Data32bitsDirective << FloatToBits(Val) << \"\\t\" << CommentString\n << \" float \" << Val << \"\\n\";\n return;\n }\n } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {\n if (const ConstantInt *CI = dyn_cast(CV)) {\n uint64_t Val = CI->getRawValue();\n\n if (Data64bitsDirective)\n O << Data64bitsDirective << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n }\n return;\n }\n }\n\n const Type *type = CV->getType();\n switch (type->getTypeID()) {\n case Type::BoolTyID:\n case Type::UByteTyID: case Type::SByteTyID:\n O << Data8bitsDirective;\n break;\n case Type::UShortTyID: case Type::ShortTyID:\n O << Data16bitsDirective;\n break;\n case Type::PointerTyID:\n if (TD.getPointerSize() == 8) {\n O << Data64bitsDirective;\n break;\n }\n \/\/Fall through for pointer size == int size\n case Type::UIntTyID: case Type::IntTyID:\n O << Data32bitsDirective;\n break;\n case Type::ULongTyID: case Type::LongTyID:\n assert(Data64bitsDirective &&\"Target cannot handle 64-bit constant exprs!\");\n O << Data64bitsDirective;\n break;\n case Type::FloatTyID: case Type::DoubleTyID:\n assert (0 && \"Should have already output floating point constant.\");\n default:\n assert (0 && \"Can't handle printing this type of thing\");\n break;\n }\n emitConstantValueOnly(CV);\n O << \"\\n\";\n}\n<|endoftext|>"} {"text":"\/\/===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the AsmPrinter class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/Mangler.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\nusing namespace llvm;\n\nbool AsmPrinter::doInitialization(Module &M) {\n Mang = new Mangler(M, GlobalPrefix);\n return false;\n}\n\nbool AsmPrinter::doFinalization(Module &M) {\n delete Mang; Mang = 0;\n return false;\n}\n\nvoid AsmPrinter::setupMachineFunction(MachineFunction &MF) {\n \/\/ What's my mangled name?\n CurrentFnName = Mang->getValueName(MF.getFunction());\n}\n\n\/\/ emitAlignment - Emit an alignment directive to the specified power of two.\nvoid AsmPrinter::emitAlignment(unsigned NumBits, const GlobalValue *GV) const {\n if (GV && GV->getAlignment())\n NumBits = Log2_32(GV->getAlignment());\n if (NumBits == 0) return; \/\/ No need to emit alignment.\n if (AlignmentIsInBytes) NumBits = 1 << NumBits;\n O << AlignDirective << NumBits << \"\\n\";\n}\n\n\/\/\/ emitZeros - Emit a block of zeros.\n\/\/\/\nvoid AsmPrinter::emitZeros(uint64_t NumZeros) const {\n if (NumZeros) {\n if (ZeroDirective)\n O << ZeroDirective << NumZeros << \"\\n\";\n else {\n for (; NumZeros; --NumZeros)\n O << Data8bitsDirective << \"0\\n\";\n }\n }\n}\n\n\/\/ Print out the specified constant, without a storage class. Only the\n\/\/ constants valid in constant expressions can occur here.\nvoid AsmPrinter::emitConstantValueOnly(const Constant *CV) {\n if (CV->isNullValue() || isa(CV))\n O << \"0\";\n else if (const ConstantBool *CB = dyn_cast(CV)) {\n assert(CB == ConstantBool::True);\n O << \"1\";\n } else if (const ConstantSInt *CI = dyn_cast(CV))\n if (((CI->getValue() << 32) >> 32) == CI->getValue())\n O << CI->getValue();\n else\n O << (uint64_t)CI->getValue();\n else if (const ConstantUInt *CI = dyn_cast(CV))\n O << CI->getValue();\n else if (const GlobalValue *GV = dyn_cast(CV)) {\n \/\/ This is a constant address for a global variable or function. Use the\n \/\/ name of the variable or function as the address value, possibly\n \/\/ decorating it with GlobalVarAddrPrefix\/Suffix or\n \/\/ FunctionAddrPrefix\/Suffix (these all default to \"\" )\n if (isa(GV))\n O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;\n else\n O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;\n } else if (const ConstantExpr *CE = dyn_cast(CV)) {\n const TargetData &TD = TM.getTargetData();\n switch(CE->getOpcode()) {\n case Instruction::GetElementPtr: {\n \/\/ generate a symbolic expression for the byte address\n const Constant *ptrVal = CE->getOperand(0);\n std::vector idxVec(CE->op_begin()+1, CE->op_end());\n if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {\n if (Offset)\n O << \"(\";\n emitConstantValueOnly(ptrVal);\n if (Offset > 0)\n O << \") + \" << Offset;\n else if (Offset < 0)\n O << \") - \" << -Offset;\n } else {\n emitConstantValueOnly(ptrVal);\n }\n break;\n }\n case Instruction::Cast: {\n \/\/ Support only non-converting or widening casts for now, that is, ones\n \/\/ that do not involve a change in value. This assertion is really gross,\n \/\/ and may not even be a complete check.\n Constant *Op = CE->getOperand(0);\n const Type *OpTy = Op->getType(), *Ty = CE->getType();\n\n \/\/ Remember, kids, pointers can be losslessly converted back and forth\n \/\/ into 32-bit or wider integers, regardless of signedness. :-P\n assert(((isa(OpTy)\n && (Ty == Type::LongTy || Ty == Type::ULongTy\n || Ty == Type::IntTy || Ty == Type::UIntTy))\n || (isa(Ty)\n && (OpTy == Type::LongTy || OpTy == Type::ULongTy\n || OpTy == Type::IntTy || OpTy == Type::UIntTy))\n || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))\n && OpTy->isLosslesslyConvertibleTo(Ty))))\n && \"FIXME: Don't yet support this kind of constant cast expr\");\n O << \"(\";\n emitConstantValueOnly(Op);\n O << \")\";\n break;\n }\n case Instruction::Add:\n O << \"(\";\n emitConstantValueOnly(CE->getOperand(0));\n O << \") + (\";\n emitConstantValueOnly(CE->getOperand(1));\n O << \")\";\n break;\n default:\n assert(0 && \"Unsupported operator!\");\n }\n } else {\n assert(0 && \"Unknown constant value!\");\n }\n}\n\n\/\/\/ toOctal - Convert the low order bits of X into an octal digit.\n\/\/\/\nstatic inline char toOctal(int X) {\n return (X&7)+'0';\n}\n\n\/\/\/ printAsCString - Print the specified array as a C compatible string, only if\n\/\/\/ the predicate isString is true.\n\/\/\/\nstatic void printAsCString(std::ostream &O, const ConstantArray *CVA,\n unsigned LastElt) {\n assert(CVA->isString() && \"Array is not string compatible!\");\n\n O << \"\\\"\";\n for (unsigned i = 0; i != LastElt; ++i) {\n unsigned char C =\n (unsigned char)cast(CVA->getOperand(i))->getRawValue();\n\n if (C == '\"') {\n O << \"\\\\\\\"\";\n } else if (C == '\\\\') {\n O << \"\\\\\\\\\";\n } else if (isprint(C)) {\n O << C;\n } else {\n switch(C) {\n case '\\b': O << \"\\\\b\"; break;\n case '\\f': O << \"\\\\f\"; break;\n case '\\n': O << \"\\\\n\"; break;\n case '\\r': O << \"\\\\r\"; break;\n case '\\t': O << \"\\\\t\"; break;\n default:\n O << '\\\\';\n O << toOctal(C >> 6);\n O << toOctal(C >> 3);\n O << toOctal(C >> 0);\n break;\n }\n }\n }\n O << \"\\\"\";\n}\n\n\/\/\/ emitGlobalConstant - Print a general LLVM constant to the .s file.\n\/\/\/\nvoid AsmPrinter::emitGlobalConstant(const Constant *CV) {\n const TargetData &TD = TM.getTargetData();\n\n if (CV->isNullValue() || isa(CV)) {\n emitZeros(TD.getTypeSize(CV->getType()));\n return;\n } else if (const ConstantArray *CVA = dyn_cast(CV)) {\n if (CVA->isString()) {\n unsigned NumElts = CVA->getNumOperands();\n if (AscizDirective && NumElts && \n cast(CVA->getOperand(NumElts-1))->getRawValue() == 0) {\n O << AscizDirective;\n printAsCString(O, CVA, NumElts-1);\n } else {\n O << AsciiDirective;\n printAsCString(O, CVA, NumElts);\n }\n O << \"\\n\";\n } else { \/\/ Not a string. Print the values in successive locations\n for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)\n emitGlobalConstant(CVA->getOperand(i));\n }\n return;\n } else if (const ConstantStruct *CVS = dyn_cast(CV)) {\n \/\/ Print the fields in successive locations. Pad to align if needed!\n const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());\n uint64_t sizeSoFar = 0;\n for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {\n const Constant* field = CVS->getOperand(i);\n\n \/\/ Check if padding is needed and insert one or more 0s.\n uint64_t fieldSize = TD.getTypeSize(field->getType());\n uint64_t padSize = ((i == e-1? cvsLayout->StructSize\n : cvsLayout->MemberOffsets[i+1])\n - cvsLayout->MemberOffsets[i]) - fieldSize;\n sizeSoFar += fieldSize + padSize;\n\n \/\/ Now print the actual field value\n emitGlobalConstant(field);\n\n \/\/ Insert the field padding unless it's zero bytes...\n emitZeros(padSize);\n }\n assert(sizeSoFar == cvsLayout->StructSize &&\n \"Layout of constant struct may be incorrect!\");\n return;\n } else if (const ConstantFP *CFP = dyn_cast(CV)) {\n \/\/ FP Constants are printed as integer constants to avoid losing\n \/\/ precision...\n double Val = CFP->getValue();\n if (CFP->getType() == Type::DoubleTy) {\n if (Data64bitsDirective)\n O << Data64bitsDirective << DoubleToBits(Val) << \"\\t\" << CommentString\n << \" double value: \" << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \" << Val\n << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \" << Val\n << \"\\n\";\n }\n return;\n } else {\n O << Data32bitsDirective << FloatToBits(Val) << \"\\t\" << CommentString\n << \" float \" << Val << \"\\n\";\n return;\n }\n } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {\n if (const ConstantInt *CI = dyn_cast(CV)) {\n uint64_t Val = CI->getRawValue();\n\n if (Data64bitsDirective)\n O << Data64bitsDirective << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n }\n return;\n }\n }\n\n const Type *type = CV->getType();\n switch (type->getTypeID()) {\n case Type::BoolTyID:\n case Type::UByteTyID: case Type::SByteTyID:\n O << Data8bitsDirective;\n break;\n case Type::UShortTyID: case Type::ShortTyID:\n O << Data16bitsDirective;\n break;\n case Type::PointerTyID:\n if (TD.getPointerSize() == 8) {\n O << Data64bitsDirective;\n break;\n }\n \/\/Fall through for pointer size == int size\n case Type::UIntTyID: case Type::IntTyID:\n O << Data32bitsDirective;\n break;\n case Type::ULongTyID: case Type::LongTyID:\n assert(Data64bitsDirective &&\"Target cannot handle 64-bit constant exprs!\");\n O << Data64bitsDirective;\n break;\n case Type::FloatTyID: case Type::DoubleTyID:\n assert (0 && \"Should have already output floating point constant.\");\n default:\n assert (0 && \"Can't handle printing this type of thing\");\n break;\n }\n emitConstantValueOnly(CV);\n O << \"\\n\";\n}\nRemove extraneous parents around constants when using a constant expr cast.\/\/===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the AsmPrinter class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/Mangler.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\nusing namespace llvm;\n\nbool AsmPrinter::doInitialization(Module &M) {\n Mang = new Mangler(M, GlobalPrefix);\n return false;\n}\n\nbool AsmPrinter::doFinalization(Module &M) {\n delete Mang; Mang = 0;\n return false;\n}\n\nvoid AsmPrinter::setupMachineFunction(MachineFunction &MF) {\n \/\/ What's my mangled name?\n CurrentFnName = Mang->getValueName(MF.getFunction());\n}\n\n\/\/ emitAlignment - Emit an alignment directive to the specified power of two.\nvoid AsmPrinter::emitAlignment(unsigned NumBits, const GlobalValue *GV) const {\n if (GV && GV->getAlignment())\n NumBits = Log2_32(GV->getAlignment());\n if (NumBits == 0) return; \/\/ No need to emit alignment.\n if (AlignmentIsInBytes) NumBits = 1 << NumBits;\n O << AlignDirective << NumBits << \"\\n\";\n}\n\n\/\/\/ emitZeros - Emit a block of zeros.\n\/\/\/\nvoid AsmPrinter::emitZeros(uint64_t NumZeros) const {\n if (NumZeros) {\n if (ZeroDirective)\n O << ZeroDirective << NumZeros << \"\\n\";\n else {\n for (; NumZeros; --NumZeros)\n O << Data8bitsDirective << \"0\\n\";\n }\n }\n}\n\n\/\/ Print out the specified constant, without a storage class. Only the\n\/\/ constants valid in constant expressions can occur here.\nvoid AsmPrinter::emitConstantValueOnly(const Constant *CV) {\n if (CV->isNullValue() || isa(CV))\n O << \"0\";\n else if (const ConstantBool *CB = dyn_cast(CV)) {\n assert(CB == ConstantBool::True);\n O << \"1\";\n } else if (const ConstantSInt *CI = dyn_cast(CV))\n if (((CI->getValue() << 32) >> 32) == CI->getValue())\n O << CI->getValue();\n else\n O << (uint64_t)CI->getValue();\n else if (const ConstantUInt *CI = dyn_cast(CV))\n O << CI->getValue();\n else if (const GlobalValue *GV = dyn_cast(CV)) {\n \/\/ This is a constant address for a global variable or function. Use the\n \/\/ name of the variable or function as the address value, possibly\n \/\/ decorating it with GlobalVarAddrPrefix\/Suffix or\n \/\/ FunctionAddrPrefix\/Suffix (these all default to \"\" )\n if (isa(GV))\n O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;\n else\n O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;\n } else if (const ConstantExpr *CE = dyn_cast(CV)) {\n const TargetData &TD = TM.getTargetData();\n switch(CE->getOpcode()) {\n case Instruction::GetElementPtr: {\n \/\/ generate a symbolic expression for the byte address\n const Constant *ptrVal = CE->getOperand(0);\n std::vector idxVec(CE->op_begin()+1, CE->op_end());\n if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {\n if (Offset)\n O << \"(\";\n emitConstantValueOnly(ptrVal);\n if (Offset > 0)\n O << \") + \" << Offset;\n else if (Offset < 0)\n O << \") - \" << -Offset;\n } else {\n emitConstantValueOnly(ptrVal);\n }\n break;\n }\n case Instruction::Cast: {\n \/\/ Support only non-converting or widening casts for now, that is, ones\n \/\/ that do not involve a change in value. This assertion is really gross,\n \/\/ and may not even be a complete check.\n Constant *Op = CE->getOperand(0);\n const Type *OpTy = Op->getType(), *Ty = CE->getType();\n\n \/\/ Remember, kids, pointers can be losslessly converted back and forth\n \/\/ into 32-bit or wider integers, regardless of signedness. :-P\n assert(((isa(OpTy)\n && (Ty == Type::LongTy || Ty == Type::ULongTy\n || Ty == Type::IntTy || Ty == Type::UIntTy))\n || (isa(Ty)\n && (OpTy == Type::LongTy || OpTy == Type::ULongTy\n || OpTy == Type::IntTy || OpTy == Type::UIntTy))\n || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))\n && OpTy->isLosslesslyConvertibleTo(Ty))))\n && \"FIXME: Don't yet support this kind of constant cast expr\");\n emitConstantValueOnly(Op);\n break;\n }\n case Instruction::Add:\n O << \"(\";\n emitConstantValueOnly(CE->getOperand(0));\n O << \") + (\";\n emitConstantValueOnly(CE->getOperand(1));\n O << \")\";\n break;\n default:\n assert(0 && \"Unsupported operator!\");\n }\n } else {\n assert(0 && \"Unknown constant value!\");\n }\n}\n\n\/\/\/ toOctal - Convert the low order bits of X into an octal digit.\n\/\/\/\nstatic inline char toOctal(int X) {\n return (X&7)+'0';\n}\n\n\/\/\/ printAsCString - Print the specified array as a C compatible string, only if\n\/\/\/ the predicate isString is true.\n\/\/\/\nstatic void printAsCString(std::ostream &O, const ConstantArray *CVA,\n unsigned LastElt) {\n assert(CVA->isString() && \"Array is not string compatible!\");\n\n O << \"\\\"\";\n for (unsigned i = 0; i != LastElt; ++i) {\n unsigned char C =\n (unsigned char)cast(CVA->getOperand(i))->getRawValue();\n\n if (C == '\"') {\n O << \"\\\\\\\"\";\n } else if (C == '\\\\') {\n O << \"\\\\\\\\\";\n } else if (isprint(C)) {\n O << C;\n } else {\n switch(C) {\n case '\\b': O << \"\\\\b\"; break;\n case '\\f': O << \"\\\\f\"; break;\n case '\\n': O << \"\\\\n\"; break;\n case '\\r': O << \"\\\\r\"; break;\n case '\\t': O << \"\\\\t\"; break;\n default:\n O << '\\\\';\n O << toOctal(C >> 6);\n O << toOctal(C >> 3);\n O << toOctal(C >> 0);\n break;\n }\n }\n }\n O << \"\\\"\";\n}\n\n\/\/\/ emitGlobalConstant - Print a general LLVM constant to the .s file.\n\/\/\/\nvoid AsmPrinter::emitGlobalConstant(const Constant *CV) {\n const TargetData &TD = TM.getTargetData();\n\n if (CV->isNullValue() || isa(CV)) {\n emitZeros(TD.getTypeSize(CV->getType()));\n return;\n } else if (const ConstantArray *CVA = dyn_cast(CV)) {\n if (CVA->isString()) {\n unsigned NumElts = CVA->getNumOperands();\n if (AscizDirective && NumElts && \n cast(CVA->getOperand(NumElts-1))->getRawValue() == 0) {\n O << AscizDirective;\n printAsCString(O, CVA, NumElts-1);\n } else {\n O << AsciiDirective;\n printAsCString(O, CVA, NumElts);\n }\n O << \"\\n\";\n } else { \/\/ Not a string. Print the values in successive locations\n for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)\n emitGlobalConstant(CVA->getOperand(i));\n }\n return;\n } else if (const ConstantStruct *CVS = dyn_cast(CV)) {\n \/\/ Print the fields in successive locations. Pad to align if needed!\n const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());\n uint64_t sizeSoFar = 0;\n for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {\n const Constant* field = CVS->getOperand(i);\n\n \/\/ Check if padding is needed and insert one or more 0s.\n uint64_t fieldSize = TD.getTypeSize(field->getType());\n uint64_t padSize = ((i == e-1? cvsLayout->StructSize\n : cvsLayout->MemberOffsets[i+1])\n - cvsLayout->MemberOffsets[i]) - fieldSize;\n sizeSoFar += fieldSize + padSize;\n\n \/\/ Now print the actual field value\n emitGlobalConstant(field);\n\n \/\/ Insert the field padding unless it's zero bytes...\n emitZeros(padSize);\n }\n assert(sizeSoFar == cvsLayout->StructSize &&\n \"Layout of constant struct may be incorrect!\");\n return;\n } else if (const ConstantFP *CFP = dyn_cast(CV)) {\n \/\/ FP Constants are printed as integer constants to avoid losing\n \/\/ precision...\n double Val = CFP->getValue();\n if (CFP->getType() == Type::DoubleTy) {\n if (Data64bitsDirective)\n O << Data64bitsDirective << DoubleToBits(Val) << \"\\t\" << CommentString\n << \" double value: \" << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(DoubleToBits(Val))\n << \"\\t\" << CommentString << \" double least significant word \" << Val\n << \"\\n\";\n O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)\n << \"\\t\" << CommentString << \" double most significant word \" << Val\n << \"\\n\";\n }\n return;\n } else {\n O << Data32bitsDirective << FloatToBits(Val) << \"\\t\" << CommentString\n << \" float \" << Val << \"\\n\";\n return;\n }\n } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {\n if (const ConstantInt *CI = dyn_cast(CV)) {\n uint64_t Val = CI->getRawValue();\n\n if (Data64bitsDirective)\n O << Data64bitsDirective << Val << \"\\n\";\n else if (TD.isBigEndian()) {\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n } else {\n O << Data32bitsDirective << unsigned(Val)\n << \"\\t\" << CommentString << \" Double-word least significant word \"\n << Val << \"\\n\";\n O << Data32bitsDirective << unsigned(Val >> 32)\n << \"\\t\" << CommentString << \" Double-word most significant word \"\n << Val << \"\\n\";\n }\n return;\n }\n }\n\n const Type *type = CV->getType();\n switch (type->getTypeID()) {\n case Type::BoolTyID:\n case Type::UByteTyID: case Type::SByteTyID:\n O << Data8bitsDirective;\n break;\n case Type::UShortTyID: case Type::ShortTyID:\n O << Data16bitsDirective;\n break;\n case Type::PointerTyID:\n if (TD.getPointerSize() == 8) {\n O << Data64bitsDirective;\n break;\n }\n \/\/Fall through for pointer size == int size\n case Type::UIntTyID: case Type::IntTyID:\n O << Data32bitsDirective;\n break;\n case Type::ULongTyID: case Type::LongTyID:\n assert(Data64bitsDirective &&\"Target cannot handle 64-bit constant exprs!\");\n O << Data64bitsDirective;\n break;\n case Type::FloatTyID: case Type::DoubleTyID:\n assert (0 && \"Should have already output floating point constant.\");\n default:\n assert (0 && \"Can't handle printing this type of thing\");\n break;\n }\n emitConstantValueOnly(CV);\n O << \"\\n\";\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/base_paths.h\"\n#include \"base\/file_util.h\"\n#include \"media\/base\/yuv_convert.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Size of raw image.\nstatic const int kWidth = 1280;\nstatic const int kHeight = 720;\nstatic const int kBpp = 4;\n\nTEST(YuvConvertTest, Basic) {\n \/\/ Read YUV reference data from file.\n FilePath yuv_url;\n EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));\n yuv_url = yuv_url.Append(FILE_PATH_LITERAL(\"media\"))\n .Append(FILE_PATH_LITERAL(\"test\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"yuv_file\"));\n const size_t size_of_yuv = kWidth * kHeight * 12 \/ 8;\n uint8* yuv_bytes = new uint8[size_of_yuv];\n EXPECT_EQ(size_of_yuv, file_util::ReadFile(yuv_url,\n reinterpret_cast(yuv_bytes),\n static_cast(size_of_yuv)));\n\n \/\/ Read RGB reference data from file.\n \/\/ To keep the file smaller, only the first quarter of the file\n \/\/ is checked into SVN.\n FilePath rgb_url;\n EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &rgb_url));\n rgb_url = rgb_url.Append(FILE_PATH_LITERAL(\"media\"))\n .Append(FILE_PATH_LITERAL(\"test\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"rgb_file\"));\n const size_t size_of_rgb = kWidth * kHeight * kBpp \/ 4;\n uint8* rgb_bytes = new uint8[size_of_rgb];\n EXPECT_EQ(size_of_rgb, file_util::ReadFile(rgb_url,\n reinterpret_cast(rgb_bytes),\n static_cast(size_of_rgb)));\n\n \/\/ Convert a frame of YUV to 32 bit ARGB.\n const size_t size_of_rgb_converted = kWidth * kHeight * kBpp;\n uint8* rgb_converted_bytes = new uint8[size_of_rgb_converted];\n\n media::ConvertYV12ToRGB32(yuv_bytes, \/\/ Y plane\n yuv_bytes + kWidth * kHeight, \/\/ U plane\n yuv_bytes + kWidth * kHeight * 5 \/ 4, \/\/ V plane\n rgb_converted_bytes, \/\/ Rgb output\n kWidth, kHeight, \/\/ Dimensions\n kWidth, \/\/ YStride\n kWidth \/ 2, \/\/ UvStride\n kWidth * kBpp); \/\/ RgbStride\n\n \/\/ Compare converted YUV to reference conversion file.\n int rgb_diff = memcmp(rgb_converted_bytes, rgb_bytes, size_of_rgb);\n\n EXPECT_EQ(rgb_diff, 0);\n}\n\nCast size_t to int for comparison with ReadFile return value. What gcc compile option checks sign on equality? I'd like to test this, even if try server does not.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/base_paths.h\"\n#include \"base\/file_util.h\"\n#include \"media\/base\/yuv_convert.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Size of raw image.\nstatic const int kWidth = 1280;\nstatic const int kHeight = 720;\nstatic const int kBpp = 4;\n\nTEST(YuvConvertTest, Basic) {\n \/\/ Read YUV reference data from file.\n FilePath yuv_url;\n EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));\n yuv_url = yuv_url.Append(FILE_PATH_LITERAL(\"media\"))\n .Append(FILE_PATH_LITERAL(\"test\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"yuv_file\"));\n const size_t size_of_yuv = kWidth * kHeight * 12 \/ 8;\n uint8* yuv_bytes = new uint8[size_of_yuv];\n EXPECT_EQ(static_cast(size_of_yuv),\n file_util::ReadFile(yuv_url,\n reinterpret_cast(yuv_bytes),\n static_cast(size_of_yuv)));\n\n \/\/ Read RGB reference data from file.\n \/\/ To keep the file smaller, only the first quarter of the file\n \/\/ is checked into SVN.\n FilePath rgb_url;\n EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &rgb_url));\n rgb_url = rgb_url.Append(FILE_PATH_LITERAL(\"media\"))\n .Append(FILE_PATH_LITERAL(\"test\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"rgb_file\"));\n const size_t size_of_rgb = kWidth * kHeight * kBpp \/ 4;\n uint8* rgb_bytes = new uint8[size_of_rgb];\n EXPECT_EQ(static_cast(size_of_rgb),\n file_util::ReadFile(rgb_url,\n reinterpret_cast(rgb_bytes),\n static_cast(size_of_rgb)));\n\n \/\/ Convert a frame of YUV to 32 bit ARGB.\n const size_t size_of_rgb_converted = kWidth * kHeight * kBpp;\n uint8* rgb_converted_bytes = new uint8[size_of_rgb_converted];\n\n media::ConvertYV12ToRGB32(yuv_bytes, \/\/ Y plane\n yuv_bytes + kWidth * kHeight, \/\/ U plane\n yuv_bytes + kWidth * kHeight * 5 \/ 4, \/\/ V plane\n rgb_converted_bytes, \/\/ Rgb output\n kWidth, kHeight, \/\/ Dimensions\n kWidth, \/\/ YStride\n kWidth \/ 2, \/\/ UvStride\n kWidth * kBpp); \/\/ RgbStride\n\n \/\/ Compare converted YUV to reference conversion file.\n int rgb_diff = memcmp(rgb_converted_bytes, rgb_bytes, size_of_rgb);\n\n EXPECT_EQ(rgb_diff, 0);\n}\n\n<|endoftext|>"} {"text":"\/\/ @(#)root\/gui:$Name: $:$Id: TGWindow.cxx,v 1.12 2004\/06\/11 13:35:38 rdm Exp $\n\/\/ Author: Fons Rademakers 28\/12\/97\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\/**************************************************************************\n\n This source is based on Xclass95, a Win95-looking GUI toolkit.\n Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.\n\n Xclass95 is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n**************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGWindow \/\/\n\/\/ \/\/\n\/\/ ROOT GUI Window base class. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGWindow.h\"\n#include \"TMath.h\"\n#include \"Riostream.h\"\n\nClassImp(TGWindow)\nClassImp(TGUnknownWindowHandler)\n\nInt_t TGWindow::fgCounter = 0;\n\n\/\/______________________________________________________________________________\nTGWindow::TGWindow(const TGWindow *p, Int_t x, Int_t y, UInt_t w, UInt_t h,\n UInt_t border, Int_t depth, UInt_t clss, void *visual,\n SetWindowAttributes_t *attr, UInt_t wtype)\n{\n \/\/ Create a new window. Parent p must exist. No specified arguments\n \/\/ result in values from parent to be taken (or defaults).\n\n UInt_t type = wtype;\n\n if (!p && gClient) p = gClient->GetRoot();\n if (p) {\n fClient = p->fClient;\n if (fClient->IsEditable()) type = wtype & ~1;\n\n fParent = p;\n fId = gVirtualX->CreateWindow(fParent->fId, x, y,\n TMath::Max(w, (UInt_t) 1),\n TMath::Max(h, (UInt_t) 1), border,\n \t\t\t depth, clss, visual, attr, type);\n fClient->RegisterWindow(this);\n fNeedRedraw = kFALSE;\n\n \/\/ name will be used in SavePrimitive methods\n fgCounter++;\n fName = \"frame\";\n fName += fgCounter;\n } else {\n Error(\"TGWindow\", \"no parent specified\");\n }\n}\n\n\/\/______________________________________________________________________________\nTGWindow::TGWindow(TGClient *c, Window_t id, const TGWindow *parent)\n{\n \/\/ Create a copy of a window.\n\n fClient = c;\n fId = id;\n fParent = parent;\n fClient->RegisterWindow(this);\n fNeedRedraw = kFALSE;\n\n \/\/ name used in SavePrimitive methods\n fgCounter++;\n fName = \"frame\";\n fName += fgCounter;\n}\n\n\/\/______________________________________________________________________________\nTGWindow::~TGWindow()\n{\n \/\/ Window destructor. Unregisters the window.\n\n if (fClient) {\n if (fParent == fClient->GetDefaultRoot()) DestroyWindow();\n fClient->UnregisterWindow(this);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::SetWindowName(const char *name)\n{\n \/\/ Set window name.\n\n TString wname = name;\n\n if (!name) {\n wname = ClassName();\n wname += \"::\" + fName;\n }\n gVirtualX->SetWindowName(fId, (char *)wname.Data());\n}\n\n\/\/______________________________________________________________________________\nconst TGWindow *TGWindow::GetMainFrame() const\n{\n \/\/ Returns top level main frame.\n\n return (fParent == fClient->GetDefaultRoot()) ? this : fParent->GetMainFrame();\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::ReparentWindow(const TGWindow *p, Int_t x, Int_t y)\n{\n \/\/ Reparent window, make p the new parent and position the window at\n \/\/ position (x,y) in new parent.\n\n if (p == fParent) return;\n\n if (p) gVirtualX->ReparentWindow(fId, p->GetId(), x, y);\n fParent = p;\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::Move(Int_t x, Int_t y)\n{\n \/\/ Move the window.\n\n gVirtualX->MoveWindow(fId, x, y);\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::Resize(UInt_t w, UInt_t h)\n{\n \/\/ Resize the window.\n\n gVirtualX->ResizeWindow(fId, TMath::Max(w, (UInt_t)1), TMath::Max(h, (UInt_t)1));\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h)\n{\n \/\/ Move and resize the window.\n\n gVirtualX->MoveResizeWindow(fId, x, y, TMath::Max(w, (UInt_t)1), TMath::Max(h, (UInt_t)1));\n}\n\n\/\/______________________________________________________________________________\nBool_t TGWindow::IsMapped()\n{\n \/\/ Returns kTRUE if window is mapped on screen, kFALSE otherwise.\n\n WindowAttributes_t attr;\n\n gVirtualX->GetWindowAttributes(fId, attr);\n return (attr.fMapState != kIsUnmapped);\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::Print(Option_t *) const\n{\n \/\/ Print window id.\n\n cout << ClassName() << \":\\t\" << fId << endl;\n}\n\n\/\/______________________________________________________________________________\nInt_t TGWindow::GetCounter()\n{\n \/\/ Return global window counter (total number of created windows).\n\n return fgCounter;\n}\ncreate gClient when it does not exist, this can happen when libGui was loaded at program startup but not initialized because application is in batch mode.\/\/ @(#)root\/gui:$Name: $:$Id: TGWindow.cxx,v 1.13 2004\/06\/11 15:59:10 brun Exp $\n\/\/ Author: Fons Rademakers 28\/12\/97\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\/**************************************************************************\n\n This source is based on Xclass95, a Win95-looking GUI toolkit.\n Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.\n\n Xclass95 is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n**************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGWindow \/\/\n\/\/ \/\/\n\/\/ ROOT GUI Window base class. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGWindow.h\"\n#include \"TMath.h\"\n#include \"Riostream.h\"\n\nClassImp(TGWindow)\nClassImp(TGUnknownWindowHandler)\n\nInt_t TGWindow::fgCounter = 0;\n\n\/\/______________________________________________________________________________\nTGWindow::TGWindow(const TGWindow *p, Int_t x, Int_t y, UInt_t w, UInt_t h,\n UInt_t border, Int_t depth, UInt_t clss, void *visual,\n SetWindowAttributes_t *attr, UInt_t wtype)\n{\n \/\/ Create a new window. Parent p must exist otherwise the root window\n \/\/ is taken as parent. No arguments specified results in values from\n \/\/ parent to be taken (or defaults).\n\n \/\/ this can only happen when libGui was loaded at program startup\n \/\/ but not initialized because application is in batch mode\n if (!gClient) new TGClient();\n\n UInt_t type = wtype;\n\n if (!p)\n p = gClient->GetRoot();\n\n fClient = p->fClient;\n if (fClient->IsEditable()) type = wtype & ~1;\n\n fParent = p;\n fId = gVirtualX->CreateWindow(fParent->fId, x, y,\n TMath::Max(w, (UInt_t) 1),\n TMath::Max(h, (UInt_t) 1), border,\n depth, clss, visual, attr, type);\n fClient->RegisterWindow(this);\n fNeedRedraw = kFALSE;\n\n \/\/ name will be used in SavePrimitive methods\n fgCounter++;\n fName = \"frame\";\n fName += fgCounter;\n}\n\n\/\/______________________________________________________________________________\nTGWindow::TGWindow(TGClient *c, Window_t id, const TGWindow *parent)\n{\n \/\/ Create a copy of a window.\n\n fClient = c;\n fId = id;\n fParent = parent;\n fClient->RegisterWindow(this);\n fNeedRedraw = kFALSE;\n\n \/\/ name used in SavePrimitive methods\n fgCounter++;\n fName = \"frame\";\n fName += fgCounter;\n}\n\n\/\/______________________________________________________________________________\nTGWindow::~TGWindow()\n{\n \/\/ Window destructor. Unregisters the window.\n\n if (fClient) {\n if (fParent == fClient->GetDefaultRoot()) DestroyWindow();\n fClient->UnregisterWindow(this);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::SetWindowName(const char *name)\n{\n \/\/ Set window name.\n\n TString wname = name;\n\n if (!name) {\n wname = ClassName();\n wname += \"::\" + fName;\n }\n gVirtualX->SetWindowName(fId, (char *)wname.Data());\n}\n\n\/\/______________________________________________________________________________\nconst TGWindow *TGWindow::GetMainFrame() const\n{\n \/\/ Returns top level main frame.\n\n return (fParent == fClient->GetDefaultRoot()) ? this : fParent->GetMainFrame();\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::ReparentWindow(const TGWindow *p, Int_t x, Int_t y)\n{\n \/\/ Reparent window, make p the new parent and position the window at\n \/\/ position (x,y) in new parent.\n\n if (p == fParent) return;\n\n if (p) gVirtualX->ReparentWindow(fId, p->GetId(), x, y);\n fParent = p;\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::Move(Int_t x, Int_t y)\n{\n \/\/ Move the window.\n\n gVirtualX->MoveWindow(fId, x, y);\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::Resize(UInt_t w, UInt_t h)\n{\n \/\/ Resize the window.\n\n gVirtualX->ResizeWindow(fId, TMath::Max(w, (UInt_t)1), TMath::Max(h, (UInt_t)1));\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h)\n{\n \/\/ Move and resize the window.\n\n gVirtualX->MoveResizeWindow(fId, x, y, TMath::Max(w, (UInt_t)1), TMath::Max(h, (UInt_t)1));\n}\n\n\/\/______________________________________________________________________________\nBool_t TGWindow::IsMapped()\n{\n \/\/ Returns kTRUE if window is mapped on screen, kFALSE otherwise.\n\n WindowAttributes_t attr;\n\n gVirtualX->GetWindowAttributes(fId, attr);\n return (attr.fMapState != kIsUnmapped);\n}\n\n\/\/______________________________________________________________________________\nvoid TGWindow::Print(Option_t *) const\n{\n \/\/ Print window id.\n\n cout << ClassName() << \":\\t\" << fId << endl;\n}\n\n\/\/______________________________________________________________________________\nInt_t TGWindow::GetCounter()\n{\n \/\/ Return global window counter (total number of created windows).\n\n return fgCounter;\n}\n<|endoftext|>"} {"text":"\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Clifford Wolf \n * Copyright (C) 2018 Miodrag Milanovic \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#ifdef MAIN_EXECUTABLE\n\n#include \n#include \"bitstream.h\"\n#include \"command.h\"\n#include \"design_utils.h\"\n#include \"jsonparse.h\"\n#include \"log.h\"\n#include \"pcf.h\"\n#include \"timing.h\"\n\nUSING_NEXTPNR_NAMESPACE\n\nclass Ice40CommandHandler : public CommandHandler\n{\n public:\n Ice40CommandHandler(int argc, char **argv);\n virtual ~Ice40CommandHandler(){};\n std::unique_ptr createContext(std::unordered_map &values) override;\n void setupArchContext(Context *ctx) override;\n void validate() override;\n void customAfterLoad(Context *ctx) override;\n void customBitstream(Context *ctx) override;\n\n protected:\n po::options_description getArchOptions() override;\n};\n\nIce40CommandHandler::Ice40CommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}\n\npo::options_description Ice40CommandHandler::getArchOptions()\n{\n po::options_description specific(\"Architecture specific options\");\n#ifdef ICE40_HX1K_ONLY\n specific.add_options()(\"hx1k\", \"set device type to iCE40HX1K\");\n#else\n specific.add_options()(\"lp384\", \"set device type to iCE40LP384\");\n specific.add_options()(\"lp1k\", \"set device type to iCE40LP1K\");\n specific.add_options()(\"lp8k\", \"set device type to iCE40LP8K\");\n specific.add_options()(\"hx1k\", \"set device type to iCE40HX1K\");\n specific.add_options()(\"hx8k\", \"set device type to iCE40HX8K\");\n specific.add_options()(\"up5k\", \"set device type to iCE40UP5K\");\n specific.add_options()(\"u4k\", \"set device type to iCE5LP4K\");\n#endif\n specific.add_options()(\"package\", po::value(), \"set device package\");\n specific.add_options()(\"pcf\", po::value(), \"PCF constraints file to ingest\");\n specific.add_options()(\"asc\", po::value(), \"asc bitstream file to write\");\n specific.add_options()(\"read\", po::value(), \"asc bitstream file to read\");\n specific.add_options()(\"promote-logic\",\n \"enable promotion of 'logic' globals (in addition to clk\/ce\/sr by default)\");\n specific.add_options()(\"no-promote-globals\", \"disable all global promotion\");\n specific.add_options()(\"opt-timing\", \"run post-placement timing optimisation pass (experimental)\");\n specific.add_options()(\"tmfuzz\", \"run path delay estimate fuzzer\");\n specific.add_options()(\"pcf-allow-unconstrained\", \"don't require PCF to constrain all IO\");\n\n return specific;\n}\nvoid Ice40CommandHandler::validate()\n{\n conflicting_options(vm, \"read\", \"json\");\n if ((vm.count(\"lp384\") + vm.count(\"lp1k\") + vm.count(\"lp8k\") + vm.count(\"hx1k\") + vm.count(\"hx8k\") +\n vm.count(\"up5k\") + vm.count(\"u4k\")) > 1)\n log_error(\"Only one device type can be set\\n\");\n}\n\nvoid Ice40CommandHandler::customAfterLoad(Context *ctx)\n{\n if (vm.count(\"pcf\")) {\n std::string filename = vm[\"pcf\"].as();\n std::ifstream pcf(filename);\n if (!apply_pcf(ctx, filename, pcf))\n log_error(\"Loading PCF failed.\\n\");\n } else {\n log_warning(\"No PCF file specified; IO pins will be placed automatically\\n\");\n }\n}\nvoid Ice40CommandHandler::customBitstream(Context *ctx)\n{\n if (vm.count(\"asc\")) {\n std::string filename = vm[\"asc\"].as();\n std::ofstream f(filename);\n write_asc(ctx, f);\n }\n}\n\nvoid Ice40CommandHandler::setupArchContext(Context *ctx)\n{\n if (vm.count(\"tmfuzz\"))\n ice40DelayFuzzerMain(ctx);\n\n if (vm.count(\"read\")) {\n std::string filename = vm[\"read\"].as();\n std::ifstream f(filename);\n if (!read_asc(ctx, f))\n log_error(\"Loading ASC failed.\\n\");\n }\n}\n\nstd::unique_ptr Ice40CommandHandler::createContext(std::unordered_map &values)\n{\n ArchArgs chipArgs;\n chipArgs.type = ArchArgs::NONE;\n if (vm.count(\"lp384\")) {\n chipArgs.type = ArchArgs::LP384;\n chipArgs.package = \"qn32\";\n }\n\n if (vm.count(\"lp1k\")) {\n chipArgs.type = ArchArgs::LP1K;\n chipArgs.package = \"tq144\";\n }\n\n if (vm.count(\"lp8k\")) {\n chipArgs.type = ArchArgs::LP8K;\n chipArgs.package = \"ct256\";\n }\n\n if (vm.count(\"hx1k\")) {\n chipArgs.type = ArchArgs::HX1K;\n chipArgs.package = \"tq144\";\n }\n\n if (vm.count(\"hx8k\")) {\n chipArgs.type = ArchArgs::HX8K;\n chipArgs.package = \"ct256\";\n }\n\n if (vm.count(\"up5k\")) {\n chipArgs.type = ArchArgs::UP5K;\n chipArgs.package = \"sg48\";\n }\n\n if (vm.count(\"u4k\")) {\n chipArgs.type = ArchArgs::U4K;\n chipArgs.package = \"sg48\";\n }\n\n if (vm.count(\"package\"))\n chipArgs.package = vm[\"package\"].as();\n if (values.find(\"arch.name\") != values.end()) {\n std::string arch_name = values[\"arch.name\"].as_string();\n if (arch_name != \"ice40\")\n log_error(\"Unsuported architecture '%s'.\\n\", arch_name.c_str());\n }\n if (values.find(\"arch.type\") != values.end()) {\n std::string arch_type = values[\"arch.type\"].as_string();\n if (chipArgs.type != ArchArgs::NONE)\n log_error(\"Overriding architecture is unsuported.\\n\");\n\n if (arch_type == \"lp384\") {\n chipArgs.type = ArchArgs::LP384;\n }\n if (arch_type == \"lp1k\") {\n chipArgs.type = ArchArgs::LP1K;\n }\n if (arch_type == \"lp8k\") {\n chipArgs.type = ArchArgs::LP8K;\n }\n if (arch_type == \"hx1k\") {\n chipArgs.type = ArchArgs::HX1K;\n }\n if (arch_type == \"hx8k\") {\n chipArgs.type = ArchArgs::HX8K;\n }\n if (arch_type == \"up5k\") {\n chipArgs.type = ArchArgs::UP5K;\n }\n if (arch_type == \"u4k\") {\n chipArgs.type = ArchArgs::U4K;\n }\n if (chipArgs.type == ArchArgs::NONE)\n log_error(\"Unsuported FPGA type '%s'.\\n\", arch_type.c_str());\n }\n if (values.find(\"arch.package\") != values.end()) {\n if (vm.count(\"package\"))\n log_error(\"Overriding architecture is unsuported.\\n\");\n chipArgs.package = values[\"arch.package\"].as_string();\n }\n\n if (chipArgs.type == ArchArgs::NONE) {\n chipArgs.type = ArchArgs::HX1K;\n chipArgs.package = \"tq144\";\n }\n#ifdef ICE40_HX1K_ONLY\n if (chipArgs.type != ArchArgs::HX1K) {\n log_error(\"This version of nextpnr-ice40 is built with HX1K-support only.\\n\");\n }\n#endif\n\n log_warning(\"Use of default value for --package is deprecated. Please add '--package %s' to arguments.\\n\",\n chipArgs.package.c_str());\n\n auto ctx = std::unique_ptr(new Context(chipArgs));\n for (auto &val : values)\n ctx->settings[ctx->id(val.first)] = val.second;\n\n ctx->settings[ctx->id(\"arch.package\")] = ctx->archArgs().package;\n if (vm.count(\"promote-logic\"))\n ctx->settings[ctx->id(\"promote_logic\")] = Property::State::S1;\n if (vm.count(\"no-promote-globals\"))\n ctx->settings[ctx->id(\"no_promote_globals\")] = Property::State::S1;\n if (vm.count(\"opt-timing\"))\n ctx->settings[ctx->id(\"opt_timing\")] = Property::State::S1;\n if (vm.count(\"pcf-allow-unconstrained\"))\n ctx->settings[ctx->id(\"pcf_allow_unconstrained\")] = Property::State::S1;\n return ctx;\n}\n\nint main(int argc, char *argv[])\n{\n Ice40CommandHandler handler(argc, argv);\n return handler.exec();\n}\n\n#endif\nice40: Only warn about default package if there is no package argument\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Clifford Wolf \n * Copyright (C) 2018 Miodrag Milanovic \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#ifdef MAIN_EXECUTABLE\n\n#include \n#include \"bitstream.h\"\n#include \"command.h\"\n#include \"design_utils.h\"\n#include \"jsonparse.h\"\n#include \"log.h\"\n#include \"pcf.h\"\n#include \"timing.h\"\n\nUSING_NEXTPNR_NAMESPACE\n\nclass Ice40CommandHandler : public CommandHandler\n{\n public:\n Ice40CommandHandler(int argc, char **argv);\n virtual ~Ice40CommandHandler(){};\n std::unique_ptr createContext(std::unordered_map &values) override;\n void setupArchContext(Context *ctx) override;\n void validate() override;\n void customAfterLoad(Context *ctx) override;\n void customBitstream(Context *ctx) override;\n\n protected:\n po::options_description getArchOptions() override;\n};\n\nIce40CommandHandler::Ice40CommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}\n\npo::options_description Ice40CommandHandler::getArchOptions()\n{\n po::options_description specific(\"Architecture specific options\");\n#ifdef ICE40_HX1K_ONLY\n specific.add_options()(\"hx1k\", \"set device type to iCE40HX1K\");\n#else\n specific.add_options()(\"lp384\", \"set device type to iCE40LP384\");\n specific.add_options()(\"lp1k\", \"set device type to iCE40LP1K\");\n specific.add_options()(\"lp8k\", \"set device type to iCE40LP8K\");\n specific.add_options()(\"hx1k\", \"set device type to iCE40HX1K\");\n specific.add_options()(\"hx8k\", \"set device type to iCE40HX8K\");\n specific.add_options()(\"up5k\", \"set device type to iCE40UP5K\");\n specific.add_options()(\"u4k\", \"set device type to iCE5LP4K\");\n#endif\n specific.add_options()(\"package\", po::value(), \"set device package\");\n specific.add_options()(\"pcf\", po::value(), \"PCF constraints file to ingest\");\n specific.add_options()(\"asc\", po::value(), \"asc bitstream file to write\");\n specific.add_options()(\"read\", po::value(), \"asc bitstream file to read\");\n specific.add_options()(\"promote-logic\",\n \"enable promotion of 'logic' globals (in addition to clk\/ce\/sr by default)\");\n specific.add_options()(\"no-promote-globals\", \"disable all global promotion\");\n specific.add_options()(\"opt-timing\", \"run post-placement timing optimisation pass (experimental)\");\n specific.add_options()(\"tmfuzz\", \"run path delay estimate fuzzer\");\n specific.add_options()(\"pcf-allow-unconstrained\", \"don't require PCF to constrain all IO\");\n\n return specific;\n}\nvoid Ice40CommandHandler::validate()\n{\n conflicting_options(vm, \"read\", \"json\");\n if ((vm.count(\"lp384\") + vm.count(\"lp1k\") + vm.count(\"lp8k\") + vm.count(\"hx1k\") + vm.count(\"hx8k\") +\n vm.count(\"up5k\") + vm.count(\"u4k\")) > 1)\n log_error(\"Only one device type can be set\\n\");\n}\n\nvoid Ice40CommandHandler::customAfterLoad(Context *ctx)\n{\n if (vm.count(\"pcf\")) {\n std::string filename = vm[\"pcf\"].as();\n std::ifstream pcf(filename);\n if (!apply_pcf(ctx, filename, pcf))\n log_error(\"Loading PCF failed.\\n\");\n } else {\n log_warning(\"No PCF file specified; IO pins will be placed automatically\\n\");\n }\n}\nvoid Ice40CommandHandler::customBitstream(Context *ctx)\n{\n if (vm.count(\"asc\")) {\n std::string filename = vm[\"asc\"].as();\n std::ofstream f(filename);\n write_asc(ctx, f);\n }\n}\n\nvoid Ice40CommandHandler::setupArchContext(Context *ctx)\n{\n if (vm.count(\"tmfuzz\"))\n ice40DelayFuzzerMain(ctx);\n\n if (vm.count(\"read\")) {\n std::string filename = vm[\"read\"].as();\n std::ifstream f(filename);\n if (!read_asc(ctx, f))\n log_error(\"Loading ASC failed.\\n\");\n }\n}\n\nstd::unique_ptr Ice40CommandHandler::createContext(std::unordered_map &values)\n{\n ArchArgs chipArgs;\n chipArgs.type = ArchArgs::NONE;\n if (vm.count(\"lp384\")) {\n chipArgs.type = ArchArgs::LP384;\n chipArgs.package = \"qn32\";\n }\n\n if (vm.count(\"lp1k\")) {\n chipArgs.type = ArchArgs::LP1K;\n chipArgs.package = \"tq144\";\n }\n\n if (vm.count(\"lp8k\")) {\n chipArgs.type = ArchArgs::LP8K;\n chipArgs.package = \"ct256\";\n }\n\n if (vm.count(\"hx1k\")) {\n chipArgs.type = ArchArgs::HX1K;\n chipArgs.package = \"tq144\";\n }\n\n if (vm.count(\"hx8k\")) {\n chipArgs.type = ArchArgs::HX8K;\n chipArgs.package = \"ct256\";\n }\n\n if (vm.count(\"up5k\")) {\n chipArgs.type = ArchArgs::UP5K;\n chipArgs.package = \"sg48\";\n }\n\n if (vm.count(\"u4k\")) {\n chipArgs.type = ArchArgs::U4K;\n chipArgs.package = \"sg48\";\n }\n\n if (vm.count(\"package\"))\n chipArgs.package = vm[\"package\"].as();\n else\n log_warning(\"Use of default value for --package is deprecated. Please add '--package %s' to arguments.\\n\",\n chipArgs.package.c_str());\n\n if (values.find(\"arch.name\") != values.end()) {\n std::string arch_name = values[\"arch.name\"].as_string();\n if (arch_name != \"ice40\")\n log_error(\"Unsuported architecture '%s'.\\n\", arch_name.c_str());\n }\n if (values.find(\"arch.type\") != values.end()) {\n std::string arch_type = values[\"arch.type\"].as_string();\n if (chipArgs.type != ArchArgs::NONE)\n log_error(\"Overriding architecture is unsuported.\\n\");\n\n if (arch_type == \"lp384\") {\n chipArgs.type = ArchArgs::LP384;\n }\n if (arch_type == \"lp1k\") {\n chipArgs.type = ArchArgs::LP1K;\n }\n if (arch_type == \"lp8k\") {\n chipArgs.type = ArchArgs::LP8K;\n }\n if (arch_type == \"hx1k\") {\n chipArgs.type = ArchArgs::HX1K;\n }\n if (arch_type == \"hx8k\") {\n chipArgs.type = ArchArgs::HX8K;\n }\n if (arch_type == \"up5k\") {\n chipArgs.type = ArchArgs::UP5K;\n }\n if (arch_type == \"u4k\") {\n chipArgs.type = ArchArgs::U4K;\n }\n if (chipArgs.type == ArchArgs::NONE)\n log_error(\"Unsuported FPGA type '%s'.\\n\", arch_type.c_str());\n }\n if (values.find(\"arch.package\") != values.end()) {\n if (vm.count(\"package\"))\n log_error(\"Overriding architecture is unsuported.\\n\");\n chipArgs.package = values[\"arch.package\"].as_string();\n }\n\n if (chipArgs.type == ArchArgs::NONE) {\n chipArgs.type = ArchArgs::HX1K;\n chipArgs.package = \"tq144\";\n }\n#ifdef ICE40_HX1K_ONLY\n if (chipArgs.type != ArchArgs::HX1K) {\n log_error(\"This version of nextpnr-ice40 is built with HX1K-support only.\\n\");\n }\n#endif\n\n auto ctx = std::unique_ptr(new Context(chipArgs));\n for (auto &val : values)\n ctx->settings[ctx->id(val.first)] = val.second;\n\n ctx->settings[ctx->id(\"arch.package\")] = ctx->archArgs().package;\n if (vm.count(\"promote-logic\"))\n ctx->settings[ctx->id(\"promote_logic\")] = Property::State::S1;\n if (vm.count(\"no-promote-globals\"))\n ctx->settings[ctx->id(\"no_promote_globals\")] = Property::State::S1;\n if (vm.count(\"opt-timing\"))\n ctx->settings[ctx->id(\"opt_timing\")] = Property::State::S1;\n if (vm.count(\"pcf-allow-unconstrained\"))\n ctx->settings[ctx->id(\"pcf_allow_unconstrained\")] = Property::State::S1;\n return ctx;\n}\n\nint main(int argc, char *argv[])\n{\n Ice40CommandHandler handler(argc, argv);\n return handler.exec();\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Project: BaBar detector at the SLAC PEP-II B-factory\n * Package: RooFitCore\n * File: $Id: RooGaussModel.cc,v 1.7 2001\/08\/03 18:13:02 verkerke Exp $\n * Authors:\n * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu\n * History:\n * 05-Jun-2001 WV Created initial version\n *\n * Copyright (C) 2001 University of California\n *****************************************************************************\/\n\n\/\/ -- CLASS DESCRIPTION --\n\/\/ \n\n#include \n#include \"RooFitModels\/RooGaussModel.hh\"\n#include \"RooFitCore\/RooMath.hh\"\n\nClassImp(RooGaussModel) \n;\n\n\nRooGaussModel::RooGaussModel(const char *name, const char *title, RooRealVar& x, \n\t\t\t RooAbsReal& _mean, RooAbsReal& _sigma, \n\t\t\t RooAbsReal& _meanSF, RooAbsReal& _sigmaSF) : \n RooResolutionModel(name,title,x), \n mean(\"mean\",\"Mean\",this,_mean),\n sigma(\"sigma\",\"Width\",this,_sigma),\n msf(\"msf\",\"Mean Scale Factor\",this,_meanSF),\n ssf(\"ssf\",\"Sigma Scale Factor\",this,_sigmaSF)\n{ \n}\n\n\nRooGaussModel::RooGaussModel(const RooGaussModel& other, const char* name) : \n RooResolutionModel(other,name),\n mean(\"mean\",this,other.mean),\n sigma(\"sigma\",this,other.sigma),\n msf(\"msf\",this,other.msf),\n ssf(\"ssf\",this,other.ssf)\n{\n}\n\n\nRooGaussModel::~RooGaussModel()\n{\n \/\/ Destructor\n}\n\n\n\nInt_t RooGaussModel::basisCode(const char* name) const \n{\n if (!TString(\"exp(-abs(@0)\/@1)\").CompareTo(name)) return expBasisPlus ;\n if (!TString(\"exp(-abs(-@0)\/@1)\").CompareTo(name)) return expBasisMinus ;\n if (!TString(\"exp(-abs(@0)\/@1)*sin(@0*@2)\").CompareTo(name)) return sinBasisPlus ;\n if (!TString(\"exp(-abs(-@0)\/@1)*sin(@0*@2)\").CompareTo(name)) return sinBasisMinus ;\n if (!TString(\"exp(-abs(@0)\/@1)*cos(@0*@2)\").CompareTo(name)) return cosBasisPlus ;\n if (!TString(\"exp(-abs(-@0)\/@1)*cos(@0*@2)\").CompareTo(name)) return cosBasisMinus ;\n return 0 ;\n} \n\n\n\nDouble_t RooGaussModel::evaluate() const \n{ \n \/\/ *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***\n static Double_t root2(sqrt(2)) ;\n static Double_t root2pi(sqrt(2*atan2(0,-1))) ;\n\n Double_t tau = ((RooAbsReal*)basis().getParameter(1))->getVal() ;\n\n if (_basisCode==noBasis || \n ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||\n\t_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {\n Double_t xprime = (x-(mean*msf))\/(sigma*ssf) ;\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 1st form\" << endl ;\n return exp(-0.5*xprime*xprime)\/(sigma*ssf*root2pi) ;\n }\n\n \/\/ *** 2nd form: 0, used for sinBasis and cosBasis with tau=0 ***\n if (tau==0) {\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 2nd form\" << endl ;\n return 0. ;\n }\n\n \/\/ *** 3nd form: Convolution with exp(-t\/tau), used for expBasis and cosBasis(omega=0) ***\n Double_t sign = (_basisCode==expBasisPlus||_basisCode==sinBasisPlus||_basisCode==cosBasisPlus)?-1:1 ;\n Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;\n Double_t xprime = sign*(x-(mean*msf))\/tau ;\n Double_t c = (sigma*ssf)\/(root2*tau) ; \n Double_t u = xprime\/(2*c) ;\n \n if ( _basisCode==expBasisPlus || _basisCode==expBasisMinus || \n ((_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&omega==0.)) { \n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 3d form tau=\" << tau << endl ;\n return exp(xprime+c*c) * erfc(u+c) ;\n }\n \n \/\/ *** 4th form: Convolution with exp(-t\/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***\n Double_t swt = sign * omega *tau ;\n if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) {\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 4th form\" << endl ;\n return (swt==0.) ? 0. : evalCerfIm(swt,u,c) ; \n }\n\n \/\/ *** 5th form: Convolution with exp(-t\/tau)*cos(omega*t), used for cosBasis(omega<>0) ***\n if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() \n\t\t\t << \") 5th form omega = \" << omega << \", tau = \" << tau << endl ;\n return evalCerfRe(swt,u,c) ; \n }\n\n assert(0) ;\n return 0 ;\n}\n\n\n\nInt_t RooGaussModel::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const \n{\n switch(_basisCode) {\n\n \/\/ Analytical integration capability of raw PDF\n case noBasis:\n if (matchArgs(allVars,analVars,convVar())) return 1 ;\n break ;\n\n \/\/ Analytical integration capability of convoluted PDF\n case expBasisPlus:\n case expBasisMinus:\n case sinBasisPlus:\n case sinBasisMinus:\n case cosBasisPlus:\n case cosBasisMinus:\n if (matchArgs(allVars,analVars,convVar())) return 1 ;\n break ;\n }\n \n return 0 ;\n}\n\n\n\nDouble_t RooGaussModel::analyticalIntegral(Int_t code) const \n{\n static Double_t root2 = sqrt(2) ;\n static Double_t rootPiBy2 = sqrt(atan2(0.0,-1.0)\/2.0);\n\n \/\/ No integration\n if (code==0) return getVal() ;\n\n \/\/ Code must be 0 or 1\n assert(code==1) ;\n \n \/\/ *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***\n Double_t tau = ((RooAbsReal*)basis().getParameter(1))->getVal() ;\n if (_basisCode==noBasis || \n ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||\n\t_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {\n Double_t xscale = root2*(sigma*ssf);\n return 0.5*(erf((x.max()-(mean*msf))\/xscale)-erf((x.min()-(mean*msf))\/xscale));\n }\n\n Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;\n\n \/\/ *** 2nd form: unity, used for sinBasis and cosBasis with tau=0 (PDF is zero) ***\n if (tau==0&&omega!=0) return 1. ;\n\n \/\/ *** 3rd form: Convolution with exp(-t\/tau), used for expBasis and cosBasis(omega=0) ***\n Double_t sign = (_basisCode==expBasisPlus)?-1:1 ;\n Double_t c = (sigma*ssf)\/(root2*tau) ; \n Double_t xpmin = sign*(x.min()-(mean*msf))\/tau ;\n Double_t xpmax = sign*(x.max()-(mean*msf))\/tau ;\n Double_t umin = xpmin\/(2*c) ;\n Double_t umax = xpmax\/(2*c) ;\n if (_basisCode==expBasisPlus||_basisCode==expBasisMinus || \n ((_basisCode==cosBasisPlus||_basisCode==cosBasisPlus)&&omega==0.)) {\n Double_t result = sign * tau * ( erf(umax) - erf(umin) + \n exp(c*c) * ( exp(xpmax)*erfc(umax+c)\n\t\t\t\t\t\t - exp(xpmin)*erfc(umin+c) )) ; \n return result ;\n }\n\n \/\/ *** 4th form: Convolution with exp(-t\/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***\n Double_t swt = omega * tau * sign ;\n RooComplex evalDif(evalCerf(swt,umax,c) - evalCerf(swt,umin,c)) ;\n if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) { \n Double_t result = (swt==0)? 1.0 \n : (tau*sign\/(1+swt*swt) * ( evalDif.im() - swt*evalDif.re() + erf(umax) - erf(umin) )) ;\n return result ;\n }\n\n \/\/ *** 5th form: Convolution with exp(-t\/tau)*cos(omega*t), used for cosBasis(omega<>0) ***\n if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {\n Double_t result = tau*sign\/(1+swt*swt) * ( evalDif.re() + swt*evalDif.im() + erf(umax) - erf(umin) ) ;\n return result ;\n }\n\n assert(0) ;\n return 0 ;\n}\n\n\n\nRooComplex RooGaussModel::evalCerfApprox(Double_t swt, Double_t u, Double_t c) const\n{\n \/\/ use the approximation: erf(z) = exp(-z*z)\/(sqrt(pi)*z)\n \/\/ to explicitly cancel the divergent exp(y*y) behaviour of\n \/\/ CWERF for z = x + i y with large negative y\n\n static Double_t rootpi= sqrt(atan2(0,-1));\n RooComplex z(swt*c,u+c); \n RooComplex zc(u+c,-swt*c);\n RooComplex zsq= z*z;\n RooComplex v= -zsq - u*u;\n\n return v.exp()*(-zsq.exp()\/(zc*rootpi) + 1)*2 ;\n}\n\n\n\n\/*****************************************************************************\n * Project: BaBar detector at the SLAC PEP-II B-factory\n * Package: RooFitCore\n * File: $Id: RooGaussModel.cc,v 1.8 2001\/08\/23 01:23:35 verkerke Exp $\n * Authors:\n * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu\n * History:\n * 05-Jun-2001 WV Created initial version\n *\n * Copyright (C) 2001 University of California\n *****************************************************************************\/\n\n\/\/ -- CLASS DESCRIPTION --\n\/\/ \n\n#include \n#include \"RooFitModels\/RooGaussModel.hh\"\n#include \"RooFitCore\/RooMath.hh\"\n\nClassImp(RooGaussModel) \n;\n\n\nRooGaussModel::RooGaussModel(const char *name, const char *title, RooRealVar& x, \n\t\t\t RooAbsReal& _mean, RooAbsReal& _sigma, \n\t\t\t RooAbsReal& _meanSF, RooAbsReal& _sigmaSF) : \n RooResolutionModel(name,title,x), \n mean(\"mean\",\"Mean\",this,_mean),\n sigma(\"sigma\",\"Width\",this,_sigma),\n msf(\"msf\",\"Mean Scale Factor\",this,_meanSF),\n ssf(\"ssf\",\"Sigma Scale Factor\",this,_sigmaSF)\n{ \n}\n\n\nRooGaussModel::RooGaussModel(const RooGaussModel& other, const char* name) : \n RooResolutionModel(other,name),\n mean(\"mean\",this,other.mean),\n sigma(\"sigma\",this,other.sigma),\n msf(\"msf\",this,other.msf),\n ssf(\"ssf\",this,other.ssf)\n{\n}\n\n\nRooGaussModel::~RooGaussModel()\n{\n \/\/ Destructor\n}\n\n\n\nInt_t RooGaussModel::basisCode(const char* name) const \n{\n if (!TString(\"exp(-abs(@0)\/@1)\").CompareTo(name)) return expBasisPlus ;\n if (!TString(\"exp(-abs(-@0)\/@1)\").CompareTo(name)) return expBasisMinus ;\n if (!TString(\"exp(-abs(@0)\/@1)*sin(@0*@2)\").CompareTo(name)) return sinBasisPlus ;\n if (!TString(\"exp(-abs(-@0)\/@1)*sin(@0*@2)\").CompareTo(name)) return sinBasisMinus ;\n if (!TString(\"exp(-abs(@0)\/@1)*cos(@0*@2)\").CompareTo(name)) return cosBasisPlus ;\n if (!TString(\"exp(-abs(-@0)\/@1)*cos(@0*@2)\").CompareTo(name)) return cosBasisMinus ;\n return 0 ;\n} \n\n\n\nDouble_t RooGaussModel::evaluate() const \n{ \n \/\/ *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***\n static Double_t root2(sqrt(2)) ;\n static Double_t root2pi(sqrt(2*atan2(0,-1))) ;\n\n Double_t tau = (_basisCode!=noBasis)?((RooAbsReal*)basis().getParameter(1))->getVal():0 ;\n\n if (_basisCode==noBasis || \n ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||\n\t_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {\n Double_t xprime = (x-(mean*msf))\/(sigma*ssf) ;\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 1st form\" << endl ;\n return exp(-0.5*xprime*xprime)\/(sigma*ssf*root2pi) ;\n }\n\n \/\/ *** 2nd form: 0, used for sinBasis and cosBasis with tau=0 ***\n if (tau==0) {\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 2nd form\" << endl ;\n return 0. ;\n }\n\n \/\/ *** 3nd form: Convolution with exp(-t\/tau), used for expBasis and cosBasis(omega=0) ***\n Double_t sign = (_basisCode==expBasisPlus||_basisCode==sinBasisPlus||_basisCode==cosBasisPlus)?-1:1 ;\n Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;\n Double_t xprime = sign*(x-(mean*msf))\/tau ;\n Double_t c = (sigma*ssf)\/(root2*tau) ; \n Double_t u = xprime\/(2*c) ;\n \n if ( _basisCode==expBasisPlus || _basisCode==expBasisMinus || \n ((_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&omega==0.)) { \n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 3d form tau=\" << tau << endl ;\n return exp(xprime+c*c) * erfc(u+c) ;\n }\n \n \/\/ *** 4th form: Convolution with exp(-t\/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***\n Double_t swt = sign * omega *tau ;\n if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) {\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() << \") 4th form\" << endl ;\n return (swt==0.) ? 0. : evalCerfIm(swt,u,c) ; \n }\n\n \/\/ *** 5th form: Convolution with exp(-t\/tau)*cos(omega*t), used for cosBasis(omega<>0) ***\n if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {\n if (_verboseEval>2) cout << \"RooGaussModel::evaluate(\" << GetName() \n\t\t\t << \") 5th form omega = \" << omega << \", tau = \" << tau << endl ;\n return evalCerfRe(swt,u,c) ; \n }\n\n assert(0) ;\n return 0 ;\n}\n\n\n\nInt_t RooGaussModel::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const \n{\n switch(_basisCode) {\n\n \/\/ Analytical integration capability of raw PDF\n case noBasis:\n if (matchArgs(allVars,analVars,convVar())) return 1 ;\n break ;\n\n \/\/ Analytical integration capability of convoluted PDF\n case expBasisPlus:\n case expBasisMinus:\n case sinBasisPlus:\n case sinBasisMinus:\n case cosBasisPlus:\n case cosBasisMinus:\n if (matchArgs(allVars,analVars,convVar())) return 1 ;\n break ;\n }\n \n return 0 ;\n}\n\n\n\nDouble_t RooGaussModel::analyticalIntegral(Int_t code) const \n{\n static Double_t root2 = sqrt(2) ;\n static Double_t rootPiBy2 = sqrt(atan2(0.0,-1.0)\/2.0);\n\n \/\/ No integration\n if (code==0) return getVal() ;\n\n \/\/ Code must be 0 or 1\n assert(code==1) ;\n \n \/\/ *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***\n Double_t tau = (_basisCode!=noBasis)?((RooAbsReal*)basis().getParameter(1))->getVal():0 ;\n if (_basisCode==noBasis || \n ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||\n\t_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {\n Double_t xscale = root2*(sigma*ssf);\n return 0.5*(erf((x.max()-(mean*msf))\/xscale)-erf((x.min()-(mean*msf))\/xscale));\n }\n\n Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;\n\n \/\/ *** 2nd form: unity, used for sinBasis and cosBasis with tau=0 (PDF is zero) ***\n if (tau==0&&omega!=0) return 1. ;\n\n \/\/ *** 3rd form: Convolution with exp(-t\/tau), used for expBasis and cosBasis(omega=0) ***\n Double_t sign = (_basisCode==expBasisPlus)?-1:1 ;\n Double_t c = (sigma*ssf)\/(root2*tau) ; \n Double_t xpmin = sign*(x.min()-(mean*msf))\/tau ;\n Double_t xpmax = sign*(x.max()-(mean*msf))\/tau ;\n Double_t umin = xpmin\/(2*c) ;\n Double_t umax = xpmax\/(2*c) ;\n if (_basisCode==expBasisPlus||_basisCode==expBasisMinus || \n ((_basisCode==cosBasisPlus||_basisCode==cosBasisPlus)&&omega==0.)) {\n Double_t result = sign * tau * ( erf(umax) - erf(umin) + \n exp(c*c) * ( exp(xpmax)*erfc(umax+c)\n\t\t\t\t\t\t - exp(xpmin)*erfc(umin+c) )) ; \n return result ;\n }\n\n \/\/ *** 4th form: Convolution with exp(-t\/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***\n Double_t swt = omega * tau * sign ;\n RooComplex evalDif(evalCerf(swt,umax,c) - evalCerf(swt,umin,c)) ;\n if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) { \n Double_t result = (swt==0)? 1.0 \n : (tau*sign\/(1+swt*swt) * ( evalDif.im() - swt*evalDif.re() + erf(umax) - erf(umin) )) ;\n return result ;\n }\n\n \/\/ *** 5th form: Convolution with exp(-t\/tau)*cos(omega*t), used for cosBasis(omega<>0) ***\n if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {\n Double_t result = tau*sign\/(1+swt*swt) * ( evalDif.re() + swt*evalDif.im() + erf(umax) - erf(umin) ) ;\n return result ;\n }\n\n assert(0) ;\n return 0 ;\n}\n\n\n\nRooComplex RooGaussModel::evalCerfApprox(Double_t swt, Double_t u, Double_t c) const\n{\n \/\/ use the approximation: erf(z) = exp(-z*z)\/(sqrt(pi)*z)\n \/\/ to explicitly cancel the divergent exp(y*y) behaviour of\n \/\/ CWERF for z = x + i y with large negative y\n\n static Double_t rootpi= sqrt(atan2(0,-1));\n RooComplex z(swt*c,u+c); \n RooComplex zc(u+c,-swt*c);\n RooComplex zsq= z*z;\n RooComplex v= -zsq - u*u;\n\n return v.exp()*(-zsq.exp()\/(zc*rootpi) + 1)*2 ;\n}\n\n\n\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Project: BaBar detector at the SLAC PEP-II B-factory\n * Package: RooFitTools\n * File: $Id: RooPolynomial.cc,v 1.2 2001\/09\/26 21:44:06 verkerke Exp $\n * Authors:\n * DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu\n * History:\n * 05-Jan-2000 DK Created initial version from RooPolynomialProb\n * 02-Jul-2000 DK Add analytic optimizations for generating toy MC\n * at low orders\n *\n * Copyright (C) 1999 Stanford University\n *****************************************************************************\/\n\n\/\/ -- CLASS DESCRIPTION [PDF] --\n\n#include \n#include \n\n#include \"RooFitModels\/RooPolynomial.hh\"\n#include \"RooFitCore\/RooAbsReal.hh\"\n#include \"RooFitCore\/RooRealVar.hh\"\n#include \"RooFitCore\/RooArgList.hh\"\n\nClassImp(RooPolynomial)\n;\n\nRooPolynomial::RooPolynomial()\n{\n _coefIter = _coefList.createIterator() ;\n}\n\nRooPolynomial::RooPolynomial(const char* name, const char* title, \n\t\t\t RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) :\n RooAbsPdf(name, title),\n _x(\"x\", \"Dependent\", this, x),\n _coefList(\"coefList\",\"List of coefficients\",this),\n _lowestOrder(lowestOrder) \n{\n \/\/ Constructor\n _coefIter = coefList.createIterator() ;\n\n \/\/ Check lowest order\n if (_lowestOrder<1) {\n cout << \"RooPolynomial::ctor(\" << GetName() \n\t << \") WARNING: lowestOrder must be >=1, setting value to 1\" << endl ;\n _lowestOrder=1 ;\n }\n\n TIterator* coefIter = coefList.createIterator() ;\n RooAbsArg* coef ;\n while(coef = (RooAbsArg*)coefIter->Next()) {\n if (!dynamic_cast(coef)) {\n cout << \"RooPolynomial::ctor(\" << GetName() << \") ERROR: coefficient \" << coef->GetName() \n\t << \" is not of type RooAbsReal\" << endl ;\n assert(0) ;\n }\n _coefList.add(*coef) ;\n }\n delete coefIter ;\n}\n\n\n\nRooPolynomial::RooPolynomial(const char* name, const char* title,\n RooAbsReal& x) :\n RooAbsPdf(name, title),\n _x(\"x\", \"Dependent\", this, x),\n _coefList(\"coefList\",\"List of coefficients\",this),\n _lowestOrder(1)\n{\n _coefIter = _coefList.createIterator() ;\n} \n\n\n\nRooPolynomial::RooPolynomial(const RooPolynomial& other, const char* name) :\n RooAbsPdf(other, name), \n _x(\"x\", this, other._x), \n _coefList(\"coefList\",this,other._coefList),\n _lowestOrder(other._lowestOrder) \n{\n \/\/ Copy constructor\n _coefIter = _coefList.createIterator() ;\n}\n\n\n\n\nDouble_t RooPolynomial::evaluate() const \n{\n Double_t sum(1) ;\n Int_t order(_lowestOrder) ;\n _coefIter->Reset() ;\n\n RooAbsReal* coef ;\n const RooArgSet* nset = _coefList.nset() ;\n while(coef=(RooAbsReal*)_coefIter->Next()) {\n sum += coef->getVal(nset)*pow(_x,order++) ;\n }\n\n return sum;\n}\n\n\nInt_t RooPolynomial::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const \n{\n if (matchArgs(allVars, analVars, _x)) return 1;\n return 0;\n}\n\n\n\nDouble_t RooPolynomial::analyticalIntegral(Int_t code) const \n{\n assert(code==1) ;\n\n Double_t sum(_x.max()-_x.min()) ;\n\n const RooArgSet* nset = _coefList.nset() ;\n Int_t order(_lowestOrder) ;\n _coefIter->Reset() ;\n RooAbsReal* coef ;\n\n \/\/ Primitive = sum(k) coef_k * 1\/(k+1) x^(k+1)\n while(coef=(RooAbsReal*)_coefIter->Next()) {\n sum += coef->getVal(nset)*(pow(_x.max(),order+1)-pow(_x.min(),order+1))\/(order+1) ; \n order++ ;\n }\n\n return sum; \n \n}\n\/*****************************************************************************\n * Project: BaBar detector at the SLAC PEP-II B-factory\n * Package: RooFitTools\n * File: $Id: RooPolynomial.cc,v 1.3 2001\/10\/08 05:21:19 verkerke Exp $\n * Authors:\n * DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu\n * History:\n * 05-Jan-2000 DK Created initial version from RooPolynomialProb\n * 02-Jul-2000 DK Add analytic optimizations for generating toy MC\n * at low orders\n *\n * Copyright (C) 1999 Stanford University\n *****************************************************************************\/\n\n\/\/ -- CLASS DESCRIPTION [PDF] --\n\n#include \n#include \n\n#include \"RooFitModels\/RooPolynomial.hh\"\n#include \"RooFitCore\/RooAbsReal.hh\"\n#include \"RooFitCore\/RooRealVar.hh\"\n#include \"RooFitCore\/RooArgList.hh\"\n\nClassImp(RooPolynomial)\n;\n\nRooPolynomial::RooPolynomial()\n{\n _coefIter = _coefList.createIterator() ;\n}\n\nRooPolynomial::RooPolynomial(const char* name, const char* title, \n\t\t\t RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) :\n RooAbsPdf(name, title),\n _x(\"x\", \"Dependent\", this, x),\n _coefList(\"coefList\",\"List of coefficients\",this),\n _lowestOrder(lowestOrder) \n{\n \/\/ Constructor\n _coefIter = _coefList.createIterator() ;\n\n \/\/ Check lowest order\n if (_lowestOrder<1) {\n cout << \"RooPolynomial::ctor(\" << GetName() \n\t << \") WARNING: lowestOrder must be >=1, setting value to 1\" << endl ;\n _lowestOrder=1 ;\n }\n\n TIterator* coefIter = coefList.createIterator() ;\n RooAbsArg* coef ;\n while(coef = (RooAbsArg*)coefIter->Next()) {\n if (!dynamic_cast(coef)) {\n cout << \"RooPolynomial::ctor(\" << GetName() << \") ERROR: coefficient \" << coef->GetName() \n\t << \" is not of type RooAbsReal\" << endl ;\n assert(0) ;\n }\n _coefList.add(*coef) ;\n }\n delete coefIter ;\n}\n\n\n\nRooPolynomial::RooPolynomial(const char* name, const char* title,\n RooAbsReal& x) :\n RooAbsPdf(name, title),\n _x(\"x\", \"Dependent\", this, x),\n _coefList(\"coefList\",\"List of coefficients\",this),\n _lowestOrder(1)\n{\n _coefIter = _coefList.createIterator() ;\n} \n\n\n\nRooPolynomial::RooPolynomial(const RooPolynomial& other, const char* name) :\n RooAbsPdf(other, name), \n _x(\"x\", this, other._x), \n _coefList(\"coefList\",this,other._coefList),\n _lowestOrder(other._lowestOrder) \n{\n \/\/ Copy constructor\n _coefIter = _coefList.createIterator() ;\n}\n\n\n\n\nDouble_t RooPolynomial::evaluate() const \n{\n Double_t sum(1) ;\n Int_t order(_lowestOrder) ;\n _coefIter->Reset() ;\n\n RooAbsReal* coef ;\n const RooArgSet* nset = _coefList.nset() ;\n while(coef=(RooAbsReal*)_coefIter->Next()) {\n sum += coef->getVal(nset)*pow(_x,order++) ;\n }\n\n return sum;\n}\n\n\nInt_t RooPolynomial::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const \n{\n if (matchArgs(allVars, analVars, _x)) return 1;\n return 0;\n}\n\n\n\nDouble_t RooPolynomial::analyticalIntegral(Int_t code) const \n{\n assert(code==1) ;\n\n Double_t sum(_x.max()-_x.min()) ;\n\n const RooArgSet* nset = _coefList.nset() ;\n Int_t order(_lowestOrder) ;\n _coefIter->Reset() ;\n RooAbsReal* coef ;\n\n \/\/ Primitive = sum(k) coef_k * 1\/(k+1) x^(k+1)\n while(coef=(RooAbsReal*)_coefIter->Next()) {\n sum += coef->getVal(nset)*(pow(_x.max(),order+1)-pow(_x.min(),order+1))\/(order+1) ; \n order++ ;\n }\n\n return sum; \n \n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"SoundDS.h\"\n#include \"AudioDS.h\"\n#include \"audio\/SoundData.h\"\n#include \"core\/Engine.h\"\n#include \"utils\/Log.h\"\n\nnamespace ouzel\n{\n namespace audio\n {\n SoundDS::SoundDS()\n {\n }\n\n SoundDS::~SoundDS()\n {\n if (buffer3D) buffer3D->Release();\n if (buffer) buffer->Release();\n }\n\n bool SoundDS::update()\n {\n std::lock_guard lock(uploadMutex);\n\n if (dirty & DIRTY_SOUND_DATA)\n {\n if (soundData)\n {\n if (buffer3D)\n {\n buffer3D->Release();\n buffer3D = nullptr;\n }\n\n if (buffer)\n {\n buffer->Release();\n buffer = nullptr;\n }\n\n IDirectSoundBuffer* tempBuffer = nullptr;\n\n WAVEFORMATEX waveFormat;\n waveFormat.wFormatTag = soundData->getFormatTag();\n waveFormat.nChannels = soundData->getChannels();\n waveFormat.nSamplesPerSec = soundData->getSamplesPerSecond();\n waveFormat.wBitsPerSample = 16;\n waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample \/ 8);\n waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\n waveFormat.cbSize = 0;\n\n const std::vector data = soundData->getData();\n\n DSBUFFERDESC bufferDesc;\n bufferDesc.dwSize = sizeof(bufferDesc);\n bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME;\n\n if (soundData->getChannels() < 2)\n {\n bufferDesc.dwFlags |= DSBCAPS_CTRL3D;\n }\n\n bufferDesc.dwBufferBytes = static_cast(data.size());\n bufferDesc.dwReserved = 0;\n bufferDesc.lpwfxFormat = &waveFormat;\n bufferDesc.guid3DAlgorithm = GUID_NULL;\n\n AudioDS* audioDS = static_cast(sharedEngine->getAudio());\n HRESULT hr = audioDS->getDirectSound()->CreateSoundBuffer(&bufferDesc, &tempBuffer, nullptr);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to create DirectSound buffer, error: \" << hr;\n return false;\n }\n\n hr = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, reinterpret_cast(&buffer));\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to create DirectSound buffer, error: \" << hr;\n tempBuffer->Release();\n return false;\n }\n\n tempBuffer->Release();\n\n uint8_t* bufferPointer;\n DWORD bufferSize;\n hr = buffer->Lock(0, bufferDesc.dwBufferBytes, reinterpret_cast(&bufferPointer), &bufferSize, nullptr, 0, 0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to lock DirectSound buffer, error: \" << hr;\n return false;\n }\n\n std::copy(data.begin(), data.end(), bufferPointer);\n\n hr = buffer->Unlock(bufferPointer, bufferSize, nullptr, 0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to unlock DirectSound buffer, error: \" << hr;\n return false;\n }\n\n if (bufferDesc.dwFlags & DSBCAPS_CTRL3D)\n {\n hr = buffer->QueryInterface(IID_IDirectSound3DBuffer8, reinterpret_cast(&buffer3D));\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to get DirectSound 3D buffer, error: \" << hr;\n return false;\n }\n }\n }\n }\n\n if (dirty & DIRTY_PITCH)\n {\n if (soundData)\n {\n DWORD frequency = static_cast(soundData->getSamplesPerSecond() * pitch);\n buffer->SetFrequency(frequency);\n }\n }\n\n if (dirty & DIRTY_GAIN)\n {\n LONG volume = DSBVOLUME_MIN + static_cast((DSBVOLUME_MAX - DSBVOLUME_MIN) * gain);\n buffer->SetVolume(volume);\n }\n\n if (dirty & DIRTY_POSITION)\n {\n if (buffer3D)\n {\n HRESULT hr = buffer3D->SetPosition(position.v[0], position.v[1], position.v[2], DS3D_IMMEDIATE);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer position, error: \" << hr;\n return false;\n }\n }\n }\n\n if (dirty & DIRTY_PLAY_STATE)\n {\n if (buffer)\n {\n if (shouldPlay)\n {\n if (reset)\n {\n HRESULT hr = buffer->SetCurrentPosition(0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer current position, error: \" << hr;\n return false;\n }\n }\n\n HRESULT hr = buffer->Play(0, 0, 0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to play DirectSound buffer, error: \" << hr;\n return false;\n }\n }\n else\n {\n HRESULT hr = buffer->Stop();\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to stop DirectSound buffer, error: \" << hr;\n return false;\n }\n\n hr = buffer->SetCurrentPosition(0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer current position, error: \" << hr;\n return false;\n }\n }\n }\n }\n\n dirty = 0;\n\n return true;\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\nAdd error checks and fully initialize DirectSound source\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"SoundDS.h\"\n#include \"AudioDS.h\"\n#include \"audio\/SoundData.h\"\n#include \"core\/Engine.h\"\n#include \"utils\/Log.h\"\n\nnamespace ouzel\n{\n namespace audio\n {\n SoundDS::SoundDS()\n {\n }\n\n SoundDS::~SoundDS()\n {\n if (buffer3D) buffer3D->Release();\n if (buffer) buffer->Release();\n }\n\n bool SoundDS::update()\n {\n std::lock_guard lock(uploadMutex);\n\n if (dirty & DIRTY_SOUND_DATA)\n {\n if (soundData)\n {\n if (buffer3D)\n {\n buffer3D->Release();\n buffer3D = nullptr;\n }\n\n if (buffer)\n {\n buffer->Release();\n buffer = nullptr;\n }\n\n IDirectSoundBuffer* tempBuffer = nullptr;\n\n WAVEFORMATEX waveFormat;\n waveFormat.wFormatTag = soundData->getFormatTag();\n waveFormat.nChannels = soundData->getChannels();\n waveFormat.nSamplesPerSec = soundData->getSamplesPerSecond();\n waveFormat.wBitsPerSample = 16;\n waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample \/ 8);\n waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\n waveFormat.cbSize = 0;\n\n const std::vector data = soundData->getData();\n\n DSBUFFERDESC bufferDesc;\n bufferDesc.dwSize = sizeof(bufferDesc);\n bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME;\n\n if (soundData->getChannels() < 2)\n {\n bufferDesc.dwFlags |= DSBCAPS_CTRL3D;\n }\n\n bufferDesc.dwBufferBytes = static_cast(data.size());\n bufferDesc.dwReserved = 0;\n bufferDesc.lpwfxFormat = &waveFormat;\n bufferDesc.guid3DAlgorithm = GUID_NULL;\n\n AudioDS* audioDS = static_cast(sharedEngine->getAudio());\n HRESULT hr = audioDS->getDirectSound()->CreateSoundBuffer(&bufferDesc, &tempBuffer, nullptr);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to create DirectSound buffer, error: \" << hr;\n return false;\n }\n\n hr = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, reinterpret_cast(&buffer));\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to create DirectSound buffer, error: \" << hr;\n tempBuffer->Release();\n return false;\n }\n\n tempBuffer->Release();\n\n uint8_t* bufferPointer;\n DWORD bufferSize;\n hr = buffer->Lock(0, bufferDesc.dwBufferBytes, reinterpret_cast(&bufferPointer), &bufferSize, nullptr, 0, 0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to lock DirectSound buffer, error: \" << hr;\n return false;\n }\n\n std::copy(data.begin(), data.end(), bufferPointer);\n\n hr = buffer->Unlock(bufferPointer, bufferSize, nullptr, 0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to unlock DirectSound buffer, error: \" << hr;\n return false;\n }\n\n if (pitch != 1.0f)\n {\n DWORD frequency = static_cast(soundData->getSamplesPerSecond() * pitch);\n hr = buffer->SetFrequency(frequency);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer frequency, error: \" << hr;\n return false;\n }\n }\n\n if (gain != 1.0f)\n {\n LONG volume = DSBVOLUME_MIN + static_cast((DSBVOLUME_MAX - DSBVOLUME_MIN) * gain);\n hr = buffer->SetVolume(volume);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer volume, error: \" << hr;\n return false;\n }\n }\n\n if (bufferDesc.dwFlags & DSBCAPS_CTRL3D)\n {\n hr = buffer->QueryInterface(IID_IDirectSound3DBuffer8, reinterpret_cast(&buffer3D));\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to get DirectSound 3D buffer, error: \" << hr;\n return false;\n }\n\n hr = buffer3D->SetPosition(position.v[0], position.v[1], position.v[2], DS3D_IMMEDIATE);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer position, error: \" << hr;\n return false;\n }\n }\n }\n }\n\n if (dirty & DIRTY_PITCH)\n {\n if (buffer && soundData)\n {\n DWORD frequency = static_cast(soundData->getSamplesPerSecond() * pitch);\n HRESULT hr = buffer->SetFrequency(frequency);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer frequency, error: \" << hr;\n return false;\n }\n }\n }\n\n if (dirty & DIRTY_GAIN)\n {\n if (buffer)\n {\n LONG volume = DSBVOLUME_MIN + static_cast((DSBVOLUME_MAX - DSBVOLUME_MIN) * gain);\n HRESULT hr = buffer->SetVolume(volume);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer volume, error: \" << hr;\n return false;\n }\n }\n }\n\n if (dirty & DIRTY_POSITION)\n {\n if (buffer3D)\n {\n HRESULT hr = buffer3D->SetPosition(position.v[0], position.v[1], position.v[2], DS3D_IMMEDIATE);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer position, error: \" << hr;\n return false;\n }\n }\n }\n\n if (dirty & DIRTY_PLAY_STATE)\n {\n if (buffer)\n {\n if (shouldPlay)\n {\n if (reset)\n {\n HRESULT hr = buffer->SetCurrentPosition(0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer current position, error: \" << hr;\n return false;\n }\n }\n\n HRESULT hr = buffer->Play(0, 0, 0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to play DirectSound buffer, error: \" << hr;\n return false;\n }\n }\n else\n {\n HRESULT hr = buffer->Stop();\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to stop DirectSound buffer, error: \" << hr;\n return false;\n }\n\n hr = buffer->SetCurrentPosition(0);\n if (FAILED(hr))\n {\n Log(Log::Level::ERR) << \"Failed to set DirectSound buffer current position, error: \" << hr;\n return false;\n }\n }\n }\n }\n\n dirty = 0;\n\n return true;\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"\/** \\brief Tool for title, author and full-text extraction from XMl files corresponding to the Journal Publishing DTD.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"FileUtil.h\"\n#include \"util.h\"\n#include \"XMLParser.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" xml_input plain_test_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nbool ExtractTitle(XMLParser * const xml_parser, std::string * const article_title) {\n article_title->clear();\n\n if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, \"article-title\"))\n return false;\n\n XMLParser::XMLPart xml_part;\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == \"article-title\")\n return not article_title->empty();\n if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)\n *article_title += xml_part.data_;\n }\n\n return false;\n}\n\n\nbool ExtractAuthor(XMLParser * const xml_parser, std::vector * const article_authors) {\n if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, \"surname\"))\n return false;\n\n XMLParser::XMLPart xml_part;\n if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)\n return false;\n std::string surname(xml_part.data_);\n\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == \"contrib\") {\n article_authors->emplace_back(surname);\n return true;\n } else if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG and xml_part.data_ == \"given-names\") {\n if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)\n return false;\n article_authors->emplace_back(xml_part.data_ + \" \" + surname);\n return true;\n }\n }\n\n return false;\n}\n\n\nbool ExtractAuthors(XMLParser * const xml_parser, std::vector * const article_authors, std::string * const text_opening_tag) {\n XMLParser::XMLPart xml_part;\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG) {\n if (xml_part.data_ == \"abstract\" or xml_part.data_ == \"body\") {\n *text_opening_tag = xml_part.data_;\n return true;\n }\n else if (xml_part.data_ == \"contrib\") {\n const auto contrib_type_and_value(xml_part.attributes_.find(\"contrib-type\"));\n if (contrib_type_and_value != xml_part.attributes_.cend() and contrib_type_and_value->second == \"author\") {\n if (not ExtractAuthor(xml_parser, article_authors))\n return false;\n }\n }\n }\n }\n\n return false;\n}\n\n\nbool ExtractTextHelper(XMLParser * const xml_parser, const std::string &closing_tag, std::string * const text) {\n XMLParser::XMLPart xml_part;\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == closing_tag)\n return true;\n if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)\n *text += xml_part.data_;\n }\n\n return false;\n}\n\n\n\/\/ Extracts abstracts and bodies.\nbool ExtractText(XMLParser * const xml_parser, const std::string &text_opening_tag, std::string * const text) {\n if (not ExtractTextHelper(xml_parser, text_opening_tag, text))\n return false;\n *text += '\\n';\n\n if (text_opening_tag == \"body\")\n return true;\n\n if (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, \"body\")) {\n if (not ExtractTextHelper(xml_parser, \"body\", text))\n return false;\n *text += '\\n';\n }\n\n return not text->empty();\n}\n\n\nvoid ProcessDocument(XMLParser * const xml_parser, File * const plain_text_output) {\n std::string article_title;\n if (not ExtractTitle(xml_parser, &article_title))\n LOG_ERROR(\"no article title found!\");\n std::cout << \"Article title is \" << article_title << '\\n';\n\n std::vector article_authors;\n std::string text_opening_tag;\n if (not ExtractAuthors(xml_parser, &article_authors, &text_opening_tag))\n LOG_ERROR(\"no article authors found or an error or end-of-document were found while trying to extract an author name!\");\n std::cout << \"Article authors are:\\n\";\n for (const auto &author : article_authors)\n std::cout << '\\t' << author << '\\n';\n\n std::string text;\n if (not ExtractText(xml_parser, text_opening_tag, &text))\n LOG_ERROR(\"no text found!\");\n plain_text_output->write(text);\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 3)\n Usage();\n\n XMLParser xml_parser (argv[1], XMLParser::XML_FILE);\n auto plain_text_output(FileUtil::OpenOutputFileOrDie(argv[2]));\n ProcessDocument(&xml_parser, plain_text_output.get());\n\n return EXIT_SUCCESS;\n}\nHoly shit, it works!!!\/** \\brief Tool for title, author and full-text extraction from XMl files corresponding to the Journal Publishing DTD.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"ControlNumberGuesser.h\"\n#include \"FileUtil.h\"\n#include \"util.h\"\n#include \"XMLParser.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" xml_input plain_test_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nbool ExtractTitle(XMLParser * const xml_parser, std::string * const article_title) {\n article_title->clear();\n\n if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, \"article-title\"))\n return false;\n\n XMLParser::XMLPart xml_part;\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == \"article-title\")\n return not article_title->empty();\n if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)\n *article_title += xml_part.data_;\n }\n\n return false;\n}\n\n\nbool ExtractAuthor(XMLParser * const xml_parser, std::vector * const article_authors) {\n if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, \"surname\"))\n return false;\n\n XMLParser::XMLPart xml_part;\n if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)\n return false;\n std::string surname(xml_part.data_);\n\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == \"contrib\") {\n article_authors->emplace_back(surname);\n return true;\n } else if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG and xml_part.data_ == \"given-names\") {\n if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)\n return false;\n article_authors->emplace_back(xml_part.data_ + \" \" + surname);\n return true;\n }\n }\n\n return false;\n}\n\n\nbool ExtractAuthors(XMLParser * const xml_parser, std::vector * const article_authors, std::string * const text_opening_tag) {\n XMLParser::XMLPart xml_part;\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG) {\n if (xml_part.data_ == \"abstract\" or xml_part.data_ == \"body\") {\n *text_opening_tag = xml_part.data_;\n return true;\n }\n else if (xml_part.data_ == \"contrib\") {\n const auto contrib_type_and_value(xml_part.attributes_.find(\"contrib-type\"));\n if (contrib_type_and_value != xml_part.attributes_.cend() and contrib_type_and_value->second == \"author\") {\n if (not ExtractAuthor(xml_parser, article_authors))\n return false;\n }\n }\n }\n }\n\n return false;\n}\n\n\nbool ExtractTextHelper(XMLParser * const xml_parser, const std::string &closing_tag, std::string * const text) {\n XMLParser::XMLPart xml_part;\n while (xml_parser->getNext(&xml_part)) {\n if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == closing_tag)\n return true;\n if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)\n *text += xml_part.data_;\n }\n\n return false;\n}\n\n\n\/\/ Extracts abstracts and bodies.\nbool ExtractText(XMLParser * const xml_parser, const std::string &text_opening_tag, std::string * const text) {\n if (not ExtractTextHelper(xml_parser, text_opening_tag, text))\n return false;\n *text += '\\n';\n\n if (text_opening_tag == \"body\")\n return true;\n\n if (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, \"body\")) {\n if (not ExtractTextHelper(xml_parser, \"body\", text))\n return false;\n *text += '\\n';\n }\n\n return not text->empty();\n}\n\n\nvoid ProcessDocument(XMLParser * const xml_parser, const ControlNumberGuesser &control_number_guesser, File * const plain_text_output) {\n std::string article_title;\n if (not ExtractTitle(xml_parser, &article_title))\n LOG_ERROR(\"no article title found!\");\n\n std::vector article_authors;\n std::string text_opening_tag;\n if (not ExtractAuthors(xml_parser, &article_authors, &text_opening_tag))\n LOG_ERROR(\"no article authors found or an error or end-of-document were found while trying to extract an author name!\");\n\n const auto matching_control_numbers(control_number_guesser.getGuessedControlNumbers(article_title, article_authors));\n if (matching_control_numbers.empty())\n LOG_ERROR(\"no matching control numbers found!\");\n\n std::cout << \"Matching control numbers:\\n\";\n for (const auto matching_control_number : matching_control_numbers)\n std::cout << '\\t' << matching_control_number << '\\n';\n\n std::string text;\n if (not ExtractText(xml_parser, text_opening_tag, &text))\n LOG_ERROR(\"no text found!\");\n plain_text_output->write(text);\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 3)\n Usage();\n\n XMLParser xml_parser (argv[1], XMLParser::XML_FILE);\n auto plain_text_output(FileUtil::OpenOutputFileOrDie(argv[2]));\n ControlNumberGuesser control_number_guesser(ControlNumberGuesser::DO_NOT_CLEAR_DATABASES);\n ProcessDocument(&xml_parser, control_number_guesser, plain_text_output.get());\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define FLAG_a 1\n#define FLAG_l 2\n#define FLAG_R 4 \n\nvoid permission(const struct stat buf, dirent *dirp);\nstring addC_str(const char *name, char d_name[]);\n\n\/\/function for ls -a\nvoid ls_a(const char* path){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(path))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\terrno = 0;\n\twhile( (filespecs = readdir(dirp) ) != NULL){\n\t\tcout << filespecs -> d_name << \" \" ;\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\treturn;\n}\n\n\/\/function for ls by itself\nvoid ls(const char* path){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(path))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\terrno = 0;\n\twhile( (filespecs = readdir(dirp) ) != NULL){\n\t\tif (strcmp(filespecs->d_name, \".\")!=0 && strcmp(filespecs->d_name, \"..\")!=0 \n\t\t\t&& strcmp(filespecs->d_name, \".git\") != 0){\n\t\t\tcout << filespecs -> d_name << \" \" ;\n\t\t}\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\treturn;\n}\n\n\/\/function for ls -l and also when ls -a -l is called\nvoid ls_l(const char* dir, bool isA){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(dir))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\tstruct stat s;\n\t\/\/stat(dir, &s);\n\terrno = 0;\n\twhile( (filespecs = readdir(dirp) ) != NULL){\n\t\tstat(dir, &s);\n\t\tif(isA){\n\t\t\tpermission(s, filespecs);\t\n\t\t}\n\t\telse{\n\t\t\tif (strcmp(filespecs->d_name, \".\")!=0 \n\t\t\t\t&& strcmp(filespecs->d_name, \"..\")!=0 \n\t\t\t\t&& strcmp(filespecs->d_name, \".git\") != 0){\n\t\t\t\tpermission(s, filespecs);\n\t\t\t}\n\t\t}\t\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\t\n\treturn;\n}\n\n\/\/function for -R\nvoid ls_R(const char* dir){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(dir))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\terrno = 0;\n\t\n\twhile( (filespecs=readdir(dirp)) != NULL){\n\t\tif(filespecs-> d_name[0] != '.'){\n\t\t\tstring path;\n\t\t\tpath += addC_str(dir, filespecs->d_name);\n\t\t\t\n\t\t\tcout << filespecs->d_name << \":\" << endl; \n\t\t\t\t\n\t\t\tif(filespecs-> d_type == DT_DIR)\n\t\t\t\tls_R(path.c_str());\n\t\t\t\n\t\t}\n\t\telse{\n\t\t\tcout << filespecs->d_name << endl;\n\t\t\t\n\t\t}\n\t\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\n\treturn;\n}\n\n\/\/try to get print info function working so I can delete other functions\nvoid printDir(const char *dir){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(dir))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\tstruct stat s;\n\t\/\/stat(dir, &s);\n\terrno = 0;\n\twhile( (filespecs = readdir(dirp) ) != NULL){\n\t\tif (strcmp(filespecs->d_name, \".\")!=0 && strcmp(filespecs->d_name, \"..\")!=0 \n\t\t\t&& strcmp(filespecs->d_name, \".git\") != 0){\n\t\tstat(dir, &s);\n\t\tpermission(s, filespecs);\n\t\t}\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\t\n\treturn;\n\n}\n\n\/\/permissions to be outputted by -l\nvoid permission(const struct stat buf, dirent *dirp){\n\t\/\/create a struct with for the time\n\tstruct tm* file_t;\n\tfile_t = localtime( &buf.st_mtime);\n\tchar buffer[100];\n\tstrftime(buffer, 100, \"%h %e %R\", file_t);\n\t\n\t\/\/output all stat\n\t(buf.st_mode & S_IFDIR)? cout << \"d\":\n\t(buf.st_mode & S_IFCHR) ? cout<< 'c':\n\t(buf.st_mode & S_IFBLK) ? cout<< 'b':\n\t(buf.st_mode & S_IFIFO) ? cout<< 'f':\n\t(buf.st_mode & S_IFSOCK) ? cout<<'s':\n\t(buf.st_mode & S_IFLNK) ? cout<< 'l':\n\t\n\t(buf.st_mode & S_IRUSR)? cout << \"r\": cout << \"-\";\n\t(buf.st_mode & S_IWUSR)? cout << \"w\": cout << \"-\";\n\t(buf.st_mode & S_IXUSR)? cout << \"x\": cout << \"-\";\n\t\n\t(buf.st_mode & S_IRGRP)? cout << \"r\": cout << \"-\";\n\t(buf.st_mode & S_IWGRP)? cout << \"w\": cout << \"-\";\n\t(buf.st_mode & S_IXGRP)? cout << \"x\": cout << \"-\";\n\t\n\t(buf.st_mode & S_IROTH)? cout << \"r\": cout << \"-\";\n\t(buf.st_mode & S_IWOTH)? cout << \"w\": cout << \"-\";\n\t(buf.st_mode & S_IXOTH)? cout << \"x\": cout << \"-\";\n\tcout << \" \";\n\t\n\tcout << \" \" << buf.st_nlink << \" \";\n\tcout << getpwuid(buf.st_uid)-> pw_name << \" \";\n\tcout << getgrgid(buf.st_gid) -> gr_name << \" \";\n\tcout << buf.st_size << \" \" << buffer << \" \" << dirp->d_name << endl;\n}\n\nint main(int argc, char* argv[]){\n\t\/\/make a vector for the directory names and filenames inputted\n\t\/\/into command line\n\tvector dir_names;\n\tvector file_names;\n\t\/\/char* path;\n\t\n\t\/\/set flags\n\tint flags=0;\n\tint numFile=1;\n\t\/\/booleans to keep track of which flags are called\t\n\tbool isA=false;\n\tbool isL=false;\n\tbool isR=false;\n\t\n\t\/\/check if the arguments are flags or filenames\n\tfor(int pos=1; poscombined ls and ls -a#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define FLAG_a 1\n#define FLAG_l 2\n#define FLAG_R 4 \n\nvoid permission(const struct stat buf, dirent *dirp);\nstring addC_str(const char *name, char d_name[]);\n\n\/\/function for ls and ls -a \nvoid ls(const char* path, bool isA){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(path))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\terrno = 0;\n\twhile( (filespecs = readdir(dirp) ) != NULL){\n\t\tif(isA){\n\t\t\tcout << filespecs->d_name << \" \";\n\t\t}\n\t\telse{\n\t\t\t if (strcmp(filespecs->d_name, \".\")!=0 \n\t\t\t&& strcmp(filespecs->d_name, \"..\")!=0 \n\t\t\t&& strcmp(filespecs->d_name, \".git\") != 0){\n\t\t\tcout << filespecs -> d_name << \" \" ;\n\t\t\t}\n\t\t}\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\treturn;\n}\n\n\/\/function for ls -l and also when ls -a -l is called\nvoid ls_l(const char* dir, bool isA, bool isR){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(dir))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\tstruct stat s;\n\t\/\/stat(dir, &s);\n\terrno = 0;\n\twhile( (filespecs = readdir(dirp) ) != NULL){\n\t\tstat(dir, &s);\n\t\tif(isA){\n\t\t\tpermission(s, filespecs);\t\n\t\t}\n\t\telse if(isR){\n\t\t\t\n\t\t\t\n\t\t\t\n\t\n\t\t}\n\t\telse{\n\t\t\tif (strcmp(filespecs->d_name, \".\")!=0 \n\t\t\t\t&& strcmp(filespecs->d_name, \"..\")!=0 \n\t\t\t\t&& strcmp(filespecs->d_name, \".git\") != 0){\n\t\t\t\tpermission(s, filespecs);\n\t\t\t}\n\t\t}\t\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\t\n\treturn;\n}\n\n\/\/function for -R\nvoid ls_R(const char* dir){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(dir))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\terrno = 0;\n\t\n\twhile( (filespecs=readdir(dirp)) != NULL){\n\t\tif(filespecs-> d_name[0] != '.'){\n\t\t\tstring path;\n\t\t\tpath += addC_str(dir, filespecs->d_name);\n\t\t\t\n\t\t\tcout << filespecs->d_name << \":\" << endl; \n\t\t\t\t\n\t\t\tif(filespecs-> d_type == DT_DIR)\n\t\t\t\tls_R(path.c_str());\n\t\t\t\n\t\t}\n\t\telse{\n\t\t\tcout << filespecs->d_name << endl;\n\t\t\t\n\t\t}\n\t\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\n\treturn;\n}\n\n\/\/try to get print info function working so I can delete other functions\nvoid printDir(const char *dir){\n\tDIR *dirp;\n\tif(NULL == (dirp = opendir(dir))){\n\t\tperror(\"There was an error with opendir().\");\n\t\texit(1);\n\t}\n\tstruct dirent *filespecs;\n\tstruct stat s;\n\t\/\/stat(dir, &s);\n\terrno = 0;\n\twhile( (filespecs = readdir(dirp) ) != NULL){\n\t\tif (strcmp(filespecs->d_name, \".\")!=0 && strcmp(filespecs->d_name, \"..\")!=0 \n\t\t\t&& strcmp(filespecs->d_name, \".git\") != 0){\n\t\tstat(dir, &s);\n\t\tpermission(s, filespecs);\n\t\t}\n\t}\n\tif(errno != 0){\n\t\tperror(\"There was an error with readdir().\");\n\t\texit(1);\n\t}\n\tcout << endl;\n\tif(-1 == closedir(dirp)){\n\t\tperror(\"There was an error with closedir().\");\n\t\texit(1);\n\t}\n\t\n\treturn;\n\n}\n\n\/\/permissions to be outputted by -l\nvoid permission(const struct stat buf, dirent *dirp){\n\t\/\/create a struct with for the time\n\tstruct tm* file_t;\n\tfile_t = localtime( &buf.st_mtime);\n\tchar buffer[100];\n\tstrftime(buffer, 100, \"%h %e %R\", file_t);\n\t\n\t\/\/output all stat\n\t(buf.st_mode & S_IFDIR)? cout << \"d\":\n\t(buf.st_mode & S_IFCHR) ? cout<< 'c':\n\t(buf.st_mode & S_IFBLK) ? cout<< 'b':\n\t(buf.st_mode & S_IFIFO) ? cout<< 'f':\n\t(buf.st_mode & S_IFSOCK) ? cout<<'s':\n\t(buf.st_mode & S_IFLNK) ? cout<< 'l':\n\t\n\t(buf.st_mode & S_IRUSR)? cout << \"r\": cout << \"-\";\n\t(buf.st_mode & S_IWUSR)? cout << \"w\": cout << \"-\";\n\t(buf.st_mode & S_IXUSR)? cout << \"x\": cout << \"-\";\n\t\n\t(buf.st_mode & S_IRGRP)? cout << \"r\": cout << \"-\";\n\t(buf.st_mode & S_IWGRP)? cout << \"w\": cout << \"-\";\n\t(buf.st_mode & S_IXGRP)? cout << \"x\": cout << \"-\";\n\t\n\t(buf.st_mode & S_IROTH)? cout << \"r\": cout << \"-\";\n\t(buf.st_mode & S_IWOTH)? cout << \"w\": cout << \"-\";\n\t(buf.st_mode & S_IXOTH)? cout << \"x\": cout << \"-\";\n\tcout << \" \";\n\t\n\tcout << \" \" << buf.st_nlink << \" \";\n\tcout << getpwuid(buf.st_uid)-> pw_name << \" \";\n\tcout << getgrgid(buf.st_gid) -> gr_name << \" \";\n\tcout << buf.st_size << \" \" << buffer << \" \" << dirp->d_name << endl;\n}\n\nint main(int argc, char* argv[]){\n\t\/\/make a vector for the directory names and filenames inputted\n\t\/\/into command line\n\tvector dir_names;\n\tvector file_names;\n\t\/\/char* path;\n\t\n\t\/\/set flags\n\tint flags=0;\n\tint numFile=1;\n\t\/\/booleans to keep track of which flags are called\t\n\tbool isA=false;\n\tbool isL=false;\n\tbool isR=false;\n\t\n\t\/\/check if the arguments are flags or filenames\n\tfor(int pos=1; pos"} {"text":"\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 winlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n#include \n\nVOID TEST(AMF0Test, Size) \n{\n\tEXPECT_EQ(2+6, SrsAmf0Size::utf8(\"winlin\"));\n\tEXPECT_EQ(2+0, SrsAmf0Size::utf8(\"\"));\n\t\n\tEXPECT_EQ(1+2+6, SrsAmf0Size::str(\"winlin\"));\n\tEXPECT_EQ(1+2+0, SrsAmf0Size::str(\"\"));\n\t\n\tEXPECT_EQ(1+8, SrsAmf0Size::number());\n\t\n\tEXPECT_EQ(1, SrsAmf0Size::null());\n\t\n\tEXPECT_EQ(1, SrsAmf0Size::undefined());\n\t\n\tEXPECT_EQ(1+1, SrsAmf0Size::boolean());\n\t\n\tif (true) {\n\t\tint size = 1+3;\n\t\tSrsAmf0Object obj;\n\t\t\n\t\tEXPECT_EQ(size, SrsAmf0Size::object(&obj));\n\t}\n\tif (true) {\n\t\tint size = 1+3;\n\t\tSrsAmf0Object obj;\n\t\t\n\t\tsize += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\n\t\tobj.set(\"name\", new SrsAmf0String(\"winlin\"));\n\t\t\n\t\tEXPECT_EQ(size, SrsAmf0Size::object(&obj));\n\t}\n\t\n\tif (true) {\n\t\tint size = 1+4+3;\n\t\tSrsAmf0EcmaArray arr;\n\t\t\n\t\tEXPECT_EQ(size, SrsAmf0Size::array(&arr));\n\t}\n\tif (true) {\n\t\tint size = 1+4+3;\n\t\tSrsAmf0EcmaArray arr;\n\t\t\n\t\tsize += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\n\t\tarr.set(\"name\", new SrsAmf0String(\"winlin\"));\n\t\t\n\t\tEXPECT_EQ(size, SrsAmf0Size::array(&arr));\n\t}\n\tif (true) {\n\t\tint size = 1+4+3;\n\t\tSrsAmf0EcmaArray arr;\n\t\t\n\t\tsize += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\n\t\tarr.set(\"name\", new SrsAmf0String(\"winlin\"));\n\t\t\n\t\tSrsAmf0Object* args = new SrsAmf0Object();\n\t\tsize += SrsAmf0Size::utf8(\"args\")+SrsAmf0Size::object(args);\n\t\tarr.set(\"args\", args);\n\t\t\n\t\tEXPECT_EQ(size, SrsAmf0Size::array(&arr));\n\t}\n}\namf0 utest: refine amf0 size and finish utest.\/*\r\nThe MIT License (MIT)\r\n\r\nCopyright (c) 2013-2014 winlin\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\nthe Software, and to permit persons to whom the Software is furnished to do so,\r\nsubject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n#include \r\n\r\nVOID TEST(AMF0Test, Size) \r\n{\r\n \/\/ size of elem\r\n EXPECT_EQ(2+6, SrsAmf0Size::utf8(\"winlin\"));\r\n EXPECT_EQ(2+0, SrsAmf0Size::utf8(\"\"));\r\n \r\n EXPECT_EQ(1+2+6, SrsAmf0Size::str(\"winlin\"));\r\n EXPECT_EQ(1+2+0, SrsAmf0Size::str(\"\"));\r\n \r\n EXPECT_EQ(1+8, SrsAmf0Size::number());\r\n \r\n EXPECT_EQ(1, SrsAmf0Size::null());\r\n \r\n EXPECT_EQ(1, SrsAmf0Size::undefined());\r\n \r\n EXPECT_EQ(1+1, SrsAmf0Size::boolean());\r\n \r\n \/\/ object: empty\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n \/\/ object: elem\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"age\")+SrsAmf0Size::number();\r\n o.set(\"age\", new SrsAmf0Number(9));\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"email\")+SrsAmf0Size::null();\r\n o.set(\"email\", new SrsAmf0Null());\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"email\")+SrsAmf0Size::undefined();\r\n o.set(\"email\", new SrsAmf0Undefined());\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"sex\")+SrsAmf0Size::boolean();\r\n o.set(\"sex\", new SrsAmf0Boolean(true));\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n \r\n \/\/ array: empty\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n \/\/ array: elem\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"age\")+SrsAmf0Size::number();\r\n o.set(\"age\", new SrsAmf0Number(9));\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"email\")+SrsAmf0Size::null();\r\n o.set(\"email\", new SrsAmf0Null());\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"email\")+SrsAmf0Size::undefined();\r\n o.set(\"email\", new SrsAmf0Undefined());\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"sex\")+SrsAmf0Size::boolean();\r\n o.set(\"sex\", new SrsAmf0Boolean(true));\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n \r\n \/\/ object: array\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n SrsAmf0EcmaArray* args = new SrsAmf0EcmaArray();\r\n args->set(\"p0\", new SrsAmf0String(\"function\"));\r\n size += SrsAmf0Size::utf8(\"args\")+SrsAmf0Size::array(args);\r\n o.set(\"args\", args);\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n SrsAmf0EcmaArray* args = new SrsAmf0EcmaArray();\r\n args->set(\"p0\", new SrsAmf0String(\"function\"));\r\n size += SrsAmf0Size::utf8(\"args\")+SrsAmf0Size::array(args);\r\n o.set(\"args\", args);\r\n \r\n SrsAmf0EcmaArray* params = new SrsAmf0EcmaArray();\r\n params->set(\"p1\", new SrsAmf0Number(10));\r\n size += SrsAmf0Size::utf8(\"params\")+SrsAmf0Size::array(params);\r\n o.set(\"params\", params);\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n \r\n \/\/ array: object\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n SrsAmf0Object* args = new SrsAmf0Object();\r\n args->set(\"p0\", new SrsAmf0String(\"function\"));\r\n size += SrsAmf0Size::utf8(\"args\")+SrsAmf0Size::object(args);\r\n o.set(\"args\", args);\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n SrsAmf0Object* args = new SrsAmf0Object();\r\n args->set(\"p0\", new SrsAmf0String(\"function\"));\r\n size += SrsAmf0Size::utf8(\"args\")+SrsAmf0Size::object(args);\r\n o.set(\"args\", args);\r\n \r\n SrsAmf0Object* params = new SrsAmf0Object();\r\n params->set(\"p1\", new SrsAmf0Number(10));\r\n size += SrsAmf0Size::utf8(\"params\")+SrsAmf0Size::object(params);\r\n o.set(\"params\", params);\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n \r\n \/\/ object: object\r\n if (true) {\r\n int size = 1+3;\r\n SrsAmf0Object o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n SrsAmf0Object* args = new SrsAmf0Object();\r\n args->set(\"p0\", new SrsAmf0String(\"function\"));\r\n size += SrsAmf0Size::utf8(\"args\")+SrsAmf0Size::object(args);\r\n o.set(\"args\", args);\r\n \r\n SrsAmf0Object* params = new SrsAmf0Object();\r\n params->set(\"p1\", new SrsAmf0Number(10));\r\n size += SrsAmf0Size::utf8(\"params\")+SrsAmf0Size::object(params);\r\n o.set(\"params\", params);\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::object(&o));\r\n }\r\n \r\n \/\/ array: array\r\n if (true) {\r\n int size = 1+4+3;\r\n SrsAmf0EcmaArray o;\r\n \r\n size += SrsAmf0Size::utf8(\"name\")+SrsAmf0Size::str(\"winlin\");\r\n o.set(\"name\", new SrsAmf0String(\"winlin\"));\r\n \r\n SrsAmf0EcmaArray* args = new SrsAmf0EcmaArray();\r\n args->set(\"p0\", new SrsAmf0String(\"function\"));\r\n size += SrsAmf0Size::utf8(\"args\")+SrsAmf0Size::array(args);\r\n o.set(\"args\", args);\r\n \r\n SrsAmf0EcmaArray* params = new SrsAmf0EcmaArray();\r\n params->set(\"p1\", new SrsAmf0Number(10));\r\n size += SrsAmf0Size::utf8(\"params\")+SrsAmf0Size::array(params);\r\n o.set(\"params\", params);\r\n \r\n EXPECT_EQ(size, SrsAmf0Size::array(&o));\r\n }\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nbool isDirectory(char* directoryName) {\n\t\n\tstruct stat directoryInCurrent;\n\n\tif (-1 == (stat(directoryName, &directoryInCurrent))) {\n\n\t\tperror(\"stat failed\");\n\t\treturn false;\n\t}\n\n\tif (directoryInCurrent.st_mode & S_IFDIR) {\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nint ls(char* directoryName) {\n\n\t\n\t\tchar const *dirName = \".\";\n\t\tDIR *dirp;\n\t\tif (!(dirp = opendir(dirName))) {\n\t\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\t}\n\n\t\tdirent *direntp;\n\t\twhile ((direntp = readdir(dirp))) {\n\t\t\tif (direntp->d_name[0] != '.') {\n\t\t\t\t\t\n\t\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\t\tprintf(direntp->d_name, 8);\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t\tclosedir(dirp);\n\t\treturn 0;\n}\n\nint lsWithFlags(char* directoryName, vector flags) {\n\n\tbool isA = false;\n\tbool isL = false;\n\tbool isR = false;\n\tfor (unsigned i = 0; i < flags.size(); ++i) {\n\t\tfor (unsigned k = 0; k < flags.at(i).size(); ++k) {\n\t\t\tif (flags.at(i).at(k) == 'a') \n\t\t\t\tisA = true;\n\t\t\telse if (flags.at(i).at(k) == 'l') \n\t\t\t\tisL = true;\n\t\t\telse if (flags.at(i).at(k) == 'R')\n\t\t\t\tisR = true;\n\t\t}\n\n\t}\n\tchar const *dirName = directoryName;\n\tDIR *dirp;\n\tif (!(dirp = opendir(dirName))) {\n\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\treturn errno;\n\t}\n\n\tdirent *direntp;\n\tif (isA) {\n\t\twhile ((direntp = readdir(dirp))) {\n\t\n\t\t\t\t\t\n\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\tprintf(direntp->d_name, 8);\n\t\t\tcout << \" \";\n\n\t\t}\n\t}\n\tcout << endl;\n\tclosedir(dirp);\n\treturn 0;\n}\n\nint main(int argc, char* argv[]) {\n\t\n\tif (argc == 1) {\n\t\t\n\t\tif (errno == ls(\".\")) {\n\t\t\n\t\t\treturn errno;\n\t\t}\n\t}\t\n\t\n\telse {\n\t\t\n\t\tvector directories;\n\t\tvector flags;\n\t\tvector directoryIndex;\n\t\tbool directoryInArgv = false;\n\t\tfor (int i = 1; i < argc; ++i) {\n\t\t\t\n\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\tdirectoryInArgv = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\n\t\t\t\tif (argv[i][0] == '-') {\n\t\t\t\t\n\t\t\t\t\tflags.push_back(argv[i]);\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\tif (!directoryInArgv) {\n\t\t\t\t\t\n\t\t\tif (errno == lsWithFlags(\".\", flags)) {\n\t\t\t\n\t\t\t\treturn errno;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int i = 0; i < argc; ++i) {\n\t\t\t\n\t\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\t\tdirectories.push_back(argv[i]);\n\t\t\t\t\tdirectoryIndex.push_back(i);\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\t\n\t\t\tfor (unsigned int i = 0; i < directories.size(); ++i) {\n\t\t\t\tflags.clear();\n\t\t\t\tfor (unsigned int k = static_cast(directoryIndex.at(i)); \n\t\t\t\t\t (i + 1) < directoryIndex.size() && \n\t\t\t\t\t k != (unsigned)directoryIndex.at(i + 1);\n\t\t\t\t\t ++k) {\n\t\t\t\t\tif (argv[k][0] == '-') {\n\t\t\t\t\t\n\t\t\t\t\t\tflags.push_back(argv[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcout << \"flags: \";\n\t\t\t\tfor (unsigned i = 0; i < flags.size(); ++i) {\n\t\t\t\t\n\t\t\t\t\tcout << flags.at(i) << \" \";\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t\t\n\t\t\t\tchar* directoryName = new char[directories.at(i).size() + 1];\n\t\t\t\tstrcpy(directoryName, directories.at(i).c_str());\n\t\t\t\t\n\t\t\t\tif (errno == lsWithFlags(directoryName, flags)) {\n\t\t\t\t\n\t\t\t\t\treturn errno;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\n}\n\nchanged conditions for boolean variables in lswithflags function#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nbool isDirectory(char* directoryName) {\n\t\n\tstruct stat directoryInCurrent;\n\n\tif (-1 == (stat(directoryName, &directoryInCurrent))) {\n\n\t\tperror(\"stat failed\");\n\t\treturn false;\n\t}\n\n\tif (directoryInCurrent.st_mode & S_IFDIR) {\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nint ls(char* directoryName) {\n\n\t\n\t\tchar const *dirName = \".\";\n\t\tDIR *dirp;\n\t\tif (!(dirp = opendir(dirName))) {\n\t\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\t}\n\n\t\tdirent *direntp;\n\t\twhile ((direntp = readdir(dirp))) {\n\t\t\tif (direntp->d_name[0] != '.') {\n\t\t\t\t\t\n\t\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\t\tprintf(direntp->d_name, 8);\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t\tclosedir(dirp);\n\t\treturn 0;\n}\n\nint lsWithFlags(char* directoryName, vector flags) {\n\n\tbool isA = false;\n\tbool isL = false;\n\tbool isR = false;\n\tfor (unsigned i = 0; i < flags.size(); ++i) {\n\t\tfor (unsigned k = 0; k < flags.at(i).size(); ++k) {\n\t\t\tif (flags.at(i).at(k) == 'a') \n\t\t\t\tisA = true;\n\t\t\telse if (flags.at(i).at(k) == 'l') \n\t\t\t\tisL = true;\n\t\t\telse if (flags.at(i).at(k) == 'R')\n\t\t\t\tisR = true;\n\t\t}\n\n\t}\n\tchar const *dirName = directoryName;\n\tDIR *dirp;\n\tif (!(dirp = opendir(dirName))) {\n\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\treturn errno;\n\t}\n\n\tdirent *direntp;\n\tif (isA) {\n\t\twhile ((direntp = readdir(dirp))) {\n\t\n\t\t\t\t\t\n\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\tprintf(direntp->d_name, 8);\n\t\t\tcout << \" \";\n\n\t\t}\n\t}\n\tcout << endl;\n\tclosedir(dirp);\n\treturn 0;\n}\n\nint main(int argc, char* argv[]) {\n\t\n\tif (argc == 1) {\n\t\t\n\t\tif (errno == ls(\".\")) {\n\t\t\n\t\t\treturn errno;\n\t\t}\n\t}\t\n\t\n\telse {\n\t\t\n\t\tvector directories;\n\t\tvector flags;\n\t\tvector directoryIndex;\n\t\tbool directoryInArgv = false;\n\t\tfor (int i = 1; i < argc; ++i) {\n\t\t\t\n\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\tdirectoryInArgv = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\n\t\t\t\tif (argv[i][0] == '-') {\n\t\t\t\t\n\t\t\t\t\tflags.push_back(argv[i]);\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\tif (!directoryInArgv) {\n\t\t\t\t\t\n\t\t\tif (errno == lsWithFlags(\".\", flags)) {\n\t\t\t\n\t\t\t\treturn errno;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int i = 0; i < argc; ++i) {\n\t\t\t\n\t\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\t\tdirectories.push_back(argv[i]);\n\t\t\t\t\tdirectoryIndex.push_back(i);\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\t\n\t\t\tfor (unsigned int i = 0; i < directories.size(); ++i) {\n\t\t\t\tflags.clear();\n\t\t\t\tfor (unsigned int k = static_cast(directoryIndex.at(i)); \n\t\t\t\t\t (i + 1) < directoryIndex.size() && \n\t\t\t\t\t k != (unsigned)directoryIndex.at(i + 1);\n\t\t\t\t\t ++k) {\n\t\t\t\t\tif (argv[k][0] == '-') {\n\t\t\t\t\t\n\t\t\t\t\t\tflags.push_back(argv[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcout << \"flags: \";\n\t\t\t\tfor (unsigned j = 0; j < flags.size(); ++j) {\n\t\t\t\t\n\t\t\t\t\tcout << flags.at(j) << \" \";\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t\t\n\t\t\t\tchar* directoryName = new char[directories.at(i).size() + 1];\n\t\t\t\tstrcpy(directoryName, directories.at(i).c_str());\n\t\t\t\t\n\t\t\t\tif (errno == lsWithFlags(directoryName, flags)) {\n\t\t\t\t\n\t\t\t\t\treturn errno;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\n}\n\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief legends for shaped JSON objects to make them self-contained\n\/\/\/\n\/\/\/ @file\n\/\/\/ Code for legends.\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Max Neunhoeffer\n\/\/\/ @author Copyright 2014-2014, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ShapedJson\/Legends.h\"\n\nusing namespace std;\nusing namespace triagens;\nusing namespace triagens::basics;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Data format of a legend in memory:\n\/\/\/\n\/\/\/ Rough overview description:\n\/\/\/\n\/\/\/ - attribute-ID table\n\/\/\/ - shape table\n\/\/\/ - attribute-ID string data\n\/\/\/ - padding to achieve 8-byte alignment\n\/\/\/ - shape data\n\/\/\/ - padding to achieve 8-byte alignment\n\/\/\/\n\/\/\/ Description of the attribute-ID table (actual binary types in\n\/\/\/ [square brackets]):\n\/\/\/\n\/\/\/ - number of entries [TRI_shape_size_t]\n\/\/\/ - each entry consists of:\n\/\/\/\n\/\/\/ - attribute ID (aid) [TRI_shape_aid_t]\n\/\/\/ - offset to string value, measured from the beginning of the legend\n\/\/\/ [TRI_shape_size_t]\n\/\/\/\n\/\/\/ The entries in the attribute-ID table are sorted by ascending order of\n\/\/\/ shape IDs to allow for binary search if needed.\n\/\/\/\n\/\/\/ Description of the shape table:\n\/\/\/\n\/\/\/ - number of entries [TRI_shape_size_t]\n\/\/\/ - each entry consists of:\n\/\/\/\n\/\/\/ - shape ID (sid) [TRI_shape_sid_t]\n\/\/\/ - offset to shape data, measured from the beginning of the legend\n\/\/\/ [TRI_shape_size_t]\n\/\/\/ - size in bytes of the shape data for this shape ID [TRI_shape_size_t]\n\/\/\/\n\/\/\/ The entries in the shape table are sorted by ascending order of\n\/\/\/ shape IDs to allow for binary search if needed.\n\/\/\/\n\/\/\/ The strings for the attribute IDs are stored one after another, each\n\/\/\/ including a terminating zero byte. At the end of the string data follow\n\/\/\/ zero bytes to pad to a total length that is divisible by 8.\n\/\/\/\n\/\/\/ The actual entries of the shape data is stored one after another. Alignment\n\/\/\/ for each entry is automatically given by the length of the shape data. At\n\/\/\/ the end there is padding to make the length of the total legend divisible\n\/\/\/ by 8.\n\/\/\/\n\/\/\/ Note that the builtin shapes are never dumped and that proper legends\n\/\/\/ contain all attribute IDs\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief clear all data to build a new legend, keep shaper\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid JsonLegend::clear () {\n _have_attribute.clear();\n _attribs.clear();\n _att_data.clear();\n _have_shape.clear();\n _shapes.clear();\n _shape_data.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief add an attribute ID to the legend\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint JsonLegend::addAttributeId (TRI_shape_aid_t aid) {\n unordered_set::const_iterator it = _have_attribute.find(aid);\n if (it != _have_attribute.end()) {\n return TRI_ERROR_NO_ERROR;\n }\n\n char const* p = _shaper->lookupAttributeId(_shaper, aid);\n if (nullptr == p) {\n return TRI_ERROR_AID_NOT_FOUND;\n }\n\n _have_attribute.insert(it, aid);\n size_t len = strlen(p);\n _attribs.emplace_back(aid, _att_data.length());\n _att_data.appendText(p, len + 1); \/\/ including the zero byte\n return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief add a shape to the legend\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint JsonLegend::addShape (TRI_shape_sid_t sid,\n char const* data,\n uint32_t len) {\n \/\/ data and len must always be given, because in general we might have\n \/\/ to sniff recursively into the subobjects. :-(\n int res = TRI_ERROR_NO_ERROR;\n\n TRI_ASSERT(data != nullptr);\n\n TRI_shape_t const* shape = nullptr;\n\n \/\/ First the trivial cases:\n if (sid < TRI_FirstCustomShapeIdShaper()) {\n shape = TRI_LookupSidBasicShapeShaper(sid);\n\n TRI_ASSERT(shape != nullptr);\n }\n else {\n shape = _shaper->lookupShapeId(_shaper, sid);\n\n if (nullptr == shape) {\n return TRI_ERROR_LEGEND_INCOMPLETE;\n }\n\n unordered_set::const_iterator it = _have_shape.find(sid);\n\n if (it == _have_shape.end()) {\n _have_shape.insert(it, sid);\n Shape sh(sid, _shape_data.length(), shape->_size);\n _shapes.push_back(sh);\n _shape_data.appendText(reinterpret_cast(shape), shape->_size);\n }\n }\n\n \/\/ Now we have to add all attribute IDs and all shapes used by this\n \/\/ one recursively, note that the data of this object is in a\n \/\/ consistent state, such that we can call ourselves recursively.\n\n if (shape->_type == TRI_SHAPE_HOMOGENEOUS_SIZED_LIST) {\n \/\/ Handle a homogeneous list with equal size entries. Note that\n \/\/ this does not imply that no subobject contains any array or\n \/\/ inhomogeneous list, because they could be lists that have the\n \/\/ same size by sheer coincidence. Therefore we have to visit them\n \/\/ all recursively. :-(\n auto shape_spec = reinterpret_cast(shape);\n auto len = reinterpret_cast(data);\n auto ptr = reinterpret_cast(len+1);\n res = TRI_ERROR_NO_ERROR; \/\/ just in case the length is 0\n TRI_shape_length_list_t i;\n for (i = 0; i < *len; i++) {\n res = addShape(shape_spec->_sidEntry, ptr, static_cast(shape_spec->_sizeEntry));\n ptr += shape_spec->_sizeEntry;\n if (res != TRI_ERROR_NO_ERROR) {\n break;\n }\n }\n }\n else if (shape->_type == TRI_SHAPE_HOMOGENEOUS_LIST) {\n \/\/ Handle a homogeneous list: Only one sid, but the subobjects can\n \/\/ contain inhomogeneous lists.\n auto shape_spec = reinterpret_cast (shape);\n res = TRI_ERROR_NO_ERROR; \/\/ just in case the length is 0\n auto len = reinterpret_cast(data);\n auto offsets = reinterpret_cast(len + 1);\n TRI_shape_length_list_t i;\n for (i = 0; i < *len; i++) {\n res = addShape(shape_spec->_sidEntry, data + offsets[i], static_cast(offsets[i + 1] - offsets[i]));\n if (res != TRI_ERROR_NO_ERROR) {\n break;\n }\n }\n }\n else if (shape->_type == TRI_SHAPE_LIST) {\n \/\/ Handle an inhomogeneous list:\n \/\/ We have to scan recursively all entries of the list since they\n \/\/ contain sids in the data area.\n res = TRI_ERROR_NO_ERROR; \/\/ just in case the length is 0\n auto len = reinterpret_cast(data);\n auto sids = reinterpret_cast(len + 1);\n auto offsets = reinterpret_cast(sids + *len);\n TRI_shape_length_list_t i;\n\n for (i = 0; i < *len; i++) {\n res = addShape(sids[i], data + offsets[i], static_cast(offsets[i + 1] - offsets[i]));\n if (res != TRI_ERROR_NO_ERROR) {\n break;\n }\n }\n }\n else if (shape->_type == TRI_SHAPE_ARRAY) {\n \/\/ Handle an array:\n \/\/ Distinguish between fixed size subobjects and variable size\n \/\/ subobjects. The fixed ones cannot contain inhomogeneous lists.\n auto shape_spec = reinterpret_cast(shape);\n auto sids = reinterpret_cast(shape_spec + 1);\n auto aids = reinterpret_cast(sids + (shape_spec->_fixedEntries + shape_spec->_variableEntries));\n auto offsetsF = reinterpret_cast(aids + (shape_spec->_fixedEntries + shape_spec->_variableEntries));\n auto offsetsV = reinterpret_cast(data);\n\n TRI_shape_size_t i;\n for (i = 0; res == TRI_ERROR_NO_ERROR &&\n i < shape_spec->_fixedEntries + shape_spec->_variableEntries;\n i++) {\n res = addAttributeId(aids[i]);\n }\n for (i = 0; res == TRI_ERROR_NO_ERROR && i < shape_spec->_fixedEntries;\n i++) {\n \/\/ Fixed size subdocs cannot have inhomogeneous lists as subdocs:\n res = addShape(sids[i], data + offsetsF[i], static_cast(offsetsF[i + 1] - offsetsF[i]));\n }\n for (i = 0; res == TRI_ERROR_NO_ERROR && i < shape_spec->_variableEntries;\n i++) {\n addShape(sids[i + shape_spec->_fixedEntries], data + offsetsV[i], static_cast(offsetsV[i + 1] - offsetsV[i]));\n }\n }\n\n return res;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief round a value to the next multiple of 8\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic inline TRI_shape_size_t roundup8 (TRI_shape_size_t x) {\n return (x + 7) - ((x + 7) & 7);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief get the total size in bytes of the legend\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t JsonLegend::getSize () const {\n \/\/ Add string pool size and shape pool size and add space for header\n \/\/ and tables in bytes.\n return sizeof(TRI_shape_size_t) \/\/ number of aids\n + sizeof(AttributeId) * _attribs.size() \/\/ aid entries\n + sizeof(TRI_shape_size_t) \/\/ number of sids\n + sizeof(Shape) * _shapes.size() \/\/ sid entries\n + roundup8(_att_data.length()) \/\/ string data, padded\n + roundup8(_shape_data.length()); \/\/ shape data, padded\n}\n\nJsonLegend::AttributeComparerClass JsonLegend::AttributeComparerObject;\nJsonLegend::ShapeComparerClass JsonLegend::ShapeComparerObject;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief dump the legend to the buffer pointed to by buf\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid JsonLegend::dump (void* buf) {\n \/\/ Dump the resulting legend to a given buffer.\n\n \/\/ First sort the aids in ascending order:\n sort(_attribs.begin(), _attribs.end(), AttributeComparerObject);\n\n \/\/ Then sort the sids in ascending order:\n sort(_shapes.begin(), _shapes.end(), ShapeComparerObject);\n\n \/\/ Total length of table data to add to offsets:\n TRI_shape_size_t socle = sizeof(TRI_shape_size_t)\n + sizeof(AttributeId) * _attribs.size()\n + sizeof(TRI_shape_size_t)\n + sizeof(Shape) * _shapes.size();\n\n \/\/ Attribute ID table:\n TRI_shape_size_t* p = reinterpret_cast(buf);\n TRI_shape_size_t i;\n *p++ = _attribs.size();\n AttributeId* a = reinterpret_cast(p);\n for (i = 0; i < _attribs.size(); i++) {\n _attribs[i].offset += socle;\n *a++ = _attribs[i];\n _attribs[i].offset -= socle;\n }\n\n \/\/ Add the length of the string data to socle for second table:\n size_t const attDataLength = _att_data.length();\n socle += roundup8(attDataLength);\n\n \/\/ shape table:\n size_t const n = _shapes.size();\n p = reinterpret_cast(a);\n *p++ = n;\n Shape* s = reinterpret_cast(p);\n for (i = 0; i < n; i++) {\n _shapes[i].offset += socle;\n *s++ = _shapes[i];\n _shapes[i].offset -= socle;\n }\n\n \/\/ Attribute ID string data:\n char* c = reinterpret_cast(s);\n memcpy(c, _att_data.c_str(), attDataLength);\n i = roundup8(attDataLength);\n if (i > attDataLength) {\n memset(c + attDataLength, 0, i - attDataLength);\n }\n c += i;\n\n \/\/ Shape data:\n size_t const shapeDataLength = _shape_data.length();\n memcpy(c, _shape_data.c_str(), shapeDataLength);\n i = roundup8(shapeDataLength);\n if (i > shapeDataLength) {\n memset(c + shapeDataLength, 0, i - shapeDataLength);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\nuse auto\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief legends for shaped JSON objects to make them self-contained\n\/\/\/\n\/\/\/ @file\n\/\/\/ Code for legends.\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Max Neunhoeffer\n\/\/\/ @author Copyright 2014-2014, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ShapedJson\/Legends.h\"\n\nusing namespace std;\nusing namespace triagens;\nusing namespace triagens::basics;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Data format of a legend in memory:\n\/\/\/\n\/\/\/ Rough overview description:\n\/\/\/\n\/\/\/ - attribute-ID table\n\/\/\/ - shape table\n\/\/\/ - attribute-ID string data\n\/\/\/ - padding to achieve 8-byte alignment\n\/\/\/ - shape data\n\/\/\/ - padding to achieve 8-byte alignment\n\/\/\/\n\/\/\/ Description of the attribute-ID table (actual binary types in\n\/\/\/ [square brackets]):\n\/\/\/\n\/\/\/ - number of entries [TRI_shape_size_t]\n\/\/\/ - each entry consists of:\n\/\/\/\n\/\/\/ - attribute ID (aid) [TRI_shape_aid_t]\n\/\/\/ - offset to string value, measured from the beginning of the legend\n\/\/\/ [TRI_shape_size_t]\n\/\/\/\n\/\/\/ The entries in the attribute-ID table are sorted by ascending order of\n\/\/\/ shape IDs to allow for binary search if needed.\n\/\/\/\n\/\/\/ Description of the shape table:\n\/\/\/\n\/\/\/ - number of entries [TRI_shape_size_t]\n\/\/\/ - each entry consists of:\n\/\/\/\n\/\/\/ - shape ID (sid) [TRI_shape_sid_t]\n\/\/\/ - offset to shape data, measured from the beginning of the legend\n\/\/\/ [TRI_shape_size_t]\n\/\/\/ - size in bytes of the shape data for this shape ID [TRI_shape_size_t]\n\/\/\/\n\/\/\/ The entries in the shape table are sorted by ascending order of\n\/\/\/ shape IDs to allow for binary search if needed.\n\/\/\/\n\/\/\/ The strings for the attribute IDs are stored one after another, each\n\/\/\/ including a terminating zero byte. At the end of the string data follow\n\/\/\/ zero bytes to pad to a total length that is divisible by 8.\n\/\/\/\n\/\/\/ The actual entries of the shape data is stored one after another. Alignment\n\/\/\/ for each entry is automatically given by the length of the shape data. At\n\/\/\/ the end there is padding to make the length of the total legend divisible\n\/\/\/ by 8.\n\/\/\/\n\/\/\/ Note that the builtin shapes are never dumped and that proper legends\n\/\/\/ contain all attribute IDs\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief clear all data to build a new legend, keep shaper\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid JsonLegend::clear () {\n _have_attribute.clear();\n _attribs.clear();\n _att_data.clear();\n _have_shape.clear();\n _shapes.clear();\n _shape_data.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief add an attribute ID to the legend\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint JsonLegend::addAttributeId (TRI_shape_aid_t aid) {\n auto it = _have_attribute.find(aid);\n if (it != _have_attribute.end()) {\n return TRI_ERROR_NO_ERROR;\n }\n\n char const* p = _shaper->lookupAttributeId(_shaper, aid);\n if (nullptr == p) {\n return TRI_ERROR_AID_NOT_FOUND;\n }\n\n _have_attribute.insert(it, aid);\n size_t len = strlen(p);\n _attribs.emplace_back(aid, _att_data.length());\n _att_data.appendText(p, len + 1); \/\/ including the zero byte\n return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief add a shape to the legend\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint JsonLegend::addShape (TRI_shape_sid_t sid,\n char const* data,\n uint32_t len) {\n \/\/ data and len must always be given, because in general we might have\n \/\/ to sniff recursively into the subobjects. :-(\n int res = TRI_ERROR_NO_ERROR;\n\n TRI_ASSERT(data != nullptr);\n\n TRI_shape_t const* shape = nullptr;\n\n \/\/ First the trivial cases:\n if (sid < TRI_FirstCustomShapeIdShaper()) {\n shape = TRI_LookupSidBasicShapeShaper(sid);\n\n TRI_ASSERT(shape != nullptr);\n }\n else {\n shape = _shaper->lookupShapeId(_shaper, sid);\n\n if (nullptr == shape) {\n return TRI_ERROR_LEGEND_INCOMPLETE;\n }\n\n auto it = _have_shape.find(sid);\n\n if (it == _have_shape.end()) {\n _have_shape.insert(it, sid);\n Shape sh(sid, _shape_data.length(), shape->_size);\n _shapes.push_back(sh);\n _shape_data.appendText(reinterpret_cast(shape), shape->_size);\n }\n }\n\n \/\/ Now we have to add all attribute IDs and all shapes used by this\n \/\/ one recursively, note that the data of this object is in a\n \/\/ consistent state, such that we can call ourselves recursively.\n\n if (shape->_type == TRI_SHAPE_HOMOGENEOUS_SIZED_LIST) {\n \/\/ Handle a homogeneous list with equal size entries. Note that\n \/\/ this does not imply that no subobject contains any array or\n \/\/ inhomogeneous list, because they could be lists that have the\n \/\/ same size by sheer coincidence. Therefore we have to visit them\n \/\/ all recursively. :-(\n auto shape_spec = reinterpret_cast(shape);\n auto len = reinterpret_cast(data);\n auto ptr = reinterpret_cast(len+1);\n res = TRI_ERROR_NO_ERROR; \/\/ just in case the length is 0\n TRI_shape_length_list_t i;\n for (i = 0; i < *len; i++) {\n res = addShape(shape_spec->_sidEntry, ptr, static_cast(shape_spec->_sizeEntry));\n ptr += shape_spec->_sizeEntry;\n if (res != TRI_ERROR_NO_ERROR) {\n break;\n }\n }\n }\n else if (shape->_type == TRI_SHAPE_HOMOGENEOUS_LIST) {\n \/\/ Handle a homogeneous list: Only one sid, but the subobjects can\n \/\/ contain inhomogeneous lists.\n auto shape_spec = reinterpret_cast (shape);\n res = TRI_ERROR_NO_ERROR; \/\/ just in case the length is 0\n auto len = reinterpret_cast(data);\n auto offsets = reinterpret_cast(len + 1);\n TRI_shape_length_list_t i;\n for (i = 0; i < *len; i++) {\n res = addShape(shape_spec->_sidEntry, data + offsets[i], static_cast(offsets[i + 1] - offsets[i]));\n if (res != TRI_ERROR_NO_ERROR) {\n break;\n }\n }\n }\n else if (shape->_type == TRI_SHAPE_LIST) {\n \/\/ Handle an inhomogeneous list:\n \/\/ We have to scan recursively all entries of the list since they\n \/\/ contain sids in the data area.\n res = TRI_ERROR_NO_ERROR; \/\/ just in case the length is 0\n auto len = reinterpret_cast(data);\n auto sids = reinterpret_cast(len + 1);\n auto offsets = reinterpret_cast(sids + *len);\n TRI_shape_length_list_t i;\n\n for (i = 0; i < *len; i++) {\n res = addShape(sids[i], data + offsets[i], static_cast(offsets[i + 1] - offsets[i]));\n if (res != TRI_ERROR_NO_ERROR) {\n break;\n }\n }\n }\n else if (shape->_type == TRI_SHAPE_ARRAY) {\n \/\/ Handle an array:\n \/\/ Distinguish between fixed size subobjects and variable size\n \/\/ subobjects. The fixed ones cannot contain inhomogeneous lists.\n auto shape_spec = reinterpret_cast(shape);\n auto sids = reinterpret_cast(shape_spec + 1);\n auto aids = reinterpret_cast(sids + (shape_spec->_fixedEntries + shape_spec->_variableEntries));\n auto offsetsF = reinterpret_cast(aids + (shape_spec->_fixedEntries + shape_spec->_variableEntries));\n auto offsetsV = reinterpret_cast(data);\n\n TRI_shape_size_t i;\n for (i = 0; res == TRI_ERROR_NO_ERROR &&\n i < shape_spec->_fixedEntries + shape_spec->_variableEntries;\n i++) {\n res = addAttributeId(aids[i]);\n }\n for (i = 0; res == TRI_ERROR_NO_ERROR && i < shape_spec->_fixedEntries;\n i++) {\n \/\/ Fixed size subdocs cannot have inhomogeneous lists as subdocs:\n res = addShape(sids[i], data + offsetsF[i], static_cast(offsetsF[i + 1] - offsetsF[i]));\n }\n for (i = 0; res == TRI_ERROR_NO_ERROR && i < shape_spec->_variableEntries;\n i++) {\n addShape(sids[i + shape_spec->_fixedEntries], data + offsetsV[i], static_cast(offsetsV[i + 1] - offsetsV[i]));\n }\n }\n\n return res;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief round a value to the next multiple of 8\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic inline TRI_shape_size_t roundup8 (TRI_shape_size_t x) {\n return (x + 7) - ((x + 7) & 7);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief get the total size in bytes of the legend\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t JsonLegend::getSize () const {\n \/\/ Add string pool size and shape pool size and add space for header\n \/\/ and tables in bytes.\n return sizeof(TRI_shape_size_t) \/\/ number of aids\n + sizeof(AttributeId) * _attribs.size() \/\/ aid entries\n + sizeof(TRI_shape_size_t) \/\/ number of sids\n + sizeof(Shape) * _shapes.size() \/\/ sid entries\n + roundup8(_att_data.length()) \/\/ string data, padded\n + roundup8(_shape_data.length()); \/\/ shape data, padded\n}\n\nJsonLegend::AttributeComparerClass JsonLegend::AttributeComparerObject;\nJsonLegend::ShapeComparerClass JsonLegend::ShapeComparerObject;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief dump the legend to the buffer pointed to by buf\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid JsonLegend::dump (void* buf) {\n \/\/ Dump the resulting legend to a given buffer.\n\n \/\/ First sort the aids in ascending order:\n sort(_attribs.begin(), _attribs.end(), AttributeComparerObject);\n\n \/\/ Then sort the sids in ascending order:\n sort(_shapes.begin(), _shapes.end(), ShapeComparerObject);\n\n \/\/ Total length of table data to add to offsets:\n TRI_shape_size_t socle = sizeof(TRI_shape_size_t)\n + sizeof(AttributeId) * _attribs.size()\n + sizeof(TRI_shape_size_t)\n + sizeof(Shape) * _shapes.size();\n\n \/\/ Attribute ID table:\n TRI_shape_size_t* p = reinterpret_cast(buf);\n TRI_shape_size_t i;\n *p++ = _attribs.size();\n AttributeId* a = reinterpret_cast(p);\n for (i = 0; i < _attribs.size(); i++) {\n _attribs[i].offset += socle;\n *a++ = _attribs[i];\n _attribs[i].offset -= socle;\n }\n\n \/\/ Add the length of the string data to socle for second table:\n size_t const attDataLength = _att_data.length();\n socle += roundup8(attDataLength);\n\n \/\/ shape table:\n size_t const n = _shapes.size();\n p = reinterpret_cast(a);\n *p++ = n;\n Shape* s = reinterpret_cast(p);\n for (i = 0; i < n; i++) {\n _shapes[i].offset += socle;\n *s++ = _shapes[i];\n _shapes[i].offset -= socle;\n }\n\n \/\/ Attribute ID string data:\n char* c = reinterpret_cast(s);\n memcpy(c, _att_data.c_str(), attDataLength);\n i = roundup8(attDataLength);\n if (i > attDataLength) {\n memset(c + attDataLength, 0, i - attDataLength);\n }\n c += i;\n\n \/\/ Shape data:\n size_t const shapeDataLength = _shape_data.length();\n memcpy(c, _shape_data.c_str(), shapeDataLength);\n i = roundup8(shapeDataLength);\n if (i > shapeDataLength) {\n memset(c + shapeDataLength, 0, i - shapeDataLength);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nbool isDirectory(char* directoryName) {\n\t\n\tstruct stat directoryInCurrent;\n\n\tif (-1 == (stat(directoryName, &directoryInCurrent))) {\n\n\t\tperror(\"stat failed\");\n\t\treturn false;\n\t}\n\n\tif (directoryInCurrent.st_mode & S_IFDIR) {\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nint ls(char* directoryName) {\n\n\t\n\t\tchar const *dirName = \".\";\n\t\tDIR *dirp;\n\t\tif (!(dirp = opendir(dirName))) {\n\t\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\t}\n\n\t\tdirent *direntp;\n\t\twhile ((direntp = readdir(dirp))) {\n\t\t\tif (direntp->d_name[0] != '.') {\n\t\t\t\t\t\n\t\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\t\tprintf(direntp->d_name, 8);\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t\tclosedir(dirp);\n\t\treturn 0;\n}\n\nint lsWithFlags(char* directoryName, vector flags) {\n\n\tbool isA = false;\n\tbool isL = false;\n\tbool isR = false;\n\tfor (unsigned i = 0; i < flags.size(); ++i) {\n\t\tfor (unsigned k = 0; k < flags.at(i).size(); ++k) {\n\t\t\tif (flags.at(i).at(k) == 'a') \n\t\t\t\tisA = true;\n\t\t\telse if (flags.at(i).at(k) == 'l') \n\t\t\t\tisL = true;\n\t\t\telse if (flags.at(i).at(k) == 'R')\n\t\t\t\tisR = true;\n\t\t}\n\n\t}\n\tchar const *dirName = directoryName;\n\tDIR *dirp;\n\tif (!(dirp = opendir(dirName))) {\n\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\treturn errno;\n\t}\n\n\tdirent *direntp;\n\tif (isA) {\n\t\twhile ((direntp = readdir(dirp))) {\n\t\n\t\t\t\t\t\n\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\tprintf(direntp->d_name, 8);\n\t\t\tcout << \" \";\n\n\t\t}\n\t}\n\tcout << endl;\n\tclosedir(dirp);\n\treturn 0;\n}\n\nint main(int argc, char* argv[]) {\n\t\n\tif (argc == 1) {\n\t\t\n\t\tif (errno == ls(\".\")) {\n\t\t\n\t\t\treturn errno;\n\t\t}\n\t}\t\n\t\n\telse {\n\t\t\n\t\tvector directories;\n\t\tvector flags;\n\t\tvector directoryIndex;\n\t\tbool directoryInArgv = false;\n\t\tfor (int i = 1; i < argc; ++i) {\n\t\t\t\n\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\tdirectoryInArgv = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\n\t\t\t\tif (argv[i][0] == '-') {\n\t\t\t\t\n\t\t\t\t\tflags.push_back(argv[i]);\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\tif (!directoryInArgv) {\n\t\t\t\t\t\n\t\t\tif (errno == lsWithFlags(\".\", flags)) {\n\t\t\t\n\t\t\t\treturn errno;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\n\t\t\tfor (int i = 0; i < argc; ++i) {\n\t\t\t\n\t\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\t\tdirectories.push_back(argv[i]);\n\t\t\t\t\tdirectoryIndex.push_back(i);\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\t\n\t\t\tfor (unsigned int i = 0; i < directories.size(); ++i) {\n\t\t\t\tflags.clear();\n\t\t\t\tfor (unsigned int k = static_cast(directoryIndex.at(i)); \n\t\t\t\t\t (i + 1) < directoryIndex.size() && \n\t\t\t\t\t k != (unsigned)directoryIndex.at(i + 1);\n\t\t\t\t\t ++k) {\n\t\t\t\t\tif (argv[k][0] == '-') {\n\t\t\t\t\t\n\t\t\t\t\t\tflags.push_back(argv[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tchar* directoryName = new char[directories.at(i).size() + 1];\n\t\t\t\tstrcpy(directoryName, directories.at(i).c_str());\n\t\t\t\tif (errno == lsWithFlags(directoryName, flags)) {\n\t\t\t\t\n\t\t\t\t\treturn errno;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\n}\n\nchanged conditions for boolean variables in lswithflags function#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nbool isDirectory(char* directoryName) {\n\t\n\tstruct stat directoryInCurrent;\n\n\tif (-1 == (stat(directoryName, &directoryInCurrent))) {\n\n\t\tperror(\"stat failed\");\n\t\treturn false;\n\t}\n\n\tif (directoryInCurrent.st_mode & S_IFDIR) {\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nint ls(char* directoryName) {\n\n\t\n\t\tchar const *dirName = \".\";\n\t\tDIR *dirp;\n\t\tif (!(dirp = opendir(dirName))) {\n\t\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\t}\n\n\t\tdirent *direntp;\n\t\twhile ((direntp = readdir(dirp))) {\n\t\t\tif (direntp->d_name[0] != '.') {\n\t\t\t\t\t\n\t\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\t\tprintf(direntp->d_name, 8);\n\t\t\t\tcout << \" \";\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t\tclosedir(dirp);\n\t\treturn 0;\n}\n\nint lsWithFlags(char* directoryName, vector flags) {\n\n\tbool isA = false;\n\tbool isL = false;\n\tbool isR = false;\n\tfor (unsigned i = 0; i < flags.size(); ++i) {\n\t\tfor (unsigned k = 0; k < flags.at(i).size(); ++k) {\n\t\t\tif (flags.at(i).at(k) == 'a') \n\t\t\t\tisA = true;\n\t\t\telse if (flags.at(i).at(k) == 'l') \n\t\t\t\tisL = true;\n\t\t\telse if (flags.at(i).at(k) == 'R')\n\t\t\t\tisR = true;\n\t\t}\n\n\t}\n\tchar const *dirName = directoryName;\n\tDIR *dirp;\n\tif (!(dirp = opendir(dirName))) {\n\t\tcerr << \"Error(\" << errno << \") opening \" << dirName << endl;\n\t\treturn errno;\n\t}\n\n\tdirent *direntp;\n\tif (isA) {\n\t\twhile ((direntp = readdir(dirp))) {\n\t\n\t\t\t\t\t\n\t\t\t\/\/cout << direntp->d_name << endl; \/\/ use stat here to find attributes of a file\n\t\t\tprintf(direntp->d_name, 8);\n\t\t\tcout << \" \";\n\n\t\t}\n\t}\n\tcout << endl;\n\tclosedir(dirp);\n\treturn 0;\n}\n\nint main(int argc, char* argv[]) {\n\t\n\tif (argc == 1) {\n\t\t\n\t\tif (errno == ls(\".\")) {\n\t\t\n\t\t\treturn errno;\n\t\t}\n\t}\t\n\t\n\telse {\n\t\t\n\t\tvector directories;\n\t\tvector flags;\n\t\tvector directoryIndex;\n\t\tbool directoryInArgv = false;\n\t\tfor (int i = 1; i < argc; ++i) {\n\t\t\t\n\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\tdirectoryInArgv = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\n\t\t\t\tif (argv[i][0] == '-') {\n\t\t\t\t\n\t\t\t\t\tflags.push_back(argv[i]);\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\tif (!directoryInArgv) {\n\t\t\t\t\t\n\t\t\tif (errno == lsWithFlags(\".\", flags)) {\n\t\t\t\n\t\t\t\treturn errno;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tcout << 130 << endl;\t\n\t\t\tfor (int i = 0; i < argc; ++i) {\n\t\t\t\n\t\t\t\tif (isDirectory(argv[i])) {\n\t\t\t\t\tdirectories.push_back(argv[i]);\n\t\t\t\t\tdirectoryIndex.push_back(i);\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\t\n\t\t\tfor (unsigned int i = 0; i < directories.size(); ++i) {\n\t\t\t\tflags.clear();\n\t\t\t\tfor (unsigned int k = static_cast(directoryIndex.at(i)); \n\t\t\t\t\t (i + 1) < directoryIndex.size() && \n\t\t\t\t\t k != (unsigned)directoryIndex.at(i + 1);\n\t\t\t\t\t ++k) {\n\t\t\t\t\tif (argv[k][0] == '-') {\n\t\t\t\t\t\n\t\t\t\t\t\tflags.push_back(argv[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tchar* directoryName = new char[directories.at(i).size() + 1];\n\t\t\t\tstrcpy(directoryName, directories.at(i).c_str());\n\t\t\t\tif (errno == lsWithFlags(directoryName, flags)) {\n\t\t\t\t\n\t\t\t\t\treturn errno;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"gc.hh\"\n#include \"percpu.hh\"\n\n\/\/ name spaces\n\/\/ XXX maybe use open hash table, no chain, better cache locality\n\n#if SPINLOCK_DEBUG\n#define NHASH 10\n#else\n#define NHASH 257\n#endif\n\ntemplate\nclass xelem : public rcu_freed {\n public:\n V val;\n K key;\n\n std::atomic next_lock;\n std::atomic*> next;\n\n int percore_c;\n std::atomic*> percore_next;\n std::atomic*>* percore_pprev;\n\n xelem(const K &k, const V &v)\n : rcu_freed(\"xelem\"), val(v), key(k),\n next_lock(0), next(0),\n percore_next(0), percore_pprev(0) {}\n virtual void do_gc() {\n delete this;\n }\n\n NEW_DELETE_OPS(xelem)\n};\n\n\/\/ XXX maybe not cache align, because it takes too much space\ntemplate\nstruct xbucket {\n std::atomic*> volatile chain;\n} ; \/\/ __attribute__((aligned (CACHELINE)));\n\ntemplate\nclass xns : public rcu_freed {\n private:\n bool allowdup;\n std::atomic nextkey;\n xbucket table[NHASH];\n std::atomic*> percore[NCPU];\n spinlock percore_lock[NCPU];\n\n public:\n xns(bool dup) : rcu_freed(\"xns\") {\n allowdup = dup;\n nextkey = 1;\n for (int i = 0; i < NHASH; i++)\n table[i].chain = 0;\n for (int i = 0; i < NCPU; i++) {\n percore[i] = nullptr;\n percore_lock[i] = spinlock(\"xns_lock\", LOCKSTAT_NS);\n }\n }\n\n ~xns() {\n for (int i = 0; i < NHASH; i++)\n if (table[i].chain)\n panic(\"~xns: not empty\");\n }\n\n virtual void do_gc() {\n delete this;\n }\n\n u64 allockey() {\n return nextkey++;\n }\n\n u64 h(const K &key) {\n return HF(key) % NHASH;\n }\n\n int insert(const K &key, const V &val) {\n auto e = new xelem(key, val);\n if (!e)\n return -1;\n\n u64 i = h(key);\n scoped_gc_epoch gc;\n\n for (;;) {\n auto root = table[i].chain;\n if (!allowdup) {\n for (auto x = root.load(); x; x = x->next) {\n if (x->key == key) {\n gc_delayed(e);\n return -1;\n }\n }\n }\n\n e->next = root.load();\n if (cmpxch(&table[i].chain, e->next.load(), e)) {\n int c = myid();\n acquire(&percore_lock[c]);\n e->percore_c = c;\n e->percore_next = percore[c].load();\n if (percore[c])\n percore[c].load()->percore_pprev = &e->percore_next;\n e->percore_pprev = &percore[c];\n percore[c] = e;\n release(&percore_lock[c]);\n return 0;\n }\n }\n }\n\n V lookup(const K &key) {\n u64 i = h(key);\n\n scoped_gc_epoch gc;\n auto e = table[i].chain.load();\n\n while (e) {\n if (e->key == key)\n return e->val;\n e = e->next;\n }\n\n return 0;\n }\n\n bool remove(const K &key, const V *vp = 0) {\n u64 i = h(key);\n scoped_gc_epoch gc;\n\n for (;;) {\n std::atomic fakelock(0);\n std::atomic *pelock = &fakelock;\n auto pe = &table[i].chain;\n\n for (;;) {\n auto e = pe->load();\n if (!e)\n return false;\n\n if (e->key == key && (!vp || e->val == *vp)) {\n if (!cmpxch(&e->next_lock, 0, 1))\n break;\n if (!cmpxch(pelock, 0, 1)) {\n e->next_lock = 0;\n break;\n }\n\n if (!cmpxch(pe, e, e->next.load())) {\n pelock->store(0);\n e->next_lock = 0;\n break;\n }\n\n int c = e->percore_c;\n acquire(&percore_lock[c]);\n *e->percore_pprev = e->percore_next.load();\n if (e->percore_next)\n e->percore_next.load()->percore_pprev = e->percore_pprev;\n release(&percore_lock[c]);\n\n pelock->store(0);\n gc_delayed(e);\n return true;\n }\n\n pe = &e->next;\n pelock = &e->next_lock;\n }\n }\n }\n\n template\n void enumerate(CB cb) {\n scoped_gc_epoch gc;\n int cpuoffset = myid();\n for (int i = 0; i < NCPU; i++) {\n auto e = percore[(i + cpuoffset) % NCPU].load();\n while (e) {\n if (cb(e->key, e->val))\n return;\n e = e->percore_next;\n }\n }\n }\n\n template\n void enumerate_key(const K &key, CB cb) {\n scoped_gc_epoch gc;\n u64 i = h(key);\n auto e = table[i].chain;\n while (e) {\n if (e->key == key && cb(e->key, e->val))\n return;\n e = e->next;\n }\n }\n\n class iterator {\n private:\n xns *ns_;\n xelem *chain_;\n int ndx_;\n\n public:\n iterator(xns *ns) {\n if (ns_)\n gc_begin_epoch();\n ns_ = ns;\n ndx_ = 0;\n chain_ = ns->table[ndx_++].chain;\n for (; chain_ == 0 && ndx_ < NHASH; ndx_++)\n chain_ = ns_->table[ndx_].chain;\n }\n\n iterator() {\n ns_ = 0;\n ndx_ = NHASH;\n chain_ = 0;\n }\n\n ~iterator() {\n if (ns_)\n gc_end_epoch();\n }\n\n bool operator!=(const iterator &other) const {\n return other.chain_ != this->chain_;\n }\n\n iterator& operator ++() {\n for (chain_ = chain_->next; chain_ == 0 && ndx_ < NHASH; ndx_++)\n chain_ = ns_->table[ndx_].chain;\n return *this;\n }\n\n V& operator *() {\n return chain_->val;\n }\n };\n\n iterator begin() {\n return iterator(this);\n }\n\n iterator end() {\n return iterator();\n }\n\n NEW_DELETE_OPS(xns)\n};\n\ntemplate\nstatic inline\ntypename xns::iterator\nbegin(xns *&ns)\n{\n return ns->begin();\n}\n\ntemplate\nstatic inline\ntypename xns::iterator\nend(xns *&ns)\n{\n return ns->end();\n}\nns: Reduce repeated atomic loads in insert#pragma once\n\n#include \"gc.hh\"\n#include \"percpu.hh\"\n\n\/\/ name spaces\n\/\/ XXX maybe use open hash table, no chain, better cache locality\n\n#if SPINLOCK_DEBUG\n#define NHASH 10\n#else\n#define NHASH 257\n#endif\n\ntemplate\nclass xelem : public rcu_freed {\n public:\n V val;\n K key;\n\n std::atomic next_lock;\n std::atomic*> next;\n\n int percore_c;\n std::atomic*> percore_next;\n std::atomic*>* percore_pprev;\n\n xelem(const K &k, const V &v)\n : rcu_freed(\"xelem\"), val(v), key(k),\n next_lock(0), next(0),\n percore_next(0), percore_pprev(0) {}\n virtual void do_gc() {\n delete this;\n }\n\n NEW_DELETE_OPS(xelem)\n};\n\n\/\/ XXX maybe not cache align, because it takes too much space\ntemplate\nstruct xbucket {\n std::atomic*> volatile chain;\n} ; \/\/ __attribute__((aligned (CACHELINE)));\n\ntemplate\nclass xns : public rcu_freed {\n private:\n bool allowdup;\n std::atomic nextkey;\n xbucket table[NHASH];\n std::atomic*> percore[NCPU];\n spinlock percore_lock[NCPU];\n\n public:\n xns(bool dup) : rcu_freed(\"xns\") {\n allowdup = dup;\n nextkey = 1;\n for (int i = 0; i < NHASH; i++)\n table[i].chain = 0;\n for (int i = 0; i < NCPU; i++) {\n percore[i] = nullptr;\n percore_lock[i] = spinlock(\"xns_lock\", LOCKSTAT_NS);\n }\n }\n\n ~xns() {\n for (int i = 0; i < NHASH; i++)\n if (table[i].chain)\n panic(\"~xns: not empty\");\n }\n\n virtual void do_gc() {\n delete this;\n }\n\n u64 allockey() {\n return nextkey++;\n }\n\n u64 h(const K &key) {\n return HF(key) % NHASH;\n }\n\n int insert(const K &key, const V &val) {\n auto e = new xelem(key, val);\n if (!e)\n return -1;\n\n u64 i = h(key);\n scoped_gc_epoch gc;\n\n for (;;) {\n auto root = table[i].chain.load();\n if (!allowdup) {\n for (auto x = root; x; x = x->next) {\n if (x->key == key) {\n gc_delayed(e);\n return -1;\n }\n }\n }\n\n e->next = root;\n if (cmpxch(&table[i].chain, root, e)) {\n int c = myid();\n acquire(&percore_lock[c]);\n e->percore_c = c;\n e->percore_next = percore[c].load();\n if (percore[c])\n percore[c].load()->percore_pprev = &e->percore_next;\n e->percore_pprev = &percore[c];\n percore[c] = e;\n release(&percore_lock[c]);\n return 0;\n }\n }\n }\n\n V lookup(const K &key) {\n u64 i = h(key);\n\n scoped_gc_epoch gc;\n auto e = table[i].chain.load();\n\n while (e) {\n if (e->key == key)\n return e->val;\n e = e->next;\n }\n\n return 0;\n }\n\n bool remove(const K &key, const V *vp = 0) {\n u64 i = h(key);\n scoped_gc_epoch gc;\n\n for (;;) {\n std::atomic fakelock(0);\n std::atomic *pelock = &fakelock;\n auto pe = &table[i].chain;\n\n for (;;) {\n auto e = pe->load();\n if (!e)\n return false;\n\n if (e->key == key && (!vp || e->val == *vp)) {\n if (!cmpxch(&e->next_lock, 0, 1))\n break;\n if (!cmpxch(pelock, 0, 1)) {\n e->next_lock = 0;\n break;\n }\n\n if (!cmpxch(pe, e, e->next.load())) {\n pelock->store(0);\n e->next_lock = 0;\n break;\n }\n\n int c = e->percore_c;\n acquire(&percore_lock[c]);\n *e->percore_pprev = e->percore_next.load();\n if (e->percore_next)\n e->percore_next.load()->percore_pprev = e->percore_pprev;\n release(&percore_lock[c]);\n\n pelock->store(0);\n gc_delayed(e);\n return true;\n }\n\n pe = &e->next;\n pelock = &e->next_lock;\n }\n }\n }\n\n template\n void enumerate(CB cb) {\n scoped_gc_epoch gc;\n int cpuoffset = myid();\n for (int i = 0; i < NCPU; i++) {\n auto e = percore[(i + cpuoffset) % NCPU].load();\n while (e) {\n if (cb(e->key, e->val))\n return;\n e = e->percore_next;\n }\n }\n }\n\n template\n void enumerate_key(const K &key, CB cb) {\n scoped_gc_epoch gc;\n u64 i = h(key);\n auto e = table[i].chain;\n while (e) {\n if (e->key == key && cb(e->key, e->val))\n return;\n e = e->next;\n }\n }\n\n class iterator {\n private:\n xns *ns_;\n xelem *chain_;\n int ndx_;\n\n public:\n iterator(xns *ns) {\n if (ns_)\n gc_begin_epoch();\n ns_ = ns;\n ndx_ = 0;\n chain_ = ns->table[ndx_++].chain;\n for (; chain_ == 0 && ndx_ < NHASH; ndx_++)\n chain_ = ns_->table[ndx_].chain;\n }\n\n iterator() {\n ns_ = 0;\n ndx_ = NHASH;\n chain_ = 0;\n }\n\n ~iterator() {\n if (ns_)\n gc_end_epoch();\n }\n\n bool operator!=(const iterator &other) const {\n return other.chain_ != this->chain_;\n }\n\n iterator& operator ++() {\n for (chain_ = chain_->next; chain_ == 0 && ndx_ < NHASH; ndx_++)\n chain_ = ns_->table[ndx_].chain;\n return *this;\n }\n\n V& operator *() {\n return chain_->val;\n }\n };\n\n iterator begin() {\n return iterator(this);\n }\n\n iterator end() {\n return iterator();\n }\n\n NEW_DELETE_OPS(xns)\n};\n\ntemplate\nstatic inline\ntypename xns::iterator\nbegin(xns *&ns)\n{\n return ns->begin();\n}\n\ntemplate\nstatic inline\ntypename xns::iterator\nend(xns *&ns)\n{\n return ns->end();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"hlt.hpp\"\n#include \"networking.hpp\"\n\nint main() {\n srand(time(NULL));\n\n std::cout.sync_with_stdio(0);\n\n unsigned char myID;\n hlt::GameMap presentMap;\n getInit(myID, presentMap);\n sendInit(\"C++Bot\");\n\n std::set moves;\n while(true) {\n moves.clear();\n\n getFrame(presentMap);\n\n for(unsigned short a = 0; a < presentMap.height; a++) {\n for(unsigned short b = 0; b < presentMap.width; b++) {\n if (presentMap.getSite({ b, a }).owner == myID) {\n\n bool movedPiece = false;\n \n for(int d : CARDINALS) {\n if(presentMap.getSite({ b, a }, d).owner != myID && presentMap.getSite({ b, a }, d).strength < presentMap.getSite({ b, a }).strength) {\n moves.insert({ { b, a }, d });\n movedPiece = true;\n break;\n }\n }\n\n if(!movedPiece && presentMap.getSite({ b, a }).strength < presentMap.getSite({ b, a }).production * 5) {\n moves.insert({ { b, a }, STILL });\n movedPiece = true;\n }\n \n if(!movedPiece) {\n moves.insert({ { b, a }, (bool)(rand() % 2) ? NORTH : WEST });\n movedPiece = true;\n }\n }\n }\n }\n\n sendFrame(moves);\n }\n\n return 0;\n}\nTook out extra includes from C++ rand tut#include \n#include \n\n#include \"hlt.hpp\"\n#include \"networking.hpp\"\n\nint main() {\n srand(time(NULL));\n\n std::cout.sync_with_stdio(0);\n\n unsigned char myID;\n hlt::GameMap presentMap;\n getInit(myID, presentMap);\n sendInit(\"C++Bot\");\n\n std::set moves;\n while(true) {\n moves.clear();\n\n getFrame(presentMap);\n\n for(unsigned short a = 0; a < presentMap.height; a++) {\n for(unsigned short b = 0; b < presentMap.width; b++) {\n if (presentMap.getSite({ b, a }).owner == myID) {\n\n bool movedPiece = false;\n \n for(int d : CARDINALS) {\n if(presentMap.getSite({ b, a }, d).owner != myID && presentMap.getSite({ b, a }, d).strength < presentMap.getSite({ b, a }).strength) {\n moves.insert({ { b, a }, d });\n movedPiece = true;\n break;\n }\n }\n\n if(!movedPiece && presentMap.getSite({ b, a }).strength < presentMap.getSite({ b, a }).production * 5) {\n moves.insert({ { b, a }, STILL });\n movedPiece = true;\n }\n \n if(!movedPiece) {\n moves.insert({ { b, a }, (bool)(rand() % 2) ? NORTH : WEST });\n movedPiece = true;\n }\n }\n }\n }\n\n sendFrame(moves);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef PITO_SANDBOX_HELPER_HPP\n#define PITO_SANDBOX_HELPER_HPP\n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#define PITO_SANDBOX_DEFAULT \"PITO_SANDBOX_DEFAULT\"\n#define PITO_SANDBOX_PATHS \"PITO_SANDBOX_PATHS\"\n\nnamespace pito { namespace sandbox {\n\nenum write_mode {\n WRITE_MODE_PRETEND,\n WRITE_MODE_WHITELIST,\n WRITE_MODE_BLACKLIST\n};\n\nstruct context {\n context();\n\n std::vector paths;\n write_mode mode;\n};\n\nextern context& ctxt;\n\nusing namespace system_call_tag;\n\ntemplate \nstruct system_call;\n\ntemplate \nstruct system_call : detail::system_call {\n template \n PITO_RETURN(Tag) operator()(Args... args) {\n return PITO_SUPER(Tag, args...);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(chmod) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(system_call_tag::chmod, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchmod) operator()(int fd, mode_t mode) {\n return PITO_SUPER(system_call_tag::fchmod, fd, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchmodat) operator()(int arg1, const char *arg2, mode_t arg3, int arg4) {\n return PITO_SUPER(system_call_tag::fchmodat, arg1, arg2, arg3, arg4);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(chown) operator()(const char *path, uid_t uid, gid_t gid) {\n return PITO_SUPER(system_call_tag::chown, path, uid, gid);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchown) operator()(int fd, uid_t uid, gid_t gid) {\n return PITO_SUPER(system_call_tag::fchown, fd, uid, gid);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchownat) operator()(int fd, const char *path, uid_t uid, gid_t gid, int flags) {\n return PITO_SUPER(system_call_tag::fchownat, fd, path, uid, gid, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(open) operator()(const char *path, int flag) {\n return PITO_SUPER(system_call_tag::open, path, flag);\n }\n\n PITO_RETURN(open) operator()(const char *path, int flag, int mode) {\n return PITO_SUPER(system_call_tag::open, path, flag, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(open64) operator()(const char *path, int flag) {\n return PITO_SUPER(system_call_tag::open64, path, flag);\n }\n\n PITO_RETURN(open64) operator()(const char *path, int flag, int mode) {\n return PITO_SUPER(system_call_tag::open64, path, flag, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(openat) operator()(int fd, const char *path, int flags) {\n return PITO_SUPER(system_call_tag::openat, fd, path, flags);\n }\n\n PITO_RETURN(openat) operator()(int fd, const char *path, int flags, int mode) {\n return PITO_SUPER(system_call_tag::openat, fd, path, flags, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(openat64) operator()(int fd, const char *path, int flags) {\n return PITO_SUPER(system_call_tag::openat64, fd, path, flags);\n }\n\n PITO_RETURN(openat64) operator()(int fd, const char *path, int flags, int mode) {\n return PITO_SUPER(system_call_tag::openat64, fd, path, flags, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(creat) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(system_call_tag::creat, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(creat) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(system_call_tag::creat64, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fopen) operator()(const char *path, const char *mode) {\n return PITO_SUPER(system_call_tag::fopen, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fopen64) operator()(const char *path, const char *mode) {\n return PITO_SUPER(system_call_tag::fopen64, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(lchown) operator()(const char *path, uid_t uid, gid_t gid) {\n return PITO_SUPER(system_call_tag::lchown, path, uid, gid);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(link) operator()(const char *oldpath, const char *newpath) {\n return PITO_SUPER(system_call_tag::link, oldpath, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(linkat) operator()(int olddirfd,\n const char *oldpath,\n int newdirfd,\n const char *newpath,\n int flags)\n {\n return PITO_SUPER(system_call_tag::linkat,\n olddirfd, oldpath, newdirfd, newpath, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkdir) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(system_call_tag::mkdir, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkdirat) operator()(int fd, const char *path, mode_t mode) {\n return PITO_SUPER(system_call_tag::mkdirat, fd, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(opendir) operator()(const char *path) {\n return PITO_SUPER(system_call_tag::opendir, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(readdir) operator()(DIR *dir) {\n return PITO_SUPER(system_call_tag::readdir, dir);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mknod) operator()(const char *path, mode_t mode, dev_t dev) {\n return PITO_SUPER(system_call_tag::mknod, path, mode, dev);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mknodat) operator()(int fd, const char *path, mode_t mode, dev_t dev) {\n return PITO_SUPER(system_call_tag::mknodat, fd, path, mode, dev);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkfifo) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(system_call_tag::mkfifo, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkfifoat) operator()(int fd, const char *path, mode_t mode) {\n return PITO_SUPER(system_call_tag::mkfifoat, fd, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(access) operator()(const char *path, int amode) {\n return PITO_SUPER(system_call_tag::access, path, amode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(faccessat) operator()(int fd, const char *path,\n int mode, int flags)\n {\n return PITO_SUPER(system_call_tag::faccessat, fd, path, mode, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(rename) operator()(const char *oldpath, const char *newpath) {\n return PITO_SUPER(system_call_tag::rename, oldpath, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(renameat) operator()(int olddirfd, const char *oldpath,\n int newdirfd, const char *newpath) {\n return PITO_SUPER(system_call_tag::renameat,\n olddirfd, oldpath, newdirfd, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(rmdir) operator()(const char *path) {\n return PITO_SUPER(system_call_tag::rmdir, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(symlink) operator()(const char *entry, const char *path) {\n return PITO_SUPER(system_call_tag::symlink, entry, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(symlinkat) operator()(const char *oldpath,\n int newdirfd, const char *newpath) {\n return PITO_SUPER(\n system_call_tag::symlinkat, oldpath, newdirfd, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(truncate) operator()(const char *path, off_t length) {\n return PITO_SUPER(system_call_tag::truncate, path, length);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(truncate64) operator()(const char *path, PITO_OFF64_TYPE length) {\n return PITO_SUPER(system_call_tag::truncate64, path, length);\n }\n};\n\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(unlink) operator()(const char *path) {\n return PITO_SUPER(system_call_tag::unlink, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(unlinkat) operator()(int fd, const char *path, int flags) {\n return PITO_SUPER(system_call_tag::unlinkat, fd, path, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(utime) operator()(const char *path, const struct utimbuf *time) {\n return PITO_SUPER(system_call_tag::utime, path, time);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(utimes) operator()(const char *path, const struct timeval times[2]) {\n return PITO_SUPER(system_call_tag::utimes, path, times);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(utimensat) operator()(\n int fd, const char *path, const struct timespec time[2], int flags)\n {\n return PITO_SUPER(system_call_tag::utimensat, fd, path, time, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(futimesat) operator()(\n int fd, const char *path, const struct timeval time[2])\n {\n return PITO_SUPER(system_call_tag::futimesat, fd, path, time);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(lutimes) operator()(const char *path, const struct timeval time[2]) {\n return PITO_SUPER(system_call_tag::lutimes, path, time);\n }\n};\n\n} }\n\n#endif\nhave included system call tag already, better TEMPLATE2#ifndef PITO_SANDBOX_HELPER_HPP\n#define PITO_SANDBOX_HELPER_HPP\n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#define PITO_SANDBOX_DEFAULT \"PITO_SANDBOX_DEFAULT\"\n#define PITO_SANDBOX_PATHS \"PITO_SANDBOX_PATHS\"\n\nnamespace pito { namespace sandbox {\n\nenum write_mode {\n WRITE_MODE_PRETEND,\n WRITE_MODE_WHITELIST,\n WRITE_MODE_BLACKLIST\n};\n\nstruct context {\n context();\n\n std::vector paths;\n write_mode mode;\n};\n\nextern context& ctxt;\n\nusing namespace system_call_tag;\n\ntemplate \nstruct system_call;\n\ntemplate \nstruct system_call : detail::system_call {\n template \n PITO_RETURN(Tag) operator()(Args... args) {\n return PITO_SUPER(Tag, args...);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(chmod) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(chmod, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchmod) operator()(int fd, mode_t mode) {\n return PITO_SUPER(fchmod, fd, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchmodat) operator()(int arg1, const char *arg2, mode_t arg3, int arg4) {\n return PITO_SUPER(fchmodat, arg1, arg2, arg3, arg4);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(chown) operator()(const char *path, uid_t uid, gid_t gid) {\n return PITO_SUPER(chown, path, uid, gid);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchown) operator()(int fd, uid_t uid, gid_t gid) {\n return PITO_SUPER(fchown, fd, uid, gid);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fchownat) operator()(int fd, const char *path, uid_t uid, gid_t gid, int flags) {\n return PITO_SUPER(fchownat, fd, path, uid, gid, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(open) operator()(const char *path, int flag) {\n return PITO_SUPER(open, path, flag);\n }\n\n PITO_RETURN(open) operator()(const char *path, int flag, int mode) {\n return PITO_SUPER(open, path, flag, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(open64) operator()(const char *path, int flag) {\n return PITO_SUPER(open64, path, flag);\n }\n\n PITO_RETURN(open64) operator()(const char *path, int flag, int mode) {\n return PITO_SUPER(open64, path, flag, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(openat) operator()(int fd, const char *path, int flags) {\n return PITO_SUPER(openat, fd, path, flags);\n }\n\n PITO_RETURN(openat) operator()(int fd, const char *path, int flags, int mode) {\n return PITO_SUPER(openat, fd, path, flags, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(openat64) operator()(int fd, const char *path, int flags) {\n return PITO_SUPER(openat64, fd, path, flags);\n }\n\n PITO_RETURN(openat64) operator()(int fd, const char *path, int flags, int mode) {\n return PITO_SUPER(openat64, fd, path, flags, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(creat) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(creat, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(creat) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(creat64, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fopen) operator()(const char *path, const char *mode) {\n return PITO_SUPER(fopen, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(fopen64) operator()(const char *path, const char *mode) {\n return PITO_SUPER(fopen64, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(lchown) operator()(const char *path, uid_t uid, gid_t gid) {\n return PITO_SUPER(lchown, path, uid, gid);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(link) operator()(const char *oldpath, const char *newpath) {\n return PITO_SUPER(link, oldpath, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(linkat) operator()(int olddirfd,\n const char *oldpath,\n int newdirfd,\n const char *newpath,\n int flags)\n {\n return PITO_SUPER(linkat, olddirfd, oldpath, newdirfd, newpath, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkdir) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(mkdir, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkdirat) operator()(int fd, const char *path, mode_t mode) {\n return PITO_SUPER(mkdirat, fd, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(opendir) operator()(const char *path) {\n return PITO_SUPER(opendir, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(readdir) operator()(DIR *dir) {\n return PITO_SUPER(readdir, dir);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mknod) operator()(const char *path, mode_t mode, dev_t dev) {\n return PITO_SUPER(mknod, path, mode, dev);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mknodat) operator()(int fd, const char *path, mode_t mode, dev_t dev) {\n return PITO_SUPER(mknodat, fd, path, mode, dev);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkfifo) operator()(const char *path, mode_t mode) {\n return PITO_SUPER(mkfifo, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(mkfifoat) operator()(int fd, const char *path, mode_t mode) {\n return PITO_SUPER(mkfifoat, fd, path, mode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(access) operator()(const char *path, int amode) {\n return PITO_SUPER(access, path, amode);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(faccessat) operator()(int fd, const char *path,\n int mode, int flags)\n {\n return PITO_SUPER(faccessat, fd, path, mode, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(rename) operator()(const char *oldpath, const char *newpath) {\n return PITO_SUPER(rename, oldpath, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(renameat) operator()(int olddirfd, const char *oldpath,\n int newdirfd, const char *newpath) {\n return PITO_SUPER(renameat,\n olddirfd, oldpath, newdirfd, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(rmdir) operator()(const char *path) {\n return PITO_SUPER(rmdir, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(symlink) operator()(const char *entry, const char *path) {\n return PITO_SUPER(symlink, entry, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(symlinkat) operator()(const char *oldpath,\n int newdirfd, const char *newpath) {\n return PITO_SUPER(symlinkat, oldpath, newdirfd, newpath);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(truncate) operator()(const char *path, off_t length) {\n return PITO_SUPER(truncate, path, length);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(truncate64) operator()(const char *path, PITO_OFF64_TYPE length) {\n return PITO_SUPER(truncate64, path, length);\n }\n};\n\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(unlink) operator()(const char *path) {\n return PITO_SUPER(unlink, path);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(unlinkat) operator()(int fd, const char *path, int flags) {\n return PITO_SUPER(unlinkat, fd, path, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(utime) operator()(const char *path, const struct utimbuf *time) {\n return PITO_SUPER(utime, path, time);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(utimes) operator()(const char *path, const struct timeval times[2]) {\n return PITO_SUPER(utimes, path, times);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(utimensat) operator()(\n int fd, const char *path, const struct timespec time[2], int flags)\n {\n return PITO_SUPER(utimensat, fd, path, time, flags);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(futimesat) operator()(\n int fd, const char *path, const struct timeval time[2])\n {\n return PITO_SUPER(futimesat, fd, path, time);\n }\n};\n\ntemplate <>\nstruct system_call : detail::system_call {\n PITO_RETURN(lutimes) operator()(const char *path, const struct timeval time[2]) {\n return PITO_SUPER(lutimes, path, time);\n }\n};\n\n} }\n\n#endif\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright (c) 2020-2022 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/* this file behaves like a config.h, comes first *\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nenum\n{\n kPrefsTypeBoolean = 1,\n kPrefsTypeInteger = 2,\n kPrefsTypeString = 3,\n kPrefsTypeBuffer = 4,\n kPrefsTypeBinary = 5\n};\n\nnamespace chip {\nnamespace DeviceLayer {\nnamespace Internal {\n\n\/\/ *** CAUTION ***: Changing the names or namespaces of these values will *break* existing devices.\n\n\/\/ NVS namespaces used to store device configuration information.\nconst char AmebaConfig::kConfigNamespace_ChipFactory[] = \"chip-factory\";\nconst char AmebaConfig::kConfigNamespace_ChipConfig[] = \"chip-config\";\nconst char AmebaConfig::kConfigNamespace_ChipCounters[] = \"chip-counters\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric1[] = \"chip-fabric-1\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric2[] = \"chip-fabric-2\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric3[] = \"chip-fabric-3\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric4[] = \"chip-fabric-4\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric5[] = \"chip-fabric-5\";\nconst char AmebaConfig::kConfigNamespace_ChipACL[] = \"chip-acl\";\nconst char AmebaConfig::kConfigNamespace_ChipGroupMessageCounters[] = \"chip-groupmsgcounters\";\nconst char AmebaConfig::kConfigNamespace_ChipAttributes[] = \"chip-attributes\";\nconst char AmebaConfig::kConfigNamespace_ChipBindingTable[] = \"chip-bindingtable\";\nconst char AmebaConfig::kConfigNamespace_ChipOTA[] = \"chip-ota\";\nconst char AmebaConfig::kConfigNamespace_ChipFailSafe[] = \"chip-failsafe\";\nconst char AmebaConfig::kConfigNamespace_ChipSessionResumption[] = \"chip-sessionresumption\";\nconst char AmebaConfig::kConfigNamespace_ChipDeviceInfoProvider[] = \"chip-deviceinfoprovider\";\nconst char AmebaConfig::kConfigNamespace_ChipGroupDataProvider[] = \"chip-groupdataprovider\";\nconst char AmebaConfig::kConfigNamespace_ChipOthers[] = \"chip-others\";\nconst char AmebaConfig::kConfigNamespace_ChipOthers2[] = \"chip-others2\";\n\n\/\/ Keys stored in the chip-factory namespace\nconst AmebaConfig::Key AmebaConfig::kConfigKey_SerialNum = { kConfigNamespace_ChipFactory, \"serial-num\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDeviceId = { kConfigNamespace_ChipFactory, \"device-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDeviceCert = { kConfigNamespace_ChipFactory, \"device-cert\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDeviceICACerts = { kConfigNamespace_ChipFactory, \"device-ca-certs\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDevicePrivateKey = { kConfigNamespace_ChipFactory, \"device-key\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_HardwareVersion = { kConfigNamespace_ChipFactory, \"hardware-ver\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_ManufacturingDate = { kConfigNamespace_ChipFactory, \"mfg-date\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_SetupPinCode = { kConfigNamespace_ChipFactory, \"pin-code\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_SetupDiscriminator = { kConfigNamespace_ChipFactory, \"discriminator\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_Spake2pIterationCount = { kConfigNamespace_ChipFactory, \"iteration-count\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_Spake2pSalt = { kConfigNamespace_ChipFactory, \"salt\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_Spake2pVerifier = { kConfigNamespace_ChipFactory, \"verifier\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_UniqueId = { kConfigNamespace_ChipFactory, \"uniqueId\" };\n\n\/\/ Keys stored in the chip-config namespace\nconst AmebaConfig::Key AmebaConfig::kConfigKey_ServiceConfig = { kConfigNamespace_ChipConfig, \"service-config\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_PairedAccountId = { kConfigNamespace_ChipConfig, \"account-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_ServiceId = { kConfigNamespace_ChipConfig, \"service-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_LastUsedEpochKeyId = { kConfigNamespace_ChipConfig, \"last-ek-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_FailSafeArmed = { kConfigNamespace_ChipConfig, \"fail-safe-armed\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_WiFiStationSecType = { kConfigNamespace_ChipConfig, \"sta-sec-type\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDeviceId = { kConfigNamespace_ChipConfig, \"op-device-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDeviceCert = { kConfigNamespace_ChipConfig, \"op-device-cert\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDeviceICACerts = { kConfigNamespace_ChipConfig, \"op-device-ca-certs\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDevicePrivateKey = { kConfigNamespace_ChipConfig, \"op-device-key\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_RegulatoryLocation = { kConfigNamespace_ChipConfig, \"regulatory-location\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_CountryCode = { kConfigNamespace_ChipConfig, \"country-code\" };\n\n\/\/ Keys stored in the Chip-counters namespace\nconst AmebaConfig::Key AmebaConfig::kCounterKey_RebootCount = { kConfigNamespace_ChipCounters, \"reboot-count\" };\nconst AmebaConfig::Key AmebaConfig::kCounterKey_UpTime = { kConfigNamespace_ChipCounters, \"up-time\" };\nconst AmebaConfig::Key AmebaConfig::kCounterKey_TotalOperationalHours = { kConfigNamespace_ChipCounters, \"total-hours\" };\nconst AmebaConfig::Key AmebaConfig::kCounterKey_BootReason = { kConfigNamespace_ChipCounters, \"boot-reason\" };\n\nCHIP_ERROR AmebaConfig::ReadConfigValue(Key key, bool & val)\n{\n uint8_t intVal;\n int32_t success = 0;\n\n success = getPref_bool_new(key.Namespace, key.Name, &intVal);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_bool_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n val = (intVal != 0);\n\n if (success == 0)\n return CHIP_NO_ERROR;\n else\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValue(Key key, uint32_t & val)\n{\n int32_t success = 0;\n\n success = getPref_u32_new(key.Namespace, key.Name, &val);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_u32_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n return CHIP_NO_ERROR;\n else\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValue(Key key, uint64_t & val)\n{\n int32_t success = 0;\n\n success = getPref_u64_new(key.Namespace, key.Name, &val);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_u32_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n return CHIP_NO_ERROR;\n else\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen)\n{\n int32_t success = 0;\n\n success = getPref_str_new(key.Namespace, key.Name, buf, bufSize, &outLen);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_str_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n {\n return CHIP_NO_ERROR;\n }\n else\n {\n outLen = 0;\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n }\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen)\n{\n int32_t success = 0;\n\n success = getPref_bin_new(key.Namespace, key.Name, buf, bufSize, &outLen);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_bin_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n {\n return CHIP_NO_ERROR;\n }\n else\n {\n outLen = 0;\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n }\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValue(Key key, bool val)\n{\n int32_t success;\n uint8_t value;\n\n if (val == 1)\n value = 1;\n else\n value = 0;\n success = setPref_new(key.Namespace, key.Name, &value, 1);\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %s failed\\n\", key.Namespace, key.Name, value ? \"true\" : \"false\");\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValue(Key key, uint32_t val)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) &val, sizeof(uint32_t));\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %d(0x%x) failed\\n\", key.Namespace, key.Name, val, val);\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValue(Key key, uint64_t val)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) &val, sizeof(uint64_t));\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %d(0x%x) failed\\n\", key.Namespace, key.Name, val, val);\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValueStr(Key key, const char * str)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) str, strlen(str) + 1);\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %s failed\\n\", key.Namespace, key.Name, str);\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen)\n{\n CHIP_ERROR err;\n chip::Platform::ScopedMemoryBuffer strCopy;\n\n if (str != NULL)\n {\n strCopy.Calloc(strLen + 1);\n VerifyOrExit(strCopy, err = CHIP_ERROR_NO_MEMORY);\n strncpy(strCopy.Get(), str, strLen);\n }\n err = AmebaConfig::WriteConfigValueStr(key, strCopy.Get());\nexit:\n return err;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) data, dataLen);\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::ClearConfigValue(Key key)\n{\n int32_t success;\n\n success = deleteKey(key.Namespace, key.Name);\n if (!success)\n ChipLogProgress(DeviceLayer, \"%s : %s\/%s failed\\n\", __FUNCTION__, key.Namespace, key.Name);\n\n return CHIP_NO_ERROR;\n}\n\nbool AmebaConfig::ConfigValueExists(Key key)\n{\n return checkExist(key.Namespace, key.Name);\n}\n\nCHIP_ERROR AmebaConfig::EnsureNamespace(const char * ns)\n{\n int32_t success = -1;\n\n success = registerPref(ns);\n if (success != 0)\n {\n ChipLogError(DeviceLayer, \"dct_register_module failed\\n\");\n }\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::EnsureNamespace2(const char * ns)\n{\n int32_t success = -1;\n\n success = registerPref2(ns);\n if (success != 0)\n {\n ChipLogError(DeviceLayer, \"dct_register_module2 failed\\n\");\n }\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::ClearNamespace(const char * ns)\n{\n int32_t success = -1;\n\n success = clearPref(ns);\n if (success != 0)\n {\n ChipLogError(DeviceLayer, \"ClearNamespace failed\\n\");\n }\n\n return CHIP_NO_ERROR;\n}\n\nvoid AmebaConfig::RunConfigUnitTest() {}\n\n} \/\/ namespace Internal\n} \/\/ namespace DeviceLayer\n} \/\/ namespace chip\n[Logs] Add NVS logs (#22662)\/*\n *\n * Copyright (c) 2020-2022 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/* this file behaves like a config.h, comes first *\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nenum\n{\n kPrefsTypeBoolean = 1,\n kPrefsTypeInteger = 2,\n kPrefsTypeString = 3,\n kPrefsTypeBuffer = 4,\n kPrefsTypeBinary = 5\n};\n\nnamespace chip {\nnamespace DeviceLayer {\nnamespace Internal {\n\n\/\/ *** CAUTION ***: Changing the names or namespaces of these values will *break* existing devices.\n\n\/\/ NVS namespaces used to store device configuration information.\nconst char AmebaConfig::kConfigNamespace_ChipFactory[] = \"chip-factory\";\nconst char AmebaConfig::kConfigNamespace_ChipConfig[] = \"chip-config\";\nconst char AmebaConfig::kConfigNamespace_ChipCounters[] = \"chip-counters\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric1[] = \"chip-fabric-1\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric2[] = \"chip-fabric-2\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric3[] = \"chip-fabric-3\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric4[] = \"chip-fabric-4\";\nconst char AmebaConfig::kConfigNamespace_ChipFabric5[] = \"chip-fabric-5\";\nconst char AmebaConfig::kConfigNamespace_ChipACL[] = \"chip-acl\";\nconst char AmebaConfig::kConfigNamespace_ChipGroupMessageCounters[] = \"chip-groupmsgcounters\";\nconst char AmebaConfig::kConfigNamespace_ChipAttributes[] = \"chip-attributes\";\nconst char AmebaConfig::kConfigNamespace_ChipBindingTable[] = \"chip-bindingtable\";\nconst char AmebaConfig::kConfigNamespace_ChipOTA[] = \"chip-ota\";\nconst char AmebaConfig::kConfigNamespace_ChipFailSafe[] = \"chip-failsafe\";\nconst char AmebaConfig::kConfigNamespace_ChipSessionResumption[] = \"chip-sessionresumption\";\nconst char AmebaConfig::kConfigNamespace_ChipDeviceInfoProvider[] = \"chip-deviceinfoprovider\";\nconst char AmebaConfig::kConfigNamespace_ChipGroupDataProvider[] = \"chip-groupdataprovider\";\nconst char AmebaConfig::kConfigNamespace_ChipOthers[] = \"chip-others\";\nconst char AmebaConfig::kConfigNamespace_ChipOthers2[] = \"chip-others2\";\n\n\/\/ Keys stored in the chip-factory namespace\nconst AmebaConfig::Key AmebaConfig::kConfigKey_SerialNum = { kConfigNamespace_ChipFactory, \"serial-num\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDeviceId = { kConfigNamespace_ChipFactory, \"device-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDeviceCert = { kConfigNamespace_ChipFactory, \"device-cert\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDeviceICACerts = { kConfigNamespace_ChipFactory, \"device-ca-certs\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_MfrDevicePrivateKey = { kConfigNamespace_ChipFactory, \"device-key\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_HardwareVersion = { kConfigNamespace_ChipFactory, \"hardware-ver\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_ManufacturingDate = { kConfigNamespace_ChipFactory, \"mfg-date\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_SetupPinCode = { kConfigNamespace_ChipFactory, \"pin-code\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_SetupDiscriminator = { kConfigNamespace_ChipFactory, \"discriminator\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_Spake2pIterationCount = { kConfigNamespace_ChipFactory, \"iteration-count\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_Spake2pSalt = { kConfigNamespace_ChipFactory, \"salt\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_Spake2pVerifier = { kConfigNamespace_ChipFactory, \"verifier\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_UniqueId = { kConfigNamespace_ChipFactory, \"uniqueId\" };\n\n\/\/ Keys stored in the chip-config namespace\nconst AmebaConfig::Key AmebaConfig::kConfigKey_ServiceConfig = { kConfigNamespace_ChipConfig, \"service-config\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_PairedAccountId = { kConfigNamespace_ChipConfig, \"account-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_ServiceId = { kConfigNamespace_ChipConfig, \"service-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_LastUsedEpochKeyId = { kConfigNamespace_ChipConfig, \"last-ek-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_FailSafeArmed = { kConfigNamespace_ChipConfig, \"fail-safe-armed\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_WiFiStationSecType = { kConfigNamespace_ChipConfig, \"sta-sec-type\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDeviceId = { kConfigNamespace_ChipConfig, \"op-device-id\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDeviceCert = { kConfigNamespace_ChipConfig, \"op-device-cert\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDeviceICACerts = { kConfigNamespace_ChipConfig, \"op-device-ca-certs\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_OperationalDevicePrivateKey = { kConfigNamespace_ChipConfig, \"op-device-key\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_RegulatoryLocation = { kConfigNamespace_ChipConfig, \"regulatory-location\" };\nconst AmebaConfig::Key AmebaConfig::kConfigKey_CountryCode = { kConfigNamespace_ChipConfig, \"country-code\" };\n\n\/\/ Keys stored in the Chip-counters namespace\nconst AmebaConfig::Key AmebaConfig::kCounterKey_RebootCount = { kConfigNamespace_ChipCounters, \"reboot-count\" };\nconst AmebaConfig::Key AmebaConfig::kCounterKey_UpTime = { kConfigNamespace_ChipCounters, \"up-time\" };\nconst AmebaConfig::Key AmebaConfig::kCounterKey_TotalOperationalHours = { kConfigNamespace_ChipCounters, \"total-hours\" };\nconst AmebaConfig::Key AmebaConfig::kCounterKey_BootReason = { kConfigNamespace_ChipCounters, \"boot-reason\" };\n\nCHIP_ERROR AmebaConfig::ReadConfigValue(Key key, bool & val)\n{\n uint8_t intVal;\n int32_t success = 0;\n\n success = getPref_bool_new(key.Namespace, key.Name, &intVal);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_bool_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n val = (intVal != 0);\n\n if (success == 0)\n return CHIP_NO_ERROR;\n else\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValue(Key key, uint32_t & val)\n{\n int32_t success = 0;\n\n success = getPref_u32_new(key.Namespace, key.Name, &val);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_u32_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n return CHIP_NO_ERROR;\n else\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValue(Key key, uint64_t & val)\n{\n int32_t success = 0;\n\n success = getPref_u64_new(key.Namespace, key.Name, &val);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_u32_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n return CHIP_NO_ERROR;\n else\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen)\n{\n int32_t success = 0;\n\n success = getPref_str_new(key.Namespace, key.Name, buf, bufSize, &outLen);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_str_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n {\n return CHIP_NO_ERROR;\n }\n else\n {\n outLen = 0;\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n }\n}\n\nCHIP_ERROR AmebaConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen)\n{\n int32_t success = 0;\n\n success = getPref_bin_new(key.Namespace, key.Name, buf, bufSize, &outLen);\n if (success != 0)\n ChipLogProgress(DeviceLayer, \"getPref_bin_new: %s\/%s failed\\n\", key.Namespace, key.Name);\n\n if (success == 0)\n {\n return CHIP_NO_ERROR;\n }\n else\n {\n outLen = 0;\n return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;\n }\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValue(Key key, bool val)\n{\n int32_t success;\n uint8_t value;\n\n if (val == 1)\n value = 1;\n else\n value = 0;\n success = setPref_new(key.Namespace, key.Name, &value, 1);\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %s failed\\n\", key.Namespace, key.Name, value ? \"true\" : \"false\");\n else\n ChipLogProgress(DeviceLayer, \"NVS set: %s\/%s = %s\", key.Namespace, key.Name, val ? \"true\" : \"false\");\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValue(Key key, uint32_t val)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) &val, sizeof(uint32_t));\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %d(0x%x) failed\\n\", key.Namespace, key.Name, val, val);\n else\n ChipLogProgress(DeviceLayer, \"NVS set: %s\/%s = %\" PRIu32 \" (0x%\" PRIX32 \")\", key.Namespace, key.Name, val, val);\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValue(Key key, uint64_t val)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) &val, sizeof(uint64_t));\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %d(0x%x) failed\\n\", key.Namespace, key.Name, val, val);\n else\n ChipLogProgress(DeviceLayer, \"NVS set: %s\/%s = %\" PRIu64 \" (0x%\" PRIX64 \")\", key.Namespace, key.Name, val, val);\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValueStr(Key key, const char * str)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) str, strlen(str) + 1);\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s = %s failed\\n\", key.Namespace, key.Name, str);\n else\n ChipLogProgress(DeviceLayer, \"NVS set: %s\/%s = \\\"%s\\\"\", key.Namespace, key.Name, str);\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen)\n{\n CHIP_ERROR err;\n chip::Platform::ScopedMemoryBuffer strCopy;\n\n if (str != NULL)\n {\n strCopy.Calloc(strLen + 1);\n VerifyOrExit(strCopy, err = CHIP_ERROR_NO_MEMORY);\n strncpy(strCopy.Get(), str, strLen);\n }\n err = AmebaConfig::WriteConfigValueStr(key, strCopy.Get());\nexit:\n return err;\n}\n\nCHIP_ERROR AmebaConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen)\n{\n int32_t success;\n\n success = setPref_new(key.Namespace, key.Name, (uint8_t *) data, dataLen);\n if (!success)\n ChipLogError(DeviceLayer, \"setPref: %s\/%s failed\\n\", key.Namespace, key.Name);\n else\n ChipLogProgress(DeviceLayer, \"NVS set: %s\/%s = (blob length %\" PRId32 \")\", key.Namespace, key.Name, dataLen);\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::ClearConfigValue(Key key)\n{\n int32_t success;\n\n success = deleteKey(key.Namespace, key.Name);\n if (!success)\n ChipLogProgress(DeviceLayer, \"%s : %s\/%s failed\\n\", __FUNCTION__, key.Namespace, key.Name);\n else\n ChipLogProgress(DeviceLayer, \"NVS erase: %s\/%s\", key.Namespace, key.Name);\n\n return CHIP_NO_ERROR;\n}\n\nbool AmebaConfig::ConfigValueExists(Key key)\n{\n return checkExist(key.Namespace, key.Name);\n}\n\nCHIP_ERROR AmebaConfig::EnsureNamespace(const char * ns)\n{\n int32_t success = -1;\n\n success = registerPref(ns);\n if (success != 0)\n {\n ChipLogError(DeviceLayer, \"dct_register_module failed\\n\");\n }\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::EnsureNamespace2(const char * ns)\n{\n int32_t success = -1;\n\n success = registerPref2(ns);\n if (success != 0)\n {\n ChipLogError(DeviceLayer, \"dct_register_module2 failed\\n\");\n }\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR AmebaConfig::ClearNamespace(const char * ns)\n{\n int32_t success = -1;\n\n success = clearPref(ns);\n if (success != 0)\n {\n ChipLogError(DeviceLayer, \"ClearNamespace failed\\n\");\n }\n\n return CHIP_NO_ERROR;\n}\n\nvoid AmebaConfig::RunConfigUnitTest() {}\n\n} \/\/ namespace Internal\n} \/\/ namespace DeviceLayer\n} \/\/ namespace chip\n<|endoftext|>"} {"text":"#include \"GameController.h\"\n\n#include \"AudioProcessor.h\"\n\n#include \n\nextern \"C\" {\n#include \"gba.h\"\n#include \"gba-audio.h\"\n#include \"renderers\/video-software.h\"\n#include \"util\/vfs.h\"\n}\n\nusing namespace QGBA;\n\nGameController::GameController(QObject* parent)\n\t: QObject(parent)\n\t, m_drawContext(new uint32_t[256 * 256])\n\t, m_threadContext()\n\t, m_activeKeys(0)\n\t, m_rom(nullptr)\n\t, m_audioThread(new QThread(this))\n\t, m_audioProcessor(new AudioProcessor)\n{\n\tm_renderer = new GBAVideoSoftwareRenderer;\n\tGBAVideoSoftwareRendererCreate(m_renderer);\n\tm_renderer->outputBuffer = (color_t*) m_drawContext;\n\tm_renderer->outputBufferStride = 256;\n\tm_threadContext.state = THREAD_INITIALIZED;\n\tm_threadContext.debugger = 0;\n\tm_threadContext.frameskip = 0;\n\tm_threadContext.bios = 0;\n\tm_threadContext.renderer = &m_renderer->d;\n\tm_threadContext.userData = this;\n\tm_threadContext.rewindBufferCapacity = 0;\n\tm_threadContext.logLevel = -1;\n\n\tGBAInputMapInit(&m_threadContext.inputMap);\n\n#ifdef BUILD_SDL\n\tSDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);\n\tm_sdlEvents.bindings = &m_threadContext.inputMap;\n\tGBASDLInitEvents(&m_sdlEvents);\n\tSDL_JoystickEventState(SDL_QUERY);\n#endif\n\n\tm_threadContext.startCallback = [] (GBAThread* context) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->m_audioProcessor->setInput(context);\n\t\tcontroller->gameStarted(context);\n\t};\n\n\tm_threadContext.cleanCallback = [] (GBAThread* context) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->gameStopped(context);\n\t};\n\n\tm_threadContext.frameCallback = [] (GBAThread* context) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->m_pauseMutex.lock();\n\t\tif (controller->m_pauseAfterFrame) {\n\t\t\tGBAThreadPauseFromThread(context);\n\t\t\tcontroller->m_pauseAfterFrame = false;\n\t\t\tcontroller->gamePaused(&controller->m_threadContext);\n\t\t}\n\t\tcontroller->m_pauseMutex.unlock();\n\t\tcontroller->frameAvailable(controller->m_drawContext);\n\t};\n\n\tm_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->postLog(level, QString().vsprintf(format, args));\n\t};\n\n\tm_audioThread->start(QThread::TimeCriticalPriority);\n\tm_audioProcessor->moveToThread(m_audioThread);\n\tconnect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));\n\tconnect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));\n\tconnect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));\n\tconnect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));\n\n#ifdef BUILD_SDL\n\tconnect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));\n#endif\n}\n\nGameController::~GameController() {\n\tm_audioThread->quit();\n\tm_audioThread->wait();\n\tif (GBAThreadIsPaused(&m_threadContext)) {\n\t\tGBAThreadUnpause(&m_threadContext);\n\t}\n\tGBAThreadEnd(&m_threadContext);\n\tGBAThreadJoin(&m_threadContext);\n\tdelete m_renderer;\n}\n\nARMDebugger* GameController::debugger() {\n\treturn m_threadContext.debugger;\n}\n\nvoid GameController::setDebugger(ARMDebugger* debugger) {\n\tbool wasPaused = isPaused();\n\tsetPaused(true);\n\tif (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {\n\t\tGBADetachDebugger(m_threadContext.gba);\n\t}\n\tm_threadContext.debugger = debugger;\n\tif (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {\n\t\tGBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);\n\t}\n\tsetPaused(wasPaused);\n}\n\nvoid GameController::loadGame(const QString& path) {\n\tcloseGame();\n\tm_threadContext.sync.videoFrameWait = 0;\n\tm_threadContext.sync.audioWait = 1;\n\tm_rom = new QFile(path);\n\tif (!m_rom->open(QIODevice::ReadOnly)) {\n\t\tdelete m_rom;\n\t\tm_rom = nullptr;\n\t}\n\n\tm_pauseAfterFrame = false;\n\n\tm_threadContext.rom = VFileFromFD(m_rom->handle());\n\tm_threadContext.fname = strdup(path.toLocal8Bit().constData());\n\n\tGBAThreadStart(&m_threadContext);\n}\n\nvoid GameController::closeGame() {\n\tif (!m_rom) {\n\t\treturn;\n\t}\n\tGBAThreadEnd(&m_threadContext);\n\tGBAThreadJoin(&m_threadContext);\n\tif (m_threadContext.fname) {\n\t\tfree(const_cast(m_threadContext.fname));\n\t\tm_threadContext.fname = nullptr;\n\t}\n\tif (m_rom) {\n\t\tm_rom->close();\n\t\tdelete m_rom;\n\t\tm_rom = nullptr;\n\t}\n\temit gameStopped(&m_threadContext);\n}\n\nbool GameController::isPaused() {\n\treturn GBAThreadIsPaused(&m_threadContext);\n}\n\nvoid GameController::setPaused(bool paused) {\n\tif (paused == GBAThreadIsPaused(&m_threadContext)) {\n\t\treturn;\n\t}\n\tif (paused) {\n\t\tGBAThreadPause(&m_threadContext);\n\t\temit gamePaused(&m_threadContext);\n\t} else {\n\t\tGBAThreadUnpause(&m_threadContext);\n\t\temit gameUnpaused(&m_threadContext);\n\t}\n}\n\nvoid GameController::reset() {\n\tGBAThreadReset(&m_threadContext);\n}\n\nvoid GameController::frameAdvance() {\n\tm_pauseMutex.lock();\n\tm_pauseAfterFrame = true;\n\tsetPaused(false);\n\tm_pauseMutex.unlock();\n}\n\nvoid GameController::keyPressed(int key) {\n\tint mappedKey = 1 << key;\n\tm_activeKeys |= mappedKey;\n\tupdateKeys();\n}\n\nvoid GameController::keyReleased(int key) {\n\tint mappedKey = 1 << key;\n\tm_activeKeys &= ~mappedKey;\n\tupdateKeys();\n}\n\nvoid GameController::setAudioBufferSamples(int samples) {\n\tGBAThreadInterrupt(&m_threadContext);\n\tm_threadContext.audioBuffers = samples;\n\tGBAAudioResizeBuffer(&m_threadContext.gba->audio, samples);\n\tGBAThreadContinue(&m_threadContext);\n\tQMetaObject::invokeMethod(m_audioProcessor, \"setBufferSamples\", Q_ARG(int, samples));\n}\n\nvoid GameController::setFPSTarget(float fps) {\n\tGBAThreadInterrupt(&m_threadContext);\n\tm_threadContext.fpsTarget = fps;\n\tGBAThreadContinue(&m_threadContext);\n\tQMetaObject::invokeMethod(m_audioProcessor, \"inputParametersChanged\");\n}\n\nvoid GameController::updateKeys() {\n\tint activeKeys = m_activeKeys;\n#ifdef BUILD_SDL\n\tactiveKeys |= m_activeButtons;\n#endif\n\tm_threadContext.activeKeys = activeKeys;\n}\n\n#ifdef BUILD_SDL\nvoid GameController::testSDLEvents() {\n\tSDL_Joystick* joystick = m_sdlEvents.joystick;\n\tSDL_JoystickUpdate();\n\tint numButtons = SDL_JoystickNumButtons(joystick);\n\tm_activeButtons = 0;\n\tint i;\n\tfor (i = 0; i < numButtons; ++i) {\n\t\tGBAKey key = GBAInputMapKey(&m_threadContext.inputMap, SDL_BINDING_BUTTON, i);\n\t\tif (key == GBA_KEY_NONE) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (SDL_JoystickGetButton(joystick, i)) {\n\t\t\tm_activeButtons |= 1 << key;\n\t\t}\n\t}\n\tint numHats = SDL_JoystickNumHats(joystick);\n\tfor (i = 0; i < numHats; ++i) {\n\t\tint hat = SDL_JoystickGetHat(joystick, i);\n\t\tif (hat & SDL_HAT_UP) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_UP;\n\t\t}\n\t\tif (hat & SDL_HAT_LEFT) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_LEFT;\n\t\t}\n\t\tif (hat & SDL_HAT_DOWN) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_DOWN;\n\t\t}\n\t\tif (hat & SDL_HAT_RIGHT) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_RIGHT;\n\t\t}\n\t}\n\tupdateKeys();\n}\n#endif\nFix double-ending the GBA thread#include \"GameController.h\"\n\n#include \"AudioProcessor.h\"\n\n#include \n\nextern \"C\" {\n#include \"gba.h\"\n#include \"gba-audio.h\"\n#include \"renderers\/video-software.h\"\n#include \"util\/vfs.h\"\n}\n\nusing namespace QGBA;\n\nGameController::GameController(QObject* parent)\n\t: QObject(parent)\n\t, m_drawContext(new uint32_t[256 * 256])\n\t, m_threadContext()\n\t, m_activeKeys(0)\n\t, m_rom(nullptr)\n\t, m_audioThread(new QThread(this))\n\t, m_audioProcessor(new AudioProcessor)\n{\n\tm_renderer = new GBAVideoSoftwareRenderer;\n\tGBAVideoSoftwareRendererCreate(m_renderer);\n\tm_renderer->outputBuffer = (color_t*) m_drawContext;\n\tm_renderer->outputBufferStride = 256;\n\tm_threadContext.state = THREAD_INITIALIZED;\n\tm_threadContext.debugger = 0;\n\tm_threadContext.frameskip = 0;\n\tm_threadContext.bios = 0;\n\tm_threadContext.renderer = &m_renderer->d;\n\tm_threadContext.userData = this;\n\tm_threadContext.rewindBufferCapacity = 0;\n\tm_threadContext.logLevel = -1;\n\n\tGBAInputMapInit(&m_threadContext.inputMap);\n\n#ifdef BUILD_SDL\n\tSDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);\n\tm_sdlEvents.bindings = &m_threadContext.inputMap;\n\tGBASDLInitEvents(&m_sdlEvents);\n\tSDL_JoystickEventState(SDL_QUERY);\n#endif\n\n\tm_threadContext.startCallback = [] (GBAThread* context) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->m_audioProcessor->setInput(context);\n\t\tcontroller->gameStarted(context);\n\t};\n\n\tm_threadContext.cleanCallback = [] (GBAThread* context) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->gameStopped(context);\n\t};\n\n\tm_threadContext.frameCallback = [] (GBAThread* context) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->m_pauseMutex.lock();\n\t\tif (controller->m_pauseAfterFrame) {\n\t\t\tGBAThreadPauseFromThread(context);\n\t\t\tcontroller->m_pauseAfterFrame = false;\n\t\t\tcontroller->gamePaused(&controller->m_threadContext);\n\t\t}\n\t\tcontroller->m_pauseMutex.unlock();\n\t\tcontroller->frameAvailable(controller->m_drawContext);\n\t};\n\n\tm_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {\n\t\tGameController* controller = static_cast(context->userData);\n\t\tcontroller->postLog(level, QString().vsprintf(format, args));\n\t};\n\n\tm_audioThread->start(QThread::TimeCriticalPriority);\n\tm_audioProcessor->moveToThread(m_audioThread);\n\tconnect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));\n\tconnect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));\n\tconnect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));\n\tconnect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));\n\n#ifdef BUILD_SDL\n\tconnect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));\n#endif\n}\n\nGameController::~GameController() {\n\tm_audioThread->quit();\n\tm_audioThread->wait();\n\tif (GBAThreadIsPaused(&m_threadContext)) {\n\t\tGBAThreadUnpause(&m_threadContext);\n\t}\n\tdisconnect();\n\tcloseGame();\n\tdelete m_renderer;\n}\n\nARMDebugger* GameController::debugger() {\n\treturn m_threadContext.debugger;\n}\n\nvoid GameController::setDebugger(ARMDebugger* debugger) {\n\tbool wasPaused = isPaused();\n\tsetPaused(true);\n\tif (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {\n\t\tGBADetachDebugger(m_threadContext.gba);\n\t}\n\tm_threadContext.debugger = debugger;\n\tif (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {\n\t\tGBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);\n\t}\n\tsetPaused(wasPaused);\n}\n\nvoid GameController::loadGame(const QString& path) {\n\tcloseGame();\n\tm_threadContext.sync.videoFrameWait = 0;\n\tm_threadContext.sync.audioWait = 1;\n\tm_rom = new QFile(path);\n\tif (!m_rom->open(QIODevice::ReadOnly)) {\n\t\tdelete m_rom;\n\t\tm_rom = nullptr;\n\t}\n\n\tm_pauseAfterFrame = false;\n\n\tm_threadContext.rom = VFileFromFD(m_rom->handle());\n\tm_threadContext.fname = strdup(path.toLocal8Bit().constData());\n\n\tGBAThreadStart(&m_threadContext);\n}\n\nvoid GameController::closeGame() {\n\tif (!m_rom) {\n\t\treturn;\n\t}\n\tGBAThreadEnd(&m_threadContext);\n\tGBAThreadJoin(&m_threadContext);\n\tif (m_threadContext.fname) {\n\t\tfree(const_cast(m_threadContext.fname));\n\t\tm_threadContext.fname = nullptr;\n\t}\n\tif (m_rom) {\n\t\tm_rom->close();\n\t\tdelete m_rom;\n\t\tm_rom = nullptr;\n\t}\n\temit gameStopped(&m_threadContext);\n}\n\nbool GameController::isPaused() {\n\treturn GBAThreadIsPaused(&m_threadContext);\n}\n\nvoid GameController::setPaused(bool paused) {\n\tif (paused == GBAThreadIsPaused(&m_threadContext)) {\n\t\treturn;\n\t}\n\tif (paused) {\n\t\tGBAThreadPause(&m_threadContext);\n\t\temit gamePaused(&m_threadContext);\n\t} else {\n\t\tGBAThreadUnpause(&m_threadContext);\n\t\temit gameUnpaused(&m_threadContext);\n\t}\n}\n\nvoid GameController::reset() {\n\tGBAThreadReset(&m_threadContext);\n}\n\nvoid GameController::frameAdvance() {\n\tm_pauseMutex.lock();\n\tm_pauseAfterFrame = true;\n\tsetPaused(false);\n\tm_pauseMutex.unlock();\n}\n\nvoid GameController::keyPressed(int key) {\n\tint mappedKey = 1 << key;\n\tm_activeKeys |= mappedKey;\n\tupdateKeys();\n}\n\nvoid GameController::keyReleased(int key) {\n\tint mappedKey = 1 << key;\n\tm_activeKeys &= ~mappedKey;\n\tupdateKeys();\n}\n\nvoid GameController::setAudioBufferSamples(int samples) {\n\tGBAThreadInterrupt(&m_threadContext);\n\tm_threadContext.audioBuffers = samples;\n\tGBAAudioResizeBuffer(&m_threadContext.gba->audio, samples);\n\tGBAThreadContinue(&m_threadContext);\n\tQMetaObject::invokeMethod(m_audioProcessor, \"setBufferSamples\", Q_ARG(int, samples));\n}\n\nvoid GameController::setFPSTarget(float fps) {\n\tGBAThreadInterrupt(&m_threadContext);\n\tm_threadContext.fpsTarget = fps;\n\tGBAThreadContinue(&m_threadContext);\n\tQMetaObject::invokeMethod(m_audioProcessor, \"inputParametersChanged\");\n}\n\nvoid GameController::updateKeys() {\n\tint activeKeys = m_activeKeys;\n#ifdef BUILD_SDL\n\tactiveKeys |= m_activeButtons;\n#endif\n\tm_threadContext.activeKeys = activeKeys;\n}\n\n#ifdef BUILD_SDL\nvoid GameController::testSDLEvents() {\n\tSDL_Joystick* joystick = m_sdlEvents.joystick;\n\tSDL_JoystickUpdate();\n\tint numButtons = SDL_JoystickNumButtons(joystick);\n\tm_activeButtons = 0;\n\tint i;\n\tfor (i = 0; i < numButtons; ++i) {\n\t\tGBAKey key = GBAInputMapKey(&m_threadContext.inputMap, SDL_BINDING_BUTTON, i);\n\t\tif (key == GBA_KEY_NONE) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (SDL_JoystickGetButton(joystick, i)) {\n\t\t\tm_activeButtons |= 1 << key;\n\t\t}\n\t}\n\tint numHats = SDL_JoystickNumHats(joystick);\n\tfor (i = 0; i < numHats; ++i) {\n\t\tint hat = SDL_JoystickGetHat(joystick, i);\n\t\tif (hat & SDL_HAT_UP) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_UP;\n\t\t}\n\t\tif (hat & SDL_HAT_LEFT) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_LEFT;\n\t\t}\n\t\tif (hat & SDL_HAT_DOWN) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_DOWN;\n\t\t}\n\t\tif (hat & SDL_HAT_RIGHT) {\n\t\t\tm_activeButtons |= 1 << GBA_KEY_RIGHT;\n\t\t}\n\t}\n\tupdateKeys();\n}\n#endif\n<|endoftext|>"} {"text":"add unit test for tdf#88786<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef SC_AUTOFMT_HXX\n#define SC_AUTOFMT_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"scdllapi.h\"\n\n\/\/------------------------------------------------------------------------\n\nclass ScAutoFormatData;\nclass SvxBoxItem;\nclass SvxLineItem;\nclass ScAutoFmtPreview; \/\/ s.u.\nclass SvNumberFormatter;\nclass ScDocument;\n\n\/\/------------------------------------------------------------------------\n\nenum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };\n\n\/\/========================================================================\n\nclass SC_DLLPUBLIC ScAutoFmtPreview : public Window\n{\npublic:\n ScAutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );\n ~ScAutoFmtPreview();\n\n void NotifyChange( ScAutoFormatData* pNewData );\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n\nprivate:\n ScAutoFormatData* pCurData;\n VirtualDevice aVD;\n SvtScriptedTextHelper aScriptedText;\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;\n bool bFitWidth;\n svx::frame::Array maArray; \/\/\/ Implementation to draw the frame borders.\n bool mbRTL;\n Size aPrvSize;\n long mnLabelColWidth;\n long mnDataColWidth1;\n long mnDataColWidth2;\n long mnRowHeight;\n const OUString aStrJan;\n const OUString aStrFeb;\n const OUString aStrMar;\n const OUString aStrNorth;\n const OUString aStrMid;\n const OUString aStrSouth;\n const OUString aStrSum;\n SvNumberFormatter* pNumFmt;\n \/\/-------------------------------------------\n SAL_DLLPRIVATE void Init ();\n SAL_DLLPRIVATE void DoPaint ( const Rectangle& rRect );\n SAL_DLLPRIVATE void CalcCellArray ( bool bFitWidth );\n SAL_DLLPRIVATE void CalcLineMap ();\n SAL_DLLPRIVATE void PaintCells ();\n\n\/* Usage of type size_t instead of SCCOL\/SCROW is correct here - used in\n conjunction with class svx::frame::Array (svx\/framelinkarray.hxx), which\n expects size_t coordinates. *\/\n\n SAL_DLLPRIVATE sal_uInt16 GetFormatIndex( size_t nCol, size_t nRow ) const;\n SAL_DLLPRIVATE const SvxBoxItem& GetBoxItem( size_t nCol, size_t nRow ) const;\n SAL_DLLPRIVATE const SvxLineItem& GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;\n\n SAL_DLLPRIVATE void DrawString( size_t nCol, size_t nRow );\n SAL_DLLPRIVATE void DrawStrings();\n SAL_DLLPRIVATE void DrawBackground();\n\n SAL_DLLPRIVATE void MakeFonts ( sal_uInt16 nIndex,\n Font& rFont,\n Font& rCJKFont,\n Font& rCTLFont );\n\n SAL_DLLPRIVATE OUString MakeNumberString( OUString cellString, sal_Bool bAddDec );\n SAL_DLLPRIVATE void DrawFrameLine ( const ::editeng::SvxBorderLine& rLineD,\n Point from,\n Point to,\n sal_Bool bHorizontal,\n const ::editeng::SvxBorderLine& rLineLT,\n const ::editeng::SvxBorderLine& rLineL,\n const ::editeng::SvxBorderLine& rLineLB,\n const ::editeng::SvxBorderLine& rLineRT,\n const ::editeng::SvxBorderLine& rLineR,\n const ::editeng::SvxBorderLine& rLineRB );\n SAL_DLLPRIVATE void CheckPriority ( sal_uInt16 nCurLine,\n AutoFmtLine eLine,\n ::editeng::SvxBorderLine& rLine );\n SAL_DLLPRIVATE void GetLines ( sal_uInt16 nIndex, AutoFmtLine eLine,\n ::editeng::SvxBorderLine& rLineD,\n ::editeng::SvxBorderLine& rLineLT,\n ::editeng::SvxBorderLine& rLineL,\n ::editeng::SvxBorderLine& rLineLB,\n ::editeng::SvxBorderLine& rLineRT,\n ::editeng::SvxBorderLine& rLineR,\n ::editeng::SvxBorderLine& rLineRB );\n};\n\n#endif \/\/ SC_AUTOFMT_HXX\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nremove dead method definitions\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef SC_AUTOFMT_HXX\n#define SC_AUTOFMT_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"scdllapi.h\"\n\n\/\/------------------------------------------------------------------------\n\nclass ScAutoFormatData;\nclass SvxBoxItem;\nclass SvxLineItem;\nclass ScAutoFmtPreview; \/\/ s.u.\nclass SvNumberFormatter;\nclass ScDocument;\n\n\/\/------------------------------------------------------------------------\n\nenum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };\n\n\/\/========================================================================\n\nclass SC_DLLPUBLIC ScAutoFmtPreview : public Window\n{\npublic:\n ScAutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );\n ~ScAutoFmtPreview();\n\n void NotifyChange( ScAutoFormatData* pNewData );\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n\nprivate:\n ScAutoFormatData* pCurData;\n VirtualDevice aVD;\n SvtScriptedTextHelper aScriptedText;\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;\n bool bFitWidth;\n svx::frame::Array maArray; \/\/\/ Implementation to draw the frame borders.\n bool mbRTL;\n Size aPrvSize;\n long mnLabelColWidth;\n long mnDataColWidth1;\n long mnDataColWidth2;\n long mnRowHeight;\n const OUString aStrJan;\n const OUString aStrFeb;\n const OUString aStrMar;\n const OUString aStrNorth;\n const OUString aStrMid;\n const OUString aStrSouth;\n const OUString aStrSum;\n SvNumberFormatter* pNumFmt;\n \/\/-------------------------------------------\n SAL_DLLPRIVATE void Init ();\n SAL_DLLPRIVATE void DoPaint ( const Rectangle& rRect );\n SAL_DLLPRIVATE void CalcCellArray ( bool bFitWidth );\n SAL_DLLPRIVATE void CalcLineMap ();\n SAL_DLLPRIVATE void PaintCells ();\n\n\/* Usage of type size_t instead of SCCOL\/SCROW is correct here - used in\n conjunction with class svx::frame::Array (svx\/framelinkarray.hxx), which\n expects size_t coordinates. *\/\n\n SAL_DLLPRIVATE sal_uInt16 GetFormatIndex( size_t nCol, size_t nRow ) const;\n SAL_DLLPRIVATE const SvxBoxItem& GetBoxItem( size_t nCol, size_t nRow ) const;\n SAL_DLLPRIVATE const SvxLineItem& GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;\n\n SAL_DLLPRIVATE void DrawString( size_t nCol, size_t nRow );\n SAL_DLLPRIVATE void DrawStrings();\n SAL_DLLPRIVATE void DrawBackground();\n\n SAL_DLLPRIVATE void MakeFonts ( sal_uInt16 nIndex,\n Font& rFont,\n Font& rCJKFont,\n Font& rCTLFont );\n\n SAL_DLLPRIVATE void CheckPriority ( sal_uInt16 nCurLine,\n AutoFmtLine eLine,\n ::editeng::SvxBorderLine& rLine );\n SAL_DLLPRIVATE void GetLines ( sal_uInt16 nIndex, AutoFmtLine eLine,\n ::editeng::SvxBorderLine& rLineD,\n ::editeng::SvxBorderLine& rLineLT,\n ::editeng::SvxBorderLine& rLineL,\n ::editeng::SvxBorderLine& rLineLB,\n ::editeng::SvxBorderLine& rLineRT,\n ::editeng::SvxBorderLine& rLineR,\n ::editeng::SvxBorderLine& rLineRB );\n};\n\n#endif \/\/ SC_AUTOFMT_HXX\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: drtxtob.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: nn $ $Date: 2001-03-26 19:21:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_DRTXTOB_HXX\n#define SC_DRTXTOB_HXX\n\n#ifndef _SFX_HXX\n#endif\n\n#ifndef _SFX_SHELL_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXMODULE_HXX \/\/autogen\n#include \n#endif\n\n#include \"shellids.hxx\"\n\nUSHORT ScGetFontWorkId(); \/\/ statt SvxFontWorkChildWindow::GetChildWindowId()\n\nclass ScViewData;\n\nclass ScDrawTextObjectBar : public SfxShell\n{\n ScViewData* pViewData;\n\npublic:\n TYPEINFO();\n SFX_DECL_INTERFACE(SCID_DRAW_TEXT_SHELL);\n\n ScDrawTextObjectBar(ScViewData* pData);\n ~ScDrawTextObjectBar();\n\n void StateDisableItems( SfxItemSet &rSet );\n\n void Execute( SfxRequest &rReq );\n void ExecuteTrans( SfxRequest& rReq );\n void GetState( SfxItemSet& rSet );\n void GetClipState( SfxItemSet& rSet );\n\n void ExecuteAttr( SfxRequest &rReq );\n void GetAttrState( SfxItemSet& rSet );\n void ExecuteToggle( SfxRequest &rReq );\n\n BOOL ExecuteCharDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );\n BOOL ExecuteParaDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );\n\n void ExecuteExtra( SfxRequest &rReq );\n void ExecFormText(SfxRequest& rReq); \/\/ StarFontWork\n void GetFormTextState(SfxItemSet& rSet);\n\nprivate:\n void ExecuteGlobal( SfxRequest &rReq ); \/\/ von Execute gerufen fuer ganze Objekte\n void GetGlobalClipState( SfxItemSet& rSet );\n void ExecutePasteContents( SfxRequest &rReq );\n BOOL HasPasteContents();\n BOOL IsNoteEdit();\n};\n\n\n\n#endif\n\nremoved unused method HasPasteContents\/*************************************************************************\n *\n * $RCSfile: drtxtob.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: nn $ $Date: 2001-04-23 17:02:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_DRTXTOB_HXX\n#define SC_DRTXTOB_HXX\n\n#ifndef _SFX_HXX\n#endif\n\n#ifndef _SFX_SHELL_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXMODULE_HXX \/\/autogen\n#include \n#endif\n\n#include \"shellids.hxx\"\n\nUSHORT ScGetFontWorkId(); \/\/ statt SvxFontWorkChildWindow::GetChildWindowId()\n\nclass ScViewData;\n\nclass ScDrawTextObjectBar : public SfxShell\n{\n ScViewData* pViewData;\n\npublic:\n TYPEINFO();\n SFX_DECL_INTERFACE(SCID_DRAW_TEXT_SHELL);\n\n ScDrawTextObjectBar(ScViewData* pData);\n ~ScDrawTextObjectBar();\n\n void StateDisableItems( SfxItemSet &rSet );\n\n void Execute( SfxRequest &rReq );\n void ExecuteTrans( SfxRequest& rReq );\n void GetState( SfxItemSet& rSet );\n void GetClipState( SfxItemSet& rSet );\n\n void ExecuteAttr( SfxRequest &rReq );\n void GetAttrState( SfxItemSet& rSet );\n void ExecuteToggle( SfxRequest &rReq );\n\n BOOL ExecuteCharDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );\n BOOL ExecuteParaDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );\n\n void ExecuteExtra( SfxRequest &rReq );\n void ExecFormText(SfxRequest& rReq); \/\/ StarFontWork\n void GetFormTextState(SfxItemSet& rSet);\n\nprivate:\n void ExecuteGlobal( SfxRequest &rReq ); \/\/ von Execute gerufen fuer ganze Objekte\n void GetGlobalClipState( SfxItemSet& rSet );\n void ExecutePasteContents( SfxRequest &rReq );\n BOOL IsNoteEdit();\n};\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"#include \n\n\nstatic const String name(\"MCPP Information\");\nstatic const Word priority=1;\nstatic const String identifier(\"mcpp\");\nstatic const String help(\"Display information about mcpp.dll.\");\nstatic const String mcpp_banner(\"MINECRAFT++:\");\nstatic const String compiled_by_template(\"Compiled by {0} on {1}\");\n\n\nclass MCPPInfo : public Module, public InformationProvider {\n\n\n\tpublic:\n\t\n\t\n\t\tvirtual const String & Name () const noexcept override {\n\t\t\n\t\t\treturn name;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual Word Priority () const noexcept override {\n\t\t\n\t\t\treturn priority;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual void Install () override {\n\t\t\n\t\t\tInformation::Get().Add(this);\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual const String & Identifier () const noexcept override {\n\t\t\n\t\t\treturn identifier;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual const String & Help () const noexcept override {\n\t\t\n\t\t\treturn help;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual void Execute (ChatMessage & message) const override {\n\t\t\n\t\t\tmessage\t<<\tChatStyle::Bold\n\t\t\t\t\t<<\tmcpp_banner\n\t\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t\t<<\tNewline\n\t\t\t\t\t<<\tString::Format(\n\t\t\t\t\t\t\tcompiled_by_template,\n\t\t\t\t\t\t\tServer::Get().CompiledWith(),\n\t\t\t\t\t\t\tServer::Get().BuildDate()\n\t\t\t\t\t\t);\n\t\t\n\t\t}\n\n\n};\n\n\nstatic Nullable module;\n\n\nextern \"C\" {\n\n\n\tModule * Load () {\n\t\n\t\tif (module.IsNull()) module.Construct();\n\t\t\n\t\treturn &(*module);\n\t\n\t}\n\t\n\t\n\tvoid Unload () {\n\t\n\t\tmodule.Destroy();\n\t\n\t}\n\n\n}\nMCPP Info Improvements#include \n#include \n\n\nusing namespace MCPP;\n\n\nstatic const String name(\"MCPP Information\");\nstatic const Word priority=1;\nstatic const String identifier(\"mcpp\");\nstatic const String help(\"Display information about mcpp.dll.\");\nstatic const String mcpp_banner(\"MINECRAFT++:\");\nstatic const String compiled_by_template(\"Compiled by {0} on {1}\");\nstatic const String minecraft_compat(\"Compatible with Minecraft {0} (protocol version {1})\");\nstatic const String version_template(\"{0}.{1}.{2}\");\n\n\nclass MCPPInfo : public Module, public InformationProvider {\n\n\n\tpublic:\n\t\n\t\n\t\tvirtual const String & Name () const noexcept override {\n\t\t\n\t\t\treturn name;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual Word Priority () const noexcept override {\n\t\t\n\t\t\treturn priority;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual void Install () override {\n\t\t\n\t\t\tInformation::Get().Add(this);\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual const String & Identifier () const noexcept override {\n\t\t\n\t\t\treturn identifier;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual const String & Help () const noexcept override {\n\t\t\n\t\t\treturn help;\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\tvirtual void Execute (ChatMessage & message) const override {\n\t\t\n\t\t\tmessage\t<<\tChatStyle::Bold\n\t\t\t\t\t<<\tmcpp_banner\n\t\t\t\t\t<<\tChatFormat::Pop\n\t\t\t\t\t<<\tNewline\n\t\t\t\t\t<<\tString::Format(\n\t\t\t\t\t\t\tcompiled_by_template,\n\t\t\t\t\t\t\tServer::Get().CompiledWith(),\n\t\t\t\t\t\t\tServer::Get().BuildDate()\n\t\t\t\t\t\t)\n\t\t\t\t\t<<\tNewline\n\t\t\t\t\t<<\tString::Format(\n\t\t\t\t\t\t\tminecraft_compat,\n\t\t\t\t\t\t\tString::Format(\n\t\t\t\t\t\t\t\tversion_template,\n\t\t\t\t\t\t\t\tMinecraftMajorVersion,\n\t\t\t\t\t\t\t\tMinecraftMinorVersion,\n\t\t\t\t\t\t\t\tMinecraftSubminorVersion\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tProtocolVersion\n\t\t\t\t\t\t);\n\t\t\n\t\t}\n\n\n};\n\n\nstatic Nullable module;\n\n\nextern \"C\" {\n\n\n\tModule * Load () {\n\t\n\t\tif (module.IsNull()) module.Construct();\n\t\t\n\t\treturn &(*module);\n\t\n\t}\n\t\n\t\n\tvoid Unload () {\n\t\n\t\tmodule.Destroy();\n\t\n\t}\n\n\n}\n<|endoftext|>"} {"text":"#include \"parser.hpp\"\n\n#include \n#include \n\nnamespace LightGBM {\n\nvoid GetStatistic(const char* str, int* comma_cnt, int* tab_cnt, int* colon_cnt) {\n *comma_cnt = 0;\n *tab_cnt = 0;\n *colon_cnt = 0;\n for (int i = 0; str[i] != '\\0'; ++i) {\n if (str[i] == ',') {\n ++(*comma_cnt);\n } else if (str[i] == '\\t') {\n ++(*tab_cnt);\n } else if (str[i] == ':') {\n ++(*colon_cnt);\n }\n }\n}\n\nbool CheckHasLabelForLibsvm(std::string& str) {\n str = Common::Trim(str);\n auto pos_space = str.find_first_of(\" \\f\\n\\r\\t\\v\");\n auto pos_colon = str.find_first_of(\":\");\n if (pos_colon == std::string::npos || pos_colon > pos_space) {\n return true;\n } else {\n return false;\n }\n}\n\nbool CheckHasLabelForTSV(std::string& str, int num_features) {\n str = Common::Trim(str);\n auto tokens = Common::Split(str.c_str(), '\\t');\n if (tokens.size() == num_features) {\n return false;\n } else {\n return true;\n }\n}\n\nbool CheckHasLabelForCSV(std::string& str, int num_features) {\n str = Common::Trim(str);\n auto tokens = Common::Split(str.c_str(), ',');\n if (tokens.size() == num_features) {\n return false;\n } else {\n return true;\n }\n}\n\nParser* Parser::CreateParser(const char* filename, int num_features, bool* has_label) {\n std::ifstream tmp_file;\n tmp_file.open(filename);\n if (!tmp_file.is_open()) {\n Log::Stderr(\"Data file: %s doesn't exist\", filename);\n }\n std::string line1, line2;\n if (!tmp_file.eof()) {\n std::getline(tmp_file, line1);\n } else {\n Log::Stderr(\"Data file: %s at least should have one line\", filename);\n }\n if (!tmp_file.eof()) {\n std::getline(tmp_file, line2);\n } else {\n Log::Stdout(\"Data file: %s only have one line\", filename);\n }\n tmp_file.close();\n int comma_cnt = 0, comma_cnt2 = 0;\n int tab_cnt = 0, tab_cnt2 = 0;\n int colon_cnt = 0, colon_cnt2 = 0;\n \/\/ Get some statistic from 2 line\n GetStatistic(line1.c_str(), &comma_cnt, &tab_cnt, &colon_cnt);\n GetStatistic(line2.c_str(), &comma_cnt2, &tab_cnt2, &colon_cnt2);\n Parser* ret = nullptr;\n if (line2.size() == 0) {\n \/\/ if only have one line on file\n if (colon_cnt > 0) {\n ret = new LibSVMParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForLibsvm(line1);\n }\n } else if (tab_cnt > 0) {\n ret = new TSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForTSV(line1, num_features);\n }\n } else if (comma_cnt > 0) {\n ret = new CSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForCSV(line1, num_features);\n }\n } \n } else {\n if (colon_cnt > 0 || colon_cnt2 > 0) {\n ret = new LibSVMParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForLibsvm(line1);\n }\n }\n else if (tab_cnt == tab_cnt2 && tab_cnt > 0) {\n ret = new TSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForTSV(line1, num_features);\n }\n } else if (comma_cnt == comma_cnt2 && comma_cnt > 0) {\n ret = new CSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForCSV(line1, num_features);\n }\n }\n }\n return ret;\n}\n\n} \/\/ namespace LightGBM\nwarning fixed#include \"parser.hpp\"\n\n#include \n#include \n\nnamespace LightGBM {\n\nvoid GetStatistic(const char* str, int* comma_cnt, int* tab_cnt, int* colon_cnt) {\n *comma_cnt = 0;\n *tab_cnt = 0;\n *colon_cnt = 0;\n for (int i = 0; str[i] != '\\0'; ++i) {\n if (str[i] == ',') {\n ++(*comma_cnt);\n } else if (str[i] == '\\t') {\n ++(*tab_cnt);\n } else if (str[i] == ':') {\n ++(*colon_cnt);\n }\n }\n}\n\nbool CheckHasLabelForLibsvm(std::string& str) {\n str = Common::Trim(str);\n auto pos_space = str.find_first_of(\" \\f\\n\\r\\t\\v\");\n auto pos_colon = str.find_first_of(\":\");\n if (pos_colon == std::string::npos || pos_colon > pos_space) {\n return true;\n } else {\n return false;\n }\n}\n\nbool CheckHasLabelForTSV(std::string& str, int num_features) {\n str = Common::Trim(str);\n auto tokens = Common::Split(str.c_str(), '\\t');\n if (static_cast(tokens.size()) == num_features) {\n return false;\n } else {\n return true;\n }\n}\n\nbool CheckHasLabelForCSV(std::string& str, int num_features) {\n str = Common::Trim(str);\n auto tokens = Common::Split(str.c_str(), ',');\n if (static_cast(tokens.size()) == num_features) {\n return false;\n } else {\n return true;\n }\n}\n\nParser* Parser::CreateParser(const char* filename, int num_features, bool* has_label) {\n std::ifstream tmp_file;\n tmp_file.open(filename);\n if (!tmp_file.is_open()) {\n Log::Stderr(\"Data file: %s doesn't exist\", filename);\n }\n std::string line1, line2;\n if (!tmp_file.eof()) {\n std::getline(tmp_file, line1);\n } else {\n Log::Stderr(\"Data file: %s at least should have one line\", filename);\n }\n if (!tmp_file.eof()) {\n std::getline(tmp_file, line2);\n } else {\n Log::Stdout(\"Data file: %s only have one line\", filename);\n }\n tmp_file.close();\n int comma_cnt = 0, comma_cnt2 = 0;\n int tab_cnt = 0, tab_cnt2 = 0;\n int colon_cnt = 0, colon_cnt2 = 0;\n \/\/ Get some statistic from 2 line\n GetStatistic(line1.c_str(), &comma_cnt, &tab_cnt, &colon_cnt);\n GetStatistic(line2.c_str(), &comma_cnt2, &tab_cnt2, &colon_cnt2);\n Parser* ret = nullptr;\n if (line2.size() == 0) {\n \/\/ if only have one line on file\n if (colon_cnt > 0) {\n ret = new LibSVMParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForLibsvm(line1);\n }\n } else if (tab_cnt > 0) {\n ret = new TSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForTSV(line1, num_features);\n }\n } else if (comma_cnt > 0) {\n ret = new CSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForCSV(line1, num_features);\n }\n } \n } else {\n if (colon_cnt > 0 || colon_cnt2 > 0) {\n ret = new LibSVMParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForLibsvm(line1);\n }\n }\n else if (tab_cnt == tab_cnt2 && tab_cnt > 0) {\n ret = new TSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForTSV(line1, num_features);\n }\n } else if (comma_cnt == comma_cnt2 && comma_cnt > 0) {\n ret = new CSVParser();\n if (num_features > 0 && has_label != nullptr) {\n *has_label = CheckHasLabelForCSV(line1, num_features);\n }\n }\n }\n return ret;\n}\n\n} \/\/ namespace LightGBM\n<|endoftext|>"} {"text":"\/**\n *\n * @file grid.cpp\n * @brief Implementation of Grid class functions\n * @author Vontrelle Collins\n * @copyright MIT License\n *\n **\/\n\n#include \n#include \n#include \n#include \n#include \"grid.hpp\"\n\nGrid::Grid() : gridSize(20) {\n\n for(int i=0; i startIndex(0, (N\/2)-1);\n std::uniform_int_distribution destinationIndex(N\/2, N);\n\n iStart = startIndex(mt);\n iDestination = destinationIndex(mt);\n\n grid[iStart].setStatus(START);\n grid[iDestination].setStatus(DESTINATION);\n\n unsigned long index {0};\n while(index<=N) {\n grid[index].calH(grid[iDestination]);\n ++index;\n }\n}\n\n\nvoid Grid::printGrid() {\n\n int colCount {1};\n for(auto point : grid) {\n\n switch(point.getStatus()) {\n\n case START:\n std::cout << \"O \";\n break;\n\n case DESTINATION:\n std::cout << \"X \";\n break;\n\n case PATH:\n std::cout << \"# \";\n break;\n\n default:\n std::cout << \"- \";\n }\n \n\n if(colCount%gridSize == 0)\n std::cout << std::endl;\n\n ++colCount;\n\n }\n}\n\nint Grid::findIndex(GridPoint &p) {\n\n int index {0};\n int i {0};\n for(auto gp : grid) {\n if(gp == p)\n index = i;\n\n ++i;\n }\n\n return index;\n}\n\nvoid Grid::findPath() {\n\n closedList.push_back(std::make_shared(grid[iStart]));\n bool pathfound {false};\n \n GridPoint x(1,0);\n GridPoint y(0,1);\n\n\n std::shared_ptr p;\n int index {15};\n int ii {0};\n\n do {\n int i = findIndex(*closedList[ii]);\n p = std::make_shared(grid[i]);\n \n std::vector children {GridPoint(*p+x), GridPoint(*p-x),GridPoint(*p+y), GridPoint(*p-y)};\n\n std::shared_ptr e = std::make_shared(grid[findIndex(children[0])]);\n e->calF();\n openList.push_back(e);\n\n std::shared_ptr w = std::make_shared(grid[findIndex(children[1])]);\n w->calF();\n openList.push_back(w);\n \n std::shared_ptr n = std::make_shared(grid[findIndex(children[2])]);\n n->calF();\n openList.push_back(n);\n \n std::shared_ptr s = std::make_shared(grid[findIndex(children[3])]);\n s->calF();\n openList.push_back(s);\n\n std::sort (openList.begin(), openList.end(), myFunc);\n\n for(auto point : openList) {\n if(point->getStatus() == DESTINATION)\n pathfound = true;\n }\n\n\n if(pathfound == false) {\n grid[findIndex(*openList[0])].setStatus(PATH);\n closedList.push_back(openList[0]);\n openList.erase(openList.begin());\n }\n \n ++ii;\n --index;\n\n\n }while(!pathfound);\n \n\n}\n\n\nbool myFunc(std::shared_ptr a, std::shared_ptr b) {\n return (a->getF() < b->getF());\n}\n\n\n\nTask 4 update to Grid class\/**\n *\n * @file grid.cpp\n * @brief Implementation of Grid class functions\n * @author Vontrelle Collins\n * @copyright MIT License\n *\n **\/\n\n#include \n#include \n#include \n#include \n#include \"grid.hpp\"\n\nGrid::Grid() : gridSize(20) {\n\n for(int i=0; i startIndex(0, (N\/2)-1);\n std::uniform_int_distribution destinationIndex(N\/2, N);\n\n iStart = startIndex(mt);\n iDestination = destinationIndex(mt);\n\n grid[iStart].setStatus(START);\n grid[iDestination].setStatus(DESTINATION);\n\n unsigned long index {0};\n while(index<=N) {\n grid[index].calH(grid[iDestination]);\n ++index;\n }\n}\n\n\nvoid Grid::printGrid() {\n\n int colCount {1};\n for(auto point : grid) {\n\n switch(point.getStatus()) {\n\n case START:\n std::cout << \"O \";\n break;\n\n case DESTINATION:\n std::cout << \"X \";\n break;\n\n case PATH:\n std::cout << \"# \";\n break;\n\n default:\n std::cout << \"- \";\n }\n \n\n if(colCount%gridSize == 0)\n std::cout << std::endl;\n\n ++colCount;\n\n }\n}\n\nint Grid::findIndex(GridPoint &p) {\n\n int index {0};\n int i {0};\n for(auto gp : grid) {\n if(gp == p)\n index = i;\n\n ++i;\n }\n\n return index;\n}\n\nvoid Grid::findPath() {\n\n closedList.push_back(std::make_shared(grid[iStart]));\n bool pathfound {false};\n \n GridPoint x(1,0);\n GridPoint y(0,1);\n\n\n std::shared_ptr p;\n int index {15};\n int ii {0};\n\n do {\n int i = findIndex(*closedList[ii]);\n p = std::make_shared(grid[i]);\n \n std::vector children {GridPoint(*p+x), GridPoint(*p-x),GridPoint(*p+y), GridPoint(*p-y)};\n\n std::shared_ptr e = std::make_shared(grid[findIndex(children[0])]);\n e->calF();\n\n if(!(findIndex(*e) < 0))\n openList.push_back(e);\n\n std::shared_ptr w = std::make_shared(grid[findIndex(children[1])]);\n w->calF();\n\n if(!(findIndex(*w) < 0))\n openList.push_back(w);\n\n \n std::shared_ptr n = std::make_shared(grid[findIndex(children[2])]);\n n->calF();\n \n if(!(findIndex(*n) < 0))\n openList.push_back(n);\n \n std::shared_ptr s = std::make_shared(grid[findIndex(children[3])]);\n s->calF();\n \n if(!(findIndex(*\n\n s) < 0))\n openList.push_back(s);\n\n std::sort (openList.begin(), openList.end(), myFunc);\n\n for(auto point : openList) {\n if(point->getStatus() == DESTINATION)\n pathfound = true;\n }\n\n\n if(pathfound == false) {\n grid[findIndex(*openList[0])].setStatus(PATH);\n closedList.push_back(openList[0]);\n openList.erase(openList.begin());\n }\n \n ++ii;\n --index;\n\n\n }while(!pathfound);\n \n\n}\n\n\nbool myFunc(std::shared_ptr a, std::shared_ptr b) {\n return (a->getF() < b->getF());\n}\n\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core\/core.h\"\n#include \"session\/session.h\"\n#include \"api\/plugin_instance.h\"\n#include \"core\/plugin_handler.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void* dummyCreateInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)\n{\n (void)uiFuncs;\n (void)serviceFunc;\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void dummyDestroyInstance(void* userData)\n{\n (void)userData;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int dummyUpdate(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents)\n{\n (void)userData;\n (void)uiFuncs;\n (void)inEvents;\n (void)outEvents;\n\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic PDViewPlugin s_dummyPlugin =\n{\n \"DummyPlugin\",\n dummyCreateInstance,\n dummyDestroyInstance,\n dummyUpdate,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic PluginData s_pluginData = { &s_dummyPlugin, PD_VIEW_API_VERSION, \"\", 0 };\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Session* createSession()\n{\n struct Session* session = Session_create();\n\n assert_non_null(session);\n\n return session;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void create_null_session(void** state)\n{\n (void)state;\n\n struct Session* session = createSession();\n\n Session_destroy(session);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void session_add_plugins(void** state)\n{\n (void)state;\n int pluginCount = 0;\n\n struct Session* session = createSession();\n\n struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);\n\n Session_addViewPlugin(session, i0);\n Session_addViewPlugin(session, i1);\n Session_addViewPlugin(session, i2);\n\n struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);\n\n assert_true(pluginCount == 3);\n\n assert_true(instances[0] == i0);\n assert_true(instances[1] == i1);\n assert_true(instances[2] == i2);\n\n Session_destroy(session);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void session_delete_plugins(void** state)\n{\n (void)state;\n int pluginCount = 0;\n\n struct Session* session = createSession();\n\n struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);\n\n Session_addViewPlugin(session, i0);\n Session_addViewPlugin(session, i1);\n Session_addViewPlugin(session, i2);\n\n \/\/ Delete one of the plugins\n\n assert_true(Session_removeViewPlugin(session, i1) == true);\n assert_true(Session_removeViewPlugin(session, i1) == false);\n\n struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);\n\n assert_true(pluginCount == 2);\n assert_true(instances[0] == i0);\n assert_true(instances[1] == i2);\n\n Session_destroy(session);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main()\n{\n const UnitTest tests[] =\n {\n unit_test(create_null_session),\n unit_test(session_add_plugins),\n unit_test(session_delete_plugins),\n };\n\n return run_tests(tests);\n}\nFixed crashing unit-test#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core\/core.h\"\n#include \"session\/session.h\"\n#include \"api\/plugin_instance.h\"\n#include \"core\/plugin_handler.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void* dummyCreateInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)\n{\n (void)uiFuncs;\n (void)serviceFunc;\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void dummyDestroyInstance(void* userData)\n{\n (void)userData;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int dummyUpdate(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents)\n{\n (void)userData;\n (void)uiFuncs;\n (void)inEvents;\n (void)outEvents;\n\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic PDViewPlugin s_dummyPlugin =\n{\n \"DummyPlugin\",\n dummyCreateInstance,\n dummyDestroyInstance,\n dummyUpdate,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic PluginData s_pluginData = { &s_dummyPlugin, PD_VIEW_API_VERSION, \"\", 0 };\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Session* createSession()\n{\n struct Session* session = Session_create();\n\n assert_non_null(session);\n\n return session;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void create_null_session(void** state)\n{\n (void)state;\n\n struct Session* session = createSession();\n\n Session_destroy(session);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void session_add_plugins(void** state)\n{\n (void)state;\n int pluginCount = 0;\n\n struct Session* session = createSession();\n\n struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);\n\n Session_addViewPlugin(session, i0);\n Session_addViewPlugin(session, i1);\n Session_addViewPlugin(session, i2);\n\n struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);\n\n assert_true(pluginCount == 3);\n\n assert_true(instances[0] == i0);\n assert_true(instances[1] == i1);\n assert_true(instances[2] == i2);\n\n Session_destroy(session);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void session_delete_plugins(void** state)\n{\n (void)state;\n int pluginCount = 0;\n\n struct Session* session = createSession();\n\n struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);\n struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);\n\n Session_addViewPlugin(session, i0);\n Session_addViewPlugin(session, i1);\n Session_addViewPlugin(session, i2);\n\n \/\/ Delete one of the plugins\n\n assert_true(Session_removeViewPlugin(session, i1) == true);\n assert_true(Session_removeViewPlugin(session, i1) == false);\n\n struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);\n\n assert_true(pluginCount == 2);\n assert_true(instances[0] == i0);\n assert_true(instances[1] == i2);\n\n Session_destroy(session);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main()\n{\n\tCore_init();\n\n const UnitTest tests[] =\n {\n unit_test(create_null_session),\n unit_test(session_add_plugins),\n unit_test(session_delete_plugins),\n };\n\n return run_tests(tests);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define\tMAX 1000\n\nvoid PrintLine( int Y, char *cFormat, ... )\n{\n\tCOORD Pos = {0, Y};\t\tDWORD cCharsWritten;\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\tSetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);\n\tGetConsoleScreenBufferInfo( GetStdHandle(STD_OUTPUT_HANDLE), &csbi );\n\tFillConsoleOutputCharacter(GetStdHandle(STD_OUTPUT_HANDLE), (TCHAR) ' ', csbi.dwSize.X, Pos, &cCharsWritten );\n \n\tstatic char buffer[1024];\n\tva_list\tvlList;\n\tva_start( vlList, cFormat );\n\t_vsnprintf( buffer, 1024, cFormat, vlList );\n\tprintf( buffer );\n\tva_end( vlList );\n}\n\nint Selection(int *selec){\n\tint num, numID;\n\tint\tiTick = GetTickCount();\n\n\tfor(int i=MAX; i>0; i--){\n\t\tnum = selec[0];\n\t\tnumID = 0;\n\n\t\tfor (int j = 0 ; j < i ; j++){\n\t\t\tif(selec[j] > num){\n\t\t\t\tnum = selec[j];\n\t\t\t\tnumID = j;\n\t\t\t}\n\t\t}\n\t\tselec[numID] = selec[i-1];\n\t\tselec[i-1] = num;\n\t}\n\t\n\treturn GetTickCount() - iTick;\n}\n\nint main()\n{\n\tint\tselec[MAX];\n\tint iTime;\n\n\tofstream fr;\n\tfr.open(\"randomData.txt\");\n\n\tsrand((unsigned int)time(NULL));\n\tfor(int i=0; i [Time(ms)::Calc...]\\n\", MAX );\n\tiTime = Selection(selec);\n\tPrintLine( 0, \"Selection Sort [Data::%8d] -----> [Time(ms)::%8d]\\n\", MAX, iTime );\n\n\tofstream fs;\n\tfs.open(\"selectionSort.txt\");\n\n\tfor(int i=0; i1000 -> 100#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define\tMAX 100\n\nvoid PrintLine( int Y, char *cFormat, ... )\n{\n\tCOORD Pos = {0, Y};\t\tDWORD cCharsWritten;\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\tSetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);\n\tGetConsoleScreenBufferInfo( GetStdHandle(STD_OUTPUT_HANDLE), &csbi );\n\tFillConsoleOutputCharacter(GetStdHandle(STD_OUTPUT_HANDLE), (TCHAR) ' ', csbi.dwSize.X, Pos, &cCharsWritten );\n \n\tstatic char buffer[1024];\n\tva_list\tvlList;\n\tva_start( vlList, cFormat );\n\t_vsnprintf( buffer, 1024, cFormat, vlList );\n\tprintf( buffer );\n\tva_end( vlList );\n}\n\nint Selection(int *selec){\n\tint num, numID;\n\tint\tiTick = GetTickCount();\n\n\tfor(int i=MAX; i>0; i--){\n\t\tnum = selec[0];\n\t\tnumID = 0;\n\n\t\tfor (int j = 0 ; j < i ; j++){\n\t\t\tif(selec[j] > num){\n\t\t\t\tnum = selec[j];\n\t\t\t\tnumID = j;\n\t\t\t}\n\t\t}\n\t\tselec[numID] = selec[i-1];\n\t\tselec[i-1] = num;\n\t}\n\t\n\treturn GetTickCount() - iTick;\n}\n\nint main()\n{\n\tint\tselec[MAX];\n\tint iTime;\n\n\tofstream fr;\n\tfr.open(\"randomData.txt\");\n\n\tsrand((unsigned int)time(NULL));\n\tfor(int i=0; i [Time(ms)::Calc...]\\n\", MAX );\n\tiTime = Selection(selec);\n\tPrintLine( 0, \"Selection Sort [Data::%8d] -----> [Time(ms)::%8d]\\n\", MAX, iTime );\n\n\tofstream fs;\n\tfs.open(\"selectionSort.txt\");\n\n\tfor(int i=0; i"} {"text":"#include \"libyaml_utils.h\"\n#include \"logger.h\"\n\n\/\/ ---------------------------------------------------------------------------------\n\/\/ ------------------------------- libyaml test code -------------------------------\n\/\/ ---------------------------------------------------------------------------------\nnamespace\n{\n\nbool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode)\n{\n if (add_to_me != nullptr)\n {\n if (reference_character == mode_type::MAP_TYPE)\n {\n if (map_mode)\n {\n *add_to_me = mode_type::KEY_TYPE;\n }\n else\n {\n *add_to_me = mode_type::VALUE_TYPE;\n }\n return !map_mode;\n }\n else if (reference_character == mode_type::SEQUENCE_TYPE)\n {\n *add_to_me = mode_type::SEQUENCE_TYPE;\n }\n else\n {\n *add_to_me = mode_type::UNKNOWN_TYPE;\n }\n }\n return map_mode;\n}\n\nvoid addTag(YAML::Node* current_node, yaml_char_t* tag)\n{\n if (current_node != nullptr)\n {\n if (tag)\n {\n std::string temp_tag_translator = ((char*)tag);\n\n current_node->SetTag(temp_tag_translator); \n }\n else if(current_node->Tag().empty())\n {\n current_node->SetTag(\"?\");\n }\n }\n}\n\nvoid addToNode\n (YAML::Node* addToMe, YAML::Node* add_me, std::stack* key_stack, \n const mode_type* tracking_current_type, yaml_char_t* tag)\n{\n addTag(add_me, tag);\n \n if (tracking_current_type != nullptr && addToMe != nullptr)\n {\n if (*tracking_current_type == mode_type::SEQUENCE_TYPE && addToMe->IsSequence())\n {\n TEST_PPRINT(\"squ type\\n\")\n addToMe->push_back(*add_me);\n }\n else if (*tracking_current_type == mode_type::KEY_TYPE && addToMe->IsMap())\n {\n TEST_PPRINT(\"key type\\n\")\n key_stack->push(*add_me);\n (*addToMe)[*add_me];\n }\n else if (*tracking_current_type == mode_type::VALUE_TYPE && addToMe->IsMap())\n {\n TEST_PPRINT(\"map type\\n\")\n if (!key_stack->empty())\n {\n (*addToMe)[key_stack->top()] = *add_me;\n key_stack->pop();\n }\n }\n else\n {\n TEST_PPRINT(\"? type\\n\")\n }\n }\n}\n\nbool endEventAddition\n (std::vector* libyaml_local_output, std::stack* mode_stack, \n std::stack* map_mode_stack, bool map_mode, std::stack* key_stack)\n{\n if (libyaml_local_output->size() > 1 && mode_stack->size() > 1)\n {\n mode_stack->pop();\n\n if (mode_stack->top() == mode_type::MAP_TYPE && !map_mode_stack->empty())\n {\n map_mode = map_mode_stack->top();\n map_mode_stack->pop();\n }\n mode_type temp_position_info;\n\n if (mode_stack->empty())\n {\n return map_mode;\n }\n positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode);\n\n YAML::Node temp_node = libyaml_local_output->back();\n\n libyaml_local_output->pop_back();\n\n addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr);\n }\n return map_mode;\n}\n\nvoid restartVariables (std::stack* key_stack, \n std::stack* mode_stack, std::stack* map_mode_stack, \n std::vector* libyaml_local_output, std::vector* libyaml_final_output,\n bool* map_mode, std::map* anchor_map)\n{\n while (!key_stack->empty())\n {\n key_stack->pop();\n }\n\n while (!mode_stack->empty())\n {\n mode_stack->pop();\n }\n mode_stack->push(mode_type::UNKNOWN_TYPE);\n\n while (!map_mode_stack->empty())\n {\n map_mode_stack->pop();\n }\n\n if (!libyaml_local_output->empty())\n {\n libyaml_final_output->push_back(libyaml_local_output->back());\n }\n\n libyaml_local_output->clear();\n\n *map_mode = true;\n\n anchor_map->clear();\n}\n\nstd::string parseLibyaml(const std::string name_of_file, std::string* error_message_container)\n{\n return name_of_file;\n}\n}\n\nstd::vector* libyaml_parsing::parseLibyaml\n (const uint8_t* input, size_t input_size, std::unique_ptr* error_message_container)\n{\n yaml_parser_t parser;\n yaml_event_t event;\n\n std::vector libyaml_local_output;\n\n std::vector* libyaml_final_output = new std::vector;\n\n std::stack key_stack;\n\n std::stack mode_stack;\n\n mode_stack.push(mode_type::UNKNOWN_TYPE);\n\n std::stack map_mode_stack;\n\n bool map_mode = true;\n \n std::map anchor_map;\n\n if (!yaml_parser_initialize(&parser)) \n {\n TEST_PPRINT(\"ERROR: Failed to initialize\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return libyaml_final_output;\n }\n\n yaml_parser_set_input_string(&parser, input, input_size);\n \n while (true) \n {\n\n YAML::Node new_node;\n\n yaml_event_type_t type;\n\n mode_type tracking_current_type;\n\n if (!yaml_parser_parse(&parser, &event)) \n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Bad parsing\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return libyaml_final_output;\n }\n type = event.type;\n \n switch (type)\n {\n case YAML_STREAM_END_EVENT:\n\n TEST_PPRINT(\"STR-\\n\");\n\n break;\n case YAML_DOCUMENT_END_EVENT:\n\n TEST_PPRINT(\"DOC-\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break; \n case YAML_DOCUMENT_START_EVENT:\n\n TEST_PPRINT(\"DOC+\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break;\n\n case YAML_MAPPING_END_EVENT:\n\n TEST_PPRINT(\"MAP-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_SEQUENCE_END_EVENT:\n\n TEST_PPRINT(\"SQU-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_MAPPING_START_EVENT:\n\n TEST_PPRINT(\"MAP+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (!mode_stack.empty())\n {\n positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n }\n\n mode_stack.push(mode_type::MAP_TYPE);\n map_mode = true;\n\n if (event.data.mapping_start.anchor)\n {\n TEST_PPRINT(\"ANCH-map+\\n\");\n anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n case YAML_SEQUENCE_START_EVENT:\n\n TEST_PPRINT(\"SQU+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (!mode_stack.empty())\n {\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n }\n\n mode_stack.push(mode_type::SEQUENCE_TYPE);\n\n if (event.data.sequence_start.anchor)\n {\n TEST_PPRINT(\"ANCH-squ+\\n\");\n\n anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n\n case YAML_SCALAR_EVENT:\n {\n TEST_PPRINT(\"SCL\\n\");\n\n YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length));\n addTag(&add_me, event.data.scalar.tag);\n\n if (event.data.scalar.anchor)\n {\n TEST_PPRINT(\"ANCH-scl\\n\");\n std::string temp_translator = ((char*)event.data.scalar.anchor);\n if (mode_stack.empty())\n {\n break;\n }\n\n if (event.data.scalar.value)\n {\n\n TEST_PPRINT(\"value\\n\");\n\n if(event.data.scalar.length != 0)\n {\n anchor_map[temp_translator] = add_me;\n \n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n\n }\n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n else\n {\n TEST_PPRINT(\"empty\\n\");\n if (mode_stack.top() == mode_type::SEQUENCE_TYPE)\n {\n TEST_PPRINT(\"sequence\\n\");\n add_me = YAML::Node(YAML::NodeType::Null);\n\n if (!libyaml_local_output.empty())\n {\n if (libyaml_local_output.back().IsSequence())\n {\n libyaml_local_output.back().push_back(add_me);\n }\n }\n\n break;\n }\n\n mode_stack.pop();\n\n if (!mode_stack.empty())\n {\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n TEST_PPRINT(\"map\\n\");\n map_mode = map_mode_stack.top();\n map_mode_stack.pop();\n }\n\n if (!libyaml_local_output.empty())\n {\n libyaml_local_output.pop_back();\n }\n }\n else\n {\n libyaml_local_output.push_back(YAML::Node());\n }\n }\n }\n }\n else\n {\n TEST_PPRINT(\"normal\\n\");\n if (mode_stack.empty())\n {\n break;\n }\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (event.data.scalar.length <= 0 && !event.data.scalar.tag && \n event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE)\n {\n TEST_PPRINT(\"Begin from nothing\\n\");\n add_me = YAML::Node();\n }\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n } \n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n\n break;\n }\n case YAML_ALIAS_EVENT:\n {\n\n TEST_PPRINT(\"ALI\\n\");\n\n std::string temp_translator = ((char*) event.data.alias.anchor);\n \n if(anchor_map.find(temp_translator) != anchor_map.end())\n {\n\n if (mode_stack.empty()) \/\/ (new)\n {\n break;\n }\n\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator], \n &key_stack, &tracking_current_type, nullptr);\n }\n else\n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Missing anchor\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return libyaml_final_output;\n }\n break;\n }\n default: \n break;\n }\n\n yaml_event_delete(&event);\n\n if (type == YAML_STREAM_END_EVENT)\n {\n break;\n }\n\n }\n\n yaml_parser_delete(&parser);\n\n fflush(stdout);\n\n return libyaml_final_output;\n}removes legacy variables, and tighens up code#include \"libyaml_utils.h\"\n#include \"logger.h\"\n\n\/\/ ---------------------------------------------------------------------------------\n\/\/ ------------------------------- libyaml test code -------------------------------\n\/\/ ---------------------------------------------------------------------------------\nnamespace\n{\n\nbool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode)\n{\n if (add_to_me != nullptr)\n {\n if (reference_character == mode_type::MAP_TYPE)\n {\n if (map_mode)\n {\n *add_to_me = mode_type::KEY_TYPE;\n }\n else\n {\n *add_to_me = mode_type::VALUE_TYPE;\n }\n return !map_mode;\n }\n else if (reference_character == mode_type::SEQUENCE_TYPE)\n {\n *add_to_me = mode_type::SEQUENCE_TYPE;\n }\n else\n {\n *add_to_me = mode_type::UNKNOWN_TYPE;\n }\n }\n return map_mode;\n}\n\nvoid addTag(YAML::Node* current_node, yaml_char_t* tag)\n{\n if (current_node != nullptr)\n {\n if (tag)\n {\n std::string temp_tag_translator = ((char*)tag);\n\n current_node->SetTag(temp_tag_translator); \n }\n else if(current_node->Tag().empty())\n {\n current_node->SetTag(\"?\");\n }\n }\n}\n\nvoid addToNode\n (YAML::Node* addToMe, YAML::Node* add_me, std::stack* key_stack, \n const mode_type* tracking_current_type, yaml_char_t* tag)\n{\n addTag(add_me, tag);\n \n if (tracking_current_type != nullptr && addToMe != nullptr)\n {\n if (*tracking_current_type == mode_type::SEQUENCE_TYPE && addToMe->IsSequence())\n {\n TEST_PPRINT(\"squ type\\n\")\n addToMe->push_back(*add_me);\n }\n else if (*tracking_current_type == mode_type::KEY_TYPE && addToMe->IsMap())\n {\n TEST_PPRINT(\"key type\\n\")\n key_stack->push(*add_me);\n (*addToMe)[*add_me];\n }\n else if (*tracking_current_type == mode_type::VALUE_TYPE && addToMe->IsMap())\n {\n TEST_PPRINT(\"map type\\n\")\n if (!key_stack->empty())\n {\n (*addToMe)[key_stack->top()] = *add_me;\n key_stack->pop();\n }\n }\n else\n {\n TEST_PPRINT(\"? type\\n\")\n }\n }\n}\n\nbool endEventAddition\n (std::vector* libyaml_local_output, std::stack* mode_stack, \n std::stack* map_mode_stack, bool map_mode, std::stack* key_stack)\n{\n if (libyaml_local_output->size() > 1 && mode_stack->size() > 1)\n {\n mode_stack->pop();\n\n if (mode_stack->top() == mode_type::MAP_TYPE && !map_mode_stack->empty())\n {\n map_mode = map_mode_stack->top();\n map_mode_stack->pop();\n }\n mode_type temp_position_info;\n\n if (mode_stack->empty())\n {\n return map_mode;\n }\n positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode);\n\n YAML::Node temp_node = libyaml_local_output->back();\n\n libyaml_local_output->pop_back();\n\n addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr);\n }\n return map_mode;\n}\n\nvoid restartVariables (std::stack* key_stack,\n std::stack* mode_stack, std::stack* map_mode_stack,\n std::vector* libyaml_local_output, std::vector* libyaml_final_output,\n bool* map_mode, std::map* anchor_map)\n{\n while (!key_stack->empty())\n {\n key_stack->pop();\n }\n\n while (!mode_stack->empty())\n {\n mode_stack->pop();\n }\n mode_stack->push(mode_type::UNKNOWN_TYPE);\n\n while (!map_mode_stack->empty())\n {\n map_mode_stack->pop();\n }\n\n if (!libyaml_local_output->empty())\n {\n libyaml_final_output->push_back(libyaml_local_output->back());\n }\n\n libyaml_local_output->clear();\n\n *map_mode = true;\n\n anchor_map->clear();\n}\n\nstd::string parseLibyaml(const std::string name_of_file, std::string* error_message_container)\n{\n return name_of_file;\n}\n}\n\nstd::vector* libyaml_parsing::parseLibyaml\n (const uint8_t* input, size_t input_size, std::unique_ptr* error_message_container)\n{\n yaml_parser_t parser;\n yaml_event_t event;\n\n std::vector libyaml_local_output;\n\n std::vector* libyaml_final_output = new std::vector;\n\n std::stack key_stack;\n\n std::stack mode_stack;\n\n mode_stack.push(mode_type::UNKNOWN_TYPE);\n\n std::stack map_mode_stack;\n\n bool map_mode = true;\n \n std::map anchor_map;\n\n if (!yaml_parser_initialize(&parser)) \n {\n TEST_PPRINT(\"ERROR: Failed to initialize\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return libyaml_final_output;\n }\n\n yaml_parser_set_input_string(&parser, input, input_size);\n \n while (true) \n {\n yaml_event_type_t type;\n\n mode_type tracking_current_type;\n\n if (!yaml_parser_parse(&parser, &event))\n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Bad parsing\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return libyaml_final_output;\n }\n type = event.type;\n \n switch (type)\n {\n case YAML_STREAM_END_EVENT:\n TEST_PPRINT(\"STR-\\n\");\n\n break;\n case YAML_DOCUMENT_END_EVENT:\n TEST_PPRINT(\"DOC-\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break; \n case YAML_DOCUMENT_START_EVENT:\n TEST_PPRINT(\"DOC+\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break;\n\n case YAML_MAPPING_END_EVENT:\n TEST_PPRINT(\"MAP-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_SEQUENCE_END_EVENT:\n TEST_PPRINT(\"SQU-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_MAPPING_START_EVENT:\n TEST_PPRINT(\"MAP+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (!mode_stack.empty())\n {\n positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n }\n\n mode_stack.push(mode_type::MAP_TYPE);\n map_mode = true;\n\n if (event.data.mapping_start.anchor)\n {\n TEST_PPRINT(\"ANCH-map+\\n\");\n anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n case YAML_SEQUENCE_START_EVENT:\n TEST_PPRINT(\"SQU+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (!mode_stack.empty())\n {\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n }\n\n mode_stack.push(mode_type::SEQUENCE_TYPE);\n\n if (event.data.sequence_start.anchor)\n {\n TEST_PPRINT(\"ANCH-squ+\\n\");\n\n anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n\n case YAML_SCALAR_EVENT:\n {\n TEST_PPRINT(\"SCL\\n\");\n\n YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length));\n addTag(&add_me, event.data.scalar.tag);\n\n if (event.data.scalar.anchor)\n {\n TEST_PPRINT(\"ANCH-scl\\n\");\n std::string temp_translator = ((char*)event.data.scalar.anchor);\n if (mode_stack.empty())\n {\n break;\n }\n\n if (event.data.scalar.value)\n {\n TEST_PPRINT(\"value\\n\");\n\n if(event.data.scalar.length != 0)\n {\n anchor_map[temp_translator] = add_me;\n \n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n\n }\n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n else\n {\n TEST_PPRINT(\"empty\\n\");\n if (mode_stack.top() == mode_type::SEQUENCE_TYPE)\n {\n TEST_PPRINT(\"sequence\\n\");\n add_me = YAML::Node(YAML::NodeType::Null);\n\n if (!libyaml_local_output.empty())\n {\n if (libyaml_local_output.back().IsSequence())\n {\n libyaml_local_output.back().push_back(add_me);\n }\n }\n\n break;\n }\n\n mode_stack.pop();\n\n if (!mode_stack.empty())\n {\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n TEST_PPRINT(\"map\\n\");\n map_mode = map_mode_stack.top();\n map_mode_stack.pop();\n }\n\n if (!libyaml_local_output.empty())\n {\n libyaml_local_output.pop_back();\n }\n }\n else\n {\n libyaml_local_output.push_back(YAML::Node());\n }\n }\n }\n }\n else\n {\n TEST_PPRINT(\"normal\\n\");\n if (mode_stack.empty())\n {\n break;\n }\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (event.data.scalar.length <= 0 && !event.data.scalar.tag && \n event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE)\n {\n TEST_PPRINT(\"Begin from nothing\\n\");\n add_me = YAML::Node();\n }\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n } \n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n\n break;\n }\n case YAML_ALIAS_EVENT:\n {\n TEST_PPRINT(\"ALI\\n\");\n\n std::string temp_translator = ((char*) event.data.alias.anchor);\n \n if(anchor_map.find(temp_translator) != anchor_map.end())\n {\n\n if (mode_stack.empty()) \/\/ (new)\n {\n break;\n }\n\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator], \n &key_stack, &tracking_current_type, nullptr);\n }\n else\n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Missing anchor\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return libyaml_final_output;\n }\n break;\n }\n default: \n break;\n }\n\n yaml_event_delete(&event);\n\n if (type == YAML_STREAM_END_EVENT)\n {\n break;\n }\n\n }\n\n yaml_parser_delete(&parser);\n\n fflush(stdout);\n\n return libyaml_final_output;\n}<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------------\r\n\/\/ MurmurHash3 was written by Austin Appleby, and is placed in the public\r\n\/\/ domain. The author hereby disclaims copyright to this source code.\r\n\r\n\/\/ Note - The x86 and x64 versions do _not_ produce the same results, as the\r\n\/\/ algorithms are optimized for their respective platforms. You can still\r\n\/\/ compile and run any of them on any platform, but your performance with the\r\n\/\/ non-native version will be less than optimal.\r\n\r\n#include \"MurmurHash3.h\"\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Platform-specific functions and macros\r\n\r\n\/\/ Microsoft Visual Studio\r\n\r\n#if defined(_MSC_VER)\r\n\r\n#define FORCE_INLINE\t__forceinline\r\n\r\n#include \r\n\r\n#define ROTL64(x,y) _rotl64(x,y)\r\n\r\n#define BIG_CONSTANT(x) (x)\r\n\r\n\/\/ Other compilers\r\n\r\n#else\t\/\/ defined(_MSC_VER)\r\n\r\n#define\tFORCE_INLINE inline __attribute__((always_inline))\r\n\r\ninline uint64_t rotl64(uint64_t x, int8_t r)\r\n{\r\n\treturn (x << r) | (x >> (64 - r));\r\n}\r\n\r\n#define ROTL64(x,y)\trotl64(x,y)\r\n\r\n#define BIG_CONSTANT(x) (x##LLU)\r\n\r\n#endif \/\/ !defined(_MSC_VER)\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Block read - if your platform needs to do endian-swapping or can only\r\n\/\/ handle aligned reads, do the conversion here\r\n\r\nFORCE_INLINE uint64_t getblock64(const uint64_t * p, int i)\r\n{\r\n\treturn p[i];\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Finalization mix - force all bits of a hash block to avalanche\r\n\r\n\r\nFORCE_INLINE uint64_t fmix64(uint64_t k)\r\n{\r\n\tk ^= k >> 33;\r\n\tk *= BIG_CONSTANT(0xff51afd7ed558ccd);\r\n\tk ^= k >> 33;\r\n\tk *= BIG_CONSTANT(0xc4ceb9fe1a85ec53);\r\n\tk ^= k >> 33;\r\n\r\n\treturn k;\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\r\nvoid MurmurHash3_x64_128(const void * key, const int len,\r\n\tconst uint32_t seed, void * out)\r\n{\r\n\tconst uint8_t * data = (const uint8_t*)key;\r\n\tconst int nblocks = len \/ 16;\r\n\r\n\tuint64_t h1 = seed;\r\n\tuint64_t h2 = seed;\r\n\r\n\tconst uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5);\r\n\tconst uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f);\r\n\r\n\t\/\/----------\r\n\t\/\/ body\r\n\r\n\tconst uint64_t * blocks = (const uint64_t *)(data);\r\n\r\n\tfor (int i = 0; i < nblocks; i++)\r\n\t{\r\n\t\tuint64_t k1 = getblock64(blocks, i * 2 + 0);\r\n\t\tuint64_t k2 = getblock64(blocks, i * 2 + 1);\r\n\r\n\t\tk1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;\r\n\r\n\t\th1 = ROTL64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729;\r\n\r\n\t\tk2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;\r\n\r\n\t\th2 = ROTL64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5;\r\n\t}\r\n\r\n\t\/\/----------\r\n\t\/\/ tail\r\n\r\n\tconst uint8_t * tail = (const uint8_t*)(data + nblocks * 16);\r\n\r\n\tuint64_t k1 = 0;\r\n\tuint64_t k2 = 0;\r\n\r\n\tswitch (len & 15)\r\n\t{\r\n\tcase 15: k2 ^= ((uint64_t)tail[14]) << 48;\r\n\tcase 14: k2 ^= ((uint64_t)tail[13]) << 40;\r\n\tcase 13: k2 ^= ((uint64_t)tail[12]) << 32;\r\n\tcase 12: k2 ^= ((uint64_t)tail[11]) << 24;\r\n\tcase 11: k2 ^= ((uint64_t)tail[10]) << 16;\r\n\tcase 10: k2 ^= ((uint64_t)tail[9]) << 8;\r\n\tcase 9: k2 ^= ((uint64_t)tail[8]) << 0;\r\n\t\tk2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;\r\n\r\n\tcase 8: k1 ^= ((uint64_t)tail[7]) << 56;\r\n\tcase 7: k1 ^= ((uint64_t)tail[6]) << 48;\r\n\tcase 6: k1 ^= ((uint64_t)tail[5]) << 40;\r\n\tcase 5: k1 ^= ((uint64_t)tail[4]) << 32;\r\n\tcase 4: k1 ^= ((uint64_t)tail[3]) << 24;\r\n\tcase 3: k1 ^= ((uint64_t)tail[2]) << 16;\r\n\tcase 2: k1 ^= ((uint64_t)tail[1]) << 8;\r\n\tcase 1: k1 ^= ((uint64_t)tail[0]) << 0;\r\n\t\tk1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;\r\n\t};\r\n\r\n\t\/\/----------\r\n\t\/\/ finalization\r\n\r\n\th1 ^= len; h2 ^= len;\r\n\r\n\th1 += h2;\r\n\th2 += h1;\r\n\r\n\th1 = fmix64(h1);\r\n\th2 = fmix64(h2);\r\n\r\n\th1 += h2;\r\n\th2 += h1;\r\n\r\n\t((uint64_t*)out)[0] = h1;\r\n\t((uint64_t*)out)[1] = h2;\r\n}\r\n\r\nstd::array MurmurHash3_x64_128(const void * key, int len)\r\n{\r\n\tstd::array hash;\r\n\tMurmurHash3_x64_128(key, len, 104729, hash.data());\r\n\r\n\treturn hash;\r\n}\r\n\r\nuint64_t MurmurHash3_x64_64(const void * key, int len)\r\n{\r\n\tuint64_t hash[2];\r\n\tMurmurHash3_x64_128(key, len, 104729, hash);\r\n\r\n\treturn hash[0] ^ hash[1];\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\r\nLinux compilation fixed\/\/-----------------------------------------------------------------------------\r\n\/\/ MurmurHash3 was written by Austin Appleby, and is placed in the public\r\n\/\/ domain. The author hereby disclaims copyright to this source code.\r\n\r\n\/\/ Note - The x86 and x64 versions do _not_ produce the same results, as the\r\n\/\/ algorithms are optimized for their respective platforms. You can still\r\n\/\/ compile and run any of them on any platform, but your performance with the\r\n\/\/ non-native version will be less than optimal.\r\n\r\n#include \"murmurhash3.h\"\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Platform-specific functions and macros\r\n\r\n\/\/ Microsoft Visual Studio\r\n\r\n#if defined(_MSC_VER)\r\n\r\n#define FORCE_INLINE\t__forceinline\r\n\r\n#include \r\n\r\n#define ROTL64(x,y) _rotl64(x,y)\r\n\r\n#define BIG_CONSTANT(x) (x)\r\n\r\n\/\/ Other compilers\r\n\r\n#else\t\/\/ defined(_MSC_VER)\r\n\r\n#define\tFORCE_INLINE inline __attribute__((always_inline))\r\n\r\ninline uint64_t rotl64(uint64_t x, int8_t r)\r\n{\r\n\treturn (x << r) | (x >> (64 - r));\r\n}\r\n\r\n#define ROTL64(x,y)\trotl64(x,y)\r\n\r\n#define BIG_CONSTANT(x) (x##LLU)\r\n\r\n#endif \/\/ !defined(_MSC_VER)\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Block read - if your platform needs to do endian-swapping or can only\r\n\/\/ handle aligned reads, do the conversion here\r\n\r\nFORCE_INLINE uint64_t getblock64(const uint64_t * p, int i)\r\n{\r\n\treturn p[i];\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Finalization mix - force all bits of a hash block to avalanche\r\n\r\n\r\nFORCE_INLINE uint64_t fmix64(uint64_t k)\r\n{\r\n\tk ^= k >> 33;\r\n\tk *= BIG_CONSTANT(0xff51afd7ed558ccd);\r\n\tk ^= k >> 33;\r\n\tk *= BIG_CONSTANT(0xc4ceb9fe1a85ec53);\r\n\tk ^= k >> 33;\r\n\r\n\treturn k;\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\r\nvoid MurmurHash3_x64_128(const void * key, const int len,\r\n\tconst uint32_t seed, void * out)\r\n{\r\n\tconst uint8_t * data = (const uint8_t*)key;\r\n\tconst int nblocks = len \/ 16;\r\n\r\n\tuint64_t h1 = seed;\r\n\tuint64_t h2 = seed;\r\n\r\n\tconst uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5);\r\n\tconst uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f);\r\n\r\n\t\/\/----------\r\n\t\/\/ body\r\n\r\n\tconst uint64_t * blocks = (const uint64_t *)(data);\r\n\r\n\tfor (int i = 0; i < nblocks; i++)\r\n\t{\r\n\t\tuint64_t k1 = getblock64(blocks, i * 2 + 0);\r\n\t\tuint64_t k2 = getblock64(blocks, i * 2 + 1);\r\n\r\n\t\tk1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;\r\n\r\n\t\th1 = ROTL64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729;\r\n\r\n\t\tk2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;\r\n\r\n\t\th2 = ROTL64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5;\r\n\t}\r\n\r\n\t\/\/----------\r\n\t\/\/ tail\r\n\r\n\tconst uint8_t * tail = (const uint8_t*)(data + nblocks * 16);\r\n\r\n\tuint64_t k1 = 0;\r\n\tuint64_t k2 = 0;\r\n\r\n\tswitch (len & 15)\r\n\t{\r\n\tcase 15: k2 ^= ((uint64_t)tail[14]) << 48;\r\n\tcase 14: k2 ^= ((uint64_t)tail[13]) << 40;\r\n\tcase 13: k2 ^= ((uint64_t)tail[12]) << 32;\r\n\tcase 12: k2 ^= ((uint64_t)tail[11]) << 24;\r\n\tcase 11: k2 ^= ((uint64_t)tail[10]) << 16;\r\n\tcase 10: k2 ^= ((uint64_t)tail[9]) << 8;\r\n\tcase 9: k2 ^= ((uint64_t)tail[8]) << 0;\r\n\t\tk2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;\r\n\r\n\tcase 8: k1 ^= ((uint64_t)tail[7]) << 56;\r\n\tcase 7: k1 ^= ((uint64_t)tail[6]) << 48;\r\n\tcase 6: k1 ^= ((uint64_t)tail[5]) << 40;\r\n\tcase 5: k1 ^= ((uint64_t)tail[4]) << 32;\r\n\tcase 4: k1 ^= ((uint64_t)tail[3]) << 24;\r\n\tcase 3: k1 ^= ((uint64_t)tail[2]) << 16;\r\n\tcase 2: k1 ^= ((uint64_t)tail[1]) << 8;\r\n\tcase 1: k1 ^= ((uint64_t)tail[0]) << 0;\r\n\t\tk1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;\r\n\t};\r\n\r\n\t\/\/----------\r\n\t\/\/ finalization\r\n\r\n\th1 ^= len; h2 ^= len;\r\n\r\n\th1 += h2;\r\n\th2 += h1;\r\n\r\n\th1 = fmix64(h1);\r\n\th2 = fmix64(h2);\r\n\r\n\th1 += h2;\r\n\th2 += h1;\r\n\r\n\t((uint64_t*)out)[0] = h1;\r\n\t((uint64_t*)out)[1] = h2;\r\n}\r\n\r\nstd::array MurmurHash3_x64_128(const void * key, int len)\r\n{\r\n\tstd::array hash;\r\n\tMurmurHash3_x64_128(key, len, 104729, hash.data());\r\n\r\n\treturn hash;\r\n}\r\n\r\nuint64_t MurmurHash3_x64_64(const void * key, int len)\r\n{\r\n\tuint64_t hash[2];\r\n\tMurmurHash3_x64_128(key, len, 104729, hash);\r\n\r\n\treturn hash[0] ^ hash[1];\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\r\n<|endoftext|>"} {"text":"#include \"mmu.h\"\n\n#include \"boot.h\"\n#include \"util\/log.h\"\n#include \"video\/video.h\"\n\n#include \n\nMMU::MMU(Cartridge& inCartridge, Video& inVideo) :\n cartridge(inCartridge),\n video(inVideo)\n{\n memory = std::vector(0xFFFF);\n}\n\nu8 MMU::read(const Address address) const {\n if (address.in_range(0x0, 0x7FFF)) {\n if (address.in_range(0x0, 0xFF) && boot_rom_active()) {\n return bootDMG[address.value()];\n }\n return cartridge.read(address);\n }\n\n \/* VRAM *\/\n if (address.in_range(0x8000, 0x9FFF)) {\n return memory_read(address);\n }\n\n \/* External (cartridge) RAM *\/\n if (address.in_range(0xA000, 0xBFFF)) {\n \/* log_warn(\"Attempting to read from cartridge RAM\"); *\/\n return memory_read(address);\n }\n\n \/* Internal work RAM *\/\n if (address.in_range(0xC000, 0xDFFF)) {\n return memory_read(address);\n }\n\n if (address.in_range(0xE000, 0xFDFF)) {\n \/* log_warn(\"Attempting to read from mirrored work RAM\"); *\/\n auto mirrored_address = Address(address.value() - 0x2000);\n return memory_read(mirrored_address);\n }\n\n \/* Mapped IO *\/\n if (address.in_range(0xFF00, 0xFF7F)) {\n return read_io(address);\n }\n\n \/* Zero Page ram *\/\n if (address.in_range(0xFF80, 0xFFFE)) {\n return memory_read(address);\n }\n\n \/* Interrupt Enable register *\/\n if (address.value() == 0xFFFF) {\n return memory_read(address);\n }\n\n log_error(\"Attempted to read from unmapped memory address %X\", address.value());\n exit(1);\n}\n\nu8 MMU::memory_read(const Address address) const {\n return memory[address.value()];\n}\n\nu8 MMU::read_io(const Address address) const {\n switch (address.value()) {\n case 0xFF42:\n return video.scroll_y.value();\n\n case 0xFF44:\n return video.line.value();\n\n \/* Disable boot rom switch *\/\n case 0xFF50:\n return memory_read(address);\n\n default:\n log_error(\"Read from unknown IO address 0x%x\", address.value());\n exit(1);\n }\n}\n\nvoid MMU::write(const Address address, const u8 byte) {\n if (address.in_range(0x0000, 0x7FFF)) {\n \/* log_warn(\"Attempting to write to cartridge ROM\"); *\/\n }\n\n \/* VRAM *\/\n if (address.in_range(0x7FFF, 0x9FFF)) {\n memory_write(address, byte);\n return;\n }\n\n \/* External (cartridge) RAM *\/\n if (address.in_range(0xA000, 0xBFFF)) {\n memory_write(address, byte);\n return;\n }\n\n \/* Internal work RAM *\/\n if (address.in_range(0xC000, 0xDFFF)) {\n memory_write(address, byte);\n return;\n }\n\n \/* Mirrored RAM *\/\n if (address.in_range(0xE000, 0xFDFF)) {\n \/* log_warn(\"Attempting to write to mirrored work RAM\"); *\/\n auto mirrored_address = Address(address.value() - 0x2000);\n memory_write(mirrored_address, byte);\n return;\n }\n\n \/* Mapped IO *\/\n if (address.in_range(0xFF00, 0xFF7F)) {\n write_io(address, byte);\n return;\n }\n\n if (address.in_range(0xFEA0, 0xFEFF)) {\n \/* log_warn(\"Attempting to write to unusable memory\"); *\/\n }\n\n \/* Zero Page ram *\/\n if (address.in_range(0xFF80, 0xFFFE)) {\n memory_write(address, byte);\n return;\n }\n\n \/* Interrupt Enable register *\/\n if (address.value() == 0xFFFF) {\n memory_write(address, byte);\n return;\n }\n\n log_error(\"Attempted to write to unmapped memory address %X\", address.value());\n exit(1);\n}\n\nvoid MMU::write_io(const Address address, const u8 byte) {\n switch (address.value()) {\n \/* Serial data transfer (SB) *\/\n case 0xFF01:\n \/* TODO *\/\n \/* log_warn(\"%c\", byte); *\/\n return;\n\n case 0xFF11:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF12:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF13:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF14:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF24:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF25:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF26:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n \/* Switch on LCD *\/\n case 0xFF40:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n \/* Vertical Scroll Register *\/\n case 0xFF42:\n video.scroll_y.set(byte);\n return;\n\n \/* LY - Line Y coordinate *\/\n case 0xFF44:\n \/* \"Writing will reset the counter *\/\n log_warn(\"Writing to FF44 will reset the line counter\");\n return;\n\n case 0xFF47:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n \/* Disable boot rom switch *\/\n case 0xFF50:\n \/* TODO *\/\n memory_write(address, byte);\n return;\n }\n}\n\nvoid MMU::memory_write(const Address address, const u8 byte) {\n memory[address.value()] = byte;\n}\n\nvoid MMU::write_word(const Address address, const u16 word) {\n}\n\nbool MMU::boot_rom_active() const {\n return read(0xFF50) != 0x1;\n}\nFix incorrect in_range for VRAM (use inclusive bound)#include \"mmu.h\"\n\n#include \"boot.h\"\n#include \"util\/log.h\"\n#include \"video\/video.h\"\n\n#include \n\nMMU::MMU(Cartridge& inCartridge, Video& inVideo) :\n cartridge(inCartridge),\n video(inVideo)\n{\n memory = std::vector(0xFFFF);\n}\n\nu8 MMU::read(const Address address) const {\n if (address.in_range(0x0, 0x7FFF)) {\n if (address.in_range(0x0, 0xFF) && boot_rom_active()) {\n return bootDMG[address.value()];\n }\n return cartridge.read(address);\n }\n\n \/* VRAM *\/\n if (address.in_range(0x8000, 0x9FFF)) {\n return memory_read(address);\n }\n\n \/* External (cartridge) RAM *\/\n if (address.in_range(0xA000, 0xBFFF)) {\n \/* log_warn(\"Attempting to read from cartridge RAM\"); *\/\n return memory_read(address);\n }\n\n \/* Internal work RAM *\/\n if (address.in_range(0xC000, 0xDFFF)) {\n return memory_read(address);\n }\n\n if (address.in_range(0xE000, 0xFDFF)) {\n \/* log_warn(\"Attempting to read from mirrored work RAM\"); *\/\n auto mirrored_address = Address(address.value() - 0x2000);\n return memory_read(mirrored_address);\n }\n\n \/* Mapped IO *\/\n if (address.in_range(0xFF00, 0xFF7F)) {\n return read_io(address);\n }\n\n \/* Zero Page ram *\/\n if (address.in_range(0xFF80, 0xFFFE)) {\n return memory_read(address);\n }\n\n \/* Interrupt Enable register *\/\n if (address.value() == 0xFFFF) {\n return memory_read(address);\n }\n\n log_error(\"Attempted to read from unmapped memory address %X\", address.value());\n exit(1);\n}\n\nu8 MMU::memory_read(const Address address) const {\n return memory[address.value()];\n}\n\nu8 MMU::read_io(const Address address) const {\n switch (address.value()) {\n case 0xFF42:\n return video.scroll_y.value();\n\n case 0xFF44:\n return video.line.value();\n\n \/* Disable boot rom switch *\/\n case 0xFF50:\n return memory_read(address);\n\n default:\n log_error(\"Read from unknown IO address 0x%x\", address.value());\n exit(1);\n }\n}\n\nvoid MMU::write(const Address address, const u8 byte) {\n if (address.in_range(0x0000, 0x7FFF)) {\n \/* log_warn(\"Attempting to write to cartridge ROM\"); *\/\n }\n\n \/* VRAM *\/\n if (address.in_range(0x8000, 0x9FFF)) {\n memory_write(address, byte);\n return;\n }\n\n \/* External (cartridge) RAM *\/\n if (address.in_range(0xA000, 0xBFFF)) {\n memory_write(address, byte);\n return;\n }\n\n \/* Internal work RAM *\/\n if (address.in_range(0xC000, 0xDFFF)) {\n memory_write(address, byte);\n return;\n }\n\n \/* Mirrored RAM *\/\n if (address.in_range(0xE000, 0xFDFF)) {\n \/* log_warn(\"Attempting to write to mirrored work RAM\"); *\/\n auto mirrored_address = Address(address.value() - 0x2000);\n memory_write(mirrored_address, byte);\n return;\n }\n\n \/* Mapped IO *\/\n if (address.in_range(0xFF00, 0xFF7F)) {\n write_io(address, byte);\n return;\n }\n\n if (address.in_range(0xFEA0, 0xFEFF)) {\n \/* log_warn(\"Attempting to write to unusable memory\"); *\/\n }\n\n \/* Zero Page ram *\/\n if (address.in_range(0xFF80, 0xFFFE)) {\n memory_write(address, byte);\n return;\n }\n\n \/* Interrupt Enable register *\/\n if (address.value() == 0xFFFF) {\n memory_write(address, byte);\n return;\n }\n\n log_error(\"Attempted to write to unmapped memory address %X\", address.value());\n exit(1);\n}\n\nvoid MMU::write_io(const Address address, const u8 byte) {\n switch (address.value()) {\n \/* Serial data transfer (SB) *\/\n case 0xFF01:\n \/* TODO *\/\n \/* log_warn(\"%c\", byte); *\/\n return;\n\n case 0xFF11:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF12:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF13:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF14:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF24:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF25:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n case 0xFF26:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n \/* Switch on LCD *\/\n case 0xFF40:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n \/* Vertical Scroll Register *\/\n case 0xFF42:\n video.scroll_y.set(byte);\n return;\n\n \/* LY - Line Y coordinate *\/\n case 0xFF44:\n \/* \"Writing will reset the counter *\/\n log_warn(\"Writing to FF44 will reset the line counter\");\n return;\n\n case 0xFF47:\n \/* TODO *\/\n \/* log_warn(\"Wrote to unknown address 0x%x\", address.value()); *\/\n memory_write(address, byte);\n return;\n\n \/* Disable boot rom switch *\/\n case 0xFF50:\n \/* TODO *\/\n memory_write(address, byte);\n return;\n }\n}\n\nvoid MMU::memory_write(const Address address, const u8 byte) {\n memory[address.value()] = byte;\n}\n\nvoid MMU::write_word(const Address address, const u16 word) {\n}\n\nbool MMU::boot_rom_active() const {\n return read(0xFF50) != 0x1;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \"prf.h\"\n\nusing std::vector;\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nusing ceres::Solve;\nusing ceres::Solver;\nusing ceres::Problem;\nusing ceres::CostFunction;\nusing ceres::AutoDiffCostFunction;\n\nusing kpsf::load_prfs;\n\n#define N_GAUSSIANS 4\n\nclass MOGResidual {\n\npublic:\n\n MOGResidual (MatrixXd img) : img_(img) {};\n\n template \n bool operator() (const T* params, T* residuals) const {\n \/\/ Initialize the residuals.\n for (int i = 0; i < DIM_X; ++i)\n for (int j = 0; j < DIM_Y; ++j)\n residuals[i*DIM_Y+j] = T(img_(i, j));\n\n \/\/ Loop over the Gaussians and compute the model.\n for (int k = 0; k < N_GAUSSIANS; ++k) {\n \/\/ Ensure that the centers are in the frame.\n const T* pos = &(params[6*k+1]);\n if (pos[0] < T(0) || pos[0] >= T(DIM_X) ||\n pos[1] < T(0) || pos[1] >= T(DIM_Y)) return false;\n\n \/\/ Compute the determinant and make sure that it's positive.\n const T* cov = &(params[6*k+3]);\n T det = cov[0] * cov[2] - cov[1] * cov[1];\n if (cov[0] <= T(0) || cov[2] <= T(0) || det <= T(0)) return false;\n\n \/\/ Pre-compute the normalization factor.\n T factor = params[6*k] \/ T(2*M_PI) \/ sqrt(det);\n\n \/\/ Loop over pixels and compute the model value.\n for (int i = 0; i < DIM_X; ++i) {\n for (int j = 0; j < DIM_Y; ++j) {\n T dx = pos[0] - T(i),\n dy = pos[1] - T(j),\n x = cov[2] * dx - cov[1] * dy,\n y = cov[0] * dy - cov[1] * dx,\n v = (dx * x + dy * y) \/ det;\n residuals[i*DIM_Y+j] -= factor * exp(T(-0.5) * v);\n }\n }\n }\n return true;\n };\n\nprivate:\n\n MatrixXd img_;\n\n};\n\nint main ()\n{\n int status;\n\n \/\/ Load the PRF files.\n vector prfs;\n status = load_prfs(\"..\/data\/kplr07.4_2011265_prf.fits\", &prfs);\n if (status) return status;\n\n \/\/ Initialize the parameters.\n VectorXd params(6*N_GAUSSIANS);\n for (int k = 0; k < N_GAUSSIANS; ++k) {\n params(6*k) = 3000.0 \/ N_GAUSSIANS;\n params(6*k+1) = CENTER_X;\n params(6*k+2) = CENTER_Y;\n params(6*k+3) = (k + 1) * CENTER_X * CENTER_X;\n params(6*k+4) = 100.0;\n params(6*k+5) = (k + 1) * CENTER_Y * CENTER_Y;\n }\n\n \/\/ Set up the problem.\n Problem problem;\n CostFunction *cost =\n new AutoDiffCostFunction (\n new MOGResidual (prfs[0]));\n problem.AddResidualBlock(cost, NULL, &(params(0)));\n\n \/\/ Set up the solver.\n Solver::Options options;\n options.max_num_iterations = 50 * N_GAUSSIANS;\n \/\/ options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n options.linear_solver_type = ceres::DENSE_SCHUR;\n options.dense_linear_algebra_library_type = ceres::LAPACK;\n options.minimizer_progress_to_stdout = true;\n\n Solver::Summary summary;\n Solve(options, &problem, &summary);\n std::cout << summary.BriefReport() << std::endl;\n\n std::cout << params << std::endl;\n\n return 0;\n}\nwriting MOG output#include \n#include \n#include \n\n#include \n#include \n\n\/\/ Ignore string warnings. It's cfitsio's fault!\n#pragma GCC diagnostic ignored \"-Wwrite-strings\"\n\nusing std::vector;\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nusing ceres::Solve;\nusing ceres::Solver;\nusing ceres::Problem;\nusing ceres::CostFunction;\nusing ceres::AutoDiffCostFunction;\n\n\/\/\n\/\/ Constants for the Kepler PRF model. These will be different for other\n\/\/ models.\n\/\/\n#define N_PSF_BASIS 5\n#define OVERSAMPLE 50\n#define DIM_X 550\n#define DIM_Y 550\n#define CENTER_X 275\n#define CENTER_Y 275\n\n\/\/\n\/\/ The number of Gaussians in our representation.\n\/\/\n#define N_GAUSSIANS 3\n#define PP_GAUSSIAN 6\n\n\/\/\n\/\/ Read in the Kepler PRF basis images from a given FITS file. Returns a\n\/\/ vector of images in Eigen::MatrixXd format. Status will be non-zero on\n\/\/ failure.\n\/\/\nint load_prfs (const char *fn, vector* prfs)\n{\n fitsfile *f;\n int status = 0;\n\n \/\/ Open the file.\n if (fits_open_file(&f, fn, READONLY, &status)) {\n fits_report_error(stderr, status);\n return status;\n }\n\n \/\/ Read in the data.\n int anynull, hdutype, i;\n long fpixel = 1;\n double nullval = -1;\n *prfs = vector(N_PSF_BASIS);\n for (i = 0; i < N_PSF_BASIS; ++i) {\n \/\/ Move to the correct HDU.\n if (fits_movabs_hdu(f, i+2, &hdutype, &status)) {\n fits_report_error(stderr, status);\n return status;\n }\n\n \/\/ Allocate the matrix and read the image.\n (*prfs)[i] = MatrixXd(DIM_X, DIM_Y);\n if (fits_read_img(f, TDOUBLE, fpixel, DIM_X * DIM_Y, &nullval,\n &((*prfs)[i](0)), &anynull, &status)) {\n fits_report_error(stderr, status);\n return status;\n }\n }\n\n \/\/ Close the file.\n if (fits_close_file(f, &status))\n fits_report_error(stderr, status);\n\n return status;\n};\n\n\/\/\n\/\/ Write the MOG representation of a PRF image to a file.\n\/\/\nint write_mog (const char *fn, VectorXd params, int hdu)\n{\n fitsfile *f;\n int status = 0;\n\n \/\/ Open the file.\n if (hdu == 1) {\n remove(fn);\n if (fits_create_file(&f, fn, &status)) {\n fits_report_error(stderr, status);\n return status;\n }\n } else {\n if (fits_open_file(&f, fn, READWRITE, &status)) {\n fits_report_error(stderr, status);\n return status;\n }\n\n \/\/ Move to the correct HDU.\n }\n\n \/\/ Create a new binary table.\n char* ttype[] = {\"amp\", \"xpos\", \"ypos\", \"xvar\", \"covar\", \"yvar\"},\n * tform[] = {\"1D\", \"1D\", \"1D\", \"1D\", \"1D\", \"1D\"},\n * tunit[] = {\"\\0\", \"\\0\", \"\\0\", \"\\0\", \"\\0\", \"\\0\"};\n if (fits_create_tbl(f, BINARY_TBL, N_GAUSSIANS, PP_GAUSSIAN, ttype, tform,\n tunit, \"MOG\", &status)) {\n fits_report_error(stderr, status);\n return status;\n }\n\n \/\/ Coerce the data into the correct form.\n VectorXd amp(N_GAUSSIANS), xpos(N_GAUSSIANS), ypos(N_GAUSSIANS),\n xvar(N_GAUSSIANS), covar(N_GAUSSIANS), yvar(N_GAUSSIANS);\n for (int i = 0; i < N_GAUSSIANS; ++i) {\n amp(i) = params(PP_GAUSSIAN*i);\n xpos(i) = params(PP_GAUSSIAN*i + 1);\n ypos(i) = params(PP_GAUSSIAN*i + 2);\n xvar(i) = params(PP_GAUSSIAN*i + 3);\n covar(i) = params(PP_GAUSSIAN*i + 4);\n yvar(i) = params(PP_GAUSSIAN*i + 5);\n }\n\n \/\/ Write the columns.\n fits_write_col(f, TDOUBLE, 1, 1, 1, N_GAUSSIANS, &(amp(0)), &status);\n fits_write_col(f, TDOUBLE, 2, 1, 1, N_GAUSSIANS, &(xpos(0)), &status);\n fits_write_col(f, TDOUBLE, 3, 1, 1, N_GAUSSIANS, &(ypos(0)), &status);\n fits_write_col(f, TDOUBLE, 4, 1, 1, N_GAUSSIANS, &(xvar(0)), &status);\n fits_write_col(f, TDOUBLE, 5, 1, 1, N_GAUSSIANS, &(covar(0)), &status);\n fits_write_col(f, TDOUBLE, 6, 1, 1, N_GAUSSIANS, &(yvar(0)), &status);\n\n \/\/ Clean up and return.\n if (status) fits_report_error(stderr, status);\n if (fits_close_file(f, &status)) fits_report_error(stderr, status);\n return status;\n}\n\n\/\/\n\/\/ The residual object used by Ceres to find the NLLS solution to the MOG\n\/\/ representation model.\n\/\/\nclass MOGResidual {\n\npublic:\n\n MOGResidual (MatrixXd img) : img_(img) {};\n\n template \n bool operator() (const T* params, T* residuals) const {\n \/\/ Initialize the residuals.\n for (int i = 0; i < DIM_X; ++i)\n for (int j = 0; j < DIM_Y; ++j)\n residuals[i*DIM_Y+j] = T(img_(i, j));\n\n \/\/ Loop over the Gaussians and compute the model.\n for (int k = 0; k < N_GAUSSIANS; ++k) {\n \/\/ Force the amplitudes to be positive.\n T amp = params[PP_GAUSSIAN*k];\n if (amp <= T(0)) return false;\n\n \/\/ Ensure that the centers are in the frame.\n T xpos = T(OVERSAMPLE) * params[PP_GAUSSIAN*k+1],\n ypos = T(OVERSAMPLE) * params[PP_GAUSSIAN*k+2];\n if (xpos < T(0) || xpos >= T(DIM_X) ||\n ypos < T(0) || ypos >= T(DIM_Y)) return false;\n\n \/\/ Compute the determinant and make sure that it's positive.\n T s2 = T(OVERSAMPLE * OVERSAMPLE),\n cov[] = {s2 * params[PP_GAUSSIAN*k+3],\n s2 * params[PP_GAUSSIAN*k+4],\n s2 * params[PP_GAUSSIAN*k+5]},\n det = cov[0] * cov[2] - cov[1] * cov[1];\n if (det <= T(0)) return false;\n\n \/\/ Pre-compute the normalization factor.\n T factor = amp \/ T(2*M_PI) \/ sqrt(det);\n\n \/\/ Loop over pixels and compute the model value.\n for (int i = 0; i < DIM_X; ++i) {\n for (int j = 0; j < DIM_Y; ++j) {\n T dx = xpos - T(i),\n dy = ypos - T(j),\n x = cov[2] * dx - cov[1] * dy,\n y = cov[0] * dy - cov[1] * dx,\n v = (dx * x + dy * y) \/ det;\n residuals[i*DIM_Y+j] -= factor * exp(T(-0.5) * v);\n }\n }\n }\n return true;\n };\n\nprivate:\n\n MatrixXd img_;\n\n};\n\n\n\nint main ()\n{\n int status;\n\n \/\/ Format the filenames.\n const char* infn = \"..\/data\/kplr07.4_2011265_prf.fits\",\n * outfn = \"..\/data\/kplr07.4_2011265_prf.mog.fits\";\n\n \/\/ Load the PRF files.\n vector prfs;\n status = load_prfs(infn, &prfs);\n if (status) return status;\n\n \/\/ Initialize the parameters.\n VectorXd params(PP_GAUSSIAN*N_GAUSSIANS);\n for (int k = 0; k < N_GAUSSIANS; ++k) {\n params(PP_GAUSSIAN*k) = 300.0 \/ (k + 1);\n params(PP_GAUSSIAN*k+1) = CENTER_X \/ OVERSAMPLE;\n params(PP_GAUSSIAN*k+2) = CENTER_Y \/ OVERSAMPLE;\n params(PP_GAUSSIAN*k+3) = (k + 1) * 2.0;\n params(PP_GAUSSIAN*k+4) = 0.0;\n params(PP_GAUSSIAN*k+5) = (k + 1) * 2.0;\n }\n\n \/\/ Set up the problem.\n Problem problem;\n CostFunction *cost =\n new AutoDiffCostFunction (\n new MOGResidual (prfs[1]));\n problem.AddResidualBlock(cost, NULL, &(params(0)));\n\n \/\/ Set up the solver.\n Solver::Options options;\n options.max_num_iterations = 20 * N_GAUSSIANS;\n options.function_tolerance = 1e-5;\n \/\/ options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n options.linear_solver_type = ceres::DENSE_SCHUR;\n options.dense_linear_algebra_library_type = ceres::LAPACK;\n options.minimizer_progress_to_stdout = true;\n\n Solver::Summary summary;\n Solve(options, &problem, &summary);\n std::cout << summary.BriefReport() << std::endl;\n\n std::cout << \"Writing output file: \" << outfn << std::endl;\n status = write_mog(outfn, params);\n if (status) return status;\n\n return 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\ntemplate \nclass LRUCache\n{\n const size_t maxSize_ = _Size;\n std::list<_Ty> values_;\n\npublic:\n using value_iterator = decltype(*values_.begin());\n using value_type = std::pair;\n using mapping_type = std::unordered_map<_Kty, value_iterator>;\n using iterator_type = typename mapping_type::iterator;\n\nprivate:\n mapping_type mapping_;\n iterator_type oldest_ {};\n\npublic:\n LRUCache() = default;\n ~LRUCache() = default;\n LRUCache(const LRUCache&) = delete;\n LRUCache& operator=(const LRUCache&) = delete;\n LRUCache(LRUCache&&) = default;\n LRUCache& operator=(LRUCache&&) = default;\n\n bool insert(const value_type& value)\n {\n static_assert(_Size > 0, \"Size must be greater than zero.\");\n if (values_.size() == _Size)\n {\n auto itToRemove = values_.cbegin();\n values_.erase(itToRemove);\n\n assert(oldest_ != mapping_.end());\n mapping_.erase(oldest_);\n oldest_ = mapping_.begin();\n }\n\n values_.push_back(value.second);\n mapping_.insert({ value.first, values_.back() });\n\n assert(values_.size() == mapping_.size());\n if (values_.size() == 1)\n {\n oldest_ = mapping_.begin();\n }\n\n return true;\n }\n\n _Ty& operator[](const _Kty& key)\n {\n auto it = mapping_.find(key);\n if (it != mapping_.cend())\n {\n return it->second;\n }\n\n \/\/ TODO: remove dummy and brace initialize\n static _Ty dummy{};\n return dummy;\n }\n\n size_t size() const\n {\n return values_.size();\n }\n};\nLRUCache operator[] implementation#pragma once\n\n#include \n#include \n#include \n\ntemplate \nclass LRUCache\n{\n const size_t maxSize_ = _Size;\n std::list<_Ty> values_;\n\npublic:\n using value_iterator = decltype(*values_.begin());\n using value_type = std::pair;\n using mapping_type = std::unordered_map<_Kty, value_iterator>;\n using mapping_iterator = typename mapping_type::iterator;\n\nprivate:\n mapping_type mapping_;\n mapping_iterator oldest_ {};\n\npublic:\n LRUCache() = default;\n ~LRUCache() = default;\n LRUCache(const LRUCache&) = delete;\n LRUCache& operator=(const LRUCache&) = delete;\n LRUCache(LRUCache&&) = default;\n LRUCache& operator=(LRUCache&&) = default;\n\n std::pair insert(const value_type& value)\n {\n static_assert(_Size > 0, \"Size must be greater than zero.\");\n if (values_.size() == _Size)\n {\n auto itToRemove = values_.cbegin();\n values_.erase(itToRemove);\n\n assert(oldest_ != mapping_.end());\n mapping_.erase(oldest_);\n oldest_ = mapping_.begin();\n }\n\n values_.push_back(value.second);\n auto result = mapping_.insert({ value.first, values_.back() });\n\n assert(values_.size() == mapping_.size());\n if (values_.size() == 1)\n {\n oldest_ = mapping_.begin();\n }\n\n return std::make_pair(result.first, true);\n }\n\n _Ty& operator[](const _Kty& key)\n {\n auto it = mapping_.find(key);\n if (it != mapping_.cend())\n {\n return it->second;\n }\n auto result = insert({ key , _Ty{} });\n return result.first->second;\n }\n\n size_t size() const\n {\n return values_.size();\n }\n};\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"paymentservertests.h\"\n\n#include \"optionsmodel.h\"\n#include \"paymentrequestdata.h\"\n\n#include \"amount.h\"\n#include \"random.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include \n#include \n\n#include \n#include \n\nX509 *parse_b64der_cert(const char* cert_data)\n{\n std::vector data = DecodeBase64(cert_data);\n assert(data.size() > 0);\n const unsigned char* dptr = &data[0];\n X509 *cert = d2i_X509(NULL, &dptr, data.size());\n assert(cert);\n return cert;\n}\n\n\/\/\n\/\/ Test payment request handling\n\/\/\n\nstatic SendCoinsRecipient handleRequest(PaymentServer* server, std::vector& data)\n{\n RecipientCatcher sigCatcher;\n QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Write data to a temp file:\n QTemporaryFile f;\n f.open();\n f.write((const char*)&data[0], data.size());\n f.close();\n\n \/\/ Create a QObject, install event filter from PaymentServer\n \/\/ and send a file open event to the object\n QObject object;\n object.installEventFilter(server);\n QFileOpenEvent event(f.fileName());\n \/\/ If sending the event fails, this will cause sigCatcher to be empty,\n \/\/ which will lead to a test failure anyway.\n QCoreApplication::sendEvent(&object, &event);\n\n QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Return results from sigCatcher\n return sigCatcher.recipient;\n}\n\nvoid PaymentServerTests::paymentServerTests()\n{\n SelectParams(CBaseChainParams::MAIN);\n OptionsModel optionsModel;\n PaymentServer* server = new PaymentServer(NULL, false);\n X509_STORE* caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));\n PaymentServer::LoadRootCAs(caStore);\n server->setOptionsModel(&optionsModel);\n server->uiReady();\n\n std::vector data;\n SendCoinsRecipient r;\n QString merchant;\n\n \/\/ Now feed PaymentRequests to server, and observe signals it produces\n\n \/\/ This payment request validates directly against the\n \/\/ caCert1 certificate authority:\n data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant.org\"));\n\n \/\/ Signed, but expired, merchant cert in the request:\n data = DecodeBase64(paymentrequest2_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ 10-long certificate chain, all intermediates valid:\n data = DecodeBase64(paymentrequest3_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant8.org\"));\n\n \/\/ Long certificate chain, with an expired certificate in the middle:\n data = DecodeBase64(paymentrequest4_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Validly signed, but by a CA not in our root CA list:\n data = DecodeBase64(paymentrequest5_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Try again with no root CA's, verifiedMerchant should be empty:\n caStore = X509_STORE_new();\n PaymentServer::LoadRootCAs(caStore);\n data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Load second root certificate\n caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));\n PaymentServer::LoadRootCAs(caStore);\n\n QByteArray byteArray;\n\n \/\/ For the tests below we just need the payment request data from\n \/\/ paymentrequestdata.h parsed + stored in r.paymentRequest.\n \/\/\n \/\/ These tests require us to bypass the following normal client execution flow\n \/\/ shown below to be able to explicitly just trigger a certain condition!\n \/\/\n \/\/ handleRequest()\n \/\/ -> PaymentServer::eventFilter()\n \/\/ -> PaymentServer::handleURIOrFile()\n \/\/ -> PaymentServer::readPaymentRequestFromFile()\n \/\/ -> PaymentServer::processPaymentRequest()\n\n \/\/ Contains a testnet paytoaddress, so payment request network doesn't match client network:\n data = DecodeBase64(paymentrequest1_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized, because network \"main\" is default, even for\n \/\/ uninizialized payment requests and that will fail our test here.\n QVERIFY(r.paymentRequest.IsInitialized());\n QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);\n\n \/\/ Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):\n data = DecodeBase64(paymentrequest2_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 1 < GetTime() == false (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):\n \/\/ 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)\n \/\/ -1 is 1969-12-31 23:59:59 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest3_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);\n\n \/\/ Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):\n \/\/ 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)\n \/\/ 0 is 1970-01-01 00:00:00 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest4_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares -9223372036854775808 < GetTime() == true (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Test BIP70 DoS protection:\n unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];\n GetRandBytes(randData, sizeof(randData));\n \/\/ Write data to a temp file:\n QTemporaryFile tempFile;\n tempFile.open();\n tempFile.write((const char*)randData, sizeof(randData));\n tempFile.close();\n \/\/ compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false\n QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);\n\n \/\/ Payment request with amount overflow (amount is set to 21000001 BTC):\n data = DecodeBase64(paymentrequest5_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ Extract address and amount from the request\n QList > sendingTos = r.paymentRequest.getPayTo();\n Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {\n CTxDestination dest;\n if (ExtractDestination(sendingTo.first, dest))\n QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);\n }\n\n delete server;\n}\n\nvoid RecipientCatcher::getRecipient(SendCoinsRecipient r)\n{\n recipient = r;\n}\nFixed compiler warning.\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"paymentservertests.h\"\n\n#include \"optionsmodel.h\"\n#include \"paymentrequestdata.h\"\n\n#include \"amount.h\"\n#include \"random.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include \n#include \n\n#include \n#include \n\nX509 *parse_b64der_cert(const char* cert_data)\n{\n std::vector data = DecodeBase64(cert_data);\n assert(data.size() > 0);\n const unsigned char* dptr = &data[0];\n X509 *cert = d2i_X509(NULL, &dptr, data.size());\n assert(cert);\n return cert;\n}\n\n\/\/\n\/\/ Test payment request handling\n\/\/\n\nstatic SendCoinsRecipient handleRequest(PaymentServer* server, std::vector& data)\n{\n RecipientCatcher sigCatcher;\n QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Write data to a temp file:\n QTemporaryFile f;\n f.open();\n f.write((const char*)&data[0], data.size());\n f.close();\n\n \/\/ Create a QObject, install event filter from PaymentServer\n \/\/ and send a file open event to the object\n QObject object;\n object.installEventFilter(server);\n QFileOpenEvent event(f.fileName());\n \/\/ If sending the event fails, this will cause sigCatcher to be empty,\n \/\/ which will lead to a test failure anyway.\n QCoreApplication::sendEvent(&object, &event);\n\n QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Return results from sigCatcher\n return sigCatcher.recipient;\n}\n\nvoid PaymentServerTests::paymentServerTests()\n{\n SelectParams(CBaseChainParams::MAIN);\n OptionsModel optionsModel;\n PaymentServer* server = new PaymentServer(NULL, false);\n X509_STORE* caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));\n PaymentServer::LoadRootCAs(caStore);\n server->setOptionsModel(&optionsModel);\n server->uiReady();\n\n std::vector data;\n SendCoinsRecipient r;\n QString merchant;\n\n \/\/ Now feed PaymentRequests to server, and observe signals it produces\n\n \/\/ This payment request validates directly against the\n \/\/ caCert1 certificate authority:\n data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant.org\"));\n\n \/\/ Signed, but expired, merchant cert in the request:\n data = DecodeBase64(paymentrequest2_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ 10-long certificate chain, all intermediates valid:\n data = DecodeBase64(paymentrequest3_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant8.org\"));\n\n \/\/ Long certificate chain, with an expired certificate in the middle:\n data = DecodeBase64(paymentrequest4_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Validly signed, but by a CA not in our root CA list:\n data = DecodeBase64(paymentrequest5_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Try again with no root CA's, verifiedMerchant should be empty:\n caStore = X509_STORE_new();\n PaymentServer::LoadRootCAs(caStore);\n data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Load second root certificate\n caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));\n PaymentServer::LoadRootCAs(caStore);\n\n QByteArray byteArray;\n\n \/\/ For the tests below we just need the payment request data from\n \/\/ paymentrequestdata.h parsed + stored in r.paymentRequest.\n \/\/\n \/\/ These tests require us to bypass the following normal client execution flow\n \/\/ shown below to be able to explicitly just trigger a certain condition!\n \/\/\n \/\/ handleRequest()\n \/\/ -> PaymentServer::eventFilter()\n \/\/ -> PaymentServer::handleURIOrFile()\n \/\/ -> PaymentServer::readPaymentRequestFromFile()\n \/\/ -> PaymentServer::processPaymentRequest()\n\n \/\/ Contains a testnet paytoaddress, so payment request network doesn't match client network:\n data = DecodeBase64(paymentrequest1_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized, because network \"main\" is default, even for\n \/\/ uninizialized payment requests and that will fail our test here.\n QVERIFY(r.paymentRequest.IsInitialized());\n QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);\n\n \/\/ Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):\n data = DecodeBase64(paymentrequest2_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 1 < GetTime() == false (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):\n \/\/ 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)\n \/\/ -1 is 1969-12-31 23:59:59 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest3_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);\n\n \/\/ Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):\n \/\/ 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)\n \/\/ 0 is 1970-01-01 00:00:00 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest4_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares -9223372036854775808 < GetTime() == true (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Test BIP70 DoS protection:\n const qint64 bip70mps = BIP70_MAX_PAYMENTREQUEST_SIZE + 1;\n unsigned char* randData = new unsigned char[bip70mps];\n GetRandBytes(randData, sizeof(unsigned char) * bip70mps);\n \/\/ Write data to a temp file:\n QTemporaryFile tempFile;\n tempFile.open();\n tempFile.write((const char*)randData, sizeof(unsigned char) * bip70mps);\n tempFile.close();\n \/\/ compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false\n QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);\n delete [] randData;\n\n \/\/ Payment request with amount overflow (amount is set to 21000001 BTC):\n data = DecodeBase64(paymentrequest5_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ Extract address and amount from the request\n QList > sendingTos = r.paymentRequest.getPayTo();\n Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {\n CTxDestination dest;\n if (ExtractDestination(sendingTo.first, dest))\n QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);\n }\n\n delete server;\n}\n\nvoid RecipientCatcher::getRecipient(SendCoinsRecipient r)\n{\n recipient = r;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017-2018, Rauli Laine\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \n\n#include \n#include \n#include \n#if PLORTH_ENABLE_MODULES\n# include \n#endif\n\n#if defined(HAVE_UNISTD_H)\n# include \n#endif\n#if defined(HAVE_SYSEXITS_H)\n# include \n#endif\n\n#if !defined(EX_USAGE)\n# define EX_USAGE 64\n#endif\n\nusing namespace plorth;\n\nstatic const char* script_filename = nullptr;\nstatic bool flag_test_syntax = false;\nstatic bool flag_fork = false;\n#if PLORTH_ENABLE_MODULES\nstatic std::unordered_set imported_modules;\n#endif\n\nstatic void scan_arguments(const std::shared_ptr&, int, char**);\n#if PLORTH_ENABLE_MODULES\nstatic void scan_module_path(const std::shared_ptr&);\n#endif\nstatic inline bool is_console_interactive();\nstatic void compile_and_run(const std::shared_ptr&,\n const std::string&,\n const unistring&);\nstatic void console_loop(const std::shared_ptr&);\nstatic void handle_error(const std::shared_ptr&);\n\nvoid initialize_repl_api(const std::shared_ptr&);\n\nint main(int argc, char** argv)\n{\n memory::manager memory_manager;\n auto runtime = runtime::make(memory_manager);\n auto context = context::make(runtime);\n\n#if PLORTH_ENABLE_MODULES\n scan_module_path(runtime);\n#endif\n\n scan_arguments(runtime, argc, argv);\n\n#if PLORTH_ENABLE_MODULES\n for (const auto& module_path : imported_modules)\n {\n if (!context->import(module_path))\n {\n handle_error(context);\n }\n }\n#endif\n\n if (script_filename)\n {\n const unistring decoded_script_filename = utf8_decode(script_filename);\n std::ifstream is(script_filename, std::ios_base::in);\n\n if (is.good())\n {\n const std::string source = std::string(\n std::istreambuf_iterator(is),\n std::istreambuf_iterator()\n );\n\n is.close();\n context->clear();\n#if PLORTH_ENABLE_MODULES\n context->filename(decoded_script_filename);\n#endif\n compile_and_run(context, source, decoded_script_filename);\n } else {\n std::cerr << argv[0]\n << \": Unable to open file `\"\n << script_filename\n << \"' for reading.\"\n << std::endl;\n std::exit(EXIT_FAILURE);\n }\n }\n else if (is_console_interactive())\n {\n console_loop(context);\n } else {\n compile_and_run(\n context,\n std::string(\n std::istreambuf_iterator(std::cin),\n std::istreambuf_iterator()\n ),\n U\"\"\n );\n }\n\n return EXIT_SUCCESS;\n}\n\nstatic void print_usage(std::ostream& out, const char* executable)\n{\n out << std::endl\n << \"Usage: \"\n << executable\n << \" [switches] [--] [programfile] [arguments]\"\n << std::endl;\n out << \" -c Check syntax only.\" << std::endl;\n#if HAVE_FORK\n out << \" -f Fork to background before executing script.\" << std::endl;\n#endif\n#if PLORTH_ENABLE_MODULES\n out << \" -r Import module before executing script.\" << std::endl;\n#endif\n out << \" --version Print the version.\" << std::endl;\n out << \" --help Display this message.\" << std::endl;\n out << std::endl;\n}\n\nstatic void scan_arguments(const std::shared_ptr& runtime,\n int argc,\n char** argv)\n{\n int offset = 1;\n\n while (offset < argc)\n {\n const char* arg = argv[offset++];\n\n if (!*arg)\n {\n continue;\n }\n else if (*arg != '-')\n {\n script_filename = arg;\n break;\n }\n else if (!arg[1])\n {\n break;\n }\n else if (arg[1] == '-')\n {\n if (!std::strcmp(arg, \"--help\"))\n {\n print_usage(std::cout, argv[0]);\n std::exit(EXIT_SUCCESS);\n }\n else if (!std::strcmp(arg, \"--version\"))\n {\n std::cerr << \"Plorth \" << utf8_encode(PLORTH_VERSION) << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n else if (!std::strcmp(arg, \"--\"))\n {\n if (offset < argc)\n {\n script_filename = argv[offset++];\n }\n break;\n } else {\n std::cerr << \"Unrecognized switch: \" << arg << std::endl;\n print_usage(std::cerr, argv[0]);\n std::exit(EX_USAGE);\n }\n }\n for (int i = 1; arg[i]; ++i)\n {\n \/\/ TODO: Add support for these command line switches:\n \/\/ -e: Compile and execute inline script.\n switch (arg[i])\n {\n case 'c':\n flag_test_syntax = true;\n break;\n\n case 'f':\n flag_fork = true;\n break;\n\n#if PLORTH_ENABLE_MODULES\n case 'r':\n if (offset < argc)\n {\n unistring module_path;\n\n if (!utf8_decode_test(argv[offset++], module_path))\n {\n std::cerr << \"Unable to decode given module path.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n imported_modules.insert(module_path);\n ++offset;\n } else {\n std::cerr << \"Argument expected for the -r option.\" << std::endl;\n print_usage(std::cerr, argv[0]);\n std::exit(EX_USAGE);\n }\n break;\n#else\n case 'r':\n std::cerr << \"Modules have been disabled.\" << std::endl;\n std::exit(EXIT_FAILURE);\n break;\n#endif\n\n case 'h':\n print_usage(std::cout, argv[0]);\n std::exit(EXIT_SUCCESS);\n break;\n\n default:\n std::cerr << \"Unrecognized switch: `\" << arg[i] << \"'\" << std::endl;\n print_usage(std::cerr, argv[0]);\n std::exit(EX_USAGE);\n }\n }\n }\n\n while (offset < argc)\n {\n runtime->arguments().push_back(utf8_decode(argv[offset++]));\n }\n}\n\n#if PLORTH_ENABLE_MODULES\nstatic void scan_module_path(const std::shared_ptr& runtime)\n{\n#if defined(_WIN32)\n static const unichar path_separator = ';';\n#else\n static const unichar path_separator = ':';\n#endif\n auto& module_paths = runtime->module_paths();\n const char* begin = std::getenv(\"PLORTHPATH\");\n const char* end = begin;\n\n if (end)\n {\n for (; *end; ++end)\n {\n if (*end != path_separator)\n {\n continue;\n }\n\n if (end - begin > 0)\n {\n module_paths.push_back(utf8_decode(std::string(begin, end - begin)));\n }\n begin = end + 1;\n }\n\n if (end - begin > 0)\n {\n module_paths.push_back(utf8_decode(std::string(begin, end - begin)));\n }\n }\n\n#if defined(PLORTH_RUNTIME_LIBRARY_PATH)\n if (module_paths.empty())\n {\n module_paths.push_back(PLORTH_RUNTIME_LIBRARY_PATH);\n }\n#endif\n}\n#endif\n\nstatic inline bool is_console_interactive()\n{\n#if defined(HAVE_ISATTY)\n return isatty(fileno(stdin));\n#else\n return false;\n#endif\n}\n\nstatic void handle_error(const std::shared_ptr& ctx)\n{\n const std::shared_ptr& err = ctx->error();\n\n if (err)\n {\n const auto position = err->position();\n\n std::cerr << \"Error: \";\n if (position && (!position->filename.empty() || position->line))\n {\n std::cerr << *position << ':';\n }\n std::cerr << err->code() << \" - \" << err->message();\n } else {\n std::cerr << \"Unknown error.\";\n }\n std::cerr << std::endl;\n std::exit(EXIT_FAILURE);\n}\n\nstatic void compile_and_run(const std::shared_ptr& ctx,\n const std::string& input,\n const unistring& filename)\n{\n unistring source;\n std::shared_ptr script;\n\n if (!utf8_decode_test(input, source))\n {\n std::cerr << \"Import error: Unable to decode source code as UTF-8.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n\n if (!(script = ctx->compile(source, filename)))\n {\n handle_error(ctx);\n return;\n }\n\n if (flag_test_syntax)\n {\n std::cerr << \"Syntax OK.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n return;\n }\n\n if (flag_fork)\n {\n#if HAVE_FORK\n if (fork())\n {\n std::exit(EXIT_SUCCESS);\n }\n#else\n std::cerr << \"Forking to background is not supported on this platform.\" << std::endl;\n#endif\n }\n\n if (!script->call(ctx))\n {\n handle_error(ctx);\n }\n}\n\nstatic void count_open_braces(const std::string& input, std::stack& open_braces)\n{\n const std::size_t length = input.length();\n\n for (std::size_t i = 0; i < length; ++i)\n {\n switch (input[i])\n {\n case '#':\n return;\n\n case '(':\n open_braces.push(')');\n break;\n\n case '[':\n open_braces.push(']');\n break;\n\n case '{':\n open_braces.push('}');\n break;\n\n case ')':\n case ']':\n case '}':\n if (!open_braces.empty() && open_braces.top() == input[i])\n {\n open_braces.pop();\n }\n break;\n\n case '\"':\n while (i < length)\n {\n if (input[i] == '\"')\n {\n break;\n }\n else if (input[i] == '\\\\' && i + 1 < length)\n {\n i += 2;\n } else {\n ++i;\n }\n }\n }\n }\n}\n\nstatic void console_loop(const std::shared_ptr& context)\n{\n int line_counter = 0;\n unistring source;\n std::stack open_braces;\n\n initialize_repl_api(context->runtime());\n\n while (std::cin.good())\n {\n std::string line;\n\n std::cout << \"plorth:\"\n << ++line_counter\n << ':'\n << context->size()\n << (open_braces.empty() ? '>' : '*')\n << ' ';\n if (!std::getline(std::cin, line))\n {\n \/\/ Output final newline after ^D has been pressed by the user.\n std::cout << std::endl;\n break;\n }\n else if (!line.empty())\n {\n if (!utf8_decode_test(line, source))\n {\n std::cout << \"Unable to decode given input as UTF-8.\" << std::endl;\n continue;\n }\n source.append(1, '\\n');\n count_open_braces(line, open_braces);\n if (open_braces.empty())\n {\n const auto script = context->compile(source, U\"\", line_counter);\n\n source.clear();\n if (script)\n {\n script->call(context);\n }\n if (context->error())\n {\n const auto& error = context->error();\n\n if (error->position())\n {\n std::cout << *error->position() << ':';\n }\n std::cout << error << std::endl;\n context->clear_error();\n }\n }\n }\n }\n}\nFix a bug in the CLI argument parser\/*\n * Copyright (c) 2017-2018, Rauli Laine\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \n\n#include \n#include \n#include \n#if PLORTH_ENABLE_MODULES\n# include \n#endif\n\n#if defined(HAVE_UNISTD_H)\n# include \n#endif\n#if defined(HAVE_SYSEXITS_H)\n# include \n#endif\n\n#if !defined(EX_USAGE)\n# define EX_USAGE 64\n#endif\n\nusing namespace plorth;\n\nstatic const char* script_filename = nullptr;\nstatic bool flag_test_syntax = false;\nstatic bool flag_fork = false;\n#if PLORTH_ENABLE_MODULES\nstatic std::unordered_set imported_modules;\n#endif\n\nstatic void scan_arguments(const std::shared_ptr&, int, char**);\n#if PLORTH_ENABLE_MODULES\nstatic void scan_module_path(const std::shared_ptr&);\n#endif\nstatic inline bool is_console_interactive();\nstatic void compile_and_run(const std::shared_ptr&,\n const std::string&,\n const unistring&);\nstatic void console_loop(const std::shared_ptr&);\nstatic void handle_error(const std::shared_ptr&);\n\nvoid initialize_repl_api(const std::shared_ptr&);\n\nint main(int argc, char** argv)\n{\n memory::manager memory_manager;\n auto runtime = runtime::make(memory_manager);\n auto context = context::make(runtime);\n\n#if PLORTH_ENABLE_MODULES\n scan_module_path(runtime);\n#endif\n\n scan_arguments(runtime, argc, argv);\n\n#if PLORTH_ENABLE_MODULES\n for (const auto& module_path : imported_modules)\n {\n if (!context->import(module_path))\n {\n handle_error(context);\n }\n }\n#endif\n\n if (script_filename)\n {\n const unistring decoded_script_filename = utf8_decode(script_filename);\n std::ifstream is(script_filename, std::ios_base::in);\n\n if (is.good())\n {\n const std::string source = std::string(\n std::istreambuf_iterator(is),\n std::istreambuf_iterator()\n );\n\n is.close();\n context->clear();\n#if PLORTH_ENABLE_MODULES\n context->filename(decoded_script_filename);\n#endif\n compile_and_run(context, source, decoded_script_filename);\n } else {\n std::cerr << argv[0]\n << \": Unable to open file `\"\n << script_filename\n << \"' for reading.\"\n << std::endl;\n std::exit(EXIT_FAILURE);\n }\n }\n else if (is_console_interactive())\n {\n console_loop(context);\n } else {\n compile_and_run(\n context,\n std::string(\n std::istreambuf_iterator(std::cin),\n std::istreambuf_iterator()\n ),\n U\"\"\n );\n }\n\n return EXIT_SUCCESS;\n}\n\nstatic void print_usage(std::ostream& out, const char* executable)\n{\n out << std::endl\n << \"Usage: \"\n << executable\n << \" [switches] [--] [programfile] [arguments]\"\n << std::endl;\n out << \" -c Check syntax only.\" << std::endl;\n#if HAVE_FORK\n out << \" -f Fork to background before executing script.\" << std::endl;\n#endif\n#if PLORTH_ENABLE_MODULES\n out << \" -r Import module before executing script.\" << std::endl;\n#endif\n out << \" --version Print the version.\" << std::endl;\n out << \" --help Display this message.\" << std::endl;\n out << std::endl;\n}\n\nstatic void scan_arguments(const std::shared_ptr& runtime,\n int argc,\n char** argv)\n{\n int offset = 1;\n\n while (offset < argc)\n {\n const char* arg = argv[offset++];\n\n if (!*arg)\n {\n continue;\n }\n else if (*arg != '-')\n {\n script_filename = arg;\n break;\n }\n else if (!arg[1])\n {\n break;\n }\n else if (arg[1] == '-')\n {\n if (!std::strcmp(arg, \"--help\"))\n {\n print_usage(std::cout, argv[0]);\n std::exit(EXIT_SUCCESS);\n }\n else if (!std::strcmp(arg, \"--version\"))\n {\n std::cerr << \"Plorth \" << utf8_encode(PLORTH_VERSION) << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n else if (!std::strcmp(arg, \"--\"))\n {\n if (offset < argc)\n {\n script_filename = argv[offset++];\n }\n break;\n } else {\n std::cerr << \"Unrecognized switch: \" << arg << std::endl;\n print_usage(std::cerr, argv[0]);\n std::exit(EX_USAGE);\n }\n }\n for (int i = 1; arg[i]; ++i)\n {\n \/\/ TODO: Add support for these command line switches:\n \/\/ -e: Compile and execute inline script.\n switch (arg[i])\n {\n case 'c':\n flag_test_syntax = true;\n break;\n\n case 'f':\n flag_fork = true;\n break;\n\n#if PLORTH_ENABLE_MODULES\n case 'r':\n if (offset < argc)\n {\n unistring module_path;\n\n if (!utf8_decode_test(argv[offset++], module_path))\n {\n std::cerr << \"Unable to decode given module path.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n imported_modules.insert(module_path);\n } else {\n std::cerr << \"Argument expected for the -r option.\" << std::endl;\n print_usage(std::cerr, argv[0]);\n std::exit(EX_USAGE);\n }\n break;\n#else\n case 'r':\n std::cerr << \"Modules have been disabled.\" << std::endl;\n std::exit(EXIT_FAILURE);\n break;\n#endif\n\n case 'h':\n print_usage(std::cout, argv[0]);\n std::exit(EXIT_SUCCESS);\n break;\n\n default:\n std::cerr << \"Unrecognized switch: `\" << arg[i] << \"'\" << std::endl;\n print_usage(std::cerr, argv[0]);\n std::exit(EX_USAGE);\n }\n }\n }\n\n while (offset < argc)\n {\n runtime->arguments().push_back(utf8_decode(argv[offset++]));\n }\n}\n\n#if PLORTH_ENABLE_MODULES\nstatic void scan_module_path(const std::shared_ptr& runtime)\n{\n#if defined(_WIN32)\n static const unichar path_separator = ';';\n#else\n static const unichar path_separator = ':';\n#endif\n auto& module_paths = runtime->module_paths();\n const char* begin = std::getenv(\"PLORTHPATH\");\n const char* end = begin;\n\n if (end)\n {\n for (; *end; ++end)\n {\n if (*end != path_separator)\n {\n continue;\n }\n\n if (end - begin > 0)\n {\n module_paths.push_back(utf8_decode(std::string(begin, end - begin)));\n }\n begin = end + 1;\n }\n\n if (end - begin > 0)\n {\n module_paths.push_back(utf8_decode(std::string(begin, end - begin)));\n }\n }\n\n#if defined(PLORTH_RUNTIME_LIBRARY_PATH)\n if (module_paths.empty())\n {\n module_paths.push_back(PLORTH_RUNTIME_LIBRARY_PATH);\n }\n#endif\n}\n#endif\n\nstatic inline bool is_console_interactive()\n{\n#if defined(HAVE_ISATTY)\n return isatty(fileno(stdin));\n#else\n return false;\n#endif\n}\n\nstatic void handle_error(const std::shared_ptr& ctx)\n{\n const std::shared_ptr& err = ctx->error();\n\n if (err)\n {\n const auto position = err->position();\n\n std::cerr << \"Error: \";\n if (position && (!position->filename.empty() || position->line))\n {\n std::cerr << *position << ':';\n }\n std::cerr << err->code() << \" - \" << err->message();\n } else {\n std::cerr << \"Unknown error.\";\n }\n std::cerr << std::endl;\n std::exit(EXIT_FAILURE);\n}\n\nstatic void compile_and_run(const std::shared_ptr& ctx,\n const std::string& input,\n const unistring& filename)\n{\n unistring source;\n std::shared_ptr script;\n\n if (!utf8_decode_test(input, source))\n {\n std::cerr << \"Import error: Unable to decode source code as UTF-8.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n\n if (!(script = ctx->compile(source, filename)))\n {\n handle_error(ctx);\n return;\n }\n\n if (flag_test_syntax)\n {\n std::cerr << \"Syntax OK.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n return;\n }\n\n if (flag_fork)\n {\n#if HAVE_FORK\n if (fork())\n {\n std::exit(EXIT_SUCCESS);\n }\n#else\n std::cerr << \"Forking to background is not supported on this platform.\" << std::endl;\n#endif\n }\n\n if (!script->call(ctx))\n {\n handle_error(ctx);\n }\n}\n\nstatic void count_open_braces(const std::string& input, std::stack& open_braces)\n{\n const std::size_t length = input.length();\n\n for (std::size_t i = 0; i < length; ++i)\n {\n switch (input[i])\n {\n case '#':\n return;\n\n case '(':\n open_braces.push(')');\n break;\n\n case '[':\n open_braces.push(']');\n break;\n\n case '{':\n open_braces.push('}');\n break;\n\n case ')':\n case ']':\n case '}':\n if (!open_braces.empty() && open_braces.top() == input[i])\n {\n open_braces.pop();\n }\n break;\n\n case '\"':\n while (i < length)\n {\n if (input[i] == '\"')\n {\n break;\n }\n else if (input[i] == '\\\\' && i + 1 < length)\n {\n i += 2;\n } else {\n ++i;\n }\n }\n }\n }\n}\n\nstatic void console_loop(const std::shared_ptr& context)\n{\n int line_counter = 0;\n unistring source;\n std::stack open_braces;\n\n initialize_repl_api(context->runtime());\n\n while (std::cin.good())\n {\n std::string line;\n\n std::cout << \"plorth:\"\n << ++line_counter\n << ':'\n << context->size()\n << (open_braces.empty() ? '>' : '*')\n << ' ';\n if (!std::getline(std::cin, line))\n {\n \/\/ Output final newline after ^D has been pressed by the user.\n std::cout << std::endl;\n break;\n }\n else if (!line.empty())\n {\n if (!utf8_decode_test(line, source))\n {\n std::cout << \"Unable to decode given input as UTF-8.\" << std::endl;\n continue;\n }\n source.append(1, '\\n');\n count_open_braces(line, open_braces);\n if (open_braces.empty())\n {\n const auto script = context->compile(source, U\"\", line_counter);\n\n source.clear();\n if (script)\n {\n script->call(context);\n }\n if (context->error())\n {\n const auto& error = context->error();\n\n if (error->position())\n {\n std::cout << *error->position() << ':';\n }\n std::cout << error << std::endl;\n context->clear_error();\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 nyorain \n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See accompanying file LICENSE or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\n\/\/\/\\file\n\/\/\/\\brief Defines the CompatibleFunction (CompFunc typedef'd) template class.\n\n#pragma once\n\n#ifndef NYTL_INCLUDE_COMPFUNC_HPP\n#define NYTL_INCLUDE_COMPFUNC_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace nytl\n{\n\n\/\/TODO: always correct reference (rvalue, lvalue) handling, perfmance improvement\n\/\/does a lamba object ever use the std::function stack storage buffer most impl have?\n\/\/custom function object (type erasure) to use then to stroe the function?\n\/\/correct forwarding of args\n\n\/\/Not specified, use the function-signature template like std::function.\ntemplate class CompatibleFunction;\n\n\/\/\/\\brief A Function object that is able to hold all functions with a compatible signature.\n\/\/\/\\ingroup function\ntemplate\nclass CompatibleFunction\n{\npublic:\n\tusing Ret = R;\n\tusing Signature = Ret(A...);\n\tusing Function = std::function;\n\tusing CompFuncType = CompatibleFunction;\n\tusing ArgsTuple = std::tuple;\n\nprotected:\n\tFunction func_ {};\n\npublic:\n\tCompatibleFunction() = default;\n\t~CompatibleFunction() = default;\n\n\t\/\/constructor\n\ttemplate>>\n\tCompatibleFunction(F func) noexcept { set(func); }\n\n\ttemplate>>\n\tCompatibleFunction(F func, O& object) noexcept { set(memberCallback(func, object)); }\n\n\tCompatibleFunction(const CompFuncType& other) noexcept\n\t\t: func_(other.func_) {}\n\ttemplate CompatibleFunction(const CompatibleFunction& other) noexcept\n\t\t{ set(other.func_); }\n\n\t\/\/assignement\n\ttemplate>>\n\tCompFuncType& operator=(F func) noexcept { set(func); return *this; }\n\n\tCompFuncType& operator=(const CompFuncType& other) noexcept\n\t\t{ func_ = other.func_; return *this; }\n\ttemplate CompFuncType& operator=(const CompatibleFunction& other) noexcept\n\t\t{ set(other.func_); return *this; }\n\n\t\/\/set\n\ttemplate\n\tvoid set(F func) noexcept\n\t{\n\t\tusing FuncTraits = FunctionTraits;\n\t\tusing RealArgsTuple = typename FuncTraits::ArgTuple;\n\t\tusing RealRet = typename FuncTraits::ReturnType;\n\t\tusing MapType = detail::TupleMap;\n\t\tconstexpr auto first = SeqGet<0, typename MapType::Seq, true>;\n\n\t\tstatic_assert(std::is_convertible::value, \"Return types not compatible\");\n\t\tstatic_assert(MapType::Seq::size() == FuncTraits::ArgSize, \"Arguments not compatible\");\n\t\tstatic_assert(first != std::size_t(-1), \"Arguments not compatible\");\n\n\t\tfunc_ = [=](A... args) -> Ret {\n\t\t\t\treturn static_cast(MapType::map(func, std::forward(args)...));\n\t\t\t};\n\t}\n\n\t\/\/get\n\tFunction function() const noexcept { return func_; }\n\n\t\/\/call\n\tRet call(A... args) const { func_(std::forward(args)...); }\n\tRet operator()(A... args) const { func_(std::forward(args)...); }\n\n\toperator bool() const { return function(); }\n};\n\ntemplate\nclass CompatibleFunction\n{\npublic:\n\tusing Ret = void;\n\tusing Signature = Ret(A...);\n\tusing Function = std::function;\n\tusing CompFuncType = CompatibleFunction;\n\tusing ArgsTuple = std::tuple;\n\nprotected:\n\tFunction func_;\n\npublic:\n\tCompatibleFunction() = default;\n\t~CompatibleFunction() = default;\n\n\t\/\/constructor\n\ttemplate>>\n\tCompatibleFunction(F func) noexcept { set(func); }\n\n\ttemplate>>\n\tCompatibleFunction(F func, O object) noexcept { set(memberCallback(func, object)); }\n\n\tCompatibleFunction(const CompFuncType& other) noexcept\n\t\t: func_(other.func_) {}\n\ttemplate CompatibleFunction(const CompatibleFunction& other) noexcept\n\t\t{ set(other.func_); }\n\n\t\/\/assignement\n\ttemplate>>\n\tCompFuncType& operator=(F func) noexcept { set(func); return *this; }\n\n\tCompFuncType& operator=(const CompFuncType& other) noexcept\n\t\t{ func_ = other.func_; return *this; }\n\ttemplate CompFuncType& operator=(const CompatibleFunction& other) noexcept\n\t\t{ set(other.func_); return *this; }\n\n\t\/\/set\n\ttemplate\n\tvoid set(F func) noexcept\n\t{\n\t\tusing FuncTraits = FunctionTraits;\n\t\tusing RealArgsTuple = typename FuncTraits::ArgTuple;\n\t\tusing MapType = detail::TupleMap;\n\t\tconstexpr auto first = SeqGet<0, typename MapType::Seq, true>;\n\n\t\tstatic_assert(MapType::Seq::size() == FuncTraits::ArgSize, \"Arguments not compatible\");\n\t\tstatic_assert(first != std::size_t(-1), \"Arguments not compatible\");\n\n\t\tfunc_ = [=](A... args) -> Ret {\n\t\t\t\tMapType::map(func, std::forward(args)...);\n\t\t\t};\n\t}\n\n\t\/\/get\n\tFunction function() const noexcept { return func_; }\n\n\t\/\/call\n\tRet call(A... args) const { func_(std::forward(args)...); }\n\tRet operator()(A... args) const { func_(std::forward(args)...); }\n\n\toperator bool() const { return function(); }\n};\n\n\/\/typedef CompFunc\ntemplate using CompFunc = CompatibleFunction;\n\n\n}\n\n#endif \/\/heade guard\nfix small compFunc copy ctor bug\/\/ Copyright (c) 2016 nyorain \n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See accompanying file LICENSE or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\n\/\/\/\\file\n\/\/\/\\brief Defines the CompatibleFunction (CompFunc typedef'd) template class.\n\n#pragma once\n\n#ifndef NYTL_INCLUDE_COMPFUNC_HPP\n#define NYTL_INCLUDE_COMPFUNC_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace nytl\n{\n\n\/\/TODO: always correct reference (rvalue, lvalue) handling, perfmance improvement\n\/\/does a lamba object ever use the std::function stack storage buffer most impl have?\n\/\/custom function object (type erasure) to use then to stroe the function?\n\/\/correct forwarding of args\n\n\/\/Not specified, use the function-signature template like std::function.\ntemplate class CompatibleFunction;\n\n\/\/\/\\brief A Function object that is able to hold all functions with a compatible signature.\n\/\/\/\\ingroup function\ntemplate\nclass CompatibleFunction\n{\npublic:\n\tusing Ret = R;\n\tusing Signature = Ret(A...);\n\tusing Function = std::function;\n\tusing CompFuncType = CompatibleFunction;\n\tusing ArgsTuple = std::tuple;\n\nprotected:\n\tFunction func_ {};\n\npublic:\n\tCompatibleFunction() = default;\n\t~CompatibleFunction() = default;\n\n\t\/\/constructor\n\ttemplate>>\n\tCompatibleFunction(F func) noexcept { set(func); }\n\n\ttemplate>>\n\tCompatibleFunction(F func, O& object) noexcept { set(memberCallback(func, object)); }\n\n\tCompatibleFunction(const CompFuncType& other) noexcept\n\t\t: func_(other.func_) {}\n\ttemplate CompatibleFunction(const CompatibleFunction& other) noexcept\n\t\t{ set(other.function()); }\n\n\t\/\/assignement\n\ttemplate>>\n\tCompFuncType& operator=(F func) noexcept { set(func); return *this; }\n\n\tCompFuncType& operator=(const CompFuncType& other) noexcept\n\t\t{ func_ = other.func_; return *this; }\n\ttemplate CompFuncType& operator=(const CompatibleFunction& other) noexcept\n\t\t{ set(other.function()); return *this; }\n\n\t\/\/set\n\ttemplate\n\tvoid set(F func) noexcept\n\t{\n\t\tusing FuncTraits = FunctionTraits;\n\t\tusing RealArgsTuple = typename FuncTraits::ArgTuple;\n\t\tusing RealRet = typename FuncTraits::ReturnType;\n\t\tusing MapType = detail::TupleMap;\n\t\tconstexpr auto first = SeqGet<0, typename MapType::Seq, true>;\n\n\t\tstatic_assert(std::is_convertible::value, \"Return types not compatible\");\n\t\tstatic_assert(MapType::Seq::size() == FuncTraits::ArgSize, \"Arguments not compatible\");\n\t\tstatic_assert(first != std::size_t(-1), \"Arguments not compatible\");\n\n\t\tfunc_ = [=](A... args) -> Ret {\n\t\t\t\treturn static_cast(MapType::map(func, std::forward(args)...));\n\t\t\t};\n\t}\n\n\t\/\/get\n\tFunction function() const noexcept { return func_; }\n\n\t\/\/call\n\tRet call(A... args) const { func_(std::forward(args)...); }\n\tRet operator()(A... args) const { func_(std::forward(args)...); }\n\n\toperator bool() const { return function(); }\n};\n\ntemplate\nclass CompatibleFunction\n{\npublic:\n\tusing Ret = void;\n\tusing Signature = Ret(A...);\n\tusing Function = std::function;\n\tusing CompFuncType = CompatibleFunction;\n\tusing ArgsTuple = std::tuple;\n\nprotected:\n\tFunction func_;\n\npublic:\n\tCompatibleFunction() = default;\n\t~CompatibleFunction() = default;\n\n\t\/\/constructor\n\ttemplate>>\n\tCompatibleFunction(F func) noexcept { set(func); }\n\n\ttemplate>>\n\tCompatibleFunction(F func, O object) noexcept { set(memberCallback(func, object)); }\n\n\tCompatibleFunction(const CompFuncType& other) noexcept\n\t\t: func_(other.function()) {}\n\ttemplate CompatibleFunction(const CompatibleFunction& other) noexcept\n\t\t{ set(other.function()); }\n\n\t\/\/assignement\n\ttemplate>>\n\tCompFuncType& operator=(F func) noexcept { set(func); return *this; }\n\n\tCompFuncType& operator=(const CompFuncType& other) noexcept\n\t\t{ func_ = other.func_; return *this; }\n\ttemplate CompFuncType& operator=(const CompatibleFunction& other) noexcept\n\t\t{ set(other.function()); return *this; }\n\n\t\/\/set\n\ttemplate\n\tvoid set(F func) noexcept\n\t{\n\t\tusing FuncTraits = FunctionTraits;\n\t\tusing RealArgsTuple = typename FuncTraits::ArgTuple;\n\t\tusing MapType = detail::TupleMap;\n\t\tconstexpr auto first = SeqGet<0, typename MapType::Seq, true>;\n\n\t\tstatic_assert(MapType::Seq::size() == FuncTraits::ArgSize, \"Arguments not compatible\");\n\t\tstatic_assert(first != std::size_t(-1), \"Arguments not compatible\");\n\n\t\tfunc_ = [=](A... args) -> Ret {\n\t\t\t\tMapType::map(func, std::forward(args)...);\n\t\t\t};\n\t}\n\n\t\/\/get\n\tFunction function() const noexcept { return func_; }\n\n\t\/\/call\n\tRet call(A... args) const { func_(std::forward(args)...); }\n\tRet operator()(A... args) const { func_(std::forward(args)...); }\n\n\toperator bool() const { return function(); }\n};\n\n\/\/typedef CompFunc\ntemplate using CompFunc = CompatibleFunction;\n\n\n}\n\n#endif \/\/heade guard\n<|endoftext|>"} {"text":"\/************************************************************************\n\tfilename: \tCEGUIPropertyHelper.cpp\n\tcreated:\t6\/7\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplementation of PropertyHelper methods\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/www.cegui.org.uk)\n Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"CEGUIPropertyHelper.h\"\n#include \"CEGUIImagesetManager.h\"\n#include \"CEGUIImageset.h\"\n#include \"CEGUIExceptions.h\"\n\n#include \n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\nfloat PropertyHelper::stringToFloat(const String& str)\n{\n\tusing namespace std;\n\n\tfloat val = 0;\n\tsscanf(str.c_str(), \" %f\", &val);\n\n\treturn val;\n}\n\n\nuint PropertyHelper::stringToUint(const String& str)\n{\n\tusing namespace std;\n\n\tuint val = 0;\n\tsscanf(str.c_str(), \" %u\", &val);\n\n\treturn val;\n}\n\n\nint PropertyHelper::stringToInt(const String& str)\n{\n\tusing namespace std;\n\n\tuint val = 0;\n\tsscanf(str.c_str(), \" %d\", &val);\n\n\treturn val;\n}\n\n\nbool PropertyHelper::stringToBool(const String& str)\n{\n\tif ((str == \"True\") || (str == \"true\"))\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n\n}\n\n\nSize PropertyHelper::stringToSize(const String& str)\n{\n\tusing namespace std;\n\n\tSize val(0,0);\n\tsscanf(str.c_str(), \" w:%f h:%f\", &val.d_width, &val.d_height);\n\n\treturn val;\n}\n\n\nPoint PropertyHelper::stringToPoint(const String& str)\n{\n\tusing namespace std;\n\n\tPoint val(0,0) ;\n\tsscanf(str.c_str(), \" x:%f y:%f\", &val.d_x, &val.d_y);\n\n\treturn val;\n}\n\n\nRect PropertyHelper::stringToRect(const String& str)\n{\n\tusing namespace std;\n\n\tRect val(0, 0, 0, 0);\n\tsscanf(str.c_str(), \" l:%f t:%f r:%f b:%f\", &val.d_left, &val.d_top, &val.d_right, &val.d_bottom);\n\n\treturn val;\n}\n\n\nconst Image* PropertyHelper::stringToImage(const String& str)\n{\n\tusing namespace std;\n\n\tchar imageSet[128];\n\tchar imageName[128];\n\n\tsscanf(str.c_str(), \" set:%127s image:%127s\", imageSet, imageName);\n\n\tconst Image* image;\n\n\ttry\n\t{\n\t\timage = &ImagesetManager::getSingleton().getImageset(imageSet)->getImage(imageName);\n\t}\n\tcatch (UnknownObjectException)\n\t{\n\t\timage = 0;\n\t}\n\n\treturn image;\n}\n\n\nUDim PropertyHelper::stringToUDim(const String& str)\n{\n\tusing namespace std;\n\n\tUDim ud;\n\tsscanf(str.c_str(),\" {%f,%f}\", &ud.d_scale, &ud.d_offset);\n\n\treturn ud;\n}\n\n\nUVector2 PropertyHelper::stringToUVector2(const String& str)\n{\n\tusing namespace std;\n\n\tUVector2 uv;\n\tsscanf(str.c_str(), \" {{%f,%f},{%f,%f}}\", &uv.d_x.d_scale,&uv.d_x.d_offset, &uv.d_y.d_scale,&uv.d_y.d_offset);\n\n\treturn uv;\n}\n\n\nURect PropertyHelper::stringToURect(const String& str)\n{\n\tusing namespace std;\n\n\tURect ur;\n\tsscanf(\n\t\tstr.c_str(),\n\t\t\" {{%f,%f},{%f,%f},{%f,%f},{%f,%f}}\",\n\t\t&ur.d_min.d_x.d_scale, &ur.d_min.d_x.d_offset,\n\t\t&ur.d_min.d_y.d_scale, &ur.d_min.d_y.d_offset,\n\t\t&ur.d_max.d_x.d_scale, &ur.d_max.d_x.d_offset,\n\t\t&ur.d_max.d_y.d_scale, &ur.d_max.d_y.d_offset\n\t);\n\n\treturn ur;\n}\n\n\nString PropertyHelper::floatToString(float val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"%f\", val);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::uintToString(uint val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"%u\", val);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::intToString(int val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"%d\", val);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::boolToString(bool val)\n{\n\tif (val)\n\t{\n\t\treturn String(\"True\");\n\t}\n\telse\n\t{\n\t\treturn String (\"False\");\n\t}\n\n}\n\n\nString PropertyHelper::sizeToString(const Size& val)\n{\n\tusing namespace std;\n\n\tchar buff[128];\n\tsprintf(buff, \"w:%f h:%f\", val.d_width, val.d_height);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::pointToString(const Point& val)\n{\n\tusing namespace std;\n\n\tchar buff[128];\n\tsprintf(buff, \"x:%f y:%f\", val.d_x, val.d_y);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::rectToString(const Rect& val)\n{\n\tusing namespace std;\n\n\tchar buff[256];\n\tsprintf(buff, \"l:%f t:%f r:%f b:%f\", val.d_left, val.d_top, val.d_right, val.d_bottom);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::imageToString(const Image* const val)\n{\n\tif (val)\n\t{\n\t\treturn String(\"set:\" + val->getImagesetName() + \" image:\" + val->getName());\n\t}\n\n\treturn String(\"\");\n}\n\n\nString PropertyHelper::udimToString(const UDim& val)\n{\n\tusing namespace std;\n\n\tchar buff[128];\n\tsprintf(buff, \"{%f,%f}\", val.d_scale, val.d_offset);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::uvector2ToString(const UVector2& val)\n{\n\tusing namespace std;\n\n\tchar buff[256];\n\tsprintf(buff, \"{{%f,%f},{%f,%f}}\", val.d_x.d_scale, val.d_x.d_offset, val.d_y.d_scale, val.d_y.d_offset);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::urectToString(const URect& val)\n{\n\tusing namespace std;\n\n\tchar buff[512];\n\tsprintf(\n\t\tbuff,\n\t\t\"{{%f,%f},{%f,%f},{%f,%f},{%f,%f}}\",\n\t\tval.d_min.d_x.d_scale,val.d_min.d_x.d_offset,\n\t\tval.d_min.d_y.d_scale,val.d_min.d_y.d_offset,\n\t\tval.d_max.d_x.d_scale,val.d_max.d_x.d_offset,\n\t\tval.d_max.d_y.d_scale,val.d_max.d_y.d_offset\n\t);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::colourToString(const colour& val)\n{\n\tusing namespace std;\n\n\tchar buff[16];\n\tsprintf(buff, \"%.8X\", val.getARGB());\n\n\treturn String(buff);\n}\n\n\ncolour PropertyHelper::stringToColour(const String& str)\n{\n\tusing namespace std;\n\n\targb_t val = 0xFF000000;\n\tsscanf(str.c_str(), \" %8X\", &val);\n\n\treturn colour(val);\n\n}\n\n\nString PropertyHelper::colourRectToString(const ColourRect& val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"tl:%.8X tr:%.8X bl:%.8X br:%.8X\", val.d_top_left.getARGB(), val.d_top_right.getARGB(), val.d_bottom_left.getARGB(), val.d_bottom_right.getARGB());\n\n\treturn String(buff);\n}\n\n\nColourRect PropertyHelper::stringToColourRect(const String& str)\n{\n\tusing namespace std;\n\n\targb_t topLeft = 0xFF000000, topRight = 0xFF000000, bottomLeft = 0xFF000000, bottomRight = 0xFF000000;\n\tsscanf(str.c_str(), \"tl:%8X tr:%8X bl:%8X br:%8X\", &topLeft, &topRight, &bottomLeft, &bottomRight);\n\n\treturn ColourRect(topLeft, topRight, bottomLeft, bottomRight);\n}\n\n} \/\/ End of CEGUI namespace section\nBug Fix: PropertyHelper::stringToImage was not handling empty string case.\/************************************************************************\n\tfilename: \tCEGUIPropertyHelper.cpp\n\tcreated:\t6\/7\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplementation of PropertyHelper methods\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/www.cegui.org.uk)\n Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"CEGUIPropertyHelper.h\"\n#include \"CEGUIImagesetManager.h\"\n#include \"CEGUIImageset.h\"\n#include \"CEGUIExceptions.h\"\n\n#include \n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\nfloat PropertyHelper::stringToFloat(const String& str)\n{\n\tusing namespace std;\n\n\tfloat val = 0;\n\tsscanf(str.c_str(), \" %f\", &val);\n\n\treturn val;\n}\n\n\nuint PropertyHelper::stringToUint(const String& str)\n{\n\tusing namespace std;\n\n\tuint val = 0;\n\tsscanf(str.c_str(), \" %u\", &val);\n\n\treturn val;\n}\n\n\nint PropertyHelper::stringToInt(const String& str)\n{\n\tusing namespace std;\n\n\tuint val = 0;\n\tsscanf(str.c_str(), \" %d\", &val);\n\n\treturn val;\n}\n\n\nbool PropertyHelper::stringToBool(const String& str)\n{\n\tif ((str == \"True\") || (str == \"true\"))\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n\n}\n\n\nSize PropertyHelper::stringToSize(const String& str)\n{\n\tusing namespace std;\n\n\tSize val(0,0);\n\tsscanf(str.c_str(), \" w:%f h:%f\", &val.d_width, &val.d_height);\n\n\treturn val;\n}\n\n\nPoint PropertyHelper::stringToPoint(const String& str)\n{\n\tusing namespace std;\n\n\tPoint val(0,0) ;\n\tsscanf(str.c_str(), \" x:%f y:%f\", &val.d_x, &val.d_y);\n\n\treturn val;\n}\n\n\nRect PropertyHelper::stringToRect(const String& str)\n{\n\tusing namespace std;\n\n\tRect val(0, 0, 0, 0);\n\tsscanf(str.c_str(), \" l:%f t:%f r:%f b:%f\", &val.d_left, &val.d_top, &val.d_right, &val.d_bottom);\n\n\treturn val;\n}\n\n\nconst Image* PropertyHelper::stringToImage(const String& str)\n{\n\tusing namespace std;\n\n \/\/ handle empty string case\n if (str.empty())\n return 0;\n\n\tchar imageSet[128];\n\tchar imageName[128];\n\n\tsscanf(str.c_str(), \" set:%127s image:%127s\", imageSet, imageName);\n\n\tconst Image* image;\n\n\ttry\n\t{\n\t\timage = &ImagesetManager::getSingleton().getImageset(imageSet)->getImage(imageName);\n\t}\n\tcatch (UnknownObjectException)\n\t{\n\t\timage = 0;\n\t}\n\n\treturn image;\n}\n\n\nUDim PropertyHelper::stringToUDim(const String& str)\n{\n\tusing namespace std;\n\n\tUDim ud;\n\tsscanf(str.c_str(),\" {%f,%f}\", &ud.d_scale, &ud.d_offset);\n\n\treturn ud;\n}\n\n\nUVector2 PropertyHelper::stringToUVector2(const String& str)\n{\n\tusing namespace std;\n\n\tUVector2 uv;\n\tsscanf(str.c_str(), \" {{%f,%f},{%f,%f}}\", &uv.d_x.d_scale,&uv.d_x.d_offset, &uv.d_y.d_scale,&uv.d_y.d_offset);\n\n\treturn uv;\n}\n\n\nURect PropertyHelper::stringToURect(const String& str)\n{\n\tusing namespace std;\n\n\tURect ur;\n\tsscanf(\n\t\tstr.c_str(),\n\t\t\" {{%f,%f},{%f,%f},{%f,%f},{%f,%f}}\",\n\t\t&ur.d_min.d_x.d_scale, &ur.d_min.d_x.d_offset,\n\t\t&ur.d_min.d_y.d_scale, &ur.d_min.d_y.d_offset,\n\t\t&ur.d_max.d_x.d_scale, &ur.d_max.d_x.d_offset,\n\t\t&ur.d_max.d_y.d_scale, &ur.d_max.d_y.d_offset\n\t);\n\n\treturn ur;\n}\n\n\nString PropertyHelper::floatToString(float val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"%f\", val);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::uintToString(uint val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"%u\", val);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::intToString(int val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"%d\", val);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::boolToString(bool val)\n{\n\tif (val)\n\t{\n\t\treturn String(\"True\");\n\t}\n\telse\n\t{\n\t\treturn String (\"False\");\n\t}\n\n}\n\n\nString PropertyHelper::sizeToString(const Size& val)\n{\n\tusing namespace std;\n\n\tchar buff[128];\n\tsprintf(buff, \"w:%f h:%f\", val.d_width, val.d_height);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::pointToString(const Point& val)\n{\n\tusing namespace std;\n\n\tchar buff[128];\n\tsprintf(buff, \"x:%f y:%f\", val.d_x, val.d_y);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::rectToString(const Rect& val)\n{\n\tusing namespace std;\n\n\tchar buff[256];\n\tsprintf(buff, \"l:%f t:%f r:%f b:%f\", val.d_left, val.d_top, val.d_right, val.d_bottom);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::imageToString(const Image* const val)\n{\n\tif (val)\n\t{\n\t\treturn String(\"set:\" + val->getImagesetName() + \" image:\" + val->getName());\n\t}\n\n\treturn String(\"\");\n}\n\n\nString PropertyHelper::udimToString(const UDim& val)\n{\n\tusing namespace std;\n\n\tchar buff[128];\n\tsprintf(buff, \"{%f,%f}\", val.d_scale, val.d_offset);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::uvector2ToString(const UVector2& val)\n{\n\tusing namespace std;\n\n\tchar buff[256];\n\tsprintf(buff, \"{{%f,%f},{%f,%f}}\", val.d_x.d_scale, val.d_x.d_offset, val.d_y.d_scale, val.d_y.d_offset);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::urectToString(const URect& val)\n{\n\tusing namespace std;\n\n\tchar buff[512];\n\tsprintf(\n\t\tbuff,\n\t\t\"{{%f,%f},{%f,%f},{%f,%f},{%f,%f}}\",\n\t\tval.d_min.d_x.d_scale,val.d_min.d_x.d_offset,\n\t\tval.d_min.d_y.d_scale,val.d_min.d_y.d_offset,\n\t\tval.d_max.d_x.d_scale,val.d_max.d_x.d_offset,\n\t\tval.d_max.d_y.d_scale,val.d_max.d_y.d_offset\n\t);\n\n\treturn String(buff);\n}\n\n\nString PropertyHelper::colourToString(const colour& val)\n{\n\tusing namespace std;\n\n\tchar buff[16];\n\tsprintf(buff, \"%.8X\", val.getARGB());\n\n\treturn String(buff);\n}\n\n\ncolour PropertyHelper::stringToColour(const String& str)\n{\n\tusing namespace std;\n\n\targb_t val = 0xFF000000;\n\tsscanf(str.c_str(), \" %8X\", &val);\n\n\treturn colour(val);\n\n}\n\n\nString PropertyHelper::colourRectToString(const ColourRect& val)\n{\n\tusing namespace std;\n\n\tchar buff[64];\n\tsprintf(buff, \"tl:%.8X tr:%.8X bl:%.8X br:%.8X\", val.d_top_left.getARGB(), val.d_top_right.getARGB(), val.d_bottom_left.getARGB(), val.d_bottom_right.getARGB());\n\n\treturn String(buff);\n}\n\n\nColourRect PropertyHelper::stringToColourRect(const String& str)\n{\n\tusing namespace std;\n\n\targb_t topLeft = 0xFF000000, topRight = 0xFF000000, bottomLeft = 0xFF000000, bottomRight = 0xFF000000;\n\tsscanf(str.c_str(), \"tl:%8X tr:%8X bl:%8X br:%8X\", &topLeft, &topRight, &bottomLeft, &bottomRight);\n\n\treturn ColourRect(topLeft, topRight, bottomLeft, bottomRight);\n}\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"#include \"CLSmith\/CLOutputMgr.h\"\n\n#include \n\n#include \"CLSmith\/Globals.h\"\n#include \"Function.h\"\n#include \"OutputMgr.h\"\n#include \"Type.h\"\n#include \"VariableSelector.h\"\n\nnamespace CLSmith {\n\nconst std::string kFileName = \"CLProg.c\";\n\nCLOutputMgr::CLOutputMgr() : out_(kFileName.c_str()) {\n}\n\nvoid CLOutputMgr::OutputHeader(int argc, char *argv[], unsigned long seed) {\n \/\/ Redefine platform independent scalar C types to platform independent scalar\n \/\/ OpenCL types.\n std::ostream &out = get_main_out();\n out <<\n \"#define int64_t long\\n\"\n \"#define uint64_t ulong\\n\"\n \"#define int_least64_t long\\n\"\n \"#define uint_least64_t ulong\\n\"\n \"#define int_fast64_t long\\n\"\n \"#define uint_fast64_t ulong\\n\"\n \"#define intmax_t long\\n\"\n \"#define uintmax_t ulong\\n\"\n \"#define int32_t int\\n\"\n \"#define uint32_t uint\\n\"\n \"#define int16_t short\\n\"\n \"#define uint16_t ushort\\n\"\n \"#define int8_t char\\n\"\n \"#define uint8_t uchar\\n\"\n \"\\n\"\n \"#define INT64_MIN LONG_MIN\\n\"\n \"#define INT64_MAX LONG_MAX\\n\"\n \"#define INT32_MIN INT_MIN\\n\"\n \"#define INT32_MAX INT_MAX\\n\"\n \"#define INT16_MIN SHRT_MIN\\n\"\n \"#define INT16_MAX SHRT_MAX\\n\"\n \"#define INT8_MIN CHAR_MIN\\n\"\n \"#define INT8_MAX CHAR_MAX\\n\"\n \"#define UINT64_MIN ULONG_MIN\\n\"\n \"#define UINT64_MAX ULONG_MAX\\n\"\n \"#define UINT32_MIN UINT_MIN\\n\"\n \"#define UINT32_MAX UINT_MAX\\n\"\n \"#define UINT16_MIN USHRT_MIN\\n\"\n \"#define UINT16_MAX USHRT_MAX\\n\"\n \"#define UINT8_MIN UCHAR_MIN\\n\"\n \"#define UINT8_MAX UCHAR_MAX\\n\"\n \"\\n\"\n \"#define transparent_crc(X, Y, Z) \"\n \"transparent_crc_(&crc64_context, X, Y, Z)\\n\"\n << std::endl;\n\n out << std::endl;\n out << \"\/\/ Seed: \" << seed << std::endl;\n out << std::endl;\n out << \"#include \\\"CLSmith.h\\\"\" << std::endl;\n out << std::endl;\n}\n\nvoid CLOutputMgr::Output() {\n std::ostream &out = get_main_out();\n OutputStructUnionDeclarations(out);\n\n Globals globals = Globals::CreateGlobals();\n globals.OutputStructDefinition(out);\n globals.ModifyGlobalVariableReferences();\n globals.AddGlobalStructToAllFunctions();\n\n OutputForwardDeclarations(out);\n OutputFunctions(out);\n OutputEntryFunction(globals);\n}\n\nstd::ostream& CLOutputMgr::get_main_out() {\n return out_;\n}\n\nvoid CLOutputMgr::OutputEntryFunction(Globals& globals) {\n \/\/ Would ideally use the ExtensionMgr, but there is no way to set it to our\n \/\/ own custom made one (without modifying the code).\n std::ostream& out = get_main_out();\n out << \"__kernel void entry(__global ulong *result) {\" << std::endl;\n globals.OutputStructInit(out);\n\n output_tab(out, 1);\n out << \"func_1(\";\n globals.GetGlobalStructVar().Output(out);\n out << \");\" << std::endl;\n\n \/\/ Handle hashing and outputting.\n output_tab(out, 1);\n out << \"uint64_t crc64_context = 0xFFFFFFFFFFFFFFFFUL;\" << std::endl;\n output_tab(out, 1);\n out << \"int print_hash_value = 0;\" << std::endl;\n HashGlobalVariables(out);\n output_tab(out, 1);\n out << \"result[get_global_id(0)] = crc64_context ^ 0xFFFFFFFFFFFFFFFFUL;\"\n << std::endl;\n \n output_tab(out, 1);\n out << \"return 0;\" << std::endl;\n out << \"}\" << std::endl;\n}\n\n} \/\/ namespace CLSmith\nRemove return statement in kernel entry.#include \"CLSmith\/CLOutputMgr.h\"\n\n#include \n\n#include \"CLSmith\/Globals.h\"\n#include \"Function.h\"\n#include \"OutputMgr.h\"\n#include \"Type.h\"\n#include \"VariableSelector.h\"\n\nnamespace CLSmith {\n\nconst std::string kFileName = \"CLProg.c\";\n\nCLOutputMgr::CLOutputMgr() : out_(kFileName.c_str()) {\n}\n\nvoid CLOutputMgr::OutputHeader(int argc, char *argv[], unsigned long seed) {\n \/\/ Redefine platform independent scalar C types to platform independent scalar\n \/\/ OpenCL types.\n std::ostream &out = get_main_out();\n out <<\n \"#define int64_t long\\n\"\n \"#define uint64_t ulong\\n\"\n \"#define int_least64_t long\\n\"\n \"#define uint_least64_t ulong\\n\"\n \"#define int_fast64_t long\\n\"\n \"#define uint_fast64_t ulong\\n\"\n \"#define intmax_t long\\n\"\n \"#define uintmax_t ulong\\n\"\n \"#define int32_t int\\n\"\n \"#define uint32_t uint\\n\"\n \"#define int16_t short\\n\"\n \"#define uint16_t ushort\\n\"\n \"#define int8_t char\\n\"\n \"#define uint8_t uchar\\n\"\n \"\\n\"\n \"#define INT64_MIN LONG_MIN\\n\"\n \"#define INT64_MAX LONG_MAX\\n\"\n \"#define INT32_MIN INT_MIN\\n\"\n \"#define INT32_MAX INT_MAX\\n\"\n \"#define INT16_MIN SHRT_MIN\\n\"\n \"#define INT16_MAX SHRT_MAX\\n\"\n \"#define INT8_MIN CHAR_MIN\\n\"\n \"#define INT8_MAX CHAR_MAX\\n\"\n \"#define UINT64_MIN ULONG_MIN\\n\"\n \"#define UINT64_MAX ULONG_MAX\\n\"\n \"#define UINT32_MIN UINT_MIN\\n\"\n \"#define UINT32_MAX UINT_MAX\\n\"\n \"#define UINT16_MIN USHRT_MIN\\n\"\n \"#define UINT16_MAX USHRT_MAX\\n\"\n \"#define UINT8_MIN UCHAR_MIN\\n\"\n \"#define UINT8_MAX UCHAR_MAX\\n\"\n \"\\n\"\n \"#define transparent_crc(X, Y, Z) \"\n \"transparent_crc_(&crc64_context, X, Y, Z)\\n\"\n << std::endl;\n\n out << std::endl;\n out << \"\/\/ Seed: \" << seed << std::endl;\n out << std::endl;\n out << \"#include \\\"CLSmith.h\\\"\" << std::endl;\n out << std::endl;\n}\n\nvoid CLOutputMgr::Output() {\n std::ostream &out = get_main_out();\n OutputStructUnionDeclarations(out);\n\n Globals globals = Globals::CreateGlobals();\n globals.OutputStructDefinition(out);\n globals.ModifyGlobalVariableReferences();\n globals.AddGlobalStructToAllFunctions();\n\n OutputForwardDeclarations(out);\n OutputFunctions(out);\n OutputEntryFunction(globals);\n}\n\nstd::ostream& CLOutputMgr::get_main_out() {\n return out_;\n}\n\nvoid CLOutputMgr::OutputEntryFunction(Globals& globals) {\n \/\/ Would ideally use the ExtensionMgr, but there is no way to set it to our\n \/\/ own custom made one (without modifying the code).\n std::ostream& out = get_main_out();\n out << \"__kernel void entry(__global ulong *result) {\" << std::endl;\n globals.OutputStructInit(out);\n\n output_tab(out, 1);\n out << \"func_1(\";\n globals.GetGlobalStructVar().Output(out);\n out << \");\" << std::endl;\n\n \/\/ Handle hashing and outputting.\n output_tab(out, 1);\n out << \"uint64_t crc64_context = 0xFFFFFFFFFFFFFFFFUL;\" << std::endl;\n output_tab(out, 1);\n out << \"int print_hash_value = 0;\" << std::endl;\n HashGlobalVariables(out);\n output_tab(out, 1);\n out << \"result[get_global_id(0)] = crc64_context ^ 0xFFFFFFFFFFFFFFFFUL;\"\n << std::endl;\n out << \"}\" << std::endl;\n}\n\n} \/\/ namespace CLSmith\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"c9\/channel9.hpp\"\n#include \"c9\/environment.hpp\"\n#include \"c9\/context.hpp\"\n#include \"c9\/string.hpp\"\n#include \"c9\/value.hpp\"\n#include \"c9\/message.hpp\"\n#include \"c9\/loader.hpp\"\n#include \"c9\/ffi.hpp\"\n\n#include \"ruby.h\"\n\nusing namespace Channel9;\n\nstatic VALUE rb_ruby_mod;\nstatic ID rb_compile;\nstatic ID rb_compile_string;\nstatic ID rb_to_json;\n\n#ifndef STR2CSTR\nconst char *STR2CSTR(VALUE val)\n{\n return StringValuePtr(val);\n}\n#endif\n\nclass NoReturnChannel : public Channel9::CallableContext\n{\npublic:\n\tNoReturnChannel(){}\n\t~NoReturnChannel(){}\n\n\tvoid send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)\n\t{\n\t\tstd::cout << \"Unexpected return to no return channel.\\n\";\n\t\texit(1);\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"No Return Channel\";\n\t}\n};\nNoReturnChannel *no_return_channel = new NoReturnChannel;\n\nclass SetSpecialChannel : public CallableContext\n{\npublic:\n\tSetSpecialChannel(){}\n\t~SetSpecialChannel(){}\n\n\tvoid send(Environment *env, const Value &val, const Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->arg_count() == 2)\n\t\t\t{\n\t\t\t\tif (is(msg->args()[0], STRING))\n\t\t\t\t{\n\t\t\t\t\tenv->set_special_channel(ptr(msg->args()[0])->str(), msg->args()[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tchannel_send(env, ret, val, value(no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Set Special Channel\";\n\t}\n};\n\nclass GlobChannel : public CallableContext\n{\npublic:\n\tGlobChannel(){}\n\t~GlobChannel(){}\n\n\tvoid send(Environment *env, const Value &val, const Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->arg_count() == 1)\n\t\t\t{\n\t\t\t\tif (is(msg->args()[0], STRING))\n\t\t\t\t{\n\t\t\t\t\tString *pattern = ptr(msg->args()[0]);\n\t\t\t\t\tglob_t matches = {0};\n\t\t\t\t\tint ok = glob(pattern->c_str(), 0, NULL, &matches);\n\t\t\t\t\tstd::vector match_vals;\n\t\t\t\t\tif (ok == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t i = 0; i < matches.gl_pathc; i++)\n\t\t\t\t\t\t\tmatch_vals.push_back(value(new_string(matches.gl_pathv[i])));\n\t\t\t\t\t}\n\t\t\t\t\tTuple *res = new_tuple(match_vals.begin(), match_vals.end());\n\t\t\t\t\tchannel_send(env, ret, value(res), value(no_return_channel));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tchannel_send(env, ret, Nil, value(no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Glob Channel\";\n\t}\n};\n\nclass SprintfChannel : public CallableContext\n{\n\tFFIDefinition *m_string_holder;\n\npublic:\n\tSprintfChannel(FFIDefinition *string_holder) : m_string_holder(string_holder) {}\n\t~SprintfChannel(){}\n\n\tvoid send(Environment *env, const Value &val, const Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->arg_count() >= 2)\n\t\t\t{\n\t\t\t\tFFIDefinition *types = new FFIDefinition(\"sprintf args\");\n\t\t\t\ttypes->add_pointer(m_string_holder); \/\/ output pointer\n\t\t\t\ttypes->add_pointer(); \/\/ format string\n\n\t\t\t\tMessage::const_iterator it;\n\t\t\t\tfor (it = msg->args()+2; it != msg->args_end(); it++)\n\t\t\t\t{\n\t\t\t\t\tswitch (type(*it))\n\t\t\t\t\t{\n\t\t\t\t\tcase POSITIVE_NUMBER:\n\t\t\t\t\tcase NEGATIVE_NUMBER:\n\t\t\t\t\t\ttypes->add(&ffi_type_sint);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase FLOAT_NUM:\n\t\t\t\t\t\ttypes->add(&ffi_type_double);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase NIL:\n\t\t\t\t\tcase UNDEF:\n\t\t\t\t\tcase STRING:\n\t\t\t\t\t\ttypes->add_pointer();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase BFALSE:\n\t\t\t\t\tcase BTRUE:\n\t\t\t\t\t\ttypes->add(&ffi_type_uint);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow std::runtime_error(\"Invalid input given to sprintf\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tFFICall *sprintf_call = new FFICall(ffi_fn(asprintf), &ffi_type_sint, types);\n\t\t\t\tsprintf_call->send(env, value(msg), ret);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tchannel_send(env, ret, val, value(no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Sprintf primitive channel\";\n\t}\n};\n\nclass LoaderChannel : public CallableContext\n{\nprivate:\n\tstd::string environment_path;\n\tuint64_t mid_load_c9;\n\tuint64_t mid_load;\n\tuint64_t mid_compile;\n\tuint64_t mid_backtrace;\n\npublic:\n\tLoaderChannel(const std::string &environment_path)\n\t : environment_path(environment_path),\n\t mid_load_c9(make_message_id(\"load_c9\")),\n\t mid_load(make_message_id(\"load\")),\n\t mid_compile(make_message_id(\"compile\")),\n\t mid_backtrace(make_message_id(\"backtrace\"))\n\t{}\n\n\tvoid send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->m_message_id == mid_load_c9 && msg->arg_count() == 1 && is(msg->args()[0], STRING))\n\t\t\t{\n\t\t\t\ttry {\n\t\t\t\t\tstd::string path = environment_path + \"\/\";\n\t\t\t\t\tpath += ptr(*msg->args())->str();\n\t\t\t\t\tGCRef ctx = load_bytecode(env, path);\n\t\t\t\t\tchannel_send(env, value(*ctx), Nil, ret);\n\t\t\t\t\treturn;\n\t\t\t\t} catch (loader_error &err) {\n\t\t\t\t\tchannel_send(env, ret, False, Channel9::value(no_return_channel));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (msg->m_message_id == mid_backtrace) {\n\t\t\t\tstd::vector bt;\n\t\t\t\tRunningContext *ctx;\n\t\t\t\tif (is(ret, RUNNING_CONTEXT))\n\t\t\t\t\tctx = ptr(ret);\n\t\t\t\telse\n\t\t\t\t\tctx = env->context();\n\t\t\t\twhile (ctx)\n\t\t\t\t{\n\t\t\t\t\tSourcePos pos = ctx->m_instructions->source_pos(ctx->m_pos);\n\t\t\t\t\tstd::stringstream posinfo;\n\t\t\t\t\tposinfo << pos.file << \":\" << pos.line_num << \":\" << pos.column;\n\t\t\t\t\tif (!pos.annotation.empty())\n\t\t\t\t\t\tposinfo << \" (\" << pos.annotation << \")\";\n\t\t\t\t\tbt.push_back(value(new_string(posinfo.str())));\n\t\t\t\t\tctx = ctx->m_caller;\n\t\t\t\t}\n\t\t\t\tchannel_send(env, ret, value(new_tuple(bt.begin(), bt.end())), Channel9::value(no_return_channel));\n\t\t\t\treturn;\n\t\t\t} else if (msg->m_message_id == mid_load && msg->arg_count() == 1 && is(msg->args()[0], STRING)) {\n\t\t\t\t\/\/ try to load an alongside bytecode object directly first.\n\t\t\t\tstd::string path = ptr(*msg->args())->str();\n\t\t\t\ttry {\n\t\t\t\t\tGCRef ctx = load_bytecode(env, path + \".c9b\");\n\t\t\t\t\tchannel_send(env, value(*ctx), Nil, ret);\n\t\t\t\t\treturn;\n\t\t\t\t} catch (loader_error &err) {\n\t\t\t\t\t\/\/ now try to compile it.\n\t\t\t\t\tVALUE res = rb_funcall(rb_ruby_mod, rb_compile, 1, rb_str_new2(path.c_str()));\n\t\t\t\t\tif (!NIL_P(res)) {\n\t\t\t\t\t\t\/\/ make it a json string.\n\t\t\t\t\t\tres = rb_funcall(res, rb_to_json, 0);\n\t\t\t\t\t\tGCRef ctx = load_bytecode(env, path, STR2CSTR(res));\n\t\t\t\t\t\tchannel_send(env, value(*ctx), Nil, ret);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchannel_send(env, ret, False, Channel9::value(no_return_channel));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (msg->m_message_id == mid_compile && msg->arg_count() == 4 &&\n\t\t\t\tis(msg->args()[0], STRING) && is(msg->args()[1], STRING) &&\n\t\t\t\tis(msg->args()[2], STRING) && is_number(msg->args()[3])) {\n\t\t\t\tstd::string type = ptr(msg->args()[0])->str();\n\t\t\t\tstd::string path = ptr(msg->args()[1])->str();\n\t\t\t\tstd::string code = ptr(msg->args()[2])->str();\n\t\t\t\tint64_t line_num = msg->args()[3].machine_num;\n\n\t\t\t\tVALUE res = rb_funcall(rb_ruby_mod, rb_compile_string, 4,\n\t\t\t\t\tID2SYM(rb_intern(type.c_str())), rb_str_new2(path.c_str()),\n\t\t\t\t\trb_str_new2(code.c_str()), INT2NUM(line_num));\n\t\t\t\tif (!NIL_P(res)) {\n\t\t\t\t\t\/\/ make it a json string.\n\t\t\t\t\tres = rb_funcall(res, rb_to_json, 0);\n\t\t\t\t\tchannel_send(env, ret, value(*load_bytecode(env, path, STR2CSTR(res))), value(no_return_channel));\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tchannel_send(env, ret, False, value(no_return_channel));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstd::cout << \"Trap: Unknown message to loader: \" << message_names[msg->m_message_id] << \"\\n\";\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\n\t\tchannel_send(env, ret, val, Channel9::value(no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Ruby Loader Channel\";\n\t}\n};\n\nvoid setup_basic_ffi_functions(Environment *env)\n{\n\tFFIDefinition *write_args = new FFIDefinition(\"write args\");\n\twrite_args->add(ffi_type_map());\n\twrite_args->add_pointer();\n\twrite_args->add(ffi_type_map());\n\tFFICall *write_call = new FFICall(ffi_fn(write), ffi_type_map(), write_args);\n\n\tenv->set_special_channel(\"ffi_write\", Channel9::value(write_call));\n\n\tFFIDefinition *time_t_holder = new FFIDefinition(\"time_t holder\");\n\ttime_t_holder->add(\"time\", ffi_type_map());\n\tFFIDefinition *time_now_args = new FFIDefinition(\"time_now_args\");\n\ttime_now_args->add_pointer(time_t_holder);\n\tFFICall *time_now_call = new FFICall(ffi_fn(time), ffi_type_map(), time_now_args);\n\n\tenv->set_special_channel(\"ffi_time_now\", Channel9::value(time_now_call));\n\n\tFFIDefinition *struct_timespec = new FFIDefinition(\"struct timespec\");\n\tstruct_timespec->add(\"tv_sec\", ffi_type_map());\n\tstruct_timespec->add(\"tv_nsec\", ffi_type_map());\n\tFFIDefinition *struct_stat = new FFIDefinition(\"struct stat\");\n\tstruct_stat->add(\"st_dev\", ffi_type_map());\n\tstruct_stat->add(\"st_ino\", ffi_type_map());\n\tstruct_stat->add(\"st_nlink\", ffi_type_map());\n\tstruct_stat->add(\"st_mode\", ffi_type_map());\n\tstruct_stat->add(\"st_uid\", ffi_type_map());\n\tstruct_stat->add(\"st_gid\", ffi_type_map());\n\tstruct_stat->add(ffi_type_map());\n\tstruct_stat->add(\"st_rdev\", ffi_type_map());\n\tstruct_stat->add(\"st_size\", ffi_type_map());\n\tstruct_stat->add(\"st_blksize\", ffi_type_map());\n\tstruct_stat->add(\"st_blocks\", ffi_type_map());\n\tstruct_stat->add(\"st_atim\", struct_timespec);\n\tstruct_stat->add(\"st_mtim\", struct_timespec);\n\tstruct_stat->add(\"st_ctim\", struct_timespec);\n\tstruct_stat->add(ffi_type_map(), 3);\n\tassert(struct_stat->size() == sizeof(struct stat));\n\n\tFFIDefinition *stat_args = new FFIDefinition(\"stat args\");\n\tstat_args->add_pointer(); \/\/ string path\n\tstat_args->add_pointer(struct_stat);\n\tFFICall *stat_call = new FFICall(ffi_fn(stat), &ffi_type_sint, stat_args);\n\n\tenv->set_special_channel(\"ffi_stat\", Channel9::value(stat_call));\n\tenv->set_special_channel(\"ffi_struct_timespec\", Channel9::value(struct_timespec));\n\tenv->set_special_channel(\"ffi_struct_stat\", Channel9::value(struct_stat));\n\n\tFFIDefinition *string_holder = new FFIDefinition(\"string holder\");\n\tstring_holder->add_pointer();\n\tenv->set_special_channel(\"ffi_sprintf_buf\", Channel9::value(string_holder));\n\tenv->set_special_channel(\"ffi_sprintf\", Channel9::value(new SprintfChannel(string_holder)));\n\n\tenv->set_special_channel(\"glob\", Channel9::value(new GlobChannel));\n}\n\nextern \"C\" int Channel9_environment_initialize(Channel9::Environment *env, const std::string &filename)\n{\n\tstd::string path = \"\";\n\tsize_t last_slash = filename.rfind('\/');\n\tif (last_slash != std::string::npos)\n\t\tpath = filename.substr(0, last_slash+1);\n\tValue initial_paths[3] = {\n\t\tvalue(new_string(path + \"lib\")),\n\t\tvalue(new_string(path + \"site-lib\")),\n\t\tvalue(new_string(\".\")),\n\t};\n\n\tenv->set_special_channel(\"set_special_channel\", Channel9::value(new SetSpecialChannel));\n\tenv->set_special_channel(\"initial_load_path\", Channel9::value(new_tuple(initial_paths, initial_paths + 3)));\n\tenv->set_special_channel(\"loader\", Channel9::value(new LoaderChannel(path)));\n\n\tsetup_basic_ffi_functions(env);\n\n\truby_init();\n\truby_init_loadpath();\n\tVALUE rb_load_path = rb_gv_get(\"LOAD_PATH\");\n\trb_ary_push(rb_load_path, rb_str_new2(C9_RUBY_LIB));\n\trb_ary_push(rb_load_path, rb_str_new2(C9RB_RUBY_LIB));\n\truby_script(\"channel9.rb\");\n\n\trb_ruby_mod = rb_define_module_under(rb_define_module(\"Channel9\"), \"Ruby\");\n\trb_compile_string = rb_intern(\"compile_string\");\n\trb_compile = rb_intern(\"compile\");\n\trb_to_json = rb_intern(\"to_json\");\n\n\trb_require(\"rubygems\");\n\trb_require(\"channel9\/ruby\");\n\n\treturn 0;\n}\nno_return_channel needs to be GC-accessible.#include \n#include \n\n#include \"c9\/channel9.hpp\"\n#include \"c9\/environment.hpp\"\n#include \"c9\/context.hpp\"\n#include \"c9\/string.hpp\"\n#include \"c9\/value.hpp\"\n#include \"c9\/message.hpp\"\n#include \"c9\/loader.hpp\"\n#include \"c9\/ffi.hpp\"\n\n#include \"ruby.h\"\n\nusing namespace Channel9;\n\nstatic VALUE rb_ruby_mod;\nstatic ID rb_compile;\nstatic ID rb_compile_string;\nstatic ID rb_to_json;\n\n#ifndef STR2CSTR\nconst char *STR2CSTR(VALUE val)\n{\n return StringValuePtr(val);\n}\n#endif\n\nclass NoReturnChannel : public Channel9::CallableContext\n{\npublic:\n\tNoReturnChannel(){}\n\t~NoReturnChannel(){}\n\n\tvoid send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)\n\t{\n\t\tstd::cout << \"Unexpected return to no return channel.\\n\";\n\t\texit(1);\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"No Return Channel\";\n\t}\n};\nGCRef no_return_channel = new NoReturnChannel;\n\nclass SetSpecialChannel : public CallableContext\n{\npublic:\n\tSetSpecialChannel(){}\n\t~SetSpecialChannel(){}\n\n\tvoid send(Environment *env, const Value &val, const Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->arg_count() == 2)\n\t\t\t{\n\t\t\t\tif (is(msg->args()[0], STRING))\n\t\t\t\t{\n\t\t\t\t\tenv->set_special_channel(ptr(msg->args()[0])->str(), msg->args()[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tchannel_send(env, ret, val, value(*no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Set Special Channel\";\n\t}\n};\n\nclass GlobChannel : public CallableContext\n{\npublic:\n\tGlobChannel(){}\n\t~GlobChannel(){}\n\n\tvoid send(Environment *env, const Value &val, const Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->arg_count() == 1)\n\t\t\t{\n\t\t\t\tif (is(msg->args()[0], STRING))\n\t\t\t\t{\n\t\t\t\t\tString *pattern = ptr(msg->args()[0]);\n\t\t\t\t\tglob_t matches = {0};\n\t\t\t\t\tint ok = glob(pattern->c_str(), 0, NULL, &matches);\n\t\t\t\t\tstd::vector match_vals;\n\t\t\t\t\tif (ok == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t i = 0; i < matches.gl_pathc; i++)\n\t\t\t\t\t\t\tmatch_vals.push_back(value(new_string(matches.gl_pathv[i])));\n\t\t\t\t\t}\n\t\t\t\t\tTuple *res = new_tuple(match_vals.begin(), match_vals.end());\n\t\t\t\t\tchannel_send(env, ret, value(res), value(*no_return_channel));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tchannel_send(env, ret, Nil, value(*no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Glob Channel\";\n\t}\n};\n\nclass SprintfChannel : public CallableContext\n{\n\tFFIDefinition *m_string_holder;\n\npublic:\n\tSprintfChannel(FFIDefinition *string_holder) : m_string_holder(string_holder) {}\n\t~SprintfChannel(){}\n\n\tvoid send(Environment *env, const Value &val, const Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->arg_count() >= 2)\n\t\t\t{\n\t\t\t\tFFIDefinition *types = new FFIDefinition(\"sprintf args\");\n\t\t\t\ttypes->add_pointer(m_string_holder); \/\/ output pointer\n\t\t\t\ttypes->add_pointer(); \/\/ format string\n\n\t\t\t\tMessage::const_iterator it;\n\t\t\t\tfor (it = msg->args()+2; it != msg->args_end(); it++)\n\t\t\t\t{\n\t\t\t\t\tswitch (type(*it))\n\t\t\t\t\t{\n\t\t\t\t\tcase POSITIVE_NUMBER:\n\t\t\t\t\tcase NEGATIVE_NUMBER:\n\t\t\t\t\t\ttypes->add(&ffi_type_sint);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase FLOAT_NUM:\n\t\t\t\t\t\ttypes->add(&ffi_type_double);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase NIL:\n\t\t\t\t\tcase UNDEF:\n\t\t\t\t\tcase STRING:\n\t\t\t\t\t\ttypes->add_pointer();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase BFALSE:\n\t\t\t\t\tcase BTRUE:\n\t\t\t\t\t\ttypes->add(&ffi_type_uint);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow std::runtime_error(\"Invalid input given to sprintf\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tFFICall *sprintf_call = new FFICall(ffi_fn(asprintf), &ffi_type_sint, types);\n\t\t\t\tsprintf_call->send(env, value(msg), ret);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tchannel_send(env, ret, val, value(*no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Sprintf primitive channel\";\n\t}\n};\n\nclass LoaderChannel : public CallableContext\n{\nprivate:\n\tstd::string environment_path;\n\tuint64_t mid_load_c9;\n\tuint64_t mid_load;\n\tuint64_t mid_compile;\n\tuint64_t mid_backtrace;\n\npublic:\n\tLoaderChannel(const std::string &environment_path)\n\t : environment_path(environment_path),\n\t mid_load_c9(make_message_id(\"load_c9\")),\n\t mid_load(make_message_id(\"load\")),\n\t mid_compile(make_message_id(\"compile\")),\n\t mid_backtrace(make_message_id(\"backtrace\"))\n\t{}\n\n\tvoid send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)\n\t{\n\t\tif (is(val, MESSAGE))\n\t\t{\n\t\t\tMessage *msg = ptr(val);\n\t\t\tif (msg->m_message_id == mid_load_c9 && msg->arg_count() == 1 && is(msg->args()[0], STRING))\n\t\t\t{\n\t\t\t\ttry {\n\t\t\t\t\tstd::string path = environment_path + \"\/\";\n\t\t\t\t\tpath += ptr(*msg->args())->str();\n\t\t\t\t\tGCRef ctx = load_bytecode(env, path);\n\t\t\t\t\tchannel_send(env, value(*ctx), Nil, ret);\n\t\t\t\t\treturn;\n\t\t\t\t} catch (loader_error &err) {\n\t\t\t\t\tchannel_send(env, ret, False, Channel9::value(*no_return_channel));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (msg->m_message_id == mid_backtrace) {\n\t\t\t\tstd::vector bt;\n\t\t\t\tRunningContext *ctx;\n\t\t\t\tif (is(ret, RUNNING_CONTEXT))\n\t\t\t\t\tctx = ptr(ret);\n\t\t\t\telse\n\t\t\t\t\tctx = env->context();\n\t\t\t\twhile (ctx)\n\t\t\t\t{\n\t\t\t\t\tSourcePos pos = ctx->m_instructions->source_pos(ctx->m_pos);\n\t\t\t\t\tstd::stringstream posinfo;\n\t\t\t\t\tposinfo << pos.file << \":\" << pos.line_num << \":\" << pos.column;\n\t\t\t\t\tif (!pos.annotation.empty())\n\t\t\t\t\t\tposinfo << \" (\" << pos.annotation << \")\";\n\t\t\t\t\tbt.push_back(value(new_string(posinfo.str())));\n\t\t\t\t\tctx = ctx->m_caller;\n\t\t\t\t}\n\t\t\t\tchannel_send(env, ret, value(new_tuple(bt.begin(), bt.end())), Channel9::value(*no_return_channel));\n\t\t\t\treturn;\n\t\t\t} else if (msg->m_message_id == mid_load && msg->arg_count() == 1 && is(msg->args()[0], STRING)) {\n\t\t\t\t\/\/ try to load an alongside bytecode object directly first.\n\t\t\t\tstd::string path = ptr(*msg->args())->str();\n\t\t\t\ttry {\n\t\t\t\t\tGCRef ctx = load_bytecode(env, path + \".c9b\");\n\t\t\t\t\tchannel_send(env, value(*ctx), Nil, ret);\n\t\t\t\t\treturn;\n\t\t\t\t} catch (loader_error &err) {\n\t\t\t\t\t\/\/ now try to compile it.\n\t\t\t\t\tVALUE res = rb_funcall(rb_ruby_mod, rb_compile, 1, rb_str_new2(path.c_str()));\n\t\t\t\t\tif (!NIL_P(res)) {\n\t\t\t\t\t\t\/\/ make it a json string.\n\t\t\t\t\t\tres = rb_funcall(res, rb_to_json, 0);\n\t\t\t\t\t\tGCRef ctx = load_bytecode(env, path, STR2CSTR(res));\n\t\t\t\t\t\tchannel_send(env, value(*ctx), Nil, ret);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchannel_send(env, ret, False, Channel9::value(*no_return_channel));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (msg->m_message_id == mid_compile && msg->arg_count() == 4 &&\n\t\t\t\tis(msg->args()[0], STRING) && is(msg->args()[1], STRING) &&\n\t\t\t\tis(msg->args()[2], STRING) && is_number(msg->args()[3])) {\n\t\t\t\tstd::string type = ptr(msg->args()[0])->str();\n\t\t\t\tstd::string path = ptr(msg->args()[1])->str();\n\t\t\t\tstd::string code = ptr(msg->args()[2])->str();\n\t\t\t\tint64_t line_num = msg->args()[3].machine_num;\n\n\t\t\t\tVALUE res = rb_funcall(rb_ruby_mod, rb_compile_string, 4,\n\t\t\t\t\tID2SYM(rb_intern(type.c_str())), rb_str_new2(path.c_str()),\n\t\t\t\t\trb_str_new2(code.c_str()), INT2NUM(line_num));\n\t\t\t\tif (!NIL_P(res)) {\n\t\t\t\t\t\/\/ make it a json string.\n\t\t\t\t\tres = rb_funcall(res, rb_to_json, 0);\n\t\t\t\t\tchannel_send(env, ret, value(*load_bytecode(env, path, STR2CSTR(res))), value(*no_return_channel));\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tchannel_send(env, ret, False, value(*no_return_channel));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstd::cout << \"Trap: Unknown message to loader: \" << message_names[msg->m_message_id] << \"\\n\";\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\n\t\tchannel_send(env, ret, val, Channel9::value(*no_return_channel));\n\t}\n\tstd::string inspect() const\n\t{\n\t\treturn \"Ruby Loader Channel\";\n\t}\n};\n\nvoid setup_basic_ffi_functions(Environment *env)\n{\n\tFFIDefinition *write_args = new FFIDefinition(\"write args\");\n\twrite_args->add(ffi_type_map());\n\twrite_args->add_pointer();\n\twrite_args->add(ffi_type_map());\n\tFFICall *write_call = new FFICall(ffi_fn(write), ffi_type_map(), write_args);\n\n\tenv->set_special_channel(\"ffi_write\", Channel9::value(write_call));\n\n\tFFIDefinition *time_t_holder = new FFIDefinition(\"time_t holder\");\n\ttime_t_holder->add(\"time\", ffi_type_map());\n\tFFIDefinition *time_now_args = new FFIDefinition(\"time_now_args\");\n\ttime_now_args->add_pointer(time_t_holder);\n\tFFICall *time_now_call = new FFICall(ffi_fn(time), ffi_type_map(), time_now_args);\n\n\tenv->set_special_channel(\"ffi_time_now\", Channel9::value(time_now_call));\n\n\tFFIDefinition *struct_timespec = new FFIDefinition(\"struct timespec\");\n\tstruct_timespec->add(\"tv_sec\", ffi_type_map());\n\tstruct_timespec->add(\"tv_nsec\", ffi_type_map());\n\tFFIDefinition *struct_stat = new FFIDefinition(\"struct stat\");\n\tstruct_stat->add(\"st_dev\", ffi_type_map());\n\tstruct_stat->add(\"st_ino\", ffi_type_map());\n\tstruct_stat->add(\"st_nlink\", ffi_type_map());\n\tstruct_stat->add(\"st_mode\", ffi_type_map());\n\tstruct_stat->add(\"st_uid\", ffi_type_map());\n\tstruct_stat->add(\"st_gid\", ffi_type_map());\n\tstruct_stat->add(ffi_type_map());\n\tstruct_stat->add(\"st_rdev\", ffi_type_map());\n\tstruct_stat->add(\"st_size\", ffi_type_map());\n\tstruct_stat->add(\"st_blksize\", ffi_type_map());\n\tstruct_stat->add(\"st_blocks\", ffi_type_map());\n\tstruct_stat->add(\"st_atim\", struct_timespec);\n\tstruct_stat->add(\"st_mtim\", struct_timespec);\n\tstruct_stat->add(\"st_ctim\", struct_timespec);\n\tstruct_stat->add(ffi_type_map(), 3);\n\tassert(struct_stat->size() == sizeof(struct stat));\n\n\tFFIDefinition *stat_args = new FFIDefinition(\"stat args\");\n\tstat_args->add_pointer(); \/\/ string path\n\tstat_args->add_pointer(struct_stat);\n\tFFICall *stat_call = new FFICall(ffi_fn(stat), &ffi_type_sint, stat_args);\n\n\tenv->set_special_channel(\"ffi_stat\", Channel9::value(stat_call));\n\tenv->set_special_channel(\"ffi_struct_timespec\", Channel9::value(struct_timespec));\n\tenv->set_special_channel(\"ffi_struct_stat\", Channel9::value(struct_stat));\n\n\tFFIDefinition *string_holder = new FFIDefinition(\"string holder\");\n\tstring_holder->add_pointer();\n\tenv->set_special_channel(\"ffi_sprintf_buf\", Channel9::value(string_holder));\n\tenv->set_special_channel(\"ffi_sprintf\", Channel9::value(new SprintfChannel(string_holder)));\n\n\tenv->set_special_channel(\"glob\", Channel9::value(new GlobChannel));\n}\n\nextern \"C\" int Channel9_environment_initialize(Channel9::Environment *env, const std::string &filename)\n{\n\tstd::string path = \"\";\n\tsize_t last_slash = filename.rfind('\/');\n\tif (last_slash != std::string::npos)\n\t\tpath = filename.substr(0, last_slash+1);\n\tValue initial_paths[3] = {\n\t\tvalue(new_string(path + \"lib\")),\n\t\tvalue(new_string(path + \"site-lib\")),\n\t\tvalue(new_string(\".\")),\n\t};\n\n\tenv->set_special_channel(\"set_special_channel\", Channel9::value(new SetSpecialChannel));\n\tenv->set_special_channel(\"initial_load_path\", Channel9::value(new_tuple(initial_paths, initial_paths + 3)));\n\tenv->set_special_channel(\"loader\", Channel9::value(new LoaderChannel(path)));\n\n\tsetup_basic_ffi_functions(env);\n\n\truby_init();\n\truby_init_loadpath();\n\tVALUE rb_load_path = rb_gv_get(\"LOAD_PATH\");\n\trb_ary_push(rb_load_path, rb_str_new2(C9_RUBY_LIB));\n\trb_ary_push(rb_load_path, rb_str_new2(C9RB_RUBY_LIB));\n\truby_script(\"channel9.rb\");\n\n\trb_ruby_mod = rb_define_module_under(rb_define_module(\"Channel9\"), \"Ruby\");\n\trb_compile_string = rb_intern(\"compile_string\");\n\trb_compile = rb_intern(\"compile\");\n\trb_to_json = rb_intern(\"to_json\");\n\n\trb_require(\"rubygems\");\n\trb_require(\"channel9\/ruby\");\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\ntemplate< typename T > void readSIGPROC(Observation & observation, const unsigned int bytestoSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(Observation & observation, unsigned int bytesToSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = 4;\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrSamplesPerPaddedSecond() * observation.getNrChannels());\n\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n\t\t\t\tinputFile.read(buffer, BUFFER_DIM);\n data.at(second)[(static_cast< long long unsigned int >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample] = *(reinterpret_cast< T * >(buffer));\n\t\t\t}\n\t\t}\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openH5::Group(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openH5::Group(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openH5::Group(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openH5::DataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(second)[(static_cast< long long unsigned int >(second) * observation.getNrSamplesPerSecond()) + sample] = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\nSmall typos due to the automatic refactoring.\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\ntemplate< typename T > void readSIGPROC(Observation & observation, const unsigned int bytestoSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(Observation & observation, unsigned int bytesToSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = 4;\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrSamplesPerPaddedSecond() * observation.getNrChannels());\n\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n\t\t\t\tinputFile.read(buffer, BUFFER_DIM);\n data.at(second)[(static_cast< long long unsigned int >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample] = *(reinterpret_cast< T * >(buffer));\n\t\t\t}\n\t\t}\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(second)[(static_cast< long long unsigned int >(second) * observation.getNrSamplesPerSecond()) + sample] = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<|endoftext|>"} {"text":"#ifndef SRL_HASH_HPP\n#define SRL_HASH_HPP\n\n#include \"Hash.h\"\n#include \"Aux.h\"\n\nnamespace Srl { namespace Lib {\n\n namespace Aux {\n\n template struct Arch;\n\n template<> struct Arch<8> {\n\n static const uint64_t Mul = 0xC6A4A7935BD1E995;\n static const uint64_t Base = 0xCBF29CE484222325;\n static const uint64_t Shr = 47;\n\n static size_t hash_rem (const uint8_t* bytes, size_t nbytes, size_t hash)\n {\n switch(nbytes % 8) {\n case 7 : hash ^= (size_t)bytes[6] << 48;\n case 6 : hash ^= (size_t)bytes[5] << 40;\n case 5 : hash ^= (size_t)bytes[4] << 32;\n case 4 : hash ^= (size_t)bytes[3] << 24;\n case 3 : hash ^= (size_t)bytes[2] << 16;\n case 2 : hash ^= (size_t)bytes[1] << 8;\n case 1 : hash ^= (size_t)bytes[0];\n hash *= Mul;\n };\n\n hash ^= hash >> Shr;\n hash *= Mul;\n hash ^= hash >> Shr;\n\n return hash;\n }\n };\n\n template<> struct Arch<4> {\n \n static const uint32_t Mul = 0x5BD1E995;\n static const uint32_t Base = 0x811C9DC5;\n static const uint32_t Shr = 24;\n\n static size_t hash_rem (const uint8_t* bytes, size_t nbytes, size_t hash)\n {\n switch(nbytes % 4) {\n case 3 : hash ^= (size_t)bytes[2] << 16;\n case 2 : hash ^= (size_t)bytes[1] << 8;\n case 1 : hash ^= (size_t)bytes[0];\n hash *= Mul;\n };\n\n hash ^= hash >> 13;\n hash *= Mul;\n hash ^= hash >> 15;\n\n return hash;\n }\n };\n }\n\n inline size_t murmur_hash2(const uint8_t * bytes, size_t nbytes)\n {\n const size_t Wordlen = sizeof(size_t);\n\n const size_t mul = Aux::Arch::Mul;\n const size_t shr = Aux::Arch::Shr;\n const size_t base = Aux::Arch::Base;\n\n size_t hash = base ^ (nbytes * mul);\n\n for(; nbytes >= Wordlen; nbytes -= Wordlen, bytes += Wordlen) {\n\n auto b = Aux::read(bytes);\n b *= mul; \n b ^= b >> shr; \n b *= mul; \n\n hash ^= b;\n hash *= mul; \n }\n\n return Aux::Arch::hash_rem(bytes, nbytes, hash);\n } \n\n template\n size_t HTable::get_bucket(size_t hash)\n {\n \/* mix in the upper half bits of the hash unless table capacity is bigger 2 ^ (bits in word \/ 2) - 1 *\/\n const auto shift = sizeof(size_t) * 4;\n const auto max = ~(size_t)0 >> shift;\n\n return (this->cap <= max ? hash ^ hash >> shift : hash) & (this->cap - 1);\n }\n\n template __attribute__ ((noinline))\n void HTable::redistribute()\n {\n if(this->limit == 0) {\n \/* initial allocation *\/\n this->table.resize(cap);\n this->limit = cap * load_factor;\n\n return;\n }\n\n auto old_dim = this->cap;\n this->cap *= 2;\n this->limit = cap * load_factor;\n\n std::vector ntable { this->cap };\n\n for(auto i = 0U; i < old_dim; i++) {\n auto* entry = table[i];\n while(entry) {\n auto hash = entry->hash;\n auto bucket = get_bucket(hash);\n auto* slot = ntable[bucket];\n\n if(slot) while(true) {\n if(!slot->next) {\n slot->next = entry;\n break;\n }\n slot = slot->next;\n\n } else {\n ntable[bucket] = entry;\n }\n\n auto* tmp = entry;\n entry = entry->next;\n tmp->next = nullptr;\n }\n }\n\n this->table = std::move(ntable);\n }\n\n template\n V* HTable::get(const K& key)\n {\n if(srl_unlikely(elements < 1)) return nullptr;\n\n auto hash = hash_fnc(key);\n auto bucket = get_bucket(hash);\n Entry* entry = table[bucket];\n\n while(entry) {\n if(entry->hash == hash) {\n return &entry->val;\n\n } else {\n entry = entry->next;\n }\n }\n\n return nullptr;\n }\n \n template\n std::pair HTable::insert(const K& key, const V& val)\n {\n auto hash = hash_fnc(key);\n return insert_hash(hash, val);\n }\n\n template\n std::pair HTable::insert_hash(size_t hash, const V& val)\n {\n if(srl_unlikely(this->elements >= this->limit)) this->redistribute();\n\n auto bucket = get_bucket(hash);\n Entry* entry = table[bucket];\n Entry* node = nullptr;\n\n while(entry) {\n\n if(entry->hash == hash) return { true, &entry->val };\n\n node = entry;\n entry = entry->next;\n }\n\n this->elements++;\n\n auto& slot = node ? node->next : table[bucket];\n slot = this->heap.create(hash, val);\n\n return { false, &slot->val };\n }\n\n template template\n typename std::enable_if::value, void>::type\n HTable::clear()\n {\n if(this->elements < 1) return;\n\n for(auto i = 0U; i < this->cap; i++) {\n auto* entry = table[i];\n while(entry) {\n entry->val.~V();\n entry = entry->next;\n }\n }\n }\n\n} }\n\n#endif\nUpdate Hash.hpp#ifndef SRL_HASH_HPP\n#define SRL_HASH_HPP\n\n#include \"Hash.h\"\n#include \"Aux.h\"\n\nnamespace Srl { namespace Lib {\n\n namespace Aux {\n\n template struct Arch;\n\n template<> struct Arch<8> {\n\n static const uint64_t Mul = 0xC6A4A7935BD1E995;\n static const uint64_t Base = 0xCBF29CE484222325;\n static const uint64_t Shr = 47;\n\n static size_t hash_rem (const uint8_t* bytes, size_t nbytes, size_t hash)\n {\n switch(nbytes % 8) {\n case 7 : hash ^= (size_t)bytes[6] << 48;\n case 6 : hash ^= (size_t)bytes[5] << 40;\n case 5 : hash ^= (size_t)bytes[4] << 32;\n case 4 : hash ^= (size_t)bytes[3] << 24;\n case 3 : hash ^= (size_t)bytes[2] << 16;\n case 2 : hash ^= (size_t)bytes[1] << 8;\n case 1 : hash ^= (size_t)bytes[0];\n hash *= Mul;\n };\n\n hash ^= hash >> Shr;\n hash *= Mul;\n hash ^= hash >> Shr;\n\n return hash;\n }\n };\n\n template<> struct Arch<4> {\n \n static const uint32_t Mul = 0x5BD1E995;\n static const uint32_t Base = 0x811C9DC5;\n static const uint32_t Shr = 24;\n\n static size_t hash_rem (const uint8_t* bytes, size_t nbytes, size_t hash)\n {\n switch(nbytes % 4) {\n case 3 : hash ^= (size_t)bytes[2] << 16;\n case 2 : hash ^= (size_t)bytes[1] << 8;\n case 1 : hash ^= (size_t)bytes[0];\n hash *= Mul;\n };\n\n hash ^= hash >> 13;\n hash *= Mul;\n hash ^= hash >> 15;\n\n return hash;\n }\n };\n }\n\n inline size_t murmur_hash2(const uint8_t * bytes, size_t nbytes)\n {\n const size_t Wordlen = sizeof(size_t);\n\n const size_t mul = Aux::Arch::Mul;\n const size_t shr = Aux::Arch::Shr;\n const size_t base = Aux::Arch::Base;\n\n size_t hash = base ^ (nbytes * mul);\n\n for(; nbytes >= Wordlen; nbytes -= Wordlen, bytes += Wordlen) {\n\n auto b = Aux::read(bytes);\n b *= mul; \n b ^= b >> shr; \n b *= mul; \n\n hash ^= b;\n hash *= mul; \n }\n\n return Aux::Arch::hash_rem(bytes, nbytes, hash);\n } \n\n template\n size_t HTable::get_bucket(size_t hash)\n {\n \/* mix in the upper half bits of the hash unless table capacity is bigger 2 ^ (bits in word \/ 2) - 1 *\/\n const auto shift = sizeof(size_t) * 4;\n const auto max = ~(size_t)0 >> shift;\n\n return (this->cap <= max ? hash ^ hash >> shift : hash) & (this->cap - 1);\n }\n\n template __attribute__ ((noinline))\n void HTable::redistribute()\n {\n if(this->limit == 0) {\n \/* initial allocation *\/\n this->table.resize(cap);\n this->limit = cap * load_factor;\n\n return;\n }\n\n auto old_dim = this->cap;\n this->cap *= 2;\n this->limit = cap * load_factor;\n\n std::vector ntable { this->cap };\n\n for(auto i = 0U; i < old_dim; i++) {\n auto* entry = table[i];\n while(entry) {\n auto bucket = get_bucket(entry->hash);\n auto* slot = ntable[bucket];\n\n if(slot) while(true) {\n if(!slot->next) {\n slot->next = entry;\n break;\n }\n slot = slot->next;\n\n } else {\n ntable[bucket] = entry;\n }\n\n auto* tmp = entry;\n entry = entry->next;\n tmp->next = nullptr;\n }\n }\n\n this->table = std::move(ntable);\n }\n\n template\n V* HTable::get(const K& key)\n {\n if(srl_unlikely(elements < 1))\n return nullptr;\n\n auto hash = hash_fnc(key);\n auto bucket = get_bucket(hash);\n Entry* entry = table[bucket];\n\n while(entry) {\n if(entry->hash == hash) {\n return &entry->val;\n\n } else {\n entry = entry->next;\n }\n }\n\n return nullptr;\n }\n \n template\n std::pair HTable::insert(const K& key, const V& val)\n {\n auto hash = hash_fnc(key);\n return insert_hash(hash, val);\n }\n\n template\n std::pair HTable::insert_hash(size_t hash, const V& val)\n {\n if(srl_unlikely(this->elements >= this->limit))\n this->redistribute();\n\n auto bucket = get_bucket(hash);\n Entry* entry = table[bucket];\n Entry* node = nullptr;\n\n while(entry) {\n\n if(entry->hash == hash)\n return { true, &entry->val };\n\n node = entry;\n entry = entry->next;\n }\n\n this->elements++;\n\n auto& slot = node ? node->next : table[bucket];\n slot = this->heap.create(hash, val);\n\n return { false, &slot->val };\n }\n\n template template\n typename std::enable_if::value, void>::type\n HTable::clear()\n {\n if(this->elements < 1) return;\n\n for(auto i = 0U; i < this->cap; i++) {\n auto* entry = table[i];\n while(entry) {\n entry->val.~V();\n entry = entry->next;\n }\n }\n }\n\n} }\n\n#endif\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace kdb;\n\nvoid printError(Key error)\n{\n\tif (!error.getMeta(\"error\"))\n\t{\n\t\t\/\/ no error available\n\t\treturn;\n\t}\n\n\ttry{\n\t\terror.getMeta(\"error\");\n\t\tstd::cerr << \"Error number \" << error.getMeta(\"error\/number\") << \" occurred!\" << std::endl;\n\t\tstd::cerr << \"description: \" << error.getMeta(\"error\/description\") << std::endl;\n\t\tstd::cerr << \"ingroup: \" << error.getMeta(\"error\/ingroup\") << std::endl;\n\t\tstd::cerr << \"module: \" << error.getMeta(\"error\/module\") << std::endl;\n\t\tstd::cerr << \"at: \" << error.getMeta(\"error\/file\") << \":\" << error.getMeta(\"error\/line\") << std::endl;\n\t\tstd::cerr << \"reason: \" << error.getMeta(\"error\/reason\") << std::endl;\n\t} catch (KeyMetaException const& e)\n\t{\n\t\tstd::cerr << \"Error meta data is not set correctly by a plugin\" << std::endl;\n\t}\n}\n\nvoid printWarnings(Key error)\n{\n\tif (!error.getMeta(\"warnings\"))\n\t{\n\t\t\/\/ no warnings were issued\n\t\treturn;\n\t}\n\n\ttry{\n\t\tint nr = error.getMeta(\"warnings\");\n\t\tstd::cerr << nr+1 << \" Warnings were issued\" << std::endl;\n\n\t\tfor (int i=0; i<=nr; i++)\n\t\t{\n\t\t\tstd::ostringstream name;\n\t\t\tname << \"warnings\/#\" << std::setfill('0') << std::setw(2) << i;\n\t\t\tstd::cerr << name.str() << \": \" << error.getMeta(name.str()) << std::endl;\n\t\t\tstd::cerr << \"number: \" << error.getMeta(name.str() + \"\/number\") << std::endl;\n\t\t\tstd::cerr << \"description: \" << error.getMeta(name.str() + \"\/description\") << std::endl;\n\t\t\tstd::cerr << \"ingroup: \" << error.getMeta(name.str() + \"\/ingroup\") << std::endl;\n\t\t\tstd::cerr << \"module: \" << error.getMeta(name.str() + \"\/module\") << std::endl;\n\t\t\tstd::cerr << \"at: \" << error.getMeta(name.str() + \"\/file\") << \":\"\n\t\t\t\t<< error.getMeta(name.str() + \"\/line\") << std::endl;\n\t\t\tstd::cerr << \"reason: \" << error.getMeta(name.str() + \"\/reason\") << std::endl;\n\t\t}\n\n\t} catch (KeyMetaException const& e)\n\t{\n\t\tstd::cerr << \"Warnings meta data not set correctly by a plugin\" << std::endl;\n\t}\n}\nMake warnings more pretty#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace kdb;\n\nvoid printError(Key error)\n{\n\tif (!error.getMeta(\"error\"))\n\t{\n\t\t\/\/ no error available\n\t\treturn;\n\t}\n\n\ttry{\n\t\terror.getMeta(\"error\");\n\t\tstd::cerr << \"Error number \" << error.getMeta(\"error\/number\") << \" occurred!\" << std::endl;\n\t\tstd::cerr << \"Description: \" << error.getMeta(\"error\/description\") << std::endl;\n\t\tstd::cerr << \"Ingroup: \" << error.getMeta(\"error\/ingroup\") << std::endl;\n\t\tstd::cerr << \"Module: \" << error.getMeta(\"error\/module\") << std::endl;\n\t\tstd::cerr << \"At: \" << error.getMeta(\"error\/file\") << \":\" << error.getMeta(\"error\/line\") << std::endl;\n\t\tstd::cerr << \"Reason: \" << error.getMeta(\"error\/reason\") << std::endl;\n\t} catch (KeyMetaException const& e)\n\t{\n\t\tstd::cerr << \"Error meta data is not set correctly by a plugin\" << std::endl;\n\t}\n}\n\nvoid printWarnings(Key error)\n{\n\tif (!error.getMeta(\"warnings\"))\n\t{\n\t\t\/\/ no warnings were issued\n\t\treturn;\n\t}\n\n\ttry{\n\t\tint nr = error.getMeta(\"warnings\");\n\t\tif (!nr)\n\t\t{\n\t\t\tstd::cerr << \"1 Warning was issued:\" << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << nr+1 << \" Warnings were issued:\" << std::endl;\n\t\t}\n\n\t\tfor (int i=0; i<=nr; i++)\n\t\t{\n\t\t\tstd::ostringstream name;\n\t\t\tname << \"warnings\/#\" << std::setfill('0') << std::setw(2) << i;\n\t\t\t\/\/ std::cerr << \"\\t\" << name.str() << \": \" << error.getMeta(name.str()) << std::endl;\n\t\t\tstd::cerr << \"\\tWarning number: \" << error.getMeta(name.str() + \"\/number\") << std::endl;\n\t\t\tstd::cerr << \"\\tDescription: \" << error.getMeta(name.str() + \"\/description\") << std::endl;\n\t\t\tstd::cerr << \"\\tIngroup: \" << error.getMeta(name.str() + \"\/ingroup\") << std::endl;\n\t\t\tstd::cerr << \"\\tModule: \" << error.getMeta(name.str() + \"\/module\") << std::endl;\n\t\t\tstd::cerr << \"\\tAt: \" << error.getMeta(name.str() + \"\/file\") << \":\"\n\t\t\t\t << error.getMeta(name.str() + \"\/line\") << std::endl;\n\t\t\tstd::cerr << \"\\tReason: \" << error.getMeta(name.str() + \"\/reason\") << std::endl;\n\t\t}\n\n\t} catch (KeyMetaException const& e)\n\t{\n\t\tstd::cerr << \"Warnings meta data not set correctly by a plugin\" << std::endl;\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012, Prevas A\/S\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of Prevas A\/S nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n *\n *\n * \\author Morten Kjaergaard\n *\/\n\n#pragma once\n\n#include \n#include \n\nnamespace darc\n{\n\ntemplate\nstruct state\n{\n const static unsigned int value = State;\n};\n\ntemplate\nclass fsm\n{\nprotected:\n \/\/** Internal stuff\n unsigned int state_;\n\n fsm() :\n state_(0)\n {\n }\n\npublic:\n template\n void post_event(Event& event)\n {\n Derived* d_this = (Derived*)this;\n\n switch(state_)\n {\n case 0:\n d_this->handle(state<0>(), event);\n break;\n case 1:\n d_this->handle(state<1>(), event);\n break;\n case 2:\n d_this->handle(state<2>(), event);\n break;\n case 3:\n d_this->handle(state<3>(), event);\n break;\n case 4:\n d_this->handle(state<4>(), event);\n break;\n case 5:\n d_this->handle(state<5>(), event);\n break;\n default:\n assert(0);\n break;\n }\n }\n\n template\n void trans(const State&)\n {\n state_ = State::value;\n BOOST_STATIC_ASSERT((State::value <= 5));\n }\n\n};\n\n}\nadded arguments to fsm\/*\n * Copyright (c) 2012, Prevas A\/S\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of Prevas A\/S nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n *\n *\n * \\author Morten Kjaergaard\n *\/\n\n#pragma once\n\n#include \n#include \n\nnamespace darc\n{\n\ntemplate\nstruct state\n{\n const static unsigned int value = State;\n};\n\nstruct arg0\n{\n};\n\ntemplate\nstruct arg1\n{\n T1& a1_;\n\n arg1(T1& a1) :\n a1_(a1)\n {\n }\n};\n\ntemplate\narg1 wrap(T1& a1)\n{\n return arg1(a1);\n}\n\nextern arg0 arg0_alloc;\n\ntemplate\nclass fsm\n{\nprotected:\n \/\/** Internal stuff\n unsigned int state_;\n\n fsm() :\n state_(0)\n {\n }\n\npublic:\n template\n void post_event(Event& event,\n Arguments& arg = arg0_alloc)\n {\n Derived* d_this = (Derived*)this;\n\n switch(state_)\n {\n case 0:\n d_this->handle(state<0>(), event, arg);\n break;\n case 1:\n d_this->handle(state<1>(), event, arg);\n break;\n case 2:\n d_this->handle(state<2>(), event, arg);\n break;\n case 3:\n d_this->handle(state<3>(), event, arg);\n break;\n case 4:\n d_this->handle(state<4>(), event, arg);\n break;\n case 5:\n d_this->handle(state<5>(), event, arg);\n break;\n default:\n assert(0);\n break;\n }\n }\n\n template\n void trans(const State&)\n {\n state_ = State::value;\n BOOST_STATIC_ASSERT((State::value <= 5));\n }\n\n};\n\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file fast_div.hpp\n\/\/\/ @brief Integer division of small types is much faster than\n\/\/\/ integer division of large types on most CPUs. The\n\/\/\/ fast_div(x, y) function tries to take advantage of\n\/\/\/ this by casting x and y to smaller types (if possible)\n\/\/\/ before doing the division.\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef FAST_DIV_HPP\n#define FAST_DIV_HPP\n\n#include \n\n#include \n#include \n#include \n\nnamespace primecount {\n\ntemplate \nstruct fastdiv\n{\n typedef typename std::conditional::type>::type type;\n};\n\ntemplate \ntypename std::enable_if<(sizeof(X) == sizeof(Y)), X>::type\nfast_div(X x, Y y)\n{\n static_assert(prt::is_integral::value &&\n prt::is_integral::value,\n \"fast_div(x, y): types must be integral\");\n\n using fastdiv_t = typename fastdiv::type;\n\n if (x <= std::numeric_limits::max() &&\n y <= std::numeric_limits::max())\n {\n return (fastdiv_t) x \/ (fastdiv_t) y;\n }\n\n return x \/ y;\n}\n\ntemplate \ntypename std::enable_if<(sizeof(X) > sizeof(Y)), X>::type\nfast_div(X x, Y y)\n{\n static_assert(prt::is_integral::value &&\n prt::is_integral::value,\n \"fast_div(x, y): types must be integral\");\n\n using fastdiv_t = typename fastdiv::type;\n\n if (x <= std::numeric_limits::max())\n return (fastdiv_t) x \/ (fastdiv_t) y;\n\n return x \/ y;\n}\n\n\/\/\/ Optimized (128-bit \/ 64-bit) = 64-bit, for x64.\n\/\/\/ uint64_t fast_div64(uint128_t x, uint64_t x)\ntemplate \ntypename std::enable_if<(sizeof(X) == sizeof(uint64_t) * 2 &&\n sizeof(Y) <= sizeof(uint64_t)), uint64_t>::type\nfast_div64(X x, Y y)\n{\n#if defined(__x86_64__) && \\\n (defined(__GNUC__) || defined(__clang__))\n\n \/\/ primecount does not need signed division so \n \/\/ we use the unsigned division instruction further\n \/\/ down as DIV is usually faster than IDIV.\n assert(x >= 0 && y > 0);\n\n uint64_t result;\n uint64_t remainder;\n uint64_t x0 = (uint64_t) x;\n uint64_t x1 = ((uint64_t*) &x)[1];\n uint64_t d = y;\n\n \/\/ We know the result is 64-bit (even though the\n \/\/ numerator is 128-bit) so we can use the divq\n \/\/ instruction instead of doing a full 128-bit division.\n __asm__(\"divq %[divider]\"\n : \"=a\"(result), \"=d\"(remainder)\n : \"a\"(x0), \"d\"(x1), [divider] \"r\"(d)\n );\n\n return result;\n#else\n return (uint64_t) fast_div(x, y);\n#endif\n}\n\n\/\/\/ (?-bit \/ 64-bit) = 64-bit\ntemplate \ntypename std::enable_if::type\nfast_div64(X x, Y y)\n{\n return (uint64_t) fast_div(x, y);\n}\n\n} \/\/ namespace\n\n#endif\nUpdate comment\/\/\/\n\/\/\/ @file fast_div.hpp\n\/\/\/ @brief Integer division of small types is much faster than\n\/\/\/ integer division of large types on most CPUs. The\n\/\/\/ fast_div(x, y) function tries to take advantage of\n\/\/\/ this by casting x and y to smaller types (if possible)\n\/\/\/ before doing the division.\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef FAST_DIV_HPP\n#define FAST_DIV_HPP\n\n#include \n\n#include \n#include \n#include \n\nnamespace primecount {\n\ntemplate \nstruct fastdiv\n{\n typedef typename std::conditional::type>::type type;\n};\n\ntemplate \ntypename std::enable_if<(sizeof(X) == sizeof(Y)), X>::type\nfast_div(X x, Y y)\n{\n static_assert(prt::is_integral::value &&\n prt::is_integral::value,\n \"fast_div(x, y): types must be integral\");\n\n using fastdiv_t = typename fastdiv::type;\n\n if (x <= std::numeric_limits::max() &&\n y <= std::numeric_limits::max())\n {\n return (fastdiv_t) x \/ (fastdiv_t) y;\n }\n\n return x \/ y;\n}\n\ntemplate \ntypename std::enable_if<(sizeof(X) > sizeof(Y)), X>::type\nfast_div(X x, Y y)\n{\n static_assert(prt::is_integral::value &&\n prt::is_integral::value,\n \"fast_div(x, y): types must be integral\");\n\n using fastdiv_t = typename fastdiv::type;\n\n if (x <= std::numeric_limits::max())\n return (fastdiv_t) x \/ (fastdiv_t) y;\n\n return x \/ y;\n}\n\n\/\/\/ Optimized (128-bit \/ 64-bit) = 64-bit, for x64.\n\/\/\/ uint64_t fast_div64(uint128_t x, uint64_t x)\ntemplate \ntypename std::enable_if<(sizeof(X) == sizeof(uint64_t) * 2 &&\n sizeof(Y) <= sizeof(uint64_t)), uint64_t>::type\nfast_div64(X x, Y y)\n{\n#if defined(__x86_64__) && \\\n (defined(__GNUC__) || defined(__clang__))\n\n \/\/ primecount does not need signed division so \n \/\/ we use the unsigned division instruction further\n \/\/ down as DIV is usually faster than IDIV.\n assert(x >= 0 && y > 0);\n\n uint64_t result;\n uint64_t remainder;\n uint64_t x0 = (uint64_t) x;\n uint64_t x1 = ((uint64_t*) &x)[1];\n uint64_t d = y;\n\n \/\/ (128-bit \/ 64-bit) = 64-bit.\n \/\/ When we know the result fits into 64-bit (even\n \/\/ though the numerator is 128-bit) we can use the divq\n \/\/ instruction instead of doing a full 128-bit division.\n __asm__(\"divq %[divider]\"\n : \"=a\"(result), \"=d\"(remainder)\n : \"a\"(x0), \"d\"(x1), [divider] \"r\"(d)\n );\n\n return result;\n#else\n return (uint64_t) fast_div(x, y);\n#endif\n}\n\n\/\/\/ (?-bit \/ 64-bit) = 64-bit\ntemplate \ntypename std::enable_if::type\nfast_div64(X x, Y y)\n{\n return (uint64_t) fast_div(x, y);\n}\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"\/*-----------------------------------------------------------------------------------------------\nThe MIT License (MIT)\n\nCopyright (c) 2015-2020 OSRE ( Open Source Render Engine ) by Kim Kulling\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n-----------------------------------------------------------------------------------------------*\/\n\n#include \n\nnamespace OSRE {\nnamespace Common {\n \nEvent::Event( const String &id )\n: m_numRefs( 1 )\n, m_hash( StringUtils::hashName( id.c_str() ) )\n, m_eventData( nullptr ) {\n \/\/ empty\n}\n\nEvent::~Event() {\n \/\/ empty\n}\n\nvoid Event::setEventData( const EventData *pData ) {\n m_eventData = pData;\n}\n\nconst EventData *Event::getEventData() const {\n return m_eventData;\n}\n\nui32 Event::getHash() const {\n return m_hash;\n}\n\nvoid Event::get() {\n ++m_numRefs;\n}\n\nvoid Event::release() {\n --m_numRefs;\n if ( 0 == m_numRefs ) {\n delete this;\n }\n}\n\nbool Event::operator == ( const Event &rhs ) const {\n return ( m_hash == rhs.m_hash );\n}\n\nEventData::EventData( const Event& e, EventTriggerer* c )\n: m_Event( e )\n, m_Source( c )\n, m_timestamp( 0.0 )\n, m_numRefs( 1 ) {\n \/\/ empty\n}\n\nEventData::~EventData() {\n \/\/ empty\n}\n\nconst Event& EventData::getEvent() const {\n return m_Event;\n}\n\nEventTriggerer* EventData::getEventSender() const {\n return m_Source;\n}\n\nvoid EventData::get() {\n ++m_numRefs;\n}\n\nvoid EventData::release() {\n if ( m_numRefs ) {\n --m_numRefs;\n if ( 0 == m_numRefs ) {\n delete this;\n }\n }\n}\n\nbool EventData::operator == ( const EventData &other ) const {\n return ( m_Event == other.m_Event && m_Source == other.m_Source );\n}\n\n} \/\/ Namespace Common\n} \/\/ Namespace OSRE\nUpdate Event.cpp\/*-----------------------------------------------------------------------------------------------\nThe MIT License (MIT)\n\nCopyright (c) 2015-2020 OSRE ( Open Source Render Engine ) by Kim Kulling\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n-----------------------------------------------------------------------------------------------*\/\n\n#include \n\nnamespace OSRE {\nnamespace Common {\n \nEvent::Event( const String &id ) :\n m_numRefs( 1 ), \n m_hash( StringUtils::hashName( id.c_str() ) ),\n m_eventData( nullptr ) {\n \/\/ empty\n}\n\nEvent::~Event() {\n \/\/ empty\n}\n\nvoid Event::setEventData( const EventData *pData ) {\n m_eventData = pData;\n}\n\nconst EventData *Event::getEventData() const {\n return m_eventData;\n}\n\nui32 Event::getHash() const {\n return m_hash;\n}\n\nvoid Event::get() {\n ++m_numRefs;\n}\n\nvoid Event::release() {\n --m_numRefs;\n if ( 0 == m_numRefs ) {\n delete this;\n }\n}\n\nbool Event::operator == ( const Event &rhs ) const {\n return ( m_hash == rhs.m_hash );\n}\n\nEventData::EventData( const Event& e, EventTriggerer* c ) :\n m_Event( e ),\n m_Source( c ), m_timestamp( 0.0 ),\n m_numRefs( 1 ) {\n \/\/ empty\n}\n\nEventData::~EventData() {\n \/\/ empty\n}\n\nconst Event& EventData::getEvent() const {\n return m_Event;\n}\n\nEventTriggerer* EventData::getEventSender() const {\n return m_Source;\n}\n\nvoid EventData::get() {\n ++m_numRefs;\n}\n\nvoid EventData::release() {\n if ( m_numRefs ) {\n --m_numRefs;\n if ( 0 == m_numRefs ) {\n delete this;\n }\n }\n}\n\nbool EventData::operator == ( const EventData &other ) const {\n return ( m_Event == other.m_Event && m_Source == other.m_Source );\n}\n\n} \/\/ Namespace Common\n} \/\/ Namespace OSRE\n<|endoftext|>"} {"text":"\n\n#include \"instance.hpp\"\n#include \"manager.hpp\"\n#include \"broker.hpp\"\n#include \"log.hpp\"\n#include \"config.hpp\"\n#include \"configloader.hpp\"\n\nnamespace cossb {\nnamespace core {\n\n\nbool cossb_init(base::config* config)\n{\n\t\/\/1. create instances for system base\n\tmanager::system_manager::get()->setup(config);\n\n\t\/\/2. system authentication\n\n\n\n\treturn true;\n}\n\nvoid cossb_destroy()\n{\n\tmanager::component_manager::get()->destroy();\n\tbroker::component_broker::get()->destroy();\n}\n\n\n\n} \/* namespace core *\/\n} \/* namespace cossb *\/\nadd comment for guiding initial sequence\n\n#include \"instance.hpp\"\n#include \"manager.hpp\"\n#include \"broker.hpp\"\n#include \"log.hpp\"\n#include \"config.hpp\"\n#include \"configloader.hpp\"\n\nnamespace cossb {\nnamespace core {\n\n\nbool cossb_init(base::config* config)\n{\n\t\/\/1. create instances for system base\n\tmanager::system_manager::get()->setup(config);\n\n\t\/\/2. system authentication from server\n\n\t\/\/3. repository check\n\n\t\/\/4. access to local database\n\n\t\/\/5. start cossb engine\n\n\n\n\treturn true;\n}\n\nvoid cossb_destroy()\n{\n\t\/\/1. disconnect to servers and databases\n\n\t\/\/2. destroy all instances\n\tmanager::component_manager::get()->destroy();\n\tbroker::component_broker::get()->destroy();\n}\n\n\n\n} \/* namespace core *\/\n} \/* namespace cossb *\/\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"c\/SYS_fstat.h\"\n#include \"c\/struct-stat.h\"\n#include \"Result.hxx\"\n\nnamespace os {\n\nstatic inline\nauto\nfstat(int fd, struct stat* buf) noexcept\n{\n#define _(name) _##name = name\n enum Error\n {\n#if defined(__linux__) || defined(__FreeBSD__)\n# include \"c\/EBADF.h\"\n# include \"c\/EFAULT.h\"\n _(EBADF),\n _(EFAULT),\n#endif\n#if defined(__FreeBSD__)\n# include \"c\/EIO.h\"\n _(EIO),\n#endif\n#if defined(__linux__)\n# include \"c\/ENOMEM.h\"\n _(ENOMEM),\n#endif\n#if defined(__linux__) || defined(__FreeBSD__)\n# include \"c\/EOVERFLOW.h\"\n _(EOVERFLOW),\n#endif\n };\n#undef _\n\n return Result(SYS_fstat, fd, buf);\n}\n\n}\nfstat error documentation#pragma once\n\n#include \"c\/SYS_fstat.h\"\n#include \"c\/struct-stat.h\"\n#include \"Result.hxx\"\n\nnamespace os {\n\nstatic inline\nauto\nfstat(int fd, struct stat* sb) noexcept\n{\n#define _(name, doc) _##name = name\n enum Error\n {\n#if defined(__FreeBSD__) || defined(__linux__)\n# include \"c\/EBADF.h\"\n# include \"c\/EFAULT.h\"\n\n _(EBADF,\n \"`fd` is not a valid open file descriptor.\"),\n\n _(EFAULT,\n \"`sb` points to an invalid address.\"),\n\n#endif\n#if defined(__FreeBSD__)\n# include \"c\/EIO.h\"\n\n _(EIO,\n \"An I\/O error occurred while reading from or writing to the file system.\"),\n\n#endif\n#if defined(__linux__)\n# include \"c\/ENOMEM.h\"\n\n _(ENOMEM,\n \"Out of kernel memory.\"),\n\n#endif\n#if defined(__FreeBSD__) || defined(__linux__)\n# include \"c\/EOVERFLOW.h\"\n\n _(EOVERFLOW,\n \"The file size in bytes cannot be represented correctly\"\n \" in the structure pointed to by `sb`.\"),\n\n#endif\n };\n#undef _\n\n return Result(SYS_fstat, fd, sb);\n}\n\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file primesum.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License.\n\/\/\/\n\n#ifndef PRIMESUM_HPP\n#define PRIMESUM_HPP\n\n#include \n#include \n#include \n\n#define PRIMESUM_VERSION \"1.0\"\n#define PRIMESUM_VERSION_MAJOR 1\n#define PRIMESUM_VERSION_MINOR 0\n\nnamespace primesum {\n\nclass primesum_error : public std::runtime_error\n{\npublic:\n primesum_error(const std::string& msg)\n : std::runtime_error(msg)\n { }\n};\n\n\/\/\/ 128-bit prime summing function.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/ @param expr Integer arithmetic expression e.g. \"1000\", \"10^22\"\n\/\/\/ @pre expr <= get_max_x()\n\/\/\/\nstd::string pi(const std::string& x);\n\n\/\/\/ Enable\/disable printing status information during computation.\nvoid set_print_status(bool print_status);\n\n\/\/\/ Set the number of threads.\nvoid set_num_threads(int num_threads);\n\n\/\/\/ Get the currently set number of threads.\nint get_num_threads();\n\n\/\/\/ Largest integer supported by pi(const std::string& x).\n\/\/\/ The return type is a string as max may be a 128-bit integer\n\/\/\/ which is not supported by some compilers.\n\/\/\/ @param alpha Tuning factor used in LMO type algorithms.\n\/\/\/ @return for 32-bit CPUs: 2^63-1, \n\/\/\/ for 64-bit CPUs: max >= 10^27\n\/\/\/\nstd::string get_max_x(double alpha = 1.0);\n\n\/\/\/ Get the primesum version number, in the form “i.j”.\nstd::string primesum_version();\n\n} \/\/ namespace\n\n#endif\nUpdate version to 1.1\/\/\/\n\/\/\/ @file primesum.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License.\n\/\/\/\n\n#ifndef PRIMESUM_HPP\n#define PRIMESUM_HPP\n\n#include \n#include \n#include \n\n#define PRIMESUM_VERSION \"1.1\"\n#define PRIMESUM_VERSION_MAJOR 1\n#define PRIMESUM_VERSION_MINOR 1\n\nnamespace primesum {\n\nclass primesum_error : public std::runtime_error\n{\npublic:\n primesum_error(const std::string& msg)\n : std::runtime_error(msg)\n { }\n};\n\n\/\/\/ 128-bit prime summing function.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/ @param expr Integer arithmetic expression e.g. \"1000\", \"10^22\"\n\/\/\/ @pre expr <= get_max_x()\n\/\/\/\nstd::string pi(const std::string& x);\n\n\/\/\/ Enable\/disable printing status information during computation.\nvoid set_print_status(bool print_status);\n\n\/\/\/ Set the number of threads.\nvoid set_num_threads(int num_threads);\n\n\/\/\/ Get the currently set number of threads.\nint get_num_threads();\n\n\/\/\/ Largest integer supported by pi(const std::string& x).\n\/\/\/ The return type is a string as max may be a 128-bit integer\n\/\/\/ which is not supported by some compilers.\n\/\/\/ @param alpha Tuning factor used in LMO type algorithms.\n\/\/\/ @return for 32-bit CPUs: 2^63-1, \n\/\/\/ for 64-bit CPUs: max >= 10^27\n\/\/\/\nstd::string get_max_x(double alpha = 1.0);\n\n\/\/\/ Get the primesum version number, in the form “i.j”.\nstd::string primesum_version();\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"#include \"keytar.h\"\n\n#include \n#include \n\nnamespace keytar {\n\nstd::string getErrorMessage(DWORD errorCode) {\n LPVOID errBuffer;\n ::FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER |\n FORMAT_MESSAGE_FROM_SYSTEM,\n NULL,\n errorCode,\n 0,\n (LPTSTR) &errBuffer,\n 0,\n NULL\n );\n std::string errMsg = std::string((char*) errBuffer);\n LocalFree(errBuffer);\n return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n const std::string& account,\n const std::string& password,\n std::string* errStr) {\n std::string target_name = service + '\/' + account;\n\n CREDENTIAL cred = { 0 };\n cred.Type = CRED_TYPE_GENERIC;\n cred.TargetName = const_cast(target_name.c_str());\n cred.CredentialBlobSize = password.size();\n cred.CredentialBlob = (LPBYTE)(password.data());\n cred.Persist = CRED_PERSIST_LOCAL_MACHINE;\n\n bool result = ::CredWrite(&cred, 0);\n if (!result) {\n *errStr = getErrorMessage(::GetLastError());\n return FAIL_ERROR;\n } else\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n const std::string& account,\n std::string* password,\n std::string* errStr) {\n std::string target_name = service + '\/' + account;\n\n CREDENTIAL* cred;\n bool result = ::CredRead(target_name.c_str(), CRED_TYPE_GENERIC, 0, &cred);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND)\n return FAIL_NONFATAL;\n else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(cred->CredentialBlob),\n cred->CredentialBlobSize);\n ::CredFree(cred);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n const std::string& account,\n std::string* errStr) {\n std::string target_name = service + '\/' + account;\n\n bool result = ::CredDelete(target_name.c_str(), CRED_TYPE_GENERIC, 0);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND)\n return FAIL_NONFATAL;\n else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n std::string* password,\n std::string* errStr) {\n std::string filter = service + \"*\";\n\n DWORD count;\n CREDENTIAL** creds;\n bool result = ::CredEnumerate(filter.c_str(), 0, &count, &creds);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND)\n return FAIL_NONFATAL;\n else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(creds[0]->CredentialBlob),\n creds[0]->CredentialBlobSize);\n ::CredFree(creds);\n return SUCCESS;\n}\n\n} \/\/ namespace keytar\n:shirt:#include \"keytar.h\"\n\n#include \n#include \n\nnamespace keytar {\n\nstd::string getErrorMessage(DWORD errorCode) {\n LPVOID errBuffer;\n ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL, errorCode, 0, (LPTSTR) &errBuffer, 0, NULL);\n std::string errMsg = std::string(reinterpret_cast(errBuffer));\n LocalFree(errBuffer);\n return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n const std::string& account,\n const std::string& password,\n std::string* errStr) {\n std::string target_name = service + '\/' + account;\n\n CREDENTIAL cred = { 0 };\n cred.Type = CRED_TYPE_GENERIC;\n cred.TargetName = const_cast(target_name.c_str());\n cred.CredentialBlobSize = password.size();\n cred.CredentialBlob = (LPBYTE)(password.data());\n cred.Persist = CRED_PERSIST_LOCAL_MACHINE;\n\n bool result = ::CredWrite(&cred, 0);\n if (!result) {\n *errStr = getErrorMessage(::GetLastError());\n return FAIL_ERROR;\n } else {\n return SUCCESS;\n }\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n const std::string& account,\n std::string* password,\n std::string* errStr) {\n std::string target_name = service + '\/' + account;\n\n CREDENTIAL* cred;\n bool result = ::CredRead(target_name.c_str(), CRED_TYPE_GENERIC, 0, &cred);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(cred->CredentialBlob),\n cred->CredentialBlobSize);\n ::CredFree(cred);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n const std::string& account,\n std::string* errStr) {\n std::string target_name = service + '\/' + account;\n\n bool result = ::CredDelete(target_name.c_str(), CRED_TYPE_GENERIC, 0);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n std::string* password,\n std::string* errStr) {\n std::string filter = service + \"*\";\n\n DWORD count;\n CREDENTIAL** creds;\n bool result = ::CredEnumerate(filter.c_str(), 0, &count, &creds);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(creds[0]->CredentialBlob),\n creds[0]->CredentialBlobSize);\n ::CredFree(creds);\n return SUCCESS;\n}\n\n} \/\/ namespace keytar\n<|endoftext|>"} {"text":"#include \"keytar.h\"\n\n#define UNICODE\n\n#include \n#include \n\n#include \"credentials.h\"\n\nnamespace keytar {\n\nLPWSTR utf8ToWideChar(std::string utf8) {\n int wide_char_length = MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n NULL,\n 0);\n if (wide_char_length == 0) {\n return NULL;\n }\n\n LPWSTR result = new WCHAR[wide_char_length];\n if (MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n result,\n wide_char_length) == 0) {\n delete[] result;\n return NULL;\n }\n\n return result;\n}\n\nstd::string wideCharToAnsi(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int ansi_length = WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (ansi_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[ansi_length];\n if (WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n buffer,\n ansi_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string wideCharToUtf8(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int utf8_length = WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (utf8_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[utf8_length];\n if (WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n buffer,\n utf8_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string getErrorMessage(DWORD errorCode) {\n LPWSTR errBuffer;\n ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL, errorCode, 0, (LPWSTR) &errBuffer, 0, NULL);\n std::string errMsg = wideCharToAnsi(errBuffer);\n LocalFree(errBuffer);\n return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n const std::string& account,\n const std::string& password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n LPWSTR user_name = utf8ToWideChar(account);\n if (user_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL cred = { 0 };\n cred.Type = CRED_TYPE_GENERIC;\n cred.TargetName = target_name;\n cred.UserName = user_name;\n cred.CredentialBlobSize = password.size();\n cred.CredentialBlob = (LPBYTE)(password.data());\n cred.Persist = CRED_PERSIST_ENTERPRISE;\n\n bool result = ::CredWrite(&cred, 0);\n delete[] target_name;\n if (!result) {\n *errStr = getErrorMessage(::GetLastError());\n return FAIL_ERROR;\n } else {\n return SUCCESS;\n }\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n const std::string& account,\n std::string* password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL* cred;\n bool result = ::CredRead(target_name, CRED_TYPE_GENERIC, 0, &cred);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(cred->CredentialBlob),\n cred->CredentialBlobSize);\n ::CredFree(cred);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n const std::string& account,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n bool result = ::CredDelete(target_name, CRED_TYPE_GENERIC, 0);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n std::string* password,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n if (filter == NULL) {\n return FAIL_ERROR;\n }\n\n DWORD count;\n CREDENTIAL** creds;\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n delete[] filter;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(creds[0]->CredentialBlob),\n creds[0]->CredentialBlobSize);\n ::CredFree(creds);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindCredentials(const std::string& service,\n std::vector* credentials,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n\n DWORD count;\n CREDENTIAL **creds;\n\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n for (unsigned int i = 0; i < count; ++i) {\n CREDENTIAL* cred = creds[i];\n\n if (cred->UserName == NULL || cred->CredentialBlobSize == NULL) {\n continue;\n }\n\n std::string login = wideCharToUtf8(cred->UserName);\n std::string password(\n reinterpret_cast(\n cred->CredentialBlob),\n cred->CredentialBlobSize);\n\n credentials->push_back(Credentials(login, password));\n }\n\n CredFree(creds);\n\n return SUCCESS;\n}\n\n\n} \/\/ namespace keytar\nguard null to match remainder of calls in file#include \"keytar.h\"\n\n#define UNICODE\n\n#include \n#include \n\n#include \"credentials.h\"\n\nnamespace keytar {\n\nLPWSTR utf8ToWideChar(std::string utf8) {\n int wide_char_length = MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n NULL,\n 0);\n if (wide_char_length == 0) {\n return NULL;\n }\n\n LPWSTR result = new WCHAR[wide_char_length];\n if (MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n result,\n wide_char_length) == 0) {\n delete[] result;\n return NULL;\n }\n\n return result;\n}\n\nstd::string wideCharToAnsi(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int ansi_length = WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (ansi_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[ansi_length];\n if (WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n buffer,\n ansi_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string wideCharToUtf8(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int utf8_length = WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (utf8_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[utf8_length];\n if (WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n buffer,\n utf8_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string getErrorMessage(DWORD errorCode) {\n LPWSTR errBuffer;\n ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL, errorCode, 0, (LPWSTR) &errBuffer, 0, NULL);\n std::string errMsg = wideCharToAnsi(errBuffer);\n LocalFree(errBuffer);\n return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n const std::string& account,\n const std::string& password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n LPWSTR user_name = utf8ToWideChar(account);\n if (user_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL cred = { 0 };\n cred.Type = CRED_TYPE_GENERIC;\n cred.TargetName = target_name;\n cred.UserName = user_name;\n cred.CredentialBlobSize = password.size();\n cred.CredentialBlob = (LPBYTE)(password.data());\n cred.Persist = CRED_PERSIST_ENTERPRISE;\n\n bool result = ::CredWrite(&cred, 0);\n delete[] target_name;\n if (!result) {\n *errStr = getErrorMessage(::GetLastError());\n return FAIL_ERROR;\n } else {\n return SUCCESS;\n }\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n const std::string& account,\n std::string* password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL* cred;\n bool result = ::CredRead(target_name, CRED_TYPE_GENERIC, 0, &cred);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(cred->CredentialBlob),\n cred->CredentialBlobSize);\n ::CredFree(cred);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n const std::string& account,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n bool result = ::CredDelete(target_name, CRED_TYPE_GENERIC, 0);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n std::string* password,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n if (filter == NULL) {\n return FAIL_ERROR;\n }\n\n DWORD count;\n CREDENTIAL** creds;\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n delete[] filter;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(creds[0]->CredentialBlob),\n creds[0]->CredentialBlobSize);\n ::CredFree(creds);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindCredentials(const std::string& service,\n std::vector* credentials,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n if (filter == NULL) {\n return FAIL_ERROR;\n }\n\n DWORD count;\n CREDENTIAL **creds;\n\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n for (unsigned int i = 0; i < count; ++i) {\n CREDENTIAL* cred = creds[i];\n\n if (cred->UserName == NULL || cred->CredentialBlobSize == NULL) {\n continue;\n }\n\n std::string login = wideCharToUtf8(cred->UserName);\n std::string password(\n reinterpret_cast(\n cred->CredentialBlob),\n cred->CredentialBlobSize);\n\n credentials->push_back(Credentials(login, password));\n }\n\n CredFree(creds);\n\n return SUCCESS;\n}\n\n\n} \/\/ namespace keytar\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n\nextern \"C\"\nstruct TensorWrapper niBlackThreshold(struct TensorWrapper src, struct TensorWrapper dst, double maxValue, int type, int blockSize, double delta);\n\n\n\/\/ GraphSegmentation\nstruct GraphSegmentationPtr {\n void *ptr;\n\n inline cv::ximgproc::segmentation::GraphSegmentation * operator->() { return static_cast(ptr); }\n inline cv::ximgproc::segmentation::GraphSegmentation * operator*() { return static_cast(ptr); }\n inline GraphSegmentationPtr(cv::ximgproc::segmentation::GraphSegmentation *ptr) { this->ptr = ptr; }\n};\n\n\/\/ GraphSegmentation\nextern \"C\"\nstruct GraphSegmentationPtr GraphSegmentation_ctor(double sigma, float k, int min_size);\n\nextern \"C\"\nstruct TensorWrapper GraphSegmentation_processImage(struct GraphSegmentationPtr ptr, struct TensorWrapper);\n\nextern \"C\"\nvoid GraphSegmentation_setSigma(struct GraphSegmentationPtr ptr, double s);\n\nextern \"C\"\ndouble GraphSegmentation_getSigma(struct GraphSegmentationPtr ptr);\n\nextern \"C\"\nvoid GraphSegmentation_setK(struct GraphSegmentationPtr ptr, float k);\n\nextern \"C\"\nfloat GraphSegmentation_getK(struct GraphSegmentationPtr ptr);\n\nextern \"C\"\nvoid GraphSegmentation_setMinSize(struct GraphSegmentationPtr ptr, int min_size);\n\nextern \"C\"\nint GraphSegmentation_getMinSize(struct GraphSegmentationPtr ptr);\n\n\n\/\/ SelectiveSearchSegmentationStrategy\nstruct SelectiveSearchSegmentationStrategyPtr {\n void *ptr;\n\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator->() { return static_cast(ptr); }\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator*() { return static_cast(ptr); }\n inline SelectiveSearchSegmentationStrategyPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *ptr) { this->ptr = ptr; }\n};\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyColor_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategySize_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyTexture_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyFill_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ void SelectiveSearchSegmentationStrategy_setImage(struct SelectiveSearchSegmentationStrategyPtr ptr, struct TensorWrapper, struct TensorWrapper, struct TensorWrapper, int);\n\/\/\n\/\/ extern \"C\"\n\/\/ float SelectiveSearchSegmentationStrategy_get(int, int);\n\/\/\n\/\/ extern \"C\"\n\/\/ void SelectiveSearchSegmentationStrategy_merge(int, int);\n\n\n\/\/ MULTIPLE STRTEGY\n\/\/\n\n\/\/ See #103\n#ifndef APPLE\n\n\/\/ SelectiveSearchSegmentation\nstruct SelectiveSearchSegmentationPtr {\n void *ptr;\n\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator->() { return static_cast(ptr); }\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator*() { return static_cast(ptr); }\n inline SelectiveSearchSegmentationPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentation *ptr) { this->ptr = ptr; }\n};\n\nextern \"C\"\nstruct SelectiveSearchSegmentationPtr SelectiveSearchSegmentation_ctor();\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_setBaseImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_switchToSingleStrategy(struct SelectiveSearchSegmentationPtr ptr, int, float);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_switchToSelectiveSearchFast(struct SelectiveSearchSegmentationPtr ptr, int, int, float);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_switchToSelectiveSearchQuality(struct SelectiveSearchSegmentationPtr ptr, int, int, float);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_addImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_clearImages(struct SelectiveSearchSegmentationPtr ptr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_addGraphSegmentation(struct SelectiveSearchSegmentationPtr ptr, struct GraphSegmentationPtr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_clearGraphSegmentations(struct SelectiveSearchSegmentationPtr ptr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_addStrategy(struct SelectiveSearchSegmentationPtr ptr, struct SelectiveSearchSegmentationStrategyPtr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_clearStrategies(struct SelectiveSearchSegmentationPtr ptr);\n\nextern \"C\"\nstruct RectArray SelectiveSearchSegmentation_process(struct SelectiveSearchSegmentationPtr ptr);\n\n#endif\nVery last fix to #103#include \n#include \n#include \n\n\nextern \"C\"\nstruct TensorWrapper niBlackThreshold(struct TensorWrapper src, struct TensorWrapper dst, double maxValue, int type, int blockSize, double delta);\n\n\n\/\/ GraphSegmentation\nstruct GraphSegmentationPtr {\n void *ptr;\n\n inline cv::ximgproc::segmentation::GraphSegmentation * operator->() { return static_cast(ptr); }\n inline cv::ximgproc::segmentation::GraphSegmentation * operator*() { return static_cast(ptr); }\n inline GraphSegmentationPtr(cv::ximgproc::segmentation::GraphSegmentation *ptr) { this->ptr = ptr; }\n};\n\n\/\/ GraphSegmentation\nextern \"C\"\nstruct GraphSegmentationPtr GraphSegmentation_ctor(double sigma, float k, int min_size);\n\nextern \"C\"\nstruct TensorWrapper GraphSegmentation_processImage(struct GraphSegmentationPtr ptr, struct TensorWrapper);\n\nextern \"C\"\nvoid GraphSegmentation_setSigma(struct GraphSegmentationPtr ptr, double s);\n\nextern \"C\"\ndouble GraphSegmentation_getSigma(struct GraphSegmentationPtr ptr);\n\nextern \"C\"\nvoid GraphSegmentation_setK(struct GraphSegmentationPtr ptr, float k);\n\nextern \"C\"\nfloat GraphSegmentation_getK(struct GraphSegmentationPtr ptr);\n\nextern \"C\"\nvoid GraphSegmentation_setMinSize(struct GraphSegmentationPtr ptr, int min_size);\n\nextern \"C\"\nint GraphSegmentation_getMinSize(struct GraphSegmentationPtr ptr);\n\n\/\/ See #103\n#ifndef APPLE\n\n\/\/ SelectiveSearchSegmentationStrategy\nstruct SelectiveSearchSegmentationStrategyPtr {\n void *ptr;\n\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator->() { return static_cast(ptr); }\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator*() { return static_cast(ptr); }\n inline SelectiveSearchSegmentationStrategyPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *ptr) { this->ptr = ptr; }\n};\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyColor_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategySize_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyTexture_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyFill_ctor();\n\/\/\n\/\/ extern \"C\"\n\/\/ void SelectiveSearchSegmentationStrategy_setImage(struct SelectiveSearchSegmentationStrategyPtr ptr, struct TensorWrapper, struct TensorWrapper, struct TensorWrapper, int);\n\/\/\n\/\/ extern \"C\"\n\/\/ float SelectiveSearchSegmentationStrategy_get(int, int);\n\/\/\n\/\/ extern \"C\"\n\/\/ void SelectiveSearchSegmentationStrategy_merge(int, int);\n\n\n\/\/ MULTIPLE STRTEGY\n\/\/\n\n\/\/ SelectiveSearchSegmentation\nstruct SelectiveSearchSegmentationPtr {\n void *ptr;\n\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator->() { return static_cast(ptr); }\n inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator*() { return static_cast(ptr); }\n inline SelectiveSearchSegmentationPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentation *ptr) { this->ptr = ptr; }\n};\n\nextern \"C\"\nstruct SelectiveSearchSegmentationPtr SelectiveSearchSegmentation_ctor();\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_setBaseImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_switchToSingleStrategy(struct SelectiveSearchSegmentationPtr ptr, int, float);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_switchToSelectiveSearchFast(struct SelectiveSearchSegmentationPtr ptr, int, int, float);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_switchToSelectiveSearchQuality(struct SelectiveSearchSegmentationPtr ptr, int, int, float);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_addImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_clearImages(struct SelectiveSearchSegmentationPtr ptr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_addGraphSegmentation(struct SelectiveSearchSegmentationPtr ptr, struct GraphSegmentationPtr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_clearGraphSegmentations(struct SelectiveSearchSegmentationPtr ptr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_addStrategy(struct SelectiveSearchSegmentationPtr ptr, struct SelectiveSearchSegmentationStrategyPtr);\n\nextern \"C\"\nvoid SelectiveSearchSegmentation_clearStrategies(struct SelectiveSearchSegmentationPtr ptr);\n\nextern \"C\"\nstruct RectArray SelectiveSearchSegmentation_process(struct SelectiveSearchSegmentationPtr ptr);\n\n#endif\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (c) 2014 Werner Mayer *\n * *\n * This file is part of the FreeCAD CAx development system. *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Library General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 51 Franklin Street, *\n * Fifth Floor, Boston, MA 02110-1301, USA *\n * *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n#ifndef _PreComp_\n# include \n# include \n#endif\n\n#include \"QuantitySpinBox.h\"\n#include \n\nusing namespace Gui;\n\nnamespace Gui {\nclass QuantitySpinBoxPrivate\n{\npublic:\n QuantitySpinBoxPrivate() :\n validInput(true),\n unitValue(0),\n maximum(DOUBLE_MAX),\n minimum(-DOUBLE_MAX),\n singleStep(1.0)\n {\n }\n ~QuantitySpinBoxPrivate()\n {\n }\n\n QString stripped(const QString &t, int *pos) const\n {\n QString text = t;\n const int s = text.size();\n text = text.trimmed();\n if (pos)\n (*pos) -= (s - text.size());\n return text;\n }\n\n Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const\n {\n Base::Quantity res;\n const double max = this->maximum;\n const double min = this->minimum;\n\n QString copy = input;\n\n int len = copy.size();\n const bool plus = max >= 0;\n const bool minus = min <= 0;\n\n switch (len) {\n case 0:\n state = max != min ? QValidator::Intermediate : QValidator::Invalid;\n goto end;\n case 1:\n if (copy.at(0) == locale.decimalPoint()) {\n state = QValidator::Intermediate;\n copy.prepend(QLatin1Char('0'));\n pos++;\n len++;\n goto end;\n }\n else if (copy.at(0) == QLatin1Char('+')) {\n \/\/ the quantity parser doesn't allow numbers of the form '+1.0'\n state = QValidator::Invalid;\n goto end;\n }\n else if (copy.at(0) == QLatin1Char('-')) {\n if (minus)\n state = QValidator::Intermediate;\n else\n state = QValidator::Invalid;\n goto end;\n }\n break;\n case 2:\n if (copy.at(1) == locale.decimalPoint()\n && (plus && copy.at(0) == QLatin1Char('+'))) {\n state = QValidator::Intermediate;\n goto end;\n }\n if (copy.at(1) == locale.decimalPoint()\n && (minus && copy.at(0) == QLatin1Char('-'))) {\n state = QValidator::Intermediate;\n copy.insert(1, QLatin1Char('0'));\n pos++;\n len++;\n goto end;\n }\n break;\n default: break;\n }\n\n if (copy.at(0) == locale.groupSeparator()) {\n state = QValidator::Invalid;\n goto end;\n }\n else if (len > 1) {\n const int dec = copy.indexOf(locale.decimalPoint());\n if (dec != -1) {\n if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) {\n copy.remove(dec + 1, 1);\n }\n else if (copy.indexOf(locale.decimalPoint(), dec + 1) != -1) {\n \/\/ trying to add a second decimal point is not allowed\n state = QValidator::Invalid;\n goto end;\n }\n }\n for (int i=dec + 1; i= min && value <= max) {\n if (copy.endsWith(locale.decimalPoint())) {\n \/\/ input shouldn't end with a decimal point\n state = QValidator::Intermediate;\n }\n else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {\n \/\/ if not dimensionless the input should have a dimension\n state = QValidator::Intermediate;\n }\n else if (res.getUnit() != this->unit) {\n state = QValidator::Invalid;\n }\n else {\n state = QValidator::Acceptable;\n }\n }\n else if (max == min) { \/\/ when max and min is the same the only non-Invalid input is max (or min)\n state = QValidator::Invalid;\n }\n else {\n if ((value >= 0 && value > max) || (value < 0 && value < min)) {\n state = QValidator::Invalid;\n }\n else {\n state = QValidator::Intermediate;\n }\n }\nend:\n if (state != QValidator::Acceptable) {\n res.setValue(max > 0 ? min : max);\n }\n\n input = copy;\n return res;\n }\n\n QLocale locale;\n bool validInput;\n QString validStr;\n Base::Quantity quantity;\n Base::Unit unit;\n double unitValue;\n QString unitStr;\n double maximum;\n double minimum;\n double singleStep;\n};\n}\n\nQuantitySpinBox::QuantitySpinBox(QWidget *parent)\n : QAbstractSpinBox(parent), d_ptr(new QuantitySpinBoxPrivate())\n{\n d_ptr->locale = locale();\n this->setContextMenuPolicy(Qt::DefaultContextMenu);\n QObject::connect(lineEdit(), SIGNAL(textChanged(QString)),\n this, SLOT(userInput(QString)));\n}\n\nQuantitySpinBox::~QuantitySpinBox()\n{\n}\n\nvoid QuantitySpinBox::updateText(const Base::Quantity& quant)\n{\n Q_D(QuantitySpinBox);\n\n double dFactor;\n QString txt = quant.getUserString(dFactor,d->unitStr);\n d->unitValue = quant.getValue()\/dFactor;\n lineEdit()->setText(txt);\n}\n\nBase::Quantity QuantitySpinBox::value() const\n{\n Q_D(const QuantitySpinBox);\n return d->quantity;\n}\n\nvoid QuantitySpinBox::setValue(const Base::Quantity& value)\n{\n Q_D(QuantitySpinBox);\n d->quantity = value;\n \/\/ check limits\n if (d->quantity.getValue() > d->maximum)\n d->quantity.setValue(d->maximum);\n if (d->quantity.getValue() < d->minimum)\n d->quantity.setValue(d->minimum);\n\n d->unit = value.getUnit();\n\n updateText(value);\n}\n\nvoid QuantitySpinBox::setValue(double value)\n{\n Q_D(QuantitySpinBox);\n setValue(Base::Quantity(value, d->unit));\n}\n\nbool QuantitySpinBox::hasValidInput() const\n{\n Q_D(const QuantitySpinBox);\n return d->validInput;\n}\n\n\/\/ Gets called after call of 'validateAndInterpret'\nvoid QuantitySpinBox::userInput(const QString & text)\n{\n Q_D(QuantitySpinBox);\n\n QString tmp = text;\n int pos;\n QValidator::State state;\n Base::Quantity res = d->validateAndInterpret(tmp, pos, state);\n if (state == QValidator::Acceptable) {\n d->validInput = true;\n d->validStr = text;\n }\n else if (state == QValidator::Intermediate) {\n tmp = tmp.trimmed();\n tmp += QLatin1Char(' ');\n tmp += d->unitStr;\n Base::Quantity res2 = d->validateAndInterpret(tmp, pos, state);\n if (state == QValidator::Acceptable) {\n d->validInput = true;\n d->validStr = tmp;\n res = res2;\n }\n else {\n d->validInput = false;\n return;\n }\n }\n else {\n d->validInput = false;\n return;\n }\n\n double factor;\n res.getUserString(factor,d->unitStr);\n d->unitValue = res.getValue()\/factor;\n d->quantity = res;\n\n \/\/ signaling\n valueChanged(res);\n valueChanged(res.getValue());\n}\n\nBase::Unit QuantitySpinBox::unit() const\n{\n Q_D(const QuantitySpinBox);\n return d->unit;\n}\n\nvoid QuantitySpinBox::setUnit(const Base::Unit &unit)\n{\n Q_D(QuantitySpinBox);\n\n d->unit = unit;\n d->quantity.setUnit(unit);\n updateText(d->quantity);\n}\n\nvoid QuantitySpinBox::setUnitText(const QString& str)\n{\n Base::Quantity quant = Base::Quantity::parse(str);\n setUnit(quant.getUnit());\n}\n\nQString QuantitySpinBox::unitText(void)\n{\n Q_D(QuantitySpinBox);\n return d->unitStr;\n}\n\ndouble QuantitySpinBox::singleStep() const\n{\n Q_D(const QuantitySpinBox);\n return d->singleStep;\n}\n\nvoid QuantitySpinBox::setSingleStep(double value)\n{\n Q_D(QuantitySpinBox);\n\n if (value >= 0) {\n d->singleStep = value;\n }\n}\n\ndouble QuantitySpinBox::minimum() const\n{\n Q_D(const QuantitySpinBox);\n return d->minimum;\n}\n\nvoid QuantitySpinBox::setMinimum(double minimum)\n{\n Q_D(QuantitySpinBox);\n d->minimum = minimum;\n}\n\ndouble QuantitySpinBox::maximum() const\n{\n Q_D(const QuantitySpinBox);\n return d->maximum;\n}\n\nvoid QuantitySpinBox::setMaximum(double maximum)\n{\n Q_D(QuantitySpinBox);\n d->maximum = maximum;\n}\n\nvoid QuantitySpinBox::setRange(double minimum, double maximum)\n{\n Q_D(QuantitySpinBox);\n d->minimum = minimum;\n d->maximum = maximum;\n}\n\nQAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const\n{\n Q_D(const QuantitySpinBox);\n if (isReadOnly()\/* || !d->validInput*\/)\n return StepNone;\n if (wrapping())\n return StepEnabled(StepUpEnabled | StepDownEnabled);\n StepEnabled ret = StepNone;\n if (d->quantity.getValue() < d->maximum) {\n ret |= StepUpEnabled;\n }\n if (d->quantity.getValue() > d->minimum) {\n ret |= StepDownEnabled;\n }\n return ret;\n}\n\nvoid QuantitySpinBox::stepBy(int steps)\n{\n Q_D(QuantitySpinBox);\n\n double step = d->singleStep * steps;\n double val = d->unitValue + step;\n if (val > d->maximum)\n val = d->maximum;\n else if (val < d->minimum)\n val = d->minimum;\n\n lineEdit()->setText(QString::fromUtf8(\"%L1 %2\").arg(val).arg(d->unitStr));\n update();\n selectNumber();\n}\n\nvoid QuantitySpinBox::showEvent(QShowEvent * event)\n{\n Q_D(QuantitySpinBox);\n\n QAbstractSpinBox::showEvent(event);\n\n bool selected = lineEdit()->hasSelectedText();\n updateText(d->quantity);\n if (selected)\n selectNumber();\n}\n\nvoid QuantitySpinBox::focusInEvent(QFocusEvent * event)\n{\n bool hasSel = lineEdit()->hasSelectedText();\n QAbstractSpinBox::focusInEvent(event);\n\n if (event->reason() == Qt::TabFocusReason ||\n event->reason() == Qt::BacktabFocusReason ||\n event->reason() == Qt::ShortcutFocusReason) {\n if (!hasSel)\n selectNumber();\n }\n}\n\nvoid QuantitySpinBox::focusOutEvent(QFocusEvent * event)\n{\n Q_D(QuantitySpinBox);\n\n int pos;\n QString text = lineEdit()->text();\n QValidator::State state;\n d->validateAndInterpret(text, pos, state);\n if (state != QValidator::Acceptable) {\n lineEdit()->setText(d->validStr);\n }\n QAbstractSpinBox::focusOutEvent(event);\n}\n\nvoid QuantitySpinBox::clear()\n{\n QAbstractSpinBox::clear();\n}\n\nvoid QuantitySpinBox::selectNumber()\n{\n QString str = lineEdit()->text();\n unsigned int i = 0;\n\n QChar d = locale().decimalPoint();\n QChar g = locale().groupSeparator();\n QChar n = locale().negativeSign();\n\n for (QString::iterator it = str.begin(); it != str.end(); ++it) {\n if (it->isDigit())\n i++;\n else if (*it == d)\n i++;\n else if (*it == g)\n i++;\n else if (*it == n)\n i++;\n else \/\/ any non-number character\n break;\n }\n\n lineEdit()->setSelection(0, i);\n}\n\nQString QuantitySpinBox::textFromValue(const Base::Quantity& value) const\n{\n double factor;\n QString unitStr;\n QString str = value.getUserString(factor, unitStr);\n if (qAbs(value.getValue()) >= 1000.0) {\n str.remove(locale().groupSeparator());\n }\n return str;\n}\n\nBase::Quantity QuantitySpinBox::valueFromText(const QString &text) const\n{\n Q_D(const QuantitySpinBox);\n\n QString copy = text;\n int pos = lineEdit()->cursorPosition();\n QValidator::State state = QValidator::Acceptable;\n Base::Quantity quant = d->validateAndInterpret(copy, pos, state);\n if (state != QValidator::Acceptable) {\n fixup(copy);\n quant = d->validateAndInterpret(copy, pos, state);\n }\n\n return quant;\n}\n\nQValidator::State QuantitySpinBox::validate(QString &text, int &pos) const\n{\n Q_D(const QuantitySpinBox);\n\n QValidator::State state;\n d->validateAndInterpret(text, pos, state);\n return state;\n}\n\nvoid QuantitySpinBox::fixup(QString &input) const\n{\n input.remove(locale().groupSeparator());\n}\n\n\n#include \"moc_QuantitySpinBox.cpp\"\n+ fix gcc build failure\/***************************************************************************\n * Copyright (c) 2014 Werner Mayer *\n * *\n * This file is part of the FreeCAD CAx development system. *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Library General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 51 Franklin Street, *\n * Fifth Floor, Boston, MA 02110-1301, USA *\n * *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n#ifndef _PreComp_\n# include \n# include \n#endif\n\n#include \"QuantitySpinBox.h\"\n#include \n\nusing namespace Gui;\n\nnamespace Gui {\nclass QuantitySpinBoxPrivate\n{\npublic:\n QuantitySpinBoxPrivate() :\n validInput(true),\n unitValue(0),\n maximum(DOUBLE_MAX),\n minimum(-DOUBLE_MAX),\n singleStep(1.0)\n {\n }\n ~QuantitySpinBoxPrivate()\n {\n }\n\n QString stripped(const QString &t, int *pos) const\n {\n QString text = t;\n const int s = text.size();\n text = text.trimmed();\n if (pos)\n (*pos) -= (s - text.size());\n return text;\n }\n\n Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const\n {\n Base::Quantity res;\n const double max = this->maximum;\n const double min = this->minimum;\n\n QString copy = input;\n\n int len = copy.size();\n const bool plus = max >= 0;\n const bool minus = min <= 0;\n\n switch (len) {\n case 0:\n state = max != min ? QValidator::Intermediate : QValidator::Invalid;\n goto end;\n case 1:\n if (copy.at(0) == locale.decimalPoint()) {\n state = QValidator::Intermediate;\n copy.prepend(QLatin1Char('0'));\n pos++;\n len++;\n goto end;\n }\n else if (copy.at(0) == QLatin1Char('+')) {\n \/\/ the quantity parser doesn't allow numbers of the form '+1.0'\n state = QValidator::Invalid;\n goto end;\n }\n else if (copy.at(0) == QLatin1Char('-')) {\n if (minus)\n state = QValidator::Intermediate;\n else\n state = QValidator::Invalid;\n goto end;\n }\n break;\n case 2:\n if (copy.at(1) == locale.decimalPoint()\n && (plus && copy.at(0) == QLatin1Char('+'))) {\n state = QValidator::Intermediate;\n goto end;\n }\n if (copy.at(1) == locale.decimalPoint()\n && (minus && copy.at(0) == QLatin1Char('-'))) {\n state = QValidator::Intermediate;\n copy.insert(1, QLatin1Char('0'));\n pos++;\n len++;\n goto end;\n }\n break;\n default: break;\n }\n\n {\n if (copy.at(0) == locale.groupSeparator()) {\n state = QValidator::Invalid;\n goto end;\n }\n else if (len > 1) {\n const int dec = copy.indexOf(locale.decimalPoint());\n if (dec != -1) {\n if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) {\n copy.remove(dec + 1, 1);\n }\n else if (copy.indexOf(locale.decimalPoint(), dec + 1) != -1) {\n \/\/ trying to add a second decimal point is not allowed\n state = QValidator::Invalid;\n goto end;\n }\n }\n for (int i=dec + 1; i= min && value <= max) {\n if (copy.endsWith(locale.decimalPoint())) {\n \/\/ input shouldn't end with a decimal point\n state = QValidator::Intermediate;\n }\n else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {\n \/\/ if not dimensionless the input should have a dimension\n state = QValidator::Intermediate;\n }\n else if (res.getUnit() != this->unit) {\n state = QValidator::Invalid;\n }\n else {\n state = QValidator::Acceptable;\n }\n }\n else if (max == min) { \/\/ when max and min is the same the only non-Invalid input is max (or min)\n state = QValidator::Invalid;\n }\n else {\n if ((value >= 0 && value > max) || (value < 0 && value < min)) {\n state = QValidator::Invalid;\n }\n else {\n state = QValidator::Intermediate;\n }\n }\n }\nend:\n if (state != QValidator::Acceptable) {\n res.setValue(max > 0 ? min : max);\n }\n\n input = copy;\n return res;\n }\n\n QLocale locale;\n bool validInput;\n QString validStr;\n Base::Quantity quantity;\n Base::Unit unit;\n double unitValue;\n QString unitStr;\n double maximum;\n double minimum;\n double singleStep;\n};\n}\n\nQuantitySpinBox::QuantitySpinBox(QWidget *parent)\n : QAbstractSpinBox(parent), d_ptr(new QuantitySpinBoxPrivate())\n{\n d_ptr->locale = locale();\n this->setContextMenuPolicy(Qt::DefaultContextMenu);\n QObject::connect(lineEdit(), SIGNAL(textChanged(QString)),\n this, SLOT(userInput(QString)));\n}\n\nQuantitySpinBox::~QuantitySpinBox()\n{\n}\n\nvoid QuantitySpinBox::updateText(const Base::Quantity& quant)\n{\n Q_D(QuantitySpinBox);\n\n double dFactor;\n QString txt = quant.getUserString(dFactor,d->unitStr);\n d->unitValue = quant.getValue()\/dFactor;\n lineEdit()->setText(txt);\n}\n\nBase::Quantity QuantitySpinBox::value() const\n{\n Q_D(const QuantitySpinBox);\n return d->quantity;\n}\n\nvoid QuantitySpinBox::setValue(const Base::Quantity& value)\n{\n Q_D(QuantitySpinBox);\n d->quantity = value;\n \/\/ check limits\n if (d->quantity.getValue() > d->maximum)\n d->quantity.setValue(d->maximum);\n if (d->quantity.getValue() < d->minimum)\n d->quantity.setValue(d->minimum);\n\n d->unit = value.getUnit();\n\n updateText(value);\n}\n\nvoid QuantitySpinBox::setValue(double value)\n{\n Q_D(QuantitySpinBox);\n setValue(Base::Quantity(value, d->unit));\n}\n\nbool QuantitySpinBox::hasValidInput() const\n{\n Q_D(const QuantitySpinBox);\n return d->validInput;\n}\n\n\/\/ Gets called after call of 'validateAndInterpret'\nvoid QuantitySpinBox::userInput(const QString & text)\n{\n Q_D(QuantitySpinBox);\n\n QString tmp = text;\n int pos;\n QValidator::State state;\n Base::Quantity res = d->validateAndInterpret(tmp, pos, state);\n if (state == QValidator::Acceptable) {\n d->validInput = true;\n d->validStr = text;\n }\n else if (state == QValidator::Intermediate) {\n tmp = tmp.trimmed();\n tmp += QLatin1Char(' ');\n tmp += d->unitStr;\n Base::Quantity res2 = d->validateAndInterpret(tmp, pos, state);\n if (state == QValidator::Acceptable) {\n d->validInput = true;\n d->validStr = tmp;\n res = res2;\n }\n else {\n d->validInput = false;\n return;\n }\n }\n else {\n d->validInput = false;\n return;\n }\n\n double factor;\n res.getUserString(factor,d->unitStr);\n d->unitValue = res.getValue()\/factor;\n d->quantity = res;\n\n \/\/ signaling\n valueChanged(res);\n valueChanged(res.getValue());\n}\n\nBase::Unit QuantitySpinBox::unit() const\n{\n Q_D(const QuantitySpinBox);\n return d->unit;\n}\n\nvoid QuantitySpinBox::setUnit(const Base::Unit &unit)\n{\n Q_D(QuantitySpinBox);\n\n d->unit = unit;\n d->quantity.setUnit(unit);\n updateText(d->quantity);\n}\n\nvoid QuantitySpinBox::setUnitText(const QString& str)\n{\n Base::Quantity quant = Base::Quantity::parse(str);\n setUnit(quant.getUnit());\n}\n\nQString QuantitySpinBox::unitText(void)\n{\n Q_D(QuantitySpinBox);\n return d->unitStr;\n}\n\ndouble QuantitySpinBox::singleStep() const\n{\n Q_D(const QuantitySpinBox);\n return d->singleStep;\n}\n\nvoid QuantitySpinBox::setSingleStep(double value)\n{\n Q_D(QuantitySpinBox);\n\n if (value >= 0) {\n d->singleStep = value;\n }\n}\n\ndouble QuantitySpinBox::minimum() const\n{\n Q_D(const QuantitySpinBox);\n return d->minimum;\n}\n\nvoid QuantitySpinBox::setMinimum(double minimum)\n{\n Q_D(QuantitySpinBox);\n d->minimum = minimum;\n}\n\ndouble QuantitySpinBox::maximum() const\n{\n Q_D(const QuantitySpinBox);\n return d->maximum;\n}\n\nvoid QuantitySpinBox::setMaximum(double maximum)\n{\n Q_D(QuantitySpinBox);\n d->maximum = maximum;\n}\n\nvoid QuantitySpinBox::setRange(double minimum, double maximum)\n{\n Q_D(QuantitySpinBox);\n d->minimum = minimum;\n d->maximum = maximum;\n}\n\nQAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const\n{\n Q_D(const QuantitySpinBox);\n if (isReadOnly()\/* || !d->validInput*\/)\n return StepNone;\n if (wrapping())\n return StepEnabled(StepUpEnabled | StepDownEnabled);\n StepEnabled ret = StepNone;\n if (d->quantity.getValue() < d->maximum) {\n ret |= StepUpEnabled;\n }\n if (d->quantity.getValue() > d->minimum) {\n ret |= StepDownEnabled;\n }\n return ret;\n}\n\nvoid QuantitySpinBox::stepBy(int steps)\n{\n Q_D(QuantitySpinBox);\n\n double step = d->singleStep * steps;\n double val = d->unitValue + step;\n if (val > d->maximum)\n val = d->maximum;\n else if (val < d->minimum)\n val = d->minimum;\n\n lineEdit()->setText(QString::fromUtf8(\"%L1 %2\").arg(val).arg(d->unitStr));\n update();\n selectNumber();\n}\n\nvoid QuantitySpinBox::showEvent(QShowEvent * event)\n{\n Q_D(QuantitySpinBox);\n\n QAbstractSpinBox::showEvent(event);\n\n bool selected = lineEdit()->hasSelectedText();\n updateText(d->quantity);\n if (selected)\n selectNumber();\n}\n\nvoid QuantitySpinBox::focusInEvent(QFocusEvent * event)\n{\n bool hasSel = lineEdit()->hasSelectedText();\n QAbstractSpinBox::focusInEvent(event);\n\n if (event->reason() == Qt::TabFocusReason ||\n event->reason() == Qt::BacktabFocusReason ||\n event->reason() == Qt::ShortcutFocusReason) {\n if (!hasSel)\n selectNumber();\n }\n}\n\nvoid QuantitySpinBox::focusOutEvent(QFocusEvent * event)\n{\n Q_D(QuantitySpinBox);\n\n int pos;\n QString text = lineEdit()->text();\n QValidator::State state;\n d->validateAndInterpret(text, pos, state);\n if (state != QValidator::Acceptable) {\n lineEdit()->setText(d->validStr);\n }\n QAbstractSpinBox::focusOutEvent(event);\n}\n\nvoid QuantitySpinBox::clear()\n{\n QAbstractSpinBox::clear();\n}\n\nvoid QuantitySpinBox::selectNumber()\n{\n QString str = lineEdit()->text();\n unsigned int i = 0;\n\n QChar d = locale().decimalPoint();\n QChar g = locale().groupSeparator();\n QChar n = locale().negativeSign();\n\n for (QString::iterator it = str.begin(); it != str.end(); ++it) {\n if (it->isDigit())\n i++;\n else if (*it == d)\n i++;\n else if (*it == g)\n i++;\n else if (*it == n)\n i++;\n else \/\/ any non-number character\n break;\n }\n\n lineEdit()->setSelection(0, i);\n}\n\nQString QuantitySpinBox::textFromValue(const Base::Quantity& value) const\n{\n double factor;\n QString unitStr;\n QString str = value.getUserString(factor, unitStr);\n if (qAbs(value.getValue()) >= 1000.0) {\n str.remove(locale().groupSeparator());\n }\n return str;\n}\n\nBase::Quantity QuantitySpinBox::valueFromText(const QString &text) const\n{\n Q_D(const QuantitySpinBox);\n\n QString copy = text;\n int pos = lineEdit()->cursorPosition();\n QValidator::State state = QValidator::Acceptable;\n Base::Quantity quant = d->validateAndInterpret(copy, pos, state);\n if (state != QValidator::Acceptable) {\n fixup(copy);\n quant = d->validateAndInterpret(copy, pos, state);\n }\n\n return quant;\n}\n\nQValidator::State QuantitySpinBox::validate(QString &text, int &pos) const\n{\n Q_D(const QuantitySpinBox);\n\n QValidator::State state;\n d->validateAndInterpret(text, pos, state);\n return state;\n}\n\nvoid QuantitySpinBox::fixup(QString &input) const\n{\n input.remove(locale().groupSeparator());\n}\n\n\n#include \"moc_QuantitySpinBox.cpp\"\n<|endoftext|>"} {"text":"void loadlibs () \n{\n gSystem->Load(\"libMC\");\n\n \/\/ libraries required by EVGEN\n \/\/ (commented libraries are already loaded in prevoius sequence)\n\n gSystem->Load(\"libmicrocern\");\n gSystem->Load(\"libEG\"); \n gSystem->Load(\"libSTEER\");\n gSystem->Load(\"libEGPythia6\");\n gSystem->Load(\"libdummypythia6\");\n gSystem->Load(\"libdummyhijing\");\n gSystem->Load(\"libTHijing\");\n gSystem->Load(\"libdummyHBTP\");\n gSystem->Load(\"libTHbtp\");\n gSystem->Load(\"libdummymevsim\");\n gSystem->Load(\"libTMEVSIM\");\n gSystem->Load(\"libdummyepemgen\");\n gSystem->Load(\"libTEPEMGEN\");\n gSystem->Load(\"libEVGEN\");\n\n gSystem->Load(\"libPhysics\");\n\n gSystem->Load(\"libCONTAINERS\");\n gSystem->Load(\"libFMD\");\n gSystem->Load(\"libMUON\");\n gSystem->Load(\"libPHOS\");\n gSystem->Load(\"libPMD\");\n gSystem->Load(\"libRICH\");\n gSystem->Load(\"libSTRUCT\");\n gSystem->Load(\"libTPC\");\n gSystem->Load(\"libTRD\");\n gSystem->Load(\"libTOF\");\n gSystem->Load(\"libZDC\");\n gSystem->Load(\"libITS\");\n gSystem->Load(\"libCRT\");\n gSystem->Load(\"libSTART\");\n gSystem->Load(\"libEMCAL\");\n gSystem->Load(\"libVZERO\");\n gSystem->Load(\"libdummyherwig\");\n gSystem->Load(\"libTHerwig\");\n}\nLoad EVGEN before external generators.void loadlibs () \n{\n gSystem->Load(\"libMC\");\n\n \/\/ libraries required by EVGEN\n \/\/ (commented libraries are already loaded in prevoius sequence)\n\n gSystem->Load(\"libmicrocern\");\n gSystem->Load(\"libEG\"); \n gSystem->Load(\"libSTEER\");\n gSystem->Load(\"libEVGEN\");\n gSystem->Load(\"libEGPythia6\");\n gSystem->Load(\"libdummypythia6\");\n gSystem->Load(\"libdummyhijing\");\n gSystem->Load(\"libTHijing\");\n gSystem->Load(\"libdummyHBTP\");\n gSystem->Load(\"libTHbtp\");\n gSystem->Load(\"libdummymevsim\");\n gSystem->Load(\"libTMEVSIM\");\n gSystem->Load(\"libdummyepemgen\");\n gSystem->Load(\"libTEPEMGEN\");\n\n\n gSystem->Load(\"libPhysics\");\n\n gSystem->Load(\"libCONTAINERS\");\n gSystem->Load(\"libFMD\");\n gSystem->Load(\"libMUON\");\n gSystem->Load(\"libPHOS\");\n gSystem->Load(\"libPMD\");\n gSystem->Load(\"libRICH\");\n gSystem->Load(\"libSTRUCT\");\n gSystem->Load(\"libTPC\");\n gSystem->Load(\"libTRD\");\n gSystem->Load(\"libTOF\");\n gSystem->Load(\"libZDC\");\n gSystem->Load(\"libITS\");\n gSystem->Load(\"libCRT\");\n gSystem->Load(\"libSTART\");\n gSystem->Load(\"libEMCAL\");\n gSystem->Load(\"libVZERO\");\n gSystem->Load(\"libdummyherwig\");\n gSystem->Load(\"libTHerwig\");\n}\n<|endoftext|>"} {"text":"\/*\r\n * IndexListIndexColor.cpp\r\n *\r\n * Copyright (C) 2016 by MegaMol Team\r\n * Alle Rechte vorbehalten.\r\n *\/\r\n#include \"stdafx.h\"\r\n#include \"IndexListIndexColor.h\"\r\n#include \"mmstd_datatools\/MultiParticleDataAdaptor.h\"\r\n#include \"mmstd_datatools\/MultiIndexListDataCall.h\"\r\n#include \r\n\r\nusing namespace megamol;\r\nusing namespace megamol::stdplugin::datatools;\r\n\r\n\r\nIndexListIndexColor::IndexListIndexColor() : stdplugin::datatools::AbstractParticleManipulator(\"outData\", \"inData\"),\r\n inIndexListDataSlot(\"inIndexListData\", \"Fetches the second ICol value stream\"),\r\n inPartsHash(0), inIndexHash(0), outHash(0),\r\n frameID(0), colors(), minCol(0.0f), maxCol(1.0f) {\r\n\r\n inIndexListDataSlot.SetCompatibleCall();\r\n MakeSlotAvailable(&inIndexListDataSlot);\r\n\r\n}\r\n\r\nIndexListIndexColor::~IndexListIndexColor() {\r\n Release();\r\n}\r\n\r\nbool IndexListIndexColor::manipulateData(\r\n core::moldyn::MultiParticleDataCall& outData,\r\n core::moldyn::MultiParticleDataCall& inData) {\r\n\r\n MultiIndexListDataCall *inListsPtr = inIndexListDataSlot.CallAs();\r\n if (inListsPtr == nullptr) return false;\r\n\r\n inListsPtr->SetFrameID(inData.FrameID());\r\n if (!(*inListsPtr)(MultiIndexListDataCall::GET_HASH)) return false;\r\n\r\n if ( (inPartsHash != inData.DataHash()) || (inData.DataHash() == 0)\r\n || (inIndexHash != inListsPtr->DataHash()) || (inListsPtr->DataHash() == 0)\r\n || (frameID != inData.FrameID()) ) {\r\n \/\/ Update data\r\n inPartsHash = inData.DataHash();\r\n inIndexHash = inListsPtr->DataHash();\r\n outHash++;\r\n frameID = inData.FrameID();\r\n\r\n stdplugin::datatools::MultiParticleDataAdaptor p(inData);\r\n size_t pCnt = p.get_count();\r\n colors.resize(pCnt);\r\n\r\n if (pCnt == 0) {\r\n minCol = maxCol = 0.0f;\r\n\r\n } else {\r\n \/\/ initialize as \"unreferenced\"\r\n std::fill(colors.begin(), colors.end(), -1.0f);\r\n size_t ptsSet = 0; \/\/ numbers of point-references set\r\n bool warnIndex = false; \/\/ should warn about illegal indices?\r\n\r\n maxCol = -1.0f; \/\/ if no particle color is ever set, this will be max\r\n\r\n \/\/ iterate through all references\r\n size_t listCnt = inListsPtr->Count();\r\n for (size_t listI = 0; listI < listCnt; ++listI) {\r\n MultiIndexListDataCall::index_list_t const& list = inListsPtr->Lists()[listI];\r\n size_t oldPtsSet = ptsSet;\r\n for (MultiIndexListDataCall::index_t const index : list) {\r\n if (index >= pCnt) {\r\n warnIndex = true;\r\n continue;\r\n }\r\n if (colors[index] < -0.9f) {\r\n ptsSet++;\r\n colors[index] = static_cast(listI);\r\n }\r\n }\r\n \/\/ if at least one point was set, listI exists as color, thus is the current max value.\r\n if (oldPtsSet < ptsSet) maxCol = static_cast(listI);\r\n }\r\n\r\n \/\/ set min, based if all points have been referenced\r\n assert(ptsSet <= pCnt);\r\n minCol = (ptsSet == pCnt) ? 0.0f : -1.0f;\r\n\r\n }\r\n\r\n }\r\n\r\n inListsPtr->Unlock();\r\n\r\n outData = inData;\r\n outData.SetDataHash(outHash);\r\n outData.SetFrameID(frameID);\r\n inData.SetUnlocker(nullptr, false);\r\n\r\n const float *data = colors.data();\r\n for (unsigned int list = 0; list < outData.GetParticleListCount(); ++list) {\r\n auto &plist = outData.AccessParticles(list);\r\n plist.SetColourData(core::moldyn::SimpleSphericalParticles::COLDATA_FLOAT_I, data, 0);\r\n plist.SetColourMapIndexValues(minCol, maxCol);\r\n data += plist.GetCount();\r\n }\r\n\r\n return true;\r\n}\r\nBug in IndexListIndexColor fixed, now fetches the actual data correctly.\/*\r\n * IndexListIndexColor.cpp\r\n *\r\n * Copyright (C) 2016 by MegaMol Team\r\n * Alle Rechte vorbehalten.\r\n *\/\r\n#include \"stdafx.h\"\r\n#include \"IndexListIndexColor.h\"\r\n#include \"mmstd_datatools\/MultiParticleDataAdaptor.h\"\r\n#include \"mmstd_datatools\/MultiIndexListDataCall.h\"\r\n#include \r\n\r\nusing namespace megamol;\r\nusing namespace megamol::stdplugin::datatools;\r\n\r\n\r\nIndexListIndexColor::IndexListIndexColor() : stdplugin::datatools::AbstractParticleManipulator(\"outData\", \"inData\"),\r\n inIndexListDataSlot(\"inIndexListData\", \"Fetches the second ICol value stream\"),\r\n inPartsHash(0), inIndexHash(0), outHash(0),\r\n frameID(0), colors(), minCol(0.0f), maxCol(1.0f) {\r\n\r\n inIndexListDataSlot.SetCompatibleCall();\r\n MakeSlotAvailable(&inIndexListDataSlot);\r\n\r\n}\r\n\r\nIndexListIndexColor::~IndexListIndexColor() {\r\n Release();\r\n}\r\n\r\nbool IndexListIndexColor::manipulateData(\r\n core::moldyn::MultiParticleDataCall& outData,\r\n core::moldyn::MultiParticleDataCall& inData) {\r\n\r\n MultiIndexListDataCall *inListsPtr = inIndexListDataSlot.CallAs();\r\n if (inListsPtr == nullptr) return false;\r\n\r\n inListsPtr->SetFrameID(inData.FrameID());\r\n if (!(*inListsPtr)(MultiIndexListDataCall::GET_HASH)) return false;\r\n\r\n if ( (inPartsHash != inData.DataHash()) || (inData.DataHash() == 0)\r\n || (inIndexHash != inListsPtr->DataHash()) || (inListsPtr->DataHash() == 0)\r\n || (frameID != inData.FrameID()) ) {\r\n \/\/ Update data\r\n inPartsHash = inData.DataHash();\r\n inIndexHash = inListsPtr->DataHash();\r\n outHash++;\r\n frameID = inData.FrameID();\r\n\r\n inListsPtr->Unlock();\r\n inListsPtr->SetFrameID(inData.FrameID());\r\n if (!(*inListsPtr)(MultiIndexListDataCall::GET_DATA)) return false;\r\n\r\n stdplugin::datatools::MultiParticleDataAdaptor p(inData);\r\n size_t pCnt = p.get_count();\r\n colors.resize(pCnt);\r\n\r\n if (pCnt == 0) {\r\n minCol = maxCol = 0.0f;\r\n\r\n } else {\r\n \/\/ initialize as \"unreferenced\"\r\n std::fill(colors.begin(), colors.end(), -1.0f);\r\n size_t ptsSet = 0; \/\/ numbers of point-references set\r\n bool warnIndex = false; \/\/ should warn about illegal indices?\r\n\r\n maxCol = -1.0f; \/\/ if no particle color is ever set, this will be max\r\n\r\n \/\/ iterate through all references\r\n size_t listCnt = inListsPtr->Count();\r\n for (size_t listI = 0; listI < listCnt; ++listI) {\r\n MultiIndexListDataCall::index_list_t const& list = inListsPtr->Lists()[listI];\r\n size_t oldPtsSet = ptsSet;\r\n for (MultiIndexListDataCall::index_t const index : list) {\r\n if (index >= pCnt) {\r\n warnIndex = true;\r\n continue;\r\n }\r\n if (colors[index] < -0.9f) {\r\n ptsSet++;\r\n colors[index] = static_cast(listI);\r\n }\r\n }\r\n \/\/ if at least one point was set, listI exists as color, thus is the current max value.\r\n if (oldPtsSet < ptsSet) maxCol = static_cast(listI);\r\n }\r\n\r\n \/\/ set min, based if all points have been referenced\r\n assert(ptsSet <= pCnt);\r\n minCol = (ptsSet == pCnt) ? 0.0f : -1.0f;\r\n\r\n }\r\n\r\n }\r\n\r\n inListsPtr->Unlock();\r\n\r\n outData = inData;\r\n outData.SetDataHash(outHash);\r\n outData.SetFrameID(frameID);\r\n inData.SetUnlocker(nullptr, false);\r\n\r\n const float *data = colors.data();\r\n for (unsigned int list = 0; list < outData.GetParticleListCount(); ++list) {\r\n auto &plist = outData.AccessParticles(list);\r\n plist.SetColourData(core::moldyn::SimpleSphericalParticles::COLDATA_FLOAT_I, data, 0);\r\n plist.SetColourMapIndexValues(minCol, maxCol);\r\n data += plist.GetCount();\r\n }\r\n\r\n return true;\r\n}\r\n<|endoftext|>"} {"text":"\n#include \"TestWindow.h\"\n\n#include \"ConsoleView.h\"\n#include \"Label.h\"\n#include \"Image.h\"\n#include \"ListView.h\"\n#include \"..\/Model\/Font.h\"\n#include \"..\/Controller\/ResourceController.h\"\n#include \"..\/Controller\/RenderController.h\"\n\nusing namespace RetroEnd::View;\nusing namespace RetroEnd::Model;\nusing namespace RetroEnd::Controller;\n\nListView* myList;\n\nTestWindow::TestWindow()\n{\t\n\tfloat H = (float)RenderController::getInstance().getScreenHeight();\n\tfloat W = (float)RenderController::getInstance().getScreenWidth();\n\n\tthis->setSize( W, H );\n\n\tImage* background = new Image();\n\tbackground->setSize( W, H );\n\tbackground->setPath(\"data\/images\/bg_bn.png\");\n\tbackground->setTiled(true);\n\taddChild(background);\n\n\tLabel* title = new Label();\n\ttitle->setText(\"TEST WINDOW\");\n\ttitle->setPosition(550,100);\n\ttitle->setColor(0x000000FF);\n\n\tthis->addChild(title);\n\n\tmConsoleView = new ConsoleView(); \/\/pre load images\n\n\tImage* logo = new Image();\n\tlogo->setSize((float)RenderController::getInstance().getScreenWidth()\/2, (float)RenderController::getInstance().getScreenHeight() \/ 2);\n\tlogo->setPosition((float)RenderController::getInstance().getScreenWidth()\/4, (float)RenderController::getInstance().getScreenHeight() \/ 4);\n\tlogo->setPath(\"data\/logo black.png\");\n\tlogo->setOpacity(0);\n\taddChild(logo);\n\n\tAnimation* a = new Animation();\n\n\ta->millisDuration = 2000;\n\ta->endCallback = [this, logo] ()\n\t{\n\t\tAnimation* a = new Animation();\n\n\t\ta->millisDuration = 2000;\n\t\ta->newOpacity = new unsigned char(255);\n\t\ta->endCallback = [this, logo] ()\n\t\t{\n\t\t\tAnimation* a = new Animation();\n\t\t\ta->millisDuration = 1000;\n\t\t\ta->newSize = new Eigen::Vector2f((float)RenderController::getInstance().getScreenWidth()\/5, (float)RenderController::getInstance().getScreenHeight() \/ 5);\n\t\t\ta->moveOffset = new Eigen::Vector3f((float)RenderController::getInstance().getScreenWidth()\/2, (float)-RenderController::getInstance().getScreenHeight() \/ 4, 0);\n\t\t\ta->endCallback = [this] ()\n\t\t\t{\n\t\t\t\t\/\/Show Consoles\n\t\t\t\tmConsoleView->setSize((float)RenderController::getInstance().getScreenWidth(), (float)RenderController::getInstance().getScreenHeight());\n\t\t\t\tmConsoleView->setPosition(0,0);\n\t\t\t\taddChild(mConsoleView);\n\t\t\t};\n\n\t\t\tlogo->animate(a);\n\t\t};\n\n\t\tlogo->animate(a);\n\t};\n\n\tlogo->animate(a);\n\n}\n\nbool TestWindow::input(Model::InputConfig* config, Model::Input input)\n{\n\tif(input.id == SDLK_p && input.value != 0 )\n\t{\n\t\tRenderController::getInstance().pushPopupMessage(\"Miao testo lungo lungo lungo lungo lungo lungo lungo lungo lungo!\", PopupMessageIcon::Info);\n\t\treturn true;\n\t}\n\n\t\/\/set input only to the last view added\n\tif(mChildren.size() > 0)\n\t{\n\t\tmChildren.at(mChildren.size() - 1)->input(config, input);\n\t}\n\treturn true;\n}\nGoing to Raspberry PI -> Back to SDL (1)\n#include \"TestWindow.h\"\n\n#include \"ConsoleView.h\"\n#include \"Label.h\"\n#include \"Image.h\"\n#include \"ListView.h\"\n#include \"..\/Model\/Font.h\"\n#include \"..\/Controller\/ResourceController.h\"\n#include \"..\/Controller\/RenderController.h\"\n\nusing namespace RetroEnd::View;\nusing namespace RetroEnd::Model;\nusing namespace RetroEnd::Controller;\n\nListView* myList;\n\nTestWindow::TestWindow()\n{\t\n\tfloat H = (float)RenderController::getInstance().getScreenHeight();\n\tfloat W = (float)RenderController::getInstance().getScreenWidth();\n\n\tthis->setSize( W, H );\n\n\tImage* background = new Image();\n\tbackground->setSize( W, H );\n\tbackground->setPath(\"data\/images\/bg_bn.png\");\n\tbackground->setTiled(true);\n\taddChild(background);\n\n\tLabel* title = new Label();\n\ttitle->setText(\"TEST WINDOW\");\n\ttitle->setPosition(550,100);\n\ttitle->setColor(0x000000FF);\n\n\tthis->addChild(title);\n\n\t\/\/mConsoleView = new ConsoleView(); \/\/pre load images\n\n\tImage* logo = new Image();\n\tlogo->setSize((float)RenderController::getInstance().getScreenWidth()\/2, (float)RenderController::getInstance().getScreenHeight() \/ 2);\n\tlogo->setPosition((float)RenderController::getInstance().getScreenWidth()\/4, (float)RenderController::getInstance().getScreenHeight() \/ 4);\n\tlogo->setPath(\"data\/logo black.png\");\n\tlogo->setOpacity(0);\n\taddChild(logo);\n\n\tAnimation* a = new Animation();\n\n\ta->millisDuration = 2000;\n\ta->endCallback = [this, logo] ()\n\t{\n\t\tAnimation* a = new Animation();\n\n\t\ta->millisDuration = 2000;\n\t\ta->newOpacity = new unsigned char(255);\n\t\ta->endCallback = [this, logo] ()\n\t\t{\n\t\t\tAnimation* a = new Animation();\n\t\t\ta->millisDuration = 1000;\n\t\t\ta->newSize = new Eigen::Vector2f((float)RenderController::getInstance().getScreenWidth()\/5, (float)RenderController::getInstance().getScreenHeight() \/ 5);\n\t\t\ta->moveOffset = new Eigen::Vector3f((float)RenderController::getInstance().getScreenWidth()\/2, (float)-RenderController::getInstance().getScreenHeight() \/ 4, 0);\n\t\t\ta->endCallback = [this] ()\n\t\t\t{\n\t\t\t\t\/\/Show Consoles\n\t\t\t\tmConsoleView->setSize((float)RenderController::getInstance().getScreenWidth(), (float)RenderController::getInstance().getScreenHeight());\n\t\t\t\tmConsoleView->setPosition(0,0);\n\t\t\t\taddChild(mConsoleView);\n\t\t\t};\n\n\t\t\tlogo->animate(a);\n\t\t};\n\n\t\tlogo->animate(a);\n\t};\n\n\tlogo->animate(a);\n\n}\n\nbool TestWindow::input(Model::InputConfig* config, Model::Input input)\n{\n\tif(input.id == SDLK_p && input.value != 0 )\n\t{\n\t\tRenderController::getInstance().pushPopupMessage(\"Miao testo lungo lungo lungo lungo lungo lungo lungo lungo lungo!\", PopupMessageIcon::Info);\n\t\treturn true;\n\t}\n\n\t\/\/set input only to the last view added\n\tif(mChildren.size() > 0)\n\t{\n\t\tmChildren.at(mChildren.size() - 1)->input(config, input);\n\t}\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\r\n * Copyright (c) 2008 Jürgen Riegel (juergen.riegel@web.de) *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n#endif\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"BrowserView.h\"\r\n\r\nusing namespace std;\r\nusing namespace Gui;\r\nusing namespace WebGui;\r\n\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebOpenWebsite\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD(CmdWebOpenWebsite);\r\n\r\nCmdWebOpenWebsite::CmdWebOpenWebsite()\r\n : Command(\"Web_OpenWebsite\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Open website...\");\r\n sToolTipText = QT_TR_NOOP(\"Opens a website in FreeCAD\");\r\n sWhatsThis = \"Web_OpenWebsite\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-browser\";\r\n}\r\n\r\n\r\nvoid CmdWebOpenWebsite::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Doc,\"import WebGui\");\r\n doCommand(Command::Gui,\"WebGui.openBrowser('http:\/\/www.freecadweb.org\/')\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserBack\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserBack);\r\n\r\nCmdWebBrowserBack::CmdWebBrowserBack()\r\n : Command(\"Web_BrowserBack\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Previous page\");\r\n sToolTipText = QT_TR_NOOP(\"Go back to the previous page\");\r\n sWhatsThis = \"Web_BrowserBack\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-previous\";\r\n}\r\n\r\nvoid CmdWebBrowserBack::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Back')\");\r\n}\r\n\r\nbool CmdWebBrowserBack::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Back\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserNext\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserNext);\r\n\r\nCmdWebBrowserNext::CmdWebBrowserNext()\r\n : Command(\"Web_BrowserNext\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Next page\");\r\n sToolTipText = QT_TR_NOOP(\"Go to the next page\");\r\n sWhatsThis = \"Web_BrowserNext\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-next\";\r\n}\r\n\r\nvoid CmdWebBrowserNext::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Next')\");\r\n}\r\n\r\nbool CmdWebBrowserNext::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Next\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserRefresh\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserRefresh);\r\n\r\nCmdWebBrowserRefresh::CmdWebBrowserRefresh()\r\n : Command(\"Web_BrowserRefresh\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Refresh web page\");\r\n sToolTipText = QT_TR_NOOP(\"Refresh web page\");\r\n sWhatsThis = \"Web_BrowserRefresh\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-refresh\";\r\n}\r\n\r\nvoid CmdWebBrowserRefresh::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Refresh')\");\r\n}\r\n\r\nbool CmdWebBrowserRefresh::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Refresh\");\r\n}\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserStop\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserStop);\r\n\r\nCmdWebBrowserStop::CmdWebBrowserStop()\r\n\t:Command(\"Web_BrowserStop\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Stop loading\");\r\n sToolTipText = QT_TR_NOOP(\"Stop the current loading\");\r\n sWhatsThis = \"Web_BrowserStop\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-stop\";\r\n}\r\n\r\n\r\nvoid CmdWebBrowserStop::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Stop')\");\r\n}\r\n\r\nbool CmdWebBrowserStop::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Stop\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserZoomIn\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserZoomIn);\r\n\r\nCmdWebBrowserZoomIn::CmdWebBrowserZoomIn()\r\n : Command(\"Web_BrowserZoomIn\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Zoom in\");\r\n sToolTipText = QT_TR_NOOP(\"Zoom into the page\");\r\n sWhatsThis = \"Web_BrowserZoomIn\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-zoom-in\";\r\n}\r\n\r\nvoid CmdWebBrowserZoomIn::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('ZoomIn')\");\r\n}\r\n\r\nbool CmdWebBrowserZoomIn::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"ZoomIn\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserZoomOut\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserZoomOut);\r\n\r\nCmdWebBrowserZoomOut::CmdWebBrowserZoomOut()\r\n : Command(\"Web_BrowserZoomOut\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Zoom out\");\r\n sToolTipText = QT_TR_NOOP(\"Zoom out of the page\");\r\n sWhatsThis = \"Web_BrowserZoomOut\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-zoom-out\";\r\n}\r\n\r\nvoid CmdWebBrowserZoomOut::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('ZoomOut')\");\r\n}\r\n\r\nbool CmdWebBrowserZoomOut::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"ZoomOut\");\r\n}\r\n\r\n\r\nvoid CreateWebCommands(void)\r\n{\r\n Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();\r\n\r\n rcCmdMgr.addCommand(new CmdWebOpenWebsite());\r\n rcCmdMgr.addCommand(new CmdWebBrowserBack());\r\n rcCmdMgr.addCommand(new CmdWebBrowserNext());\r\n rcCmdMgr.addCommand(new CmdWebBrowserRefresh());\r\n rcCmdMgr.addCommand(new CmdWebBrowserStop());\r\n rcCmdMgr.addCommand(new CmdWebBrowserZoomIn());\r\n rcCmdMgr.addCommand(new CmdWebBrowserZoomOut());\r\n }\r\nCrowdin: more fixes\/***************************************************************************\r\n * Copyright (c) 2008 Jürgen Riegel (juergen.riegel@web.de) *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n#endif\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"BrowserView.h\"\r\n\r\nusing namespace std;\r\nusing namespace Gui;\r\nusing namespace WebGui;\r\n\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebOpenWebsite\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD(CmdWebOpenWebsite);\r\n\r\nCmdWebOpenWebsite::CmdWebOpenWebsite()\r\n : Command(\"Web_OpenWebsite\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Open website...\");\r\n sToolTipText = QT_TR_NOOP(\"Opens a website in FreeCAD\");\r\n sWhatsThis = \"Web_OpenWebsite\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-browser\";\r\n}\r\n\r\n\r\nvoid CmdWebOpenWebsite::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Doc,\"import WebGui\");\r\n doCommand(Command::Gui,\"WebGui.openBrowser('http:\/\/www.freecadweb.org\/')\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserBack\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserBack);\r\n\r\nCmdWebBrowserBack::CmdWebBrowserBack()\r\n : Command(\"Web_BrowserBack\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Previous page\");\r\n sToolTipText = QT_TR_NOOP(\"Go back to the previous page\");\r\n sWhatsThis = \"Web_BrowserBack\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-previous\";\r\n}\r\n\r\nvoid CmdWebBrowserBack::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Back')\");\r\n}\r\n\r\nbool CmdWebBrowserBack::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Back\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserNext\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserNext);\r\n\r\nCmdWebBrowserNext::CmdWebBrowserNext()\r\n : Command(\"Web_BrowserNext\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Next page\");\r\n sToolTipText = QT_TR_NOOP(\"Go to the next page\");\r\n sWhatsThis = \"Web_BrowserNext\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-next\";\r\n}\r\n\r\nvoid CmdWebBrowserNext::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Next')\");\r\n}\r\n\r\nbool CmdWebBrowserNext::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Next\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserRefresh\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserRefresh);\r\n\r\nCmdWebBrowserRefresh::CmdWebBrowserRefresh()\r\n : Command(\"Web_BrowserRefresh\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Refresh web page\");\r\n sToolTipText = QT_TR_NOOP(\"Refresh web page\");\r\n sWhatsThis = \"Web_BrowserRefresh\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-refresh\";\r\n}\r\n\r\nvoid CmdWebBrowserRefresh::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Refresh')\");\r\n}\r\n\r\nbool CmdWebBrowserRefresh::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Refresh\");\r\n}\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserStop\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserStop);\r\n\r\nCmdWebBrowserStop::CmdWebBrowserStop()\r\n\t:Command(\"Web_BrowserStop\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Stop loading\");\r\n sToolTipText = QT_TR_NOOP(\"Stop loading\");\r\n sWhatsThis = \"Web_BrowserStop\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-stop\";\r\n}\r\n\r\n\r\nvoid CmdWebBrowserStop::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('Stop')\");\r\n}\r\n\r\nbool CmdWebBrowserStop::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"Stop\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserZoomIn\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserZoomIn);\r\n\r\nCmdWebBrowserZoomIn::CmdWebBrowserZoomIn()\r\n : Command(\"Web_BrowserZoomIn\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Zoom in\");\r\n sToolTipText = QT_TR_NOOP(\"Zoom in\");\r\n sWhatsThis = \"Web_BrowserZoomIn\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-zoom-in\";\r\n}\r\n\r\nvoid CmdWebBrowserZoomIn::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('ZoomIn')\");\r\n}\r\n\r\nbool CmdWebBrowserZoomIn::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"ZoomIn\");\r\n}\r\n\r\n\/\/===========================================================================\r\n\/\/ CmdWebBrowserZoomOut\r\n\/\/===========================================================================\r\n\r\nDEF_STD_CMD_A(CmdWebBrowserZoomOut);\r\n\r\nCmdWebBrowserZoomOut::CmdWebBrowserZoomOut()\r\n : Command(\"Web_BrowserZoomOut\")\r\n{\r\n sAppModule = \"Web\";\r\n sGroup = QT_TR_NOOP(\"Web\");\r\n sMenuText = QT_TR_NOOP(\"Zoom out\");\r\n sToolTipText = QT_TR_NOOP(\"Zoom out\");\r\n sWhatsThis = \"Web_BrowserZoomOut\";\r\n sStatusTip = sToolTipText;\r\n sPixmap = \"actions\/web-zoom-out\";\r\n}\r\n\r\nvoid CmdWebBrowserZoomOut::activated(int iMsg)\r\n{\r\n Q_UNUSED(iMsg);\r\n doCommand(Command::Gui,\"Gui.SendMsgToActiveView('ZoomOut')\");\r\n}\r\n\r\nbool CmdWebBrowserZoomOut::isActive(void)\r\n{\r\n return getGuiApplication()->sendHasMsgToActiveView(\"ZoomOut\");\r\n}\r\n\r\n\r\nvoid CreateWebCommands(void)\r\n{\r\n Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();\r\n\r\n rcCmdMgr.addCommand(new CmdWebOpenWebsite());\r\n rcCmdMgr.addCommand(new CmdWebBrowserBack());\r\n rcCmdMgr.addCommand(new CmdWebBrowserNext());\r\n rcCmdMgr.addCommand(new CmdWebBrowserRefresh());\r\n rcCmdMgr.addCommand(new CmdWebBrowserStop());\r\n rcCmdMgr.addCommand(new CmdWebBrowserZoomIn());\r\n rcCmdMgr.addCommand(new CmdWebBrowserZoomOut());\r\n }\r\n<|endoftext|>"} {"text":"\nDelete 1.cpp<|endoftext|>"} {"text":"RDBUFF is nice<|endoftext|>"} {"text":"\/*\n * Copyright (c), Recep Aslantas.\n *\n * MIT License (MIT), http:\/\/opensource.org\/licenses\/MIT\n * Full license can be found in the LICENSE file\n *\/\n\n#include \"sig.h\"\n\n#include \n#include \n#include \n\nnamespace sig {\n\n#define SIG_REQ_TYPE_INT 0\n#define SIG_REQ_TYPE_STR 1\n\n#define sig_def_ctx const_cast(sig_ctx_default())\n\ntypedef const char * CStringPtr;\n\nstruct sig_signal_req;\n\nunsigned int s_last_sig_id = 1;\nunsigned int s_sig_context_last_id = 1000;\n\nstruct cmp_str {\n bool operator()(char const *a, char const *b) const {\n return strcmp(a, b) < 0;\n }\n};\n\nstd::vector signals_reqs;\nstd::map string_map;\n\nstruct sig_signal_req {\n typedef sig_observer_cb_t sig_cb_t;\n typedef sig_mem_observer_base_t sig_mem_cb_t;\n typedef unsigned int uid_t;\n typedef unsigned int req_type_t;\n\n uid_t uid;\n req_type_t req_type;\n sig_context_t * ctx;\n sig_cb_t cb;\n sig_mem_cb_t * mem_cb;\n\n sig_signal_req(req_type_t req_type,\n sig_context_t * ctx,\n uid_t _uid,\n sig_cb_t _cb);\n\n sig_signal_req(req_type_t req_type,\n sig_context_t * ctx,\n uid_t _uid,\n sig_mem_cb_t * _cb);\n\n ~sig_signal_req();\n\n bool operator==(const uid_t& r1) const;\n void operator()(sig_signal_t s) const;\n};\n\nsig_signal_req::sig_signal_req(req_type_t _req_type,\n sig_context_t * _ctx,\n uid_t _uid,\n sig_cb_t _cb)\n : req_type(_req_type),\n ctx(_ctx),\n uid(_uid),\n cb(_cb),\n mem_cb(NULL) { }\n\nsig_signal_req::sig_signal_req(req_type_t _req_type,\n sig_context_t * _ctx,\n uid_t _uid,\n sig_mem_cb_t * _cb)\n : req_type(_req_type),\n ctx(_ctx),\n uid(_uid),\n cb(NULL),\n mem_cb(_cb) { }\n\nsig_signal_req::~sig_signal_req() {\n if (this->mem_cb)\n delete this->mem_cb;\n}\n\nbool\nsig::sig_signal_req::operator==(const uid_t &an_uid) const {\n return this->uid == an_uid;\n}\n\nvoid\nsig::sig_signal_req::operator()(sig_signal_t s) const {\n \/\/ non-member functions\n if (this->cb)\n this->cb(s);\n\n \/\/ Member functions\n if (this->mem_cb)\n this->mem_cb->operator()(s);\n}\n\nunsigned int\nget_mapped_uid(CStringPtr signal) {\n unsigned int signal_uid = 0;\n std::map::iterator it = string_map.find(signal);\n if (it == string_map.end()) {\n signal_uid = ++s_last_sig_id;\n string_map.insert(std::make_pair(signal, signal_uid));\n } else {\n signal_uid = it->second;\n }\n return signal_uid;\n}\n\ntemplate \nvoid\nperform_attach(int signal,\n _FuncType cb,\n sig_context_t * ctx = sig_def_ctx) {\n sig::sig_signal_req * sig_req =\n new sig::sig_signal_req(SIG_REQ_TYPE_INT, ctx, signal, cb);\n sig::signals_reqs.push_back(sig_req);\n}\n\ntemplate \nvoid\nperform_attach(CStringPtr signal,\n _FuncType cb,\n sig_context_t * ctx = sig_def_ctx) {\n unsigned int signal_uid = get_mapped_uid(signal);\n\n sig::sig_signal_req * sig_req =\n new sig::sig_signal_req(SIG_REQ_TYPE_STR, ctx, signal_uid, cb);\n sig::signals_reqs.push_back(sig_req);\n}\n\nvoid\nperform_fire(int signal,\n void * object,\n sig_context_t * ctx = sig_def_ctx) {\n std::vector::iterator it = sig::signals_reqs.begin();\n for (; it != sig::signals_reqs.end(); it++) {\n sig_signal_req sig_req = **it;\n if (sig_req.req_type == SIG_REQ_TYPE_INT\n && sig_req.ctx->ctx_id == ctx->ctx_id\n && sig_req == signal) {\n sig_signal_t signal_object(object,\n ctx,\n object);\n sig_req(signal_object);\n }\n }\n}\n\nvoid\nperform_fire(CStringPtr signal,\n void * object,\n sig_context_t * ctx = sig_def_ctx) {\n unsigned int signal_uid = get_mapped_uid(signal);\n\n std::vector::iterator it = sig::signals_reqs.begin();\n for (; it != sig::signals_reqs.end(); it++) {\n sig_signal_req sig_req = **it;\n if (sig_req.req_type == SIG_REQ_TYPE_STR\n && sig_req.ctx->ctx_id == ctx->ctx_id\n && sig_req == signal_uid) {\n sig_signal_t signal_object(object,\n ctx,\n object);\n sig_req(signal_object);\n }\n }\n}\n\n} \/\/ namespace sig\n\nsig_context_s::sig_context_s(int id)\n : ctx_id(id) { }\n\nenum sig_reserved_context_id {\n kSigReservedContextId_Default = 0,\n kSigReservedContextId_Sys = 1\n};\n\n\nconst sig_context_t *\nsig_ctx_default() {\n static sig_context_t * __sig_default_ctx;\n if (!__sig_default_ctx) {\n __sig_default_ctx = new sig_context_t(kSigReservedContextId_Default);\n }\n return __sig_default_ctx;\n}\n\nconst sig_context_t *\nsig_ctx_sys() {\n static sig_context_t * __sig_sys_ctx;\n if (!__sig_sys_ctx) {\n __sig_sys_ctx = new sig_context_t(kSigReservedContextId_Sys);\n }\n return __sig_sys_ctx;\n}\n\nconst sig_context_t *\nsig_ctx_new() {\n int next_id = ++sig::s_sig_context_last_id;\n sig_context_t * new_ctx = new sig_context_t(next_id);\n return new_ctx;\n}\n\n\/\/ default contexts\n__SIG_C_DECL void\nsig_attach(int signal, sig_observer_cb_t cb) {\n sig::perform_attach(signal, cb);\n}\n\nvoid\nsig_attach(int signal, sig_observer_cb2_t cb) {\n sig::perform_attach(signal, cb);\n}\n\nvoid\nsig_attach(const char * signal, sig_observer_cb_t cb) {\n sig::perform_attach(signal, cb);\n}\n\nvoid\nsig_attach(const char * signal, sig_observer_cb2_t cb) {\n sig::perform_attach(signal, cb);\n}\n\n__SIG_C_DECL void\nsig_attach_s(const char * signal, sig_observer_cb_t cb) {\n sig::perform_attach(signal, cb);\n}\n\n__SIG_C_DECL void\nsig_fire(int signal, void * object) {\n sig::perform_fire(signal, object);\n}\n\nvoid\nsig_fire(const char * signal, void * object) {\n sig::perform_fire(signal, object);\n}\n\n__SIG_C_DECL void\nsig_fire_s(const char * signal, void * object) {\n sig::perform_fire(signal, object);\n}\n\n\/\/ custom contexts\n__SIG_C_DECL void\nsig_attachc(int signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, const_cast(ctx));\n}\n\nvoid\nsig_attach(int signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, const_cast(ctx));\n}\n\nvoid\nsig_attach(int signal,\n sig_observer_cb2_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, const_cast(ctx));\n}\n\nvoid\nsig_attach(const char * signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, const_cast(ctx));\n}\n\nvoid\nsig_attach(const char * signal,\n sig_observer_cb2_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, const_cast(ctx));\n}\n\n__SIG_C_DECL void\nsig_attachc_s(const char * signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, const_cast(ctx));\n}\n\n__SIG_C_DECL void\nsig_firec(int signal,\n void * object,\n const sig_context_t * ctx) {\n sig::perform_fire(signal, object, const_cast(ctx));\n}\n\nvoid\nsig_fire(const char * signal,\n void * object,\n const sig_context_t * ctx) {\n sig::perform_fire(signal, object, const_cast(ctx));\n}\n\n__SIG_C_DECL void\nsig_firec_s(const char * signal,\n void * object,\n const sig_context_t * ctx) {\n sig::perform_fire(signal, object, const_cast(ctx));\n}\nremove unnecessary const_cast-ings\/*\n * Copyright (c), Recep Aslantas.\n *\n * MIT License (MIT), http:\/\/opensource.org\/licenses\/MIT\n * Full license can be found in the LICENSE file\n *\/\n\n#include \"sig.h\"\n\n#include \n#include \n#include \n\nnamespace sig {\n\n#define SIG_REQ_TYPE_INT 0\n#define SIG_REQ_TYPE_STR 1\n\n#define sig_def_ctx sig_ctx_default()\n\ntypedef const char * CStringPtr;\n\nstruct sig_signal_req;\n\nunsigned int s_last_sig_id = 1;\nunsigned int s_sig_context_last_id = 1000;\n\nstruct cmp_str {\n bool operator()(char const *a, char const *b) const {\n return strcmp(a, b) < 0;\n }\n};\n\nstd::vector signals_reqs;\nstd::map string_map;\n\nstruct sig_signal_req {\n typedef sig_observer_cb_t sig_cb_t;\n typedef sig_mem_observer_base_t sig_mem_cb_t;\n typedef unsigned int uid_t;\n typedef unsigned int req_type_t;\n\n uid_t uid;\n req_type_t req_type;\n sig_cb_t cb;\n sig_mem_cb_t * mem_cb;\n const sig_context_t * ctx;\n\n sig_signal_req(req_type_t req_type,\n const sig_context_t * ctx,\n uid_t _uid,\n sig_cb_t _cb);\n\n sig_signal_req(req_type_t req_type,\n const sig_context_t * ctx,\n uid_t _uid,\n sig_mem_cb_t * _cb);\n\n ~sig_signal_req();\n\n bool operator==(const uid_t& r1) const;\n void operator()(sig_signal_t s) const;\n};\n\nsig_signal_req::sig_signal_req(req_type_t _req_type,\n const sig_context_t * _ctx,\n uid_t _uid,\n sig_cb_t _cb)\n : req_type(_req_type),\n ctx(_ctx),\n uid(_uid),\n cb(_cb),\n mem_cb(NULL) { }\n\nsig_signal_req::sig_signal_req(req_type_t _req_type,\n const sig_context_t * _ctx,\n uid_t _uid,\n sig_mem_cb_t * _cb)\n : req_type(_req_type),\n ctx(_ctx),\n uid(_uid),\n cb(NULL),\n mem_cb(_cb) { }\n\nsig_signal_req::~sig_signal_req() {\n if (this->mem_cb)\n delete this->mem_cb;\n}\n\nbool\nsig::sig_signal_req::operator==(const uid_t &an_uid) const {\n return this->uid == an_uid;\n}\n\nvoid\nsig::sig_signal_req::operator()(sig_signal_t s) const {\n \/\/ non-member functions\n if (this->cb)\n this->cb(s);\n\n \/\/ Member functions\n if (this->mem_cb)\n this->mem_cb->operator()(s);\n}\n\nunsigned int\nget_mapped_uid(CStringPtr signal) {\n unsigned int signal_uid = 0;\n std::map::iterator it = string_map.find(signal);\n if (it == string_map.end()) {\n signal_uid = ++s_last_sig_id;\n string_map.insert(std::make_pair(signal, signal_uid));\n } else {\n signal_uid = it->second;\n }\n return signal_uid;\n}\n\ntemplate \nvoid\nperform_attach(int signal,\n _FuncType cb,\n const sig_context_t * ctx = sig_def_ctx) {\n sig::sig_signal_req * sig_req =\n new sig::sig_signal_req(SIG_REQ_TYPE_INT, ctx, signal, cb);\n sig::signals_reqs.push_back(sig_req);\n}\n\ntemplate \nvoid\nperform_attach(CStringPtr signal,\n _FuncType cb,\n const sig_context_t * ctx = sig_def_ctx) {\n unsigned int signal_uid = get_mapped_uid(signal);\n\n sig::sig_signal_req * sig_req =\n new sig::sig_signal_req(SIG_REQ_TYPE_STR, ctx, signal_uid, cb);\n sig::signals_reqs.push_back(sig_req);\n}\n\nvoid\nperform_fire(int signal,\n void * object,\n const sig_context_t * ctx = sig_def_ctx) {\n std::vector::iterator it = sig::signals_reqs.begin();\n for (; it != sig::signals_reqs.end(); it++) {\n sig_signal_req sig_req = **it;\n if (sig_req.req_type == SIG_REQ_TYPE_INT\n && sig_req.ctx->ctx_id == ctx->ctx_id\n && sig_req == signal) {\n sig_signal_t signal_object(object,\n ctx,\n object);\n sig_req(signal_object);\n }\n }\n}\n\nvoid\nperform_fire(CStringPtr signal,\n void * object,\n const sig_context_t * ctx = sig_def_ctx) {\n unsigned int signal_uid = get_mapped_uid(signal);\n\n std::vector::iterator it = sig::signals_reqs.begin();\n for (; it != sig::signals_reqs.end(); it++) {\n sig_signal_req sig_req = **it;\n if (sig_req.req_type == SIG_REQ_TYPE_STR\n && sig_req.ctx->ctx_id == ctx->ctx_id\n && sig_req == signal_uid) {\n sig_signal_t signal_object(object,\n ctx,\n object);\n sig_req(signal_object);\n }\n }\n}\n\n} \/\/ namespace sig\n\nsig_context_s::sig_context_s(int id)\n : ctx_id(id) { }\n\nenum sig_reserved_context_id {\n kSigReservedContextId_Default = 0,\n kSigReservedContextId_Sys = 1\n};\n\n\nconst sig_context_t *\nsig_ctx_default() {\n static sig_context_t * __sig_default_ctx;\n if (!__sig_default_ctx) {\n __sig_default_ctx = new sig_context_t(kSigReservedContextId_Default);\n }\n return __sig_default_ctx;\n}\n\nconst sig_context_t *\nsig_ctx_sys() {\n static sig_context_t * __sig_sys_ctx;\n if (!__sig_sys_ctx) {\n __sig_sys_ctx = new sig_context_t(kSigReservedContextId_Sys);\n }\n return __sig_sys_ctx;\n}\n\nconst sig_context_t *\nsig_ctx_new() {\n int next_id = ++sig::s_sig_context_last_id;\n sig_context_t * new_ctx = new sig_context_t(next_id);\n return new_ctx;\n}\n\n\/\/ default contexts\n__SIG_C_DECL void\nsig_attach(int signal, sig_observer_cb_t cb) {\n sig::perform_attach(signal, cb);\n}\n\nvoid\nsig_attach(int signal, sig_observer_cb2_t cb) {\n sig::perform_attach(signal, cb);\n}\n\nvoid\nsig_attach(const char * signal, sig_observer_cb_t cb) {\n sig::perform_attach(signal, cb);\n}\n\nvoid\nsig_attach(const char * signal, sig_observer_cb2_t cb) {\n sig::perform_attach(signal, cb);\n}\n\n__SIG_C_DECL void\nsig_attach_s(const char * signal, sig_observer_cb_t cb) {\n sig::perform_attach(signal, cb);\n}\n\n__SIG_C_DECL void\nsig_fire(int signal, void * object) {\n sig::perform_fire(signal, object);\n}\n\nvoid\nsig_fire(const char * signal, void * object) {\n sig::perform_fire(signal, object);\n}\n\n__SIG_C_DECL void\nsig_fire_s(const char * signal, void * object) {\n sig::perform_fire(signal, object);\n}\n\n\/\/ custom contexts\n__SIG_C_DECL void\nsig_attachc(int signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, ctx);\n}\n\nvoid\nsig_attach(int signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, ctx);\n}\n\nvoid\nsig_attach(int signal,\n sig_observer_cb2_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, ctx);\n}\n\nvoid\nsig_attach(const char * signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, ctx);\n}\n\nvoid\nsig_attach(const char * signal,\n sig_observer_cb2_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, ctx);\n}\n\n__SIG_C_DECL void\nsig_attachc_s(const char * signal,\n sig_observer_cb_t cb,\n const sig_context_t * ctx) {\n sig::perform_attach(signal, cb, ctx);\n}\n\n__SIG_C_DECL void\nsig_firec(int signal,\n void * object,\n const sig_context_t * ctx) {\n sig::perform_fire(signal, object, ctx);\n}\n\nvoid\nsig_fire(const char * signal,\n void * object,\n const sig_context_t * ctx) {\n sig::perform_fire(signal, object, ctx);\n}\n\n__SIG_C_DECL void\nsig_firec_s(const char * signal,\n void * object,\n const sig_context_t * ctx) {\n sig::perform_fire(signal, object, ctx);\n}\n<|endoftext|>"} {"text":"\/*\n\n This program will add histograms (see note) and Trees from a list of root files and write them\n to a target root file. The target file is newly created and must not be\n identical to one of the source files.\n\n Syntax:\n\n hadd targetfile source1 source2 ...\n or\n hadd -f targetfile source1 source2 ...\n (targetfile is overwritten if it exists)\n\n When the -f option is specified, one can also specify the compression\n level of the target file. By default the compression level is 1, but\n if \"-f0\" is specified, the target file will not be compressed.\n if \"-f6\" is specified, the compression level 6 will be used.\n\n For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn\n f1 with h1 h2 h3 T1\n f2 with h1 h4 T1 T2\n f3 with h5\n the result of\n hadd -f x.root f1.root f2.root f3.root\n will be a file x.root with h1 h2 h3 h4 h5 T1 T2\n where h1 will be the sum of the 2 histograms in f1 and f2\n T1 will be the merge of the Trees in f1 and f2\n\n The files may contain sub-directories.\n\n if the source files contains histograms and Trees, one can skip\n the Trees with\n hadd -T targetfile source1 source2 ...\n\n Wildcarding and indirect files are also supported\n hadd result.root myfil*.root\n will merge all files in myfil*.root\n hadd result.root file1.root @list.txt file2. root myfil*.root\n will merge file1. root, file2. root, all files in myfil*.root\n and all files in the indirect text file list.txt (\"@\" as the first\n character of the file indicates an indirect file. An indirect file\n is a text file containing a list of other files, including other\n indirect files, one line per file).\n\n If the sources and and target compression levels are identical (default),\n the program uses the TChain::Merge function with option \"fast\", ie\n the merge will be done without unzipping or unstreaming the baskets\n (i.e. direct copy of the raw byte on disk). The \"fast\" mode is typically\n 5 times faster than the mode unzipping and unstreaming the baskets.\n\n NOTE1: By default histograms are added. However hadd does not support the case where\n histograms have their bit TH1::kIsAverage set.\n\n NOTE2: hadd returns a status code: 0 if OK, -1 otherwise\n\n Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch\n : rewritten from scratch by Rene Brun (30 November 2005)\n to support files with nested directories.\n Toby Burnett implemented the possibility to use indirect files.\n *\/\n\n#include \"RConfig.h\"\n#include \n#include \"TFile.h\"\n#include \"THashList.h\"\n#include \"TKey.h\"\n#include \"TObjString.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n#include \"TSystem.h\"\n#include \n\n#include \"TFileMerger.h\"\n\n\/\/___________________________________________________________________________\nint main( int argc, char **argv )\n{\n\n if ( argc < 3 || \"-h\" == std::string(argv[1]) || \"--help\" == std::string(argv[1]) ) {\n std::cout << \"Usage: \" << argv[0] << \" [-f[0-9]] [-k] [-T] [-O] [-n maxopenedfiles] [-v verbosity] targetfile source1 [source2 source3 ...]\" << std::endl;\n std::cout << \"This program will add histograms from a list of root files and write them\" << std::endl;\n std::cout << \"to a target root file. The target file is newly created and must not \" << std::endl;\n std::cout << \"exist, or if -f (\\\"force\\\") is given, must not be one of the source files.\" << std::endl;\n std::cout << \"Supply at least two source files for this to make sense... ;-)\" << std::endl;\n std::cout << \"If the option -k is used, hadd will not exit on corrupt or non-existant input files but skip the offending files instead.\" << std::endl;\n std::cout << \"If the option -T is used, Trees are not merged\" <= argc) {\n std::cerr << \"Error: no maximum number of opened was provided after -n.\\n\";\n } else {\n Long_t request = strtol(argv[a+1], 0, 10);\n if (request < kMaxLong && request >= 0) {\n maxopenedfiles = (Int_t)request;\n ++a;\n ++ffirst;\n } else {\n std::cerr << \"Error: could not parse the max number of opened file passed after -n: \" << argv[a+1] << \". We will use the system maximum.\\n\";\n }\n }\n ++ffirst;\n } else if ( strcmp(argv[a],\"-v\") == 0 ) {\n if (a+1 >= argc) {\n std::cerr << \"Error: no verbosity level was provided after -v.\\n\";\n } else {\n Long_t request = strtol(argv[a+1], 0, 10);\n if (request < kMaxLong && request >= 0) {\n verbosity = (Int_t)request;\n ++a;\n ++ffirst;\n } else {\n std::cerr << \"Error: could not parse the verbosity level passed after -v: \" << argv[a+1] << \". We will use the default value (99).\\n\";\n }\n }\n ++ffirst;\n } else if ( argv[a][0] == '-' ) {\n char ft[4];\n for( int j=0; j<=9; ++j ) {\n snprintf(ft,4,\"-f%d\",j);\n if (!strcmp(argv[a],ft)) {\n force = kTRUE;\n newcomp = j;\n ++ffirst;\n break;\n }\n }\n if (!force) {\n \/\/ Bad argument\n std::cerr << \"Error: option \" << argv[a] << \" is not a supported option.\\n\";\n ++ffirst;\n }\n } else if (!outputPlace) {\n outputPlace = a;\n }\n }\n\n gSystem->Load(\"libTreePlayer\");\n\n const char *targetname = 0;\n if (outputPlace) {\n targetname = argv[outputPlace];\n } else {\n targetname = argv[ffirst-1];\n }\n\n if (verbosity > 1) {\n std::cout << \"hadd Target file: \" << targetname << std::endl;\n }\n\n TFileMerger merger(kFALSE,kFALSE);\n merger.SetMsgPrefix(\"hadd\");\n merger.SetPrintLevel(verbosity - 1);\n if (maxopenedfiles > 0) {\n merger.SetMaxOpenedFiles(maxopenedfiles);\n }\n if (!merger.OutputFile(targetname,force,newcomp) ) {\n std::cerr << \"hadd error opening target file (does \" << argv[ffirst-1] << \" exist?).\" << std::endl;\n std::cerr << \"Pass \\\"-f\\\" argument to force re-creation of output file.\" << std::endl;\n exit(1);\n }\n\n\n for ( int i = ffirst; i < argc; i++ ) {\n if (argv[i] && argv[i][0]=='@') {\n std::ifstream indirect_file(argv[i]+1);\n if( ! indirect_file.is_open() ) {\n std::cerr<< \"hadd could not open indirect file \" << (argv[i]+1) << std::endl;\n return 1;\n }\n while( indirect_file ){\n std::string line;\n if( std::getline(indirect_file, line) && line.length() && !merger.AddFile(line.c_str()) ) {\n return 1;\n }\n }\n } else if( ! merger.AddFile(argv[i]) ) {\n if ( skip_errors ) {\n std::cerr << \"hadd skipping file with error: \" << argv[i] << std::endl;\n } else {\n std::cerr << \"hadd exiting due to error in \" << argv[i] << std::endl;\n return 1;\n }\n }\n }\n if (reoptimize) {\n merger.SetFastMethod(kFALSE);\n } else {\n if (merger.HasCompressionChange()) {\n \/\/ Don't warn if the user any request re-optimization.\n std::cout <<\"hadd Sources and Target have different compression levels\"<GetEntries() << \" input files in \" << targetname << \".\\n\";\n }\n return 0;\n } else {\n if (verbosity == 1) {\n std::cout << \"hadd failure during the merge of \" << merger.GetMergeList()->GetEntries() << \" input files in \" << targetname << \".\\n\";\n }\n return 1;\n }\n}\nExtend hadd -f to support compression setting.\/*\n\n This program will add histograms (see note) and Trees from a list of root files and write them\n to a target root file. The target file is newly created and must not be\n identical to one of the source files.\n\n Syntax:\n\n hadd targetfile source1 source2 ...\n or\n hadd -f targetfile source1 source2 ...\n (targetfile is overwritten if it exists)\n\n When the -f option is specified, one can also specify the compression\n level of the target file. By default the compression level is 1, but\n if \"-f0\" is specified, the target file will not be compressed.\n if \"-f6\" is specified, the compression level 6 will be used.\n\n For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn\n f1 with h1 h2 h3 T1\n f2 with h1 h4 T1 T2\n f3 with h5\n the result of\n hadd -f x.root f1.root f2.root f3.root\n will be a file x.root with h1 h2 h3 h4 h5 T1 T2\n where h1 will be the sum of the 2 histograms in f1 and f2\n T1 will be the merge of the Trees in f1 and f2\n\n The files may contain sub-directories.\n\n if the source files contains histograms and Trees, one can skip\n the Trees with\n hadd -T targetfile source1 source2 ...\n\n Wildcarding and indirect files are also supported\n hadd result.root myfil*.root\n will merge all files in myfil*.root\n hadd result.root file1.root @list.txt file2. root myfil*.root\n will merge file1. root, file2. root, all files in myfil*.root\n and all files in the indirect text file list.txt (\"@\" as the first\n character of the file indicates an indirect file. An indirect file\n is a text file containing a list of other files, including other\n indirect files, one line per file).\n\n If the sources and and target compression levels are identical (default),\n the program uses the TChain::Merge function with option \"fast\", ie\n the merge will be done without unzipping or unstreaming the baskets\n (i.e. direct copy of the raw byte on disk). The \"fast\" mode is typically\n 5 times faster than the mode unzipping and unstreaming the baskets.\n\n NOTE1: By default histograms are added. However hadd does not support the case where\n histograms have their bit TH1::kIsAverage set.\n\n NOTE2: hadd returns a status code: 0 if OK, -1 otherwise\n\n Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch\n : rewritten from scratch by Rene Brun (30 November 2005)\n to support files with nested directories.\n Toby Burnett implemented the possibility to use indirect files.\n *\/\n\n#include \"RConfig.h\"\n#include \n#include \"TFile.h\"\n#include \"THashList.h\"\n#include \"TKey.h\"\n#include \"TObjString.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n#include \"TSystem.h\"\n#include \n\n#include \"TFileMerger.h\"\n\n\/\/___________________________________________________________________________\nint main( int argc, char **argv )\n{\n\n if ( argc < 3 || \"-h\" == std::string(argv[1]) || \"--help\" == std::string(argv[1]) ) {\n std::cout << \"Usage: \" << argv[0] << \" [-f[0-9]] [-k] [-T] [-O] [-n maxopenedfiles] [-v verbosity] targetfile source1 [source2 source3 ...]\" << std::endl;\n std::cout << \"This program will add histograms from a list of root files and write them\" << std::endl;\n std::cout << \"to a target root file. The target file is newly created and must not \" << std::endl;\n std::cout << \"exist, or if -f (\\\"force\\\") is given, must not be one of the source files.\" << std::endl;\n std::cout << \"Supply at least two source files for this to make sense... ;-)\" << std::endl;\n std::cout << \"If the option -k is used, hadd will not exit on corrupt or non-existant input files but skip the offending files instead.\" << std::endl;\n std::cout << \"If the option -T is used, Trees are not merged\" <= argc) {\n std::cerr << \"Error: no maximum number of opened was provided after -n.\\n\";\n } else {\n Long_t request = strtol(argv[a+1], 0, 10);\n if (request < kMaxLong && request >= 0) {\n maxopenedfiles = (Int_t)request;\n ++a;\n ++ffirst;\n } else {\n std::cerr << \"Error: could not parse the max number of opened file passed after -n: \" << argv[a+1] << \". We will use the system maximum.\\n\";\n }\n }\n ++ffirst;\n } else if ( strcmp(argv[a],\"-v\") == 0 ) {\n if (a+1 >= argc) {\n std::cerr << \"Error: no verbosity level was provided after -v.\\n\";\n } else {\n Long_t request = strtol(argv[a+1], 0, 10);\n if (request < kMaxLong && request >= 0) {\n verbosity = (Int_t)request;\n ++a;\n ++ffirst;\n } else {\n std::cerr << \"Error: could not parse the verbosity level passed after -v: \" << argv[a+1] << \". We will use the default value (99).\\n\";\n }\n }\n ++ffirst;\n } else if ( argv[a][0] == '-' ) {\n char ft[6];\n for ( int alg = 0; alg <= 2; ++alg ) {\n for( int j=0; j<=9; ++j ) {\n const int comp = (alg*100)+j;\n snprintf(ft,6,\"-f%d\",comp);\n if (!strcmp(argv[a],ft)) {\n force = kTRUE;\n newcomp = comp;\n ++ffirst;\n break;\n }\n }\n }\n if (!force) {\n \/\/ Bad argument\n std::cerr << \"Error: option \" << argv[a] << \" is not a supported option.\\n\";\n ++ffirst;\n }\n } else if (!outputPlace) {\n outputPlace = a;\n }\n }\n\n gSystem->Load(\"libTreePlayer\");\n\n const char *targetname = 0;\n if (outputPlace) {\n targetname = argv[outputPlace];\n } else {\n targetname = argv[ffirst-1];\n }\n\n if (verbosity > 1) {\n std::cout << \"hadd Target file: \" << targetname << std::endl;\n }\n\n TFileMerger merger(kFALSE,kFALSE);\n merger.SetMsgPrefix(\"hadd\");\n merger.SetPrintLevel(verbosity - 1);\n if (maxopenedfiles > 0) {\n merger.SetMaxOpenedFiles(maxopenedfiles);\n }\n if (!merger.OutputFile(targetname,force,newcomp) ) {\n std::cerr << \"hadd error opening target file (does \" << argv[ffirst-1] << \" exist?).\" << std::endl;\n std::cerr << \"Pass \\\"-f\\\" argument to force re-creation of output file.\" << std::endl;\n exit(1);\n }\n\n\n for ( int i = ffirst; i < argc; i++ ) {\n if (argv[i] && argv[i][0]=='@') {\n std::ifstream indirect_file(argv[i]+1);\n if( ! indirect_file.is_open() ) {\n std::cerr<< \"hadd could not open indirect file \" << (argv[i]+1) << std::endl;\n return 1;\n }\n while( indirect_file ){\n std::string line;\n if( std::getline(indirect_file, line) && line.length() && !merger.AddFile(line.c_str()) ) {\n return 1;\n }\n }\n } else if( ! merger.AddFile(argv[i]) ) {\n if ( skip_errors ) {\n std::cerr << \"hadd skipping file with error: \" << argv[i] << std::endl;\n } else {\n std::cerr << \"hadd exiting due to error in \" << argv[i] << std::endl;\n return 1;\n }\n }\n }\n if (reoptimize) {\n merger.SetFastMethod(kFALSE);\n } else {\n if (merger.HasCompressionChange()) {\n \/\/ Don't warn if the user any request re-optimization.\n std::cout <<\"hadd Sources and Target have different compression levels\"<GetEntries() << \" input files in \" << targetname << \".\\n\";\n }\n return 0;\n } else {\n if (verbosity == 1) {\n std::cout << \"hadd failure during the merge of \" << merger.GetMergeList()->GetEntries() << \" input files in \" << targetname << \".\\n\";\n }\n return 1;\n }\n}\n<|endoftext|>"} {"text":"\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#ifdef ORK_TEXT_HPP\n#\terror This header can only be included from ork\/ork.hpp!\n#endif\n\n#ifndef ORK_TEXT_HPP\n#define ORK_TEXT_HPP\n\n#ifndef ORK_ORK_HPP\n#\terror This header can only be included from ork\/ork.hpp!\n#endif\n\n\n#include\n#include\n\n\n#if defined UNICODE || defined _UNICODE\/\/Avoid checking both everywhere\n#\tdefine ORK_UNICODE 1\n#else\n#\tdefine ORK_UNICODE 0\n#endif\n\n\n#if ORK_GCC || ORK_MSC >= 1900\n# define ORK_STL_HAS_FILE 1\n#else\n# define ORK_STL_HAS_FILE 0\n#endif\n\n\n\/\/Forward declaration to keep boost out of headers\n#if ORK_STL_HAS_FILE\n\n#include\n\nnamespace ork {\nnamespace detail {\nnamespace fstream {\n\nusing wofstream = std::wofstream;\nusing wifstream = std::wifstream;\nusing wfstream = std::wfstream;\nusing ofstream = std::ofstream;\nusing ifstream = std::ifstream;\nusing fstream = std::fstream;\n\n}\/\/namespace fstream\n}\/\/namespace detail\n}\/\/namespace ork\n\n#else\n\n\/\/Some boost configuration here\n#define BOOST_SYSTEM_NO_DEPRECATED 1\n#define BOOST_FILESYSTEM_NO_DEPRECATED 1\n\nnamespace boost {\nnamespace filesystem {\n\nclass wofstream;\nclass wifstream;\nclass wfstream;\nclass ofstream;\nclass ifstream;\nclass fstream;\n\n}\/\/filesystem\n}\/\/boost\n\n\nnamespace ork {\nnamespace detail {\nnamespace fstream {\n\nusing wofstream = boost::filesystem::wofstream;\nusing wifstream = boost::filesystem::wifstream;\nusing wfstream = boost::filesystem::wfstream;\nusing ofstream = boost::filesystem::ofstream;\nusing ifstream = boost::filesystem::ifstream;\nusing fstream = boost::filesystem::fstream;\n\n}\/\/namespace fstream\n}\/\/namespace detail\n}\/\/namespace ork\n\n#endif\n\n\nnamespace ork {\n\n\n#define ORK_STR_(X) #X\n#define ORK_STR(X) ORK_STR_(X)\n\n\n#define ORK_CAT_(X,Y) X##Y\n#define ORK_CAT(X,Y) ORK_CAT_(X,Y)\n#define ORK_CAT3(X,Y,Z) ORK_CAT(X,ORK_CAT(Y,Z))\n#define ORK_CAT4(W,X,Y,Z) ORK_CAT(W,ORK_CAT3(X,Y,Z))\n#define ORK_CAT5(V,W,X,Y,Z) ORK_CAT(V,ORK_CAT4(W,X,Y,Z))\n\n\n#define ORK_WIDEN_(X) L##X\n#define ORK_WIDEN(X) ORK_WIDEN_(X)\n\n\n\n#if ORK_UNICODE\n\ttypedef std::wstring string;\n\ttypedef std::wstringstream string_stream;\n\ttypedef wchar_t char_t;\n\ttypedef std::wostream o_stream;\n\ttypedef std::wistream i_stream;\n\ttypedef std::wostringstream o_string_stream;\n\ttypedef std::wistringstream i_string_stream;\n\ttypedef std::wstreambuf streambuf;\n\t#define ORK(X) ORK_WIDEN(X)\/\/The shortest prefixed macro\n\t#define ORK_CIN std::wcin\n\t#define ORK_COUT std::wcout\n\t#define ORK_CERR std::wcerr\n\t#define ORK_CLOG std::wclog\n#else\n\ttypedef std::string string;\n\ttypedef std::stringstream string_stream;\n\ttypedef char char_t;\n\ttypedef std::ostream o_stream;\n\ttypedef std::istream i_stream;\n\ttypedef std::ostringstream o_string_stream;\n\ttypedef std::istringstream i_string_stream;\n\ttypedef std::streambuf streambuf;\n\t#define ORK(X) X\/\/The shortest prefixed macro\n\t#define ORK_CIN std::cin\n\t#define ORK_COUT std::cout\n\t#define ORK_CERR std::cerr\n\t#define ORK_CLOG std::clog\n#endif\ntypedef std::wstring wstring;\ntypedef std::string bstring;\/\/Byte string, so that searches can identify unhandled unicode\ntypedef std::stringstream b_string_stream;\ntypedef std::ostream bo_stream;\ntypedef std::istream bi_stream;\ntypedef std::ostringstream bo_string_stream;\ntypedef std::istringstream bi_string_stream;\n#define BORK(X) X\/\/Byte Text, so that searches can identify unhandled unicode\n\n\n#define ORK_FILEN ORK(__FILE__)\n#define ORK_LINE ORK(ORK_STR(__LINE__))\n\n\n#define _ORK_UID2(PREFIX, LINE, COUNT) ORK_CAT3(PREFIX, LINE, COUNT)\n#define _ORK_UID1(PREFIX, LINE) _ORK_UID2(PREFIX, LINE, __COUNTER__)\n#define ORK_UID(PREFIX) _ORK_UID1(PREFIX, __LINE__)\n\n\n#if ORK_MSC\n# define ORK_FUNC __FUNCTION__\n#elif ORK_GCC\n# define ORK_FUNC __PRETTY_FUNCTION__\n#else\n#\terror Compiler not supported\n#endif\n\n\n#define ORK_FLOC ORK_CAT4(ORK_FILEN, ORK(\"(\"), ORK_LINE, ORK(\")\"))\n\n\n#if ORK_UNICODE\n\ttypedef detail::fstream::wofstream of_stream;\n\ttypedef detail::fstream::wifstream if_stream;\n\ttypedef detail::fstream::wfstream f_stream;\n\t#define ORK_GEN_STR generic_wstring\n\t#define ORK_STRING wstring\n#else\n\ttypedef detail::fstream::ofstream of_stream;\n\ttypedef detail::fstream::ifstream if_stream;\n\ttypedef detail::fstream::fstream f_stream;\n\t#define ORK_GEN_STR generic_string\n\t#define ORK_STRING string\n#endif\n\n\nclass string_converter_type {\/\/Just a thread-safe wrapper for std::wstring_convert\nprivate:\n\tstruct impl;\nprivate:\n\tstd::unique_ptr_pimpl;\npublic:\n\tstring_converter_type();\n\t~string_converter_type();\n\tORK_MOVE_ONLY(string_converter_type)\npublic:\n\tORK_ORK_API bstring wide2byte(const wchar_t s);\n\tORK_ORK_API bstring wide2byte(const wchar_t*s);\n\tORK_ORK_API bstring wide2byte(const wstring&s);\n\tORK_ORK_API bstring wide2byte(const wchar_t*first, const wchar_t*last);\n\n\tORK_ORK_API wstring byte2wide(const char s);\n\tORK_ORK_API wstring byte2wide(const char*s);\n\tORK_ORK_API wstring byte2wide(const bstring&s);\n\tORK_ORK_API wstring byte2wide(const char*first, const char*last);\n};\nORK_ORK_EXT(string_converter_type&) g_string_converter();\n\n\n#if ORK_UNICODE\n#\tdefine ORK_STR_2_BYTE(ORK_STRING) ork::g_string_converter().wide2byte(ORK_STRING)\n#\tdefine ORK_STR_2_WIDE(ORK_STRING) ORK_STRING\n#\tdefine ORK_BYTE_2_STR(ORK_STRING) ork::g_string_converter().byte2wide(ORK_STRING)\n#\tdefine ORK_WIDE_2_STR(ORK_STRING) ORK_STRING\n#else\n#\tdefine ORK_STR_2_BYTE(ORK_STRING) ORK_STRING\n#\tdefine ORK_STR_2_WIDE(ORK_STRING) ork::g_string_converter().byte2wide(ORK_STRING)\n#\tdefine ORK_BYTE_2_STR(ORK_STRING) ORK_STRING\n#\tdefine ORK_WIDE_2_STR(ORK_STRING) ork::g_string_converter().wide2byte(ORK_STRING)\n#endif\n\n}\/\/namespace ork\n\n#endif\/\/ORK_TEXT_HPP\nAdded typedefs for byte and wide file streams\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#ifdef ORK_TEXT_HPP\n#\terror This header can only be included from ork\/ork.hpp!\n#endif\n\n#ifndef ORK_TEXT_HPP\n#define ORK_TEXT_HPP\n\n#ifndef ORK_ORK_HPP\n#\terror This header can only be included from ork\/ork.hpp!\n#endif\n\n\n#include\n#include\n\n\n#if defined UNICODE || defined _UNICODE\/\/Avoid checking both everywhere\n#\tdefine ORK_UNICODE 1\n#else\n#\tdefine ORK_UNICODE 0\n#endif\n\n\n#if ORK_GCC || ORK_MSC >= 1900\n# define ORK_STL_HAS_FILE 1\n#else\n# define ORK_STL_HAS_FILE 0\n#endif\n\n\n\/\/Forward declaration to keep boost out of headers\n#if ORK_STL_HAS_FILE\n\n#include\n\nnamespace ork {\nnamespace detail {\nnamespace fstream {\n\nusing wofstream = std::wofstream;\nusing wifstream = std::wifstream;\nusing wfstream = std::wfstream;\nusing ofstream = std::ofstream;\nusing ifstream = std::ifstream;\nusing fstream = std::fstream;\n\n}\/\/namespace fstream\n}\/\/namespace detail\n}\/\/namespace ork\n\n#else\n\n\/\/Some boost configuration here\n#define BOOST_SYSTEM_NO_DEPRECATED 1\n#define BOOST_FILESYSTEM_NO_DEPRECATED 1\n\nnamespace boost {\nnamespace filesystem {\n\nclass wofstream;\nclass wifstream;\nclass wfstream;\nclass ofstream;\nclass ifstream;\nclass fstream;\n\n}\/\/filesystem\n}\/\/boost\n\n\nnamespace ork {\nnamespace detail {\nnamespace fstream {\n\nusing wofstream = boost::filesystem::wofstream;\nusing wifstream = boost::filesystem::wifstream;\nusing wfstream = boost::filesystem::wfstream;\nusing ofstream = boost::filesystem::ofstream;\nusing ifstream = boost::filesystem::ifstream;\nusing fstream = boost::filesystem::fstream;\n\n}\/\/namespace fstream\n}\/\/namespace detail\n}\/\/namespace ork\n\n#endif\n\n\nnamespace ork {\n\n\n#define ORK_STR_(X) #X\n#define ORK_STR(X) ORK_STR_(X)\n\n\n#define ORK_CAT_(X,Y) X##Y\n#define ORK_CAT(X,Y) ORK_CAT_(X,Y)\n#define ORK_CAT3(X,Y,Z) ORK_CAT(X,ORK_CAT(Y,Z))\n#define ORK_CAT4(W,X,Y,Z) ORK_CAT(W,ORK_CAT3(X,Y,Z))\n#define ORK_CAT5(V,W,X,Y,Z) ORK_CAT(V,ORK_CAT4(W,X,Y,Z))\n\n\n#define ORK_WIDEN_(X) L##X\n#define ORK_WIDEN(X) ORK_WIDEN_(X)\n\n\n\n#if ORK_UNICODE\n\ttypedef std::wstring string;\n\ttypedef std::wstringstream string_stream;\n\ttypedef wchar_t char_t;\n\ttypedef std::wostream o_stream;\n\ttypedef std::wistream i_stream;\n\ttypedef std::wostringstream o_string_stream;\n\ttypedef std::wistringstream i_string_stream;\n\ttypedef std::wstreambuf streambuf;\n\t#define ORK(X) ORK_WIDEN(X)\/\/The shortest prefixed macro\n\t#define ORK_CIN std::wcin\n\t#define ORK_COUT std::wcout\n\t#define ORK_CERR std::wcerr\n\t#define ORK_CLOG std::wclog\n#else\n\ttypedef std::string string;\n\ttypedef std::stringstream string_stream;\n\ttypedef char char_t;\n\ttypedef std::ostream o_stream;\n\ttypedef std::istream i_stream;\n\ttypedef std::ostringstream o_string_stream;\n\ttypedef std::istringstream i_string_stream;\n\ttypedef std::streambuf streambuf;\n\t#define ORK(X) X\/\/The shortest prefixed macro\n\t#define ORK_CIN std::cin\n\t#define ORK_COUT std::cout\n\t#define ORK_CERR std::cerr\n\t#define ORK_CLOG std::clog\n#endif\ntypedef std::wstring wstring;\ntypedef std::string bstring;\/\/Byte string, so that searches can identify unhandled unicode\ntypedef std::stringstream b_string_stream;\ntypedef std::ostream bo_stream;\ntypedef std::istream bi_stream;\ntypedef std::ostringstream bo_string_stream;\ntypedef std::istringstream bi_string_stream;\n#define BORK(X) X\/\/Byte Text, so that searches can identify unhandled unicode\n\n\n#define ORK_FILEN ORK(__FILE__)\n#define ORK_LINE ORK(ORK_STR(__LINE__))\n\n\n#define _ORK_UID2(PREFIX, LINE, COUNT) ORK_CAT3(PREFIX, LINE, COUNT)\n#define _ORK_UID1(PREFIX, LINE) _ORK_UID2(PREFIX, LINE, __COUNTER__)\n#define ORK_UID(PREFIX) _ORK_UID1(PREFIX, __LINE__)\n\n\n#if ORK_MSC\n# define ORK_FUNC __FUNCTION__\n#elif ORK_GCC\n# define ORK_FUNC __PRETTY_FUNCTION__\n#else\n#\terror Compiler not supported\n#endif\n\n\n#define ORK_FLOC ORK_CAT4(ORK_FILEN, ORK(\"(\"), ORK_LINE, ORK(\")\"))\n\n\n#if ORK_UNICODE\n\ttypedef detail::fstream::wofstream of_stream;\n\ttypedef detail::fstream::wifstream if_stream;\n\ttypedef detail::fstream::wfstream f_stream;\n\t#define ORK_GEN_STR generic_wstring\n\t#define ORK_STRING wstring\n#else\n\ttypedef detail::fstream::ofstream of_stream;\n\ttypedef detail::fstream::ifstream if_stream;\n\ttypedef detail::fstream::fstream f_stream;\n\t#define ORK_GEN_STR generic_string\n\t#define ORK_STRING string\n#endif\ntypedef detail::fstream::wofstream wof_stream;\ntypedef detail::fstream::wifstream wif_stream;\ntypedef detail::fstream::wfstream wf_stream;\ntypedef detail::fstream::ofstream bof_stream;\ntypedef detail::fstream::ifstream bif_stream;\ntypedef detail::fstream::fstream bf_stream;\n\n\nclass string_converter_type {\/\/Just a thread-safe wrapper for std::wstring_convert\nprivate:\n\tstruct impl;\nprivate:\n\tstd::unique_ptr_pimpl;\npublic:\n\tstring_converter_type();\n\t~string_converter_type();\n\tORK_MOVE_ONLY(string_converter_type)\npublic:\n\tORK_ORK_API bstring wide2byte(const wchar_t s);\n\tORK_ORK_API bstring wide2byte(const wchar_t*s);\n\tORK_ORK_API bstring wide2byte(const wstring&s);\n\tORK_ORK_API bstring wide2byte(const wchar_t*first, const wchar_t*last);\n\n\tORK_ORK_API wstring byte2wide(const char s);\n\tORK_ORK_API wstring byte2wide(const char*s);\n\tORK_ORK_API wstring byte2wide(const bstring&s);\n\tORK_ORK_API wstring byte2wide(const char*first, const char*last);\n};\nORK_ORK_EXT(string_converter_type&) g_string_converter();\n\n\n#if ORK_UNICODE\n#\tdefine ORK_STR_2_BYTE(ORK_STRING) ork::g_string_converter().wide2byte(ORK_STRING)\n#\tdefine ORK_STR_2_WIDE(ORK_STRING) ORK_STRING\n#\tdefine ORK_BYTE_2_STR(ORK_STRING) ork::g_string_converter().byte2wide(ORK_STRING)\n#\tdefine ORK_WIDE_2_STR(ORK_STRING) ORK_STRING\n#else\n#\tdefine ORK_STR_2_BYTE(ORK_STRING) ORK_STRING\n#\tdefine ORK_STR_2_WIDE(ORK_STRING) ork::g_string_converter().byte2wide(ORK_STRING)\n#\tdefine ORK_BYTE_2_STR(ORK_STRING) ORK_STRING\n#\tdefine ORK_WIDE_2_STR(ORK_STRING) ork::g_string_converter().wide2byte(ORK_STRING)\n#endif\n\n}\/\/namespace ork\n\n#endif\/\/ORK_TEXT_HPP\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2015, Dimitri Diakopoulos All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#if (_MSC_VER)\n #pragma warning (push)\n #pragma warning (disable: 181 111 4267 4996 4244 4701 4702 4133 4100 4127 4206 4312 4505 4365 4005 4013 4334)\n#endif\n\n#ifdef __clang__\n #pragma clang diagnostic push\n #pragma clang diagnostic ignored \"-Wconversion\"\n #pragma clang diagnostic ignored \"-Wshadow\"\n #pragma clang diagnostic ignored \"-Wdeprecated-register\"\n#endif\n\n#ifndef MODPLUG_STATIC\n#define MODPLUG_STATIC\n#endif\n\n#include \"libmodplug\/src\/load_669.cpp\"\n#include \"libmodplug\/src\/load_abc.cpp\"\n#include \"libmodplug\/src\/load_amf.cpp\"\n#include \"libmodplug\/src\/load_ams.cpp\"\n#include \"libmodplug\/src\/load_dbm.cpp\"\n#include \"libmodplug\/src\/load_dmf.cpp\"\n#include \"libmodplug\/src\/load_dsm.cpp\"\n#include \"libmodplug\/src\/load_far.cpp\"\n#include \"libmodplug\/src\/load_it.cpp\"\n#include \"libmodplug\/src\/load_j2b.cpp\"\n#include \"libmodplug\/src\/load_mdl.cpp\"\n#include \"libmodplug\/src\/load_med.cpp\"\n#define none none_alt\n#define MMFILE MMFILE_alt\n#define mmfseek mmfseek_alt\n#define mmftell mmftell_alt\n#define mmreadUBYTES mmreadUBYTES_alt\n#include \"libmodplug\/src\/load_mid.cpp\"\n#include \"libmodplug\/src\/load_mod.cpp\"\n#include \"libmodplug\/src\/load_mt2.cpp\"\n#include \"libmodplug\/src\/load_mtm.cpp\"\n#include \"libmodplug\/src\/load_okt.cpp\"\n#define MMFILE MMFILE_alt2\n#define mmfseek mmfseek_alt2\n#define mmftell mmftell_alt2\n#define mmreadUBYTES mmreadUBYTES_alt2\n#include \"libmodplug\/src\/load_pat.cpp\"\n#include \"libmodplug\/src\/load_psm.cpp\"\n#include \"libmodplug\/src\/load_ptm.cpp\"\n#include \"libmodplug\/src\/load_s3m.cpp\"\n#include \"libmodplug\/src\/load_stm.cpp\"\n#include \"libmodplug\/src\/load_ult.cpp\"\n#include \"libmodplug\/src\/load_umx.cpp\"\n#include \"libmodplug\/src\/load_wav.cpp\"\n#include \"libmodplug\/src\/load_xm.cpp\"\n#include \"libmodplug\/src\/mmcmp.cpp\"\n#include \"libmodplug\/src\/modplug.cpp\"\n#include \"libmodplug\/src\/sndfile.cpp\"\n#include \"libmodplug\/src\/sndmix.cpp\"\n#include \"libmodplug\/src\/fastmix.cpp\"\n#include \"libmodplug\/src\/snd_dsp.cpp\"\n#include \"libmodplug\/src\/snd_flt.cpp\"\n#include \"libmodplug\/src\/snd_fx.cpp\"\n\n#ifdef __clang__\n #pragma clang diagnostic pop\n#endif\n\n#if (_MSC_VER)\n #pragma warning (pop)\n#endif\nupdate for osx\/clang compile\/*\nCopyright (c) 2016, Dimitri Diakopoulos All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#if (_MSC_VER)\n #pragma warning (push)\n #pragma warning (disable: 181 111 4267 4996 4244 4701 4702 4133 4100 4127 4206 4312 4505 4365 4005 4013 4334)\n#endif\n\n#ifdef __clang__\n #pragma clang diagnostic push\n #pragma clang diagnostic ignored \"-Wconversion\"\n #pragma clang diagnostic ignored \"-Wshadow\"\n #pragma clang diagnostic ignored \"-Wdeprecated-register\"\n#endif\n\n#ifndef MODPLUG_STATIC\n#define MODPLUG_STATIC\n#endif\n\n#define HAVE_SINF\n#define HAVE_SETENV\n\n#include \"libmodplug\/src\/load_669.cpp\"\n#include \"libmodplug\/src\/load_abc.cpp\"\n#include \"libmodplug\/src\/load_amf.cpp\"\n#include \"libmodplug\/src\/load_ams.cpp\"\n#include \"libmodplug\/src\/load_dbm.cpp\"\n#include \"libmodplug\/src\/load_dmf.cpp\"\n#include \"libmodplug\/src\/load_dsm.cpp\"\n#include \"libmodplug\/src\/load_far.cpp\"\n#include \"libmodplug\/src\/load_it.cpp\"\n#include \"libmodplug\/src\/load_j2b.cpp\"\n#include \"libmodplug\/src\/load_mdl.cpp\"\n#include \"libmodplug\/src\/load_med.cpp\"\n\n#define none none_alt\n#define MMFILE MMFILE_alt\n#define mmfseek mmfseek_alt\n#define mmftell mmftell_alt\n#define mmreadUBYTES mmreadUBYTES_alt\n#include \"libmodplug\/src\/load_mid.cpp\"\n#include \"libmodplug\/src\/load_mod.cpp\"\n#include \"libmodplug\/src\/load_mt2.cpp\"\n#include \"libmodplug\/src\/load_mtm.cpp\"\n#include \"libmodplug\/src\/load_okt.cpp\"\n#undef MMFILE\n#undef mmfseek\n#undef mmftell\n#undef mmreadUBYTES\n\n#define MMFILE MMFILE_alt2\n#define mmfseek mmfseek_alt2\n#define mmftell mmftell_alt2\n#define mmreadUBYTES mmreadUBYTES_alt2\n#include \"libmodplug\/src\/load_pat.cpp\"\n#include \"libmodplug\/src\/load_psm.cpp\"\n#include \"libmodplug\/src\/load_ptm.cpp\"\n#include \"libmodplug\/src\/load_s3m.cpp\"\n#include \"libmodplug\/src\/load_stm.cpp\"\n#include \"libmodplug\/src\/load_ult.cpp\"\n#include \"libmodplug\/src\/load_umx.cpp\"\n#include \"libmodplug\/src\/load_wav.cpp\"\n#include \"libmodplug\/src\/load_xm.cpp\"\n\n#include \"libmodplug\/src\/mmcmp.cpp\"\n#include \"libmodplug\/src\/modplug.cpp\"\n#include \"libmodplug\/src\/sndfile.cpp\"\n#include \"libmodplug\/src\/sndmix.cpp\"\n#include \"libmodplug\/src\/fastmix.cpp\"\n#include \"libmodplug\/src\/snd_dsp.cpp\"\n#include \"libmodplug\/src\/snd_flt.cpp\"\n#include \"libmodplug\/src\/snd_fx.cpp\"\n\n#ifdef __clang__\n #pragma clang diagnostic pop\n#endif\n\n#if (_MSC_VER)\n #pragma warning (pop)\n#endif\n<|endoftext|>"} {"text":"\/*\n\n This program will add histograms (see note) and Trees from a list of root files and write them\n to a target root file. The target file is newly created and must not be\n identical to one of the source files.\n \n Syntax:\n\n hadd targetfile source1 source2 ...\n or\n hadd -f targetfile source1 source2 ...\n (targetfile is overwritten if it exists)\n\n When -the -f option is specified, one can also specify the compression\n level of the target file. By default the compression level is 1, but\n if \"-f0\" is specified, the target file will not be compressed.\n if \"-f6\" is specified, the compression level 6 will be used.\n \n For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn\n f1 with h1 h2 h3 T1\n f2 with h1 h4 T1 T2\n f3 with h5\n the result of\n hadd -f x.root f1.root f2.root f3.root\n will be a file x.root with h1 h2 h3 h4 h5 T1 T2\n where h1 will be the sum of the 2 histograms in f1 and f2\n T1 will be the merge of the Trees in f1 and f2\n\n The files may contain sub-directories.\n \n if the source files contains histograms and Trees, one can skip \n the Trees with\n hadd -T targetfile source1 source2 ...\n \n Wildcarding and indirect files are also supported\n hadd result.root myfil*.root\n will merge all files in myfil*.root\n hadd result.root file1.root @list.txt file2. root myfil*.root\n will merge file1. root, file2. root, all files in myfil*.root\n and all files in the indirect text file list.txt (\"@\" as the first\n character of the file indicates an indirect file. An indirect file\n is a text file containing a list of other files, including other\n indirect files, one line per file).\n \n If the sources and and target compression levels are identical (default),\n the program uses the TChain::Merge function with option \"fast\", ie\n the merge will be done without unzipping or unstreaming the baskets \n (i.e. direct copy of the raw byte on disk). The \"fast\" mode is typically\n 5 times faster than the mode unzipping and unstreaming the baskets.\n \n NOTE1: By default histograms are added. However if histograms have their bit kIsAverage\n set, the contents are averaged instead of being summed. See TH1::Add.\n \n NOTE2: hadd returns a status code: 0 if OK, -1 otherwise\n \n Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch\n : rewritten from scratch by Rene Brun (30 November 2005)\n to support files with nested directories.\n Toby Burnett implemented the possibility to use indirect files.\n *\/\n\n#include \"RConfig.h\"\n#include \n#include \"TChain.h\"\n#include \"TFile.h\"\n#include \"THashList.h\"\n#include \"TH1.h\"\n#include \"TKey.h\"\n#include \"TObjString.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n#include \"TSystem.h\"\n#include \n\nTList *FileList;\nTFile *Target, *Source;\nBool_t noTrees;\nBool_t fastMethod;\n\nint AddFile(TList* sourcelist, std::string entry, int newcomp) ;\nint MergeRootfile( TDirectory *target, TList *sourcelist, Int_t isdir );\n\n\/\/___________________________________________________________________________\nint main( int argc, char **argv ) \n{\n\n if ( argc < 3 || \"-h\" == string(argv[1]) || \"--help\" == string(argv[1]) ) {\n cout << \"Usage: \" << argv[0] << \" [-f] [-T] targetfile source1 [source2 source3 ...]\" << endl;\n cout << \"This program will add histograms from a list of root files and write them\" << endl;\n cout << \"to a target root file. The target file is newly created and must not \" << endl;\n cout << \"exist, or if -f (\\\"force\\\") is given, must not be one of the source files.\" << endl;\n cout << \"Supply at least two source files for this to make sense... ;-)\" << endl;\n cout << \"If the first argument is -T, Trees are not merged\" <Load(\"libTreePlayer\");\n \n int ffirst = 2;\n if (force) ffirst++;\n if (noTrees) ffirst++;\n\n cout << \"Target file: \" << argv[ffirst-1] << endl;\n \n Target = TFile::Open( argv[ffirst-1], (force?\"RECREATE\":\"CREATE\") );\n if (!Target || Target->IsZombie()) {\n cerr << \"Error opening target file (does \" << argv[ffirst-1] << \" exist?).\" << endl;\n cerr << \"Pass \\\"-f\\\" argument to force re-creation of output file.\" << endl;\n exit(1);\n }\n Target->SetCompressionLevel(newcomp);\n \n \/\/ by default hadd can merge Trees in a file that can go up to 100 Gbytes\n Long64_t maxsize = 100000000; \/\/100GB\n maxsize *= 100; \/\/to bypass some compiler limitations with big constants\n TTree::SetMaxTreeSize(maxsize);\n \n fastMethod = kTRUE;\n for ( int i = ffirst; i < argc; i++ ) {\n if( AddFile(FileList, argv[i], newcomp) !=0 ) return 1;\n }\n if (!fastMethod) {\n cout <<\"Sources and Target have different compression levels\"<Add(source);\n if (newcomp != source->GetCompressionLevel()) fastMethod = kFALSE;\n return 0;\n}\n\n\n\/\/___________________________________________________________________________\nint MergeRootfile( TDirectory *target, TList *sourcelist, Int_t isdir ) \n{\n \/\/ Merge all objects in a directory\n int status = 0;\n cout << \"Target path: \" << target->GetPath() << endl;\n TString path( (char*)strstr( target->GetPath(), \":\" ) );\n path.Remove( 0, 2 );\n\n TDirectory *first_source = (TDirectory*)sourcelist->First();\n Int_t nguess = sourcelist->GetSize()+1000;\n THashList allNames(nguess);\n ((THashList*)target->GetList())->Rehash(nguess);\n ((THashList*)target->GetListOfKeys())->Rehash(nguess);\n TList listH;\n TString listHargs;\n listHargs.Form(\"((TCollection*)0x%lx)\",&listH);\n while(first_source) {\n TDirectory *current_sourcedir = first_source->GetDirectory(path);\n if (!current_sourcedir) {\n first_source = (TDirectory*)sourcelist->After(first_source);\n continue;\n }\n\n \/\/ loop over all keys in this directory\n TChain *globChain = 0;\n TIter nextkey( current_sourcedir->GetListOfKeys() );\n TKey *key, *oldkey=0;\n \/\/gain time, do not add the objects in the list in memory\n TH1::AddDirectory(kFALSE);\n \n while ( (key = (TKey*)nextkey())) {\n if (current_sourcedir == target) break;\n \/\/keep only the highest cycle number for each key\n if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;\n if (!strcmp(key->GetClassName(),\"TProcessID\")) {key->ReadObj(); continue;}\n if (allNames.FindObject(key->GetName())) continue;\n TClass *cl = TClass::GetClass(key->GetClassName());\n if (!cl || !cl->InheritsFrom(TObject::Class())) {\n cout << \"Cannot merge object type, name: \" \n << key->GetName() << \" title: \" << key->GetTitle() << endl;\n continue;\n }\n allNames.Add(new TObjString(key->GetName()));\n \/\/ read object from first source file\n \/\/current_sourcedir->cd();\n TObject *obj = key->ReadObj();\n \/\/printf(\"keyname=%s, obj=%x\\n\",key->GetName(),obj);\n\n if ( obj->IsA()->InheritsFrom( \"TTree\" ) ) {\n \n \/\/ loop over all source files create a chain of Trees \"globChain\"\n if (!noTrees) {\n TString obj_name;\n if (path.Length()) {\n obj_name = path + \"\/\" + obj->GetName();\n } else {\n obj_name = obj->GetName();\n }\n globChain = new TChain(obj_name);\n globChain->Add(first_source->GetName());\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) { \t \n \/\/do not add to the list a file that does not contain this Tree\n TFile *curf = TFile::Open(nextsource->GetName());\n if (curf) {\n Bool_t mustAdd = kFALSE;\n if (curf->FindKey(obj_name)) {\n mustAdd = kTRUE;\n } else {\n \/\/we could be more clever here. No need to import the object\n \/\/we are missing a function in TDirectory\n TObject *aobj = curf->Get(obj_name);\n if (aobj) { mustAdd = kTRUE; delete aobj;}\n }\n if (mustAdd) {\n globChain->Add(nextsource->GetName());\n }\n }\n delete curf;\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n }\n } else if ( obj->IsA()->InheritsFrom( \"TDirectory\" ) ) {\n \/\/ it's a subdirectory\n\n cout << \"Found subdirectory \" << obj->GetName() << endl;\n \/\/ create a new subdir of same name and title in the target file\n target->cd();\n TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );\n\n \/\/ newdir is now the starting point of another round of merging\n \/\/ newdir still knows its depth within the target file via\n \/\/ GetPath(), so we can still figure out where we are in the recursion\n status = MergeRootfile( newdir, sourcelist,1);\n if (status) return status;\n\n } else if ( obj->InheritsFrom(TObject::Class())\n && obj->IsA()->GetMethodWithPrototype(\"Merge\", \"TCollection*\") ) {\n \/\/ object implements Merge(TCollection*)\n\n \/\/ loop over all source files and merge same-name object\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) {\n \/\/ make sure we are at the correct directory level by cd'ing to path\n TDirectory *ndir = nextsource->GetDirectory(path);\n if (ndir) {\n ndir->cd();\n TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(key->GetName());\n if (key2) {\n TObject *hobj = key2->ReadObj();\n hobj->ResetBit(kMustCleanup);\n listH.Add(hobj);\n Int_t error = 0;\n obj->Execute(\"Merge\", listHargs.Data(), &error);\n if (error) {\n cerr << \"Error calling Merge() on \" << obj->GetName()\n << \" with the corresponding object in \" << nextsource->GetName() << endl;\n }\n listH.Delete();\n }\n }\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n } else {\n \/\/ object is of no type that we can merge \n cout << \"Cannot merge object type, name: \" \n << obj->GetName() << \" title: \" << obj->GetTitle() << endl;\n\n \/\/ loop over all source files and write similar objects directly to the output file\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) {\n \/\/ make sure we are at the correct directory level by cd'ing to path\n TDirectory *ndir = nextsource->GetDirectory(path);\n if (ndir) {\n ndir->cd();\n TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(key->GetName());\n if (key2) {\n TObject *nobj = key2->ReadObj();\n nobj->ResetBit(kMustCleanup);\n int nbytes1 = target->WriteTObject(nobj, key2->GetName(), \"SingleKey\" );\n if (nbytes1 <= 0) status = -1;\n delete nobj;\n }\n }\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n }\n\n \/\/ now write the merged histogram (which is \"in\" obj) to the target file\n \/\/ note that this will just store obj in the current directory level,\n \/\/ which is not persistent until the complete directory itself is stored\n \/\/ by \"target->Write()\" below\n if ( obj ) {\n target->cd();\n \n \/\/!!if the object is a tree, it is stored in globChain...\n if(obj->IsA()->InheritsFrom( \"TDirectory\" )) {\n \/\/printf(\"cas d'une directory\\n\");\n } else if(obj->IsA()->InheritsFrom( \"TTree\" )) {\n if (!noTrees) {\n globChain->ls();\n if (fastMethod) globChain->Merge(target->GetFile(),0,\"keep fast\");\n else globChain->Merge(target->GetFile(),0,\"keep\");\n delete globChain;\n }\n } else {\n int nbytes2 = obj->Write( key->GetName(), TObject::kSingleKey );\n if (nbytes2 <= 0) status = -1;\n }\n }\n oldkey = key;\n delete obj;\n } \/\/ while ( ( TKey *key = (TKey*)nextkey() ) )\n first_source = (TDirectory*)sourcelist->After(first_source);\n }\n \/\/ save modifications to target file\n target->SaveSelf(kTRUE);\n if (!isdir) sourcelist->Remove(sourcelist->First());\n return status;\n}\nRemove the argument isdir from the function MergeRootFile. Do not remove the first file in the list when returning from MergeRootFile.\/*\n\n This program will add histograms (see note) and Trees from a list of root files and write them\n to a target root file. The target file is newly created and must not be\n identical to one of the source files.\n \n Syntax:\n\n hadd targetfile source1 source2 ...\n or\n hadd -f targetfile source1 source2 ...\n (targetfile is overwritten if it exists)\n\n When -the -f option is specified, one can also specify the compression\n level of the target file. By default the compression level is 1, but\n if \"-f0\" is specified, the target file will not be compressed.\n if \"-f6\" is specified, the compression level 6 will be used.\n \n For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn\n f1 with h1 h2 h3 T1\n f2 with h1 h4 T1 T2\n f3 with h5\n the result of\n hadd -f x.root f1.root f2.root f3.root\n will be a file x.root with h1 h2 h3 h4 h5 T1 T2\n where h1 will be the sum of the 2 histograms in f1 and f2\n T1 will be the merge of the Trees in f1 and f2\n\n The files may contain sub-directories.\n \n if the source files contains histograms and Trees, one can skip \n the Trees with\n hadd -T targetfile source1 source2 ...\n \n Wildcarding and indirect files are also supported\n hadd result.root myfil*.root\n will merge all files in myfil*.root\n hadd result.root file1.root @list.txt file2. root myfil*.root\n will merge file1. root, file2. root, all files in myfil*.root\n and all files in the indirect text file list.txt (\"@\" as the first\n character of the file indicates an indirect file. An indirect file\n is a text file containing a list of other files, including other\n indirect files, one line per file).\n \n If the sources and and target compression levels are identical (default),\n the program uses the TChain::Merge function with option \"fast\", ie\n the merge will be done without unzipping or unstreaming the baskets \n (i.e. direct copy of the raw byte on disk). The \"fast\" mode is typically\n 5 times faster than the mode unzipping and unstreaming the baskets.\n \n NOTE1: By default histograms are added. However if histograms have their bit kIsAverage\n set, the contents are averaged instead of being summed. See TH1::Add.\n \n NOTE2: hadd returns a status code: 0 if OK, -1 otherwise\n \n Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch\n : rewritten from scratch by Rene Brun (30 November 2005)\n to support files with nested directories.\n Toby Burnett implemented the possibility to use indirect files.\n *\/\n\n#include \"RConfig.h\"\n#include \n#include \"TChain.h\"\n#include \"TFile.h\"\n#include \"THashList.h\"\n#include \"TH1.h\"\n#include \"TKey.h\"\n#include \"TObjString.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n#include \"TSystem.h\"\n#include \n\nTList *FileList;\nTFile *Target, *Source;\nBool_t noTrees;\nBool_t fastMethod;\n\nint AddFile(TList* sourcelist, std::string entry, int newcomp) ;\nint MergeRootfile( TDirectory *target, TList *sourcelist);\n\n\/\/___________________________________________________________________________\nint main( int argc, char **argv ) \n{\n\n if ( argc < 3 || \"-h\" == string(argv[1]) || \"--help\" == string(argv[1]) ) {\n cout << \"Usage: \" << argv[0] << \" [-f] [-T] targetfile source1 [source2 source3 ...]\" << endl;\n cout << \"This program will add histograms from a list of root files and write them\" << endl;\n cout << \"to a target root file. The target file is newly created and must not \" << endl;\n cout << \"exist, or if -f (\\\"force\\\") is given, must not be one of the source files.\" << endl;\n cout << \"Supply at least two source files for this to make sense... ;-)\" << endl;\n cout << \"If the first argument is -T, Trees are not merged\" <Load(\"libTreePlayer\");\n \n int ffirst = 2;\n if (force) ffirst++;\n if (noTrees) ffirst++;\n\n cout << \"Target file: \" << argv[ffirst-1] << endl;\n \n Target = TFile::Open( argv[ffirst-1], (force?\"RECREATE\":\"CREATE\") );\n if (!Target || Target->IsZombie()) {\n cerr << \"Error opening target file (does \" << argv[ffirst-1] << \" exist?).\" << endl;\n cerr << \"Pass \\\"-f\\\" argument to force re-creation of output file.\" << endl;\n exit(1);\n }\n Target->SetCompressionLevel(newcomp);\n \n \/\/ by default hadd can merge Trees in a file that can go up to 100 Gbytes\n Long64_t maxsize = 100000000; \/\/100GB\n maxsize *= 100; \/\/to bypass some compiler limitations with big constants\n TTree::SetMaxTreeSize(maxsize);\n \n fastMethod = kTRUE;\n for ( int i = ffirst; i < argc; i++ ) {\n if( AddFile(FileList, argv[i], newcomp) !=0 ) return 1;\n }\n if (!fastMethod) {\n cout <<\"Sources and Target have different compression levels\"<Add(source);\n if (newcomp != source->GetCompressionLevel()) fastMethod = kFALSE;\n return 0;\n}\n\n\n\/\/___________________________________________________________________________\nint MergeRootfile( TDirectory *target, TList *sourcelist) \n{\n \/\/ Merge all objects in a directory\n int status = 0;\n cout << \"Target path: \" << target->GetPath() << endl;\n TString path( (char*)strstr( target->GetPath(), \":\" ) );\n path.Remove( 0, 2 );\n\n TDirectory *first_source = (TDirectory*)sourcelist->First();\n Int_t nguess = sourcelist->GetSize()+1000;\n THashList allNames(nguess);\n ((THashList*)target->GetList())->Rehash(nguess);\n ((THashList*)target->GetListOfKeys())->Rehash(nguess);\n TList listH;\n TString listHargs;\n listHargs.Form(\"((TCollection*)0x%lx)\",&listH);\n while(first_source) {\n TDirectory *current_sourcedir = first_source->GetDirectory(path);\n if (!current_sourcedir) {\n first_source = (TDirectory*)sourcelist->After(first_source);\n continue;\n }\n\n \/\/ loop over all keys in this directory\n TChain *globChain = 0;\n TIter nextkey( current_sourcedir->GetListOfKeys() );\n TKey *key, *oldkey=0;\n \/\/gain time, do not add the objects in the list in memory\n TH1::AddDirectory(kFALSE);\n \n while ( (key = (TKey*)nextkey())) {\n if (current_sourcedir == target) break;\n \/\/keep only the highest cycle number for each key\n if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;\n if (!strcmp(key->GetClassName(),\"TProcessID\")) {key->ReadObj(); continue;}\n if (allNames.FindObject(key->GetName())) continue;\n TClass *cl = TClass::GetClass(key->GetClassName());\n if (!cl || !cl->InheritsFrom(TObject::Class())) {\n cout << \"Cannot merge object type, name: \" \n << key->GetName() << \" title: \" << key->GetTitle() << endl;\n continue;\n }\n allNames.Add(new TObjString(key->GetName()));\n \/\/ read object from first source file\n \/\/current_sourcedir->cd();\n TObject *obj = key->ReadObj();\n \/\/printf(\"keyname=%s, obj=%x\\n\",key->GetName(),obj);\n\n if ( obj->IsA()->InheritsFrom( \"TTree\" ) ) {\n \n \/\/ loop over all source files create a chain of Trees \"globChain\"\n if (!noTrees) {\n TString obj_name;\n if (path.Length()) {\n obj_name = path + \"\/\" + obj->GetName();\n } else {\n obj_name = obj->GetName();\n }\n globChain = new TChain(obj_name);\n globChain->Add(first_source->GetName());\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) { \t \n \/\/do not add to the list a file that does not contain this Tree\n TFile *curf = TFile::Open(nextsource->GetName());\n if (curf) {\n Bool_t mustAdd = kFALSE;\n if (curf->FindKey(obj_name)) {\n mustAdd = kTRUE;\n } else {\n \/\/we could be more clever here. No need to import the object\n \/\/we are missing a function in TDirectory\n TObject *aobj = curf->Get(obj_name);\n if (aobj) { mustAdd = kTRUE; delete aobj;}\n }\n if (mustAdd) {\n globChain->Add(nextsource->GetName());\n }\n }\n delete curf;\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n }\n } else if ( obj->IsA()->InheritsFrom( \"TDirectory\" ) ) {\n \/\/ it's a subdirectory\n\n cout << \"Found subdirectory \" << obj->GetName() << endl;\n \/\/ create a new subdir of same name and title in the target file\n target->cd();\n TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );\n\n \/\/ newdir is now the starting point of another round of merging\n \/\/ newdir still knows its depth within the target file via\n \/\/ GetPath(), so we can still figure out where we are in the recursion\n status = MergeRootfile( newdir, sourcelist);\n if (status) return status;\n\n } else if ( obj->InheritsFrom(TObject::Class())\n && obj->IsA()->GetMethodWithPrototype(\"Merge\", \"TCollection*\") ) {\n \/\/ object implements Merge(TCollection*)\n\n \/\/ loop over all source files and merge same-name object\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) {\n \/\/ make sure we are at the correct directory level by cd'ing to path\n TDirectory *ndir = nextsource->GetDirectory(path);\n if (ndir) {\n ndir->cd();\n TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(key->GetName());\n if (key2) {\n TObject *hobj = key2->ReadObj();\n hobj->ResetBit(kMustCleanup);\n listH.Add(hobj);\n Int_t error = 0;\n obj->Execute(\"Merge\", listHargs.Data(), &error);\n if (error) {\n cerr << \"Error calling Merge() on \" << obj->GetName()\n << \" with the corresponding object in \" << nextsource->GetName() << endl;\n }\n listH.Delete();\n }\n }\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n } else {\n \/\/ object is of no type that we can merge \n cout << \"Cannot merge object type, name: \" \n << obj->GetName() << \" title: \" << obj->GetTitle() << endl;\n\n \/\/ loop over all source files and write similar objects directly to the output file\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) {\n \/\/ make sure we are at the correct directory level by cd'ing to path\n TDirectory *ndir = nextsource->GetDirectory(path);\n if (ndir) {\n ndir->cd();\n TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(key->GetName());\n if (key2) {\n TObject *nobj = key2->ReadObj();\n nobj->ResetBit(kMustCleanup);\n int nbytes1 = target->WriteTObject(nobj, key2->GetName(), \"SingleKey\" );\n if (nbytes1 <= 0) status = -1;\n delete nobj;\n }\n }\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n }\n\n \/\/ now write the merged histogram (which is \"in\" obj) to the target file\n \/\/ note that this will just store obj in the current directory level,\n \/\/ which is not persistent until the complete directory itself is stored\n \/\/ by \"target->Write()\" below\n if ( obj ) {\n target->cd();\n \n \/\/!!if the object is a tree, it is stored in globChain...\n if(obj->IsA()->InheritsFrom( \"TDirectory\" )) {\n \/\/printf(\"cas d'une directory\\n\");\n } else if(obj->IsA()->InheritsFrom( \"TTree\" )) {\n if (!noTrees) {\n globChain->ls();\n if (fastMethod) globChain->Merge(target->GetFile(),0,\"keep fast\");\n else globChain->Merge(target->GetFile(),0,\"keep\");\n delete globChain;\n }\n } else {\n int nbytes2 = obj->Write( key->GetName(), TObject::kSingleKey );\n if (nbytes2 <= 0) status = -1;\n }\n }\n oldkey = key;\n delete obj;\n } \/\/ while ( ( TKey *key = (TKey*)nextkey() ) )\n first_source = (TDirectory*)sourcelist->After(first_source);\n }\n \/\/ save modifications to target file\n target->SaveSelf(kTRUE);\n return status;\n}\n<|endoftext|>"} {"text":"\/\/ LAF OS Library\n\/\/ Copyright (C) 2020 Igara Studio S.A.\n\/\/ Copyright (C) 2016-2017 David Capello\n\/\/\n\/\/ This file is released under the terms of the MIT license.\n\/\/ Read LICENSE.txt for more information.\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"os\/win\/wintab.h\"\n\n#include \"base\/convert_to.h\"\n#include \"base\/debug.h\"\n#include \"base\/fs.h\"\n#include \"base\/log.h\"\n#include \"base\/sha1.h\"\n#include \"base\/string.h\"\n#include \"base\/version.h\"\n\n#include \n#include \n\n#define WINTAB_TRACE(...)\n\nnamespace os {\n\nnamespace {\n\ntypedef UINT (API* WTInfoW_Func)(UINT, UINT, LPVOID);\ntypedef HCTX (API* WTOpenW_Func)(HWND, LPLOGCONTEXTW, BOOL);\ntypedef BOOL (API* WTClose_Func)(HCTX);\ntypedef int (API* WTPacketsGet_Func)(HCTX, int, LPVOID);\ntypedef BOOL (API* WTPacket_Func)(HCTX, UINT, LPVOID);\ntypedef BOOL (API* WTOverlap_Func)(HCTX, BOOL);\ntypedef int (API* WTQueueSizeGet_Func)(HCTX);\ntypedef BOOL (API* WTQueueSizeSet_Func)(HCTX, int);\n\nWTInfoW_Func WTInfo;\nWTOpenW_Func WTOpen;\nWTClose_Func WTClose;\nWTPacketsGet_Func WTPacketsGet;\nWTPacket_Func WTPacket;\nWTOverlap_Func WTOverlap;\nWTQueueSizeGet_Func WTQueueSizeGet;\nWTQueueSizeSet_Func WTQueueSizeSet;\n\n} \/\/ anonymous namespace\n\nWintabAPI::WintabAPI()\n : m_wintabLib(nullptr)\n{\n}\n\nWintabAPI::~WintabAPI()\n{\n if (!m_wintabLib)\n return;\n\n base::unload_dll(m_wintabLib);\n m_wintabLib = nullptr;\n}\n\nHCTX WintabAPI::open(HWND hwnd, bool moveMouse)\n{\n if (!m_wintabLib && !loadWintab())\n return nullptr;\n\n \/\/ Log Wintab ID\n {\n UINT nchars = WTInfo(WTI_INTERFACE, IFC_WINTABID, nullptr);\n if (nchars > 0 && nchars < 1024) {\n \/\/ Some buggy wintab implementations may not report the right\n \/\/ string size in the WTInfo call above (eg.: the Genius EasyPen\n \/\/ i405X wintab). When this happens, the WTInfo call for getting\n \/\/ the tablet id will get only a part of the string, therefore\n \/\/ without the null terminating character. This will lead to a\n \/\/ buffer overrun and may just crash instantly, or cause a heap\n \/\/ corruption that will lead to a crash latter. A quick\n \/\/ workaround to this kind of wintab misinformation is to\n \/\/ oversize the buffer to guarantee that for the most common\n \/\/ string lenghts it will be enough.\n std::vector buf(std::max(128, nchars+1), 0);\n WTInfo(WTI_INTERFACE, IFC_WINTABID, &buf[0]);\n LOG(\"PEN: Wintab ID \\\"%s\\\"\\n\", base::to_utf8(&buf[0]).c_str());\n }\n }\n\n \/\/ Log Wintab version for debugging purposes\n {\n WORD specVer = 0;\n WORD implVer = 0;\n UINT options = 0;\n WTInfo(WTI_INTERFACE, IFC_SPECVERSION, &specVer);\n WTInfo(WTI_INTERFACE, IFC_IMPLVERSION, &implVer);\n WTInfo(WTI_INTERFACE, IFC_CTXOPTIONS, &options);\n LOG(\"PEN: Wintab spec v%d.%d impl v%d.%d options 0x%x\\n\",\n (specVer & 0xff00) >> 8, (specVer & 0xff),\n (implVer & 0xff00) >> 8, (implVer & 0xff), options);\n }\n\n LOGCONTEXTW logctx;\n memset(&logctx, 0, sizeof(LOGCONTEXTW));\n UINT infoRes = WTInfo(WTI_DEFSYSCTX, 0, &logctx);\n\n if (moveMouse) {\n \/\/ Move system cursor position, you can use packets to get\n \/\/ pressure information and cursor type, and pointer movement from\n \/\/ mouse messages.\n logctx.lcOptions |= CXO_SYSTEM;\n }\n else {\n \/\/ In this case you can process packets directly converting then\n \/\/ to events (system mouse movement messages will not be\n \/\/ generated).\n logctx.lcOptions &= ~CXO_SYSTEM;\n }\n\n#if 1 \/\/ We shouldn't bypass WTOpen() if the return value from\n \/\/ WTInfo() isn't the expected one, WTOpen() should just fail\n \/\/ anyway.\n if (infoRes != sizeof(LOGCONTEXTW)) {\n LOG(ERROR,\n \"PEN: Invalid size of WTInfo:\\n\"\n \" Expected context size: %d\\n\"\n \" Actual context size: %d\\n\",\n sizeof(LOGCONTEXTW), infoRes);\n }\n#endif\n\n LOG(\"PEN: Context options=%d pktRate=%d in=%d,%d,%d,%d out=%d,%d,%d,%d sys=%d,%d,%d,%d\\n\",\n logctx.lcOptions, logctx.lcPktRate,\n logctx.lcInOrgX, logctx.lcInOrgY, logctx.lcInExtX, logctx.lcInExtY,\n logctx.lcOutOrgX, logctx.lcOutOrgY, logctx.lcOutExtX, logctx.lcOutExtY,\n logctx.lcSysOrgX, logctx.lcSysOrgY, logctx.lcSysExtX, logctx.lcSysExtY);\n\n logctx.lcOptions |=\n CXO_MESSAGES |\n CXO_CSRMESSAGES;\n logctx.lcPktData = PACKETDATA;\n logctx.lcPktMode = PACKETMODE;\n logctx.lcMoveMask = PACKETDATA;\n m_outBounds = gfx::Rect(logctx.lcOutOrgX, logctx.lcOutOrgY, logctx.lcOutExtX, logctx.lcOutExtY);\n\n AXIS pressure;\n infoRes = WTInfo(WTI_DEVICES, DVC_NPRESSURE, &pressure);\n if (infoRes >= sizeof(AXIS)) {\n m_minPressure = pressure.axMin;\n m_maxPressure = pressure.axMax;\n LOG(\"PEN: Min\/max pressure values [%d,%d]\\n\", pressure.axMin, pressure.axMax);\n }\n else {\n m_minPressure = 0;\n m_maxPressure = 0;\n LOG(\"PEN: pressure info size %d (expected %d)\", infoRes, sizeof(AXIS));\n }\n\n LOG(\"PEN: Opening context, options 0x%x\\n\", logctx.lcOptions);\n HCTX ctx = WTOpen(hwnd, &logctx, TRUE);\n if (!ctx) {\n LOG(\"PEN: Error attaching pen to display\\n\");\n return nullptr;\n }\n\n \/\/ Make the queue bigger as recommended by Wacom docs:\n \/\/\n \/\/ \"To prevent your queue from overflowing, increase the size of\n \/\/ your context's queue with the WTQueueSizeSet() function to a\n \/\/ value between 32 and 128. Memory for packet queues is a limited\n \/\/ resource, so be sure check that your call to WTQueueSizeSet()\n \/\/ succeeds. If WTQueueSizeSet() fails, request a smaller queue\n \/\/ size.\"\n \/\/\n \/\/ https:\/\/developer-docs.wacom.com\/display\/DevDocs\/Window+Developers+FAQ\n int q = WTQueueSizeGet(ctx);\n LOG(\"PEN: Original queue size=%d\\n\", q);\n if (q < 128) {\n for (int r=128; r>=q; r-=8) {\n if (WTQueueSizeSet(ctx, r))\n break;\n }\n }\n m_queueSize = q = WTQueueSizeGet(ctx);\n LOG(\"PEN: New queue size=%d\\n\", q);\n\n LOG(\"PEN: Pen attached to display, new context %p\\n\", ctx);\n return ctx;\n}\n\nvoid WintabAPI::close(HCTX ctx)\n{\n LOG(\"PEN: Closing context %p\\n\", ctx);\n if (ctx) {\n ASSERT(m_wintabLib);\n LOG(\"PEN: Pen detached from window\\n\");\n WTClose(ctx);\n }\n}\n\nvoid WintabAPI::overlap(HCTX ctx, BOOL state)\n{\n WTOverlap(ctx, state);\n}\n\nbool WintabAPI::packet(HCTX ctx, UINT serial, LPVOID packet)\n{\n return (WTPacket(ctx, serial, packet) ? true: false);\n}\n\nint WintabAPI::packets(HCTX ctx, int maxPackets, LPVOID packets)\n{\n return WTPacketsGet(ctx, maxPackets, packets);\n}\n\nvoid WintabAPI::mapCursorButton(const int cursor,\n const int logicalButton,\n const int relativeButton,\n Event::Type& evType,\n Event::MouseButton& mouseButton)\n{\n mouseButton = Event::NoneButton;\n switch (relativeButton) {\n case TBN_DOWN:\n evType = Event::MouseDown;\n break;\n case TBN_UP:\n evType = Event::MouseUp;\n break;\n case TBN_NONE:\n default:\n evType = Event::MouseMove;\n break;\n }\n\n \/\/ Invalid logical button\n if (logicalButton < 0 || logicalButton >= 32) {\n WINTAB_TRACE(\"PEN: INVALID LOGICAL BUTTON\\n\");\n return;\n }\n\n \/\/ Get \"logical button\" -> \"button action code\" mapping so we can\n \/\/ know for what specific mouse button we should generate an event\n \/\/ (or maybe if it's a double-click).\n BYTE map[32];\n WTInfo(WTI_CURSORS + cursor, CSR_SYSBTNMAP, &map);\n\n switch (map[logicalButton]) {\n\n case SBN_LDBLCLICK:\n evType = Event::MouseDoubleClick;\n case SBN_LCLICK:\n case SBN_LDRAG:\n mouseButton = Event::LeftButton;\n break;\n\n case SBN_RDBLCLICK:\n evType = Event::MouseDoubleClick;\n case SBN_RCLICK:\n case SBN_RDRAG:\n mouseButton = Event::RightButton;\n break;\n\n case SBN_MDBLCLICK:\n evType = Event::MouseDoubleClick;\n case SBN_MCLICK:\n case SBN_MDRAG:\n mouseButton = Event::MiddleButton;\n break;\n }\n\n WINTAB_TRACE(\n \" PEN: Button map logicalButton=%d action=%d -> evType=%s mouseButton=%d\\n\",\n logicalButton,\n map[logicalButton],\n (evType == Event::None ? \"-\":\n evType == Event::MouseMove ? \"move\":\n evType == Event::MouseDown ? \"DOWN\":\n evType == Event::MouseUp ? \"UP\":\n evType == Event::MouseDoubleClick ? \"DOUBLE-CLICK\": \"unknown\"),\n (int)mouseButton);\n}\n\nbool WintabAPI::loadWintab()\n{\n ASSERT(!m_wintabLib);\n\n m_wintabLib = base::load_dll(\"wintab32.dll\");\n if (!m_wintabLib) {\n LOG(ERROR, \"PEN: wintab32.dll is not present\\n\");\n return false;\n }\n\n if (!checkDll()) {\n base::unload_dll(m_wintabLib);\n m_wintabLib = nullptr;\n return false;\n }\n\n WTInfo = base::get_dll_proc(m_wintabLib, \"WTInfoW\");\n WTOpen = base::get_dll_proc(m_wintabLib, \"WTOpenW\");\n WTClose = base::get_dll_proc(m_wintabLib, \"WTClose\");\n WTPacketsGet = base::get_dll_proc(m_wintabLib, \"WTPacketsGet\");\n WTPacket = base::get_dll_proc(m_wintabLib, \"WTPacket\");\n WTOverlap = base::get_dll_proc(m_wintabLib, \"WTOverlap\");\n WTQueueSizeGet = base::get_dll_proc(m_wintabLib, \"WTQueueSizeGet\");\n WTQueueSizeSet = base::get_dll_proc(m_wintabLib, \"WTQueueSizeSet\");\n if (!WTInfo || !WTOpen || !WTClose || !WTPacket ||\n !WTQueueSizeGet || !WTQueueSizeSet) {\n LOG(ERROR, \"PEN: wintab32.dll does not contain all required functions\\n\");\n return false;\n }\n\n LOG(\"PEN: Wintab library loaded\\n\");\n return true;\n}\n\nbool WintabAPI::checkDll()\n{\n ASSERT(m_wintabLib);\n\n std::string fn = base::get_dll_filename(m_wintabLib);\n if (!base::is_file(fn))\n return false;\n\n std::string checksum = base::convert_to(base::Sha1::calculateFromFile(fn));\n base::Version ver = base::get_file_version(fn);\n LOG(\"PEN: <%s> v%s, sha1 <%s>\\n\", fn.c_str(), ver.str().c_str(), checksum.c_str());\n\n \/\/ Ugly hack to bypass the buggy WALTOP International Corp .dll that\n \/\/ hangs Aseprite completely when we call its WTInfo function.\n if (checksum == \"a3ba0d9c0f5d8b9f4070981b243a80579f8be105\")\n return false;\n\n return true;\n}\n\n} \/\/ namespace os\n[win] Don't ask for Wintab information if we are not logging info\/\/ LAF OS Library\n\/\/ Copyright (C) 2020 Igara Studio S.A.\n\/\/ Copyright (C) 2016-2017 David Capello\n\/\/\n\/\/ This file is released under the terms of the MIT license.\n\/\/ Read LICENSE.txt for more information.\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"os\/win\/wintab.h\"\n\n#include \"base\/convert_to.h\"\n#include \"base\/debug.h\"\n#include \"base\/fs.h\"\n#include \"base\/log.h\"\n#include \"base\/sha1.h\"\n#include \"base\/string.h\"\n#include \"base\/version.h\"\n\n#include \n#include \n\n#define WINTAB_TRACE(...)\n\nnamespace os {\n\nnamespace {\n\ntypedef UINT (API* WTInfoW_Func)(UINT, UINT, LPVOID);\ntypedef HCTX (API* WTOpenW_Func)(HWND, LPLOGCONTEXTW, BOOL);\ntypedef BOOL (API* WTClose_Func)(HCTX);\ntypedef int (API* WTPacketsGet_Func)(HCTX, int, LPVOID);\ntypedef BOOL (API* WTPacket_Func)(HCTX, UINT, LPVOID);\ntypedef BOOL (API* WTOverlap_Func)(HCTX, BOOL);\ntypedef int (API* WTQueueSizeGet_Func)(HCTX);\ntypedef BOOL (API* WTQueueSizeSet_Func)(HCTX, int);\n\nWTInfoW_Func WTInfo;\nWTOpenW_Func WTOpen;\nWTClose_Func WTClose;\nWTPacketsGet_Func WTPacketsGet;\nWTPacket_Func WTPacket;\nWTOverlap_Func WTOverlap;\nWTQueueSizeGet_Func WTQueueSizeGet;\nWTQueueSizeSet_Func WTQueueSizeSet;\n\n} \/\/ anonymous namespace\n\nWintabAPI::WintabAPI()\n : m_wintabLib(nullptr)\n{\n}\n\nWintabAPI::~WintabAPI()\n{\n if (!m_wintabLib)\n return;\n\n base::unload_dll(m_wintabLib);\n m_wintabLib = nullptr;\n}\n\nHCTX WintabAPI::open(HWND hwnd, bool moveMouse)\n{\n if (!m_wintabLib && !loadWintab())\n return nullptr;\n\n \/\/ Only on INFO or VERBOSE modes for debugging purposes\n if (base::get_log_level() >= INFO) {\n \/\/ Log Wintab ID\n UINT nchars = WTInfo(WTI_INTERFACE, IFC_WINTABID, nullptr);\n if (nchars > 0 && nchars < 1024) {\n \/\/ Some buggy wintab implementations may not report the right\n \/\/ string size in the WTInfo call above (eg.: the Genius EasyPen\n \/\/ i405X wintab). When this happens, the WTInfo call for getting\n \/\/ the tablet id will get only a part of the string, therefore\n \/\/ without the null terminating character. This will lead to a\n \/\/ buffer overrun and may just crash instantly, or cause a heap\n \/\/ corruption that will lead to a crash latter. A quick\n \/\/ workaround to this kind of wintab misinformation is to\n \/\/ oversize the buffer to guarantee that for the most common\n \/\/ string lenghts it will be enough.\n std::vector buf(std::max(128, nchars+1), 0);\n WTInfo(WTI_INTERFACE, IFC_WINTABID, &buf[0]);\n LOG(\"PEN: Wintab ID \\\"%s\\\"\\n\", base::to_utf8(&buf[0]).c_str());\n }\n\n \/\/ Log Wintab version\n WORD specVer = 0;\n WORD implVer = 0;\n UINT options = 0;\n WTInfo(WTI_INTERFACE, IFC_SPECVERSION, &specVer);\n WTInfo(WTI_INTERFACE, IFC_IMPLVERSION, &implVer);\n WTInfo(WTI_INTERFACE, IFC_CTXOPTIONS, &options);\n LOG(\"PEN: Wintab spec v%d.%d impl v%d.%d options 0x%x\\n\",\n (specVer & 0xff00) >> 8, (specVer & 0xff),\n (implVer & 0xff00) >> 8, (implVer & 0xff), options);\n }\n\n LOGCONTEXTW logctx;\n memset(&logctx, 0, sizeof(LOGCONTEXTW));\n UINT infoRes = WTInfo(WTI_DEFSYSCTX, 0, &logctx);\n\n if (moveMouse) {\n \/\/ Move system cursor position, you can use packets to get\n \/\/ pressure information and cursor type, and pointer movement from\n \/\/ mouse messages.\n logctx.lcOptions |= CXO_SYSTEM;\n }\n else {\n \/\/ In this case you can process packets directly converting then\n \/\/ to events (system mouse movement messages will not be\n \/\/ generated).\n logctx.lcOptions &= ~CXO_SYSTEM;\n }\n\n#if 1 \/\/ We shouldn't bypass WTOpen() if the return value from\n \/\/ WTInfo() isn't the expected one, WTOpen() should just fail\n \/\/ anyway.\n if (infoRes != sizeof(LOGCONTEXTW)) {\n LOG(ERROR,\n \"PEN: Invalid size of WTInfo:\\n\"\n \" Expected context size: %d\\n\"\n \" Actual context size: %d\\n\",\n sizeof(LOGCONTEXTW), infoRes);\n }\n#endif\n\n LOG(\"PEN: Context options=%d pktRate=%d in=%d,%d,%d,%d out=%d,%d,%d,%d sys=%d,%d,%d,%d\\n\",\n logctx.lcOptions, logctx.lcPktRate,\n logctx.lcInOrgX, logctx.lcInOrgY, logctx.lcInExtX, logctx.lcInExtY,\n logctx.lcOutOrgX, logctx.lcOutOrgY, logctx.lcOutExtX, logctx.lcOutExtY,\n logctx.lcSysOrgX, logctx.lcSysOrgY, logctx.lcSysExtX, logctx.lcSysExtY);\n\n logctx.lcOptions |=\n CXO_MESSAGES |\n CXO_CSRMESSAGES;\n logctx.lcPktData = PACKETDATA;\n logctx.lcPktMode = PACKETMODE;\n logctx.lcMoveMask = PACKETDATA;\n m_outBounds = gfx::Rect(logctx.lcOutOrgX, logctx.lcOutOrgY, logctx.lcOutExtX, logctx.lcOutExtY);\n\n AXIS pressure;\n infoRes = WTInfo(WTI_DEVICES, DVC_NPRESSURE, &pressure);\n if (infoRes >= sizeof(AXIS)) {\n m_minPressure = pressure.axMin;\n m_maxPressure = pressure.axMax;\n LOG(\"PEN: Min\/max pressure values [%d,%d]\\n\", pressure.axMin, pressure.axMax);\n }\n else {\n m_minPressure = 0;\n m_maxPressure = 0;\n LOG(\"PEN: pressure info size %d (expected %d)\", infoRes, sizeof(AXIS));\n }\n\n LOG(\"PEN: Opening context, options 0x%x\\n\", logctx.lcOptions);\n HCTX ctx = WTOpen(hwnd, &logctx, TRUE);\n if (!ctx) {\n LOG(\"PEN: Error attaching pen to display\\n\");\n return nullptr;\n }\n\n \/\/ Make the queue bigger as recommended by Wacom docs:\n \/\/\n \/\/ \"To prevent your queue from overflowing, increase the size of\n \/\/ your context's queue with the WTQueueSizeSet() function to a\n \/\/ value between 32 and 128. Memory for packet queues is a limited\n \/\/ resource, so be sure check that your call to WTQueueSizeSet()\n \/\/ succeeds. If WTQueueSizeSet() fails, request a smaller queue\n \/\/ size.\"\n \/\/\n \/\/ https:\/\/developer-docs.wacom.com\/display\/DevDocs\/Window+Developers+FAQ\n int q = WTQueueSizeGet(ctx);\n LOG(\"PEN: Original queue size=%d\\n\", q);\n if (q < 128) {\n for (int r=128; r>=q; r-=8) {\n if (WTQueueSizeSet(ctx, r))\n break;\n }\n }\n m_queueSize = q = WTQueueSizeGet(ctx);\n LOG(\"PEN: New queue size=%d\\n\", q);\n\n LOG(\"PEN: Pen attached to display, new context %p\\n\", ctx);\n return ctx;\n}\n\nvoid WintabAPI::close(HCTX ctx)\n{\n LOG(\"PEN: Closing context %p\\n\", ctx);\n if (ctx) {\n ASSERT(m_wintabLib);\n LOG(\"PEN: Pen detached from window\\n\");\n WTClose(ctx);\n }\n}\n\nvoid WintabAPI::overlap(HCTX ctx, BOOL state)\n{\n WTOverlap(ctx, state);\n}\n\nbool WintabAPI::packet(HCTX ctx, UINT serial, LPVOID packet)\n{\n return (WTPacket(ctx, serial, packet) ? true: false);\n}\n\nint WintabAPI::packets(HCTX ctx, int maxPackets, LPVOID packets)\n{\n return WTPacketsGet(ctx, maxPackets, packets);\n}\n\nvoid WintabAPI::mapCursorButton(const int cursor,\n const int logicalButton,\n const int relativeButton,\n Event::Type& evType,\n Event::MouseButton& mouseButton)\n{\n mouseButton = Event::NoneButton;\n switch (relativeButton) {\n case TBN_DOWN:\n evType = Event::MouseDown;\n break;\n case TBN_UP:\n evType = Event::MouseUp;\n break;\n case TBN_NONE:\n default:\n evType = Event::MouseMove;\n break;\n }\n\n \/\/ Invalid logical button\n if (logicalButton < 0 || logicalButton >= 32) {\n WINTAB_TRACE(\"PEN: INVALID LOGICAL BUTTON\\n\");\n return;\n }\n\n \/\/ Get \"logical button\" -> \"button action code\" mapping so we can\n \/\/ know for what specific mouse button we should generate an event\n \/\/ (or maybe if it's a double-click).\n BYTE map[32];\n WTInfo(WTI_CURSORS + cursor, CSR_SYSBTNMAP, &map);\n\n switch (map[logicalButton]) {\n\n case SBN_LDBLCLICK:\n evType = Event::MouseDoubleClick;\n case SBN_LCLICK:\n case SBN_LDRAG:\n mouseButton = Event::LeftButton;\n break;\n\n case SBN_RDBLCLICK:\n evType = Event::MouseDoubleClick;\n case SBN_RCLICK:\n case SBN_RDRAG:\n mouseButton = Event::RightButton;\n break;\n\n case SBN_MDBLCLICK:\n evType = Event::MouseDoubleClick;\n case SBN_MCLICK:\n case SBN_MDRAG:\n mouseButton = Event::MiddleButton;\n break;\n }\n\n WINTAB_TRACE(\n \" PEN: Button map logicalButton=%d action=%d -> evType=%s mouseButton=%d\\n\",\n logicalButton,\n map[logicalButton],\n (evType == Event::None ? \"-\":\n evType == Event::MouseMove ? \"move\":\n evType == Event::MouseDown ? \"DOWN\":\n evType == Event::MouseUp ? \"UP\":\n evType == Event::MouseDoubleClick ? \"DOUBLE-CLICK\": \"unknown\"),\n (int)mouseButton);\n}\n\nbool WintabAPI::loadWintab()\n{\n ASSERT(!m_wintabLib);\n\n m_wintabLib = base::load_dll(\"wintab32.dll\");\n if (!m_wintabLib) {\n LOG(ERROR, \"PEN: wintab32.dll is not present\\n\");\n return false;\n }\n\n if (!checkDll()) {\n base::unload_dll(m_wintabLib);\n m_wintabLib = nullptr;\n return false;\n }\n\n WTInfo = base::get_dll_proc(m_wintabLib, \"WTInfoW\");\n WTOpen = base::get_dll_proc(m_wintabLib, \"WTOpenW\");\n WTClose = base::get_dll_proc(m_wintabLib, \"WTClose\");\n WTPacketsGet = base::get_dll_proc(m_wintabLib, \"WTPacketsGet\");\n WTPacket = base::get_dll_proc(m_wintabLib, \"WTPacket\");\n WTOverlap = base::get_dll_proc(m_wintabLib, \"WTOverlap\");\n WTQueueSizeGet = base::get_dll_proc(m_wintabLib, \"WTQueueSizeGet\");\n WTQueueSizeSet = base::get_dll_proc(m_wintabLib, \"WTQueueSizeSet\");\n if (!WTInfo || !WTOpen || !WTClose || !WTPacket ||\n !WTQueueSizeGet || !WTQueueSizeSet) {\n LOG(ERROR, \"PEN: wintab32.dll does not contain all required functions\\n\");\n return false;\n }\n\n LOG(\"PEN: Wintab library loaded\\n\");\n return true;\n}\n\nbool WintabAPI::checkDll()\n{\n ASSERT(m_wintabLib);\n\n std::string fn = base::get_dll_filename(m_wintabLib);\n if (!base::is_file(fn))\n return false;\n\n std::string checksum = base::convert_to(base::Sha1::calculateFromFile(fn));\n base::Version ver = base::get_file_version(fn);\n LOG(\"PEN: <%s> v%s, sha1 <%s>\\n\", fn.c_str(), ver.str().c_str(), checksum.c_str());\n\n \/\/ Ugly hack to bypass the buggy WALTOP International Corp .dll that\n \/\/ hangs Aseprite completely when we call its WTInfo function.\n if (checksum == \"a3ba0d9c0f5d8b9f4070981b243a80579f8be105\")\n return false;\n\n return true;\n}\n\n} \/\/ namespace os\n<|endoftext|>"} {"text":"\/**\n * Instructions:\n * Implement the code, and write comments described in the\n * \/\/TODO:\n * formatted comments. \n * \/\/NOTE:\n * comments clarify parts of the given code.\n **\/\n\n\/\/TODO: Insert your header\n\/\/NOTE: Your header no longer needs to include inputs and outputs\n\n#include \n#include \n\nusing namespace std;\n\n\/**\n * Function Declarations\n **\/\n\n\/\/IGNORE: You can ignore these functions\nvoid test();\nvoid run_loop();\nvoid run();\nvoid test_unit_to_s();\nvoid test_to_c();\nvoid test_from_c();\nvoid test_convert();\n\n\/\/TODO: Write header comments for each of the following function declarations.\nstring unit_to_s(char unit);\ndouble to_c(char units, double temp);\ndouble from_c(char units, double temp);\ndouble convert(char in, char out, double temp);\n\n\/**\n * Main Function\n **\/\n\n\/\/IGNORE: You may safely ignore the main function.\nint main() {\n char t;\n\n cout << \"Enter [t] to test, or any other character to run.\" << endl;\n cin >> t;\n if(t == 't') {\n test();\n } else {\n run_loop();\n }\n}\n\n\/**\n * Function Definitions\n **\/\n\/\/IGNORE: You may ignore this tester.\nvoid test() {\n test_unit_to_s();\n test_to_c();\n test_from_c();\n test_convert();\n}\n\n\/\/IGNORE: You may ignore this function.\nvoid run_loop() {\n char again = 'y';\n\n while(again == 'y' || again == 'Y') {\n run();\n cout << \"Calculate again?\" << endl;\n cin >> again;\n }\n}\n\/\/NOTE: You do not have to edit this function, but you should use it as a guide\n\/\/ to understand how to implement the functions.\nvoid run() {\n \/\/ Variable Declarations\n char units_in, units_out;\n double temp;\n\n \/\/ Input\n cout << \"Enter the units you'd like to convert from:\" << endl;\n cin >> units_in;\n cout << \"Enter the units you'd like to convert to:\" << endl;\n cin >> units_out;\n cout << \"Enter the temperature in \" << unit_to_s(units_in) << \":\" << endl;\n cin >> temp;\n\n \/\/ Output\n cout << temp << \" \"\n << unit_to_s(units_in) << \" is \"\n << unit_to_s(units_out) << \" \"\n << convert(units_in, units_out, temp) << \".\" << endl;\n}\n\n\/\/TODO: Implement each of the functions below\n\/\/NOTE: You should be able to copy and modify much of your code\n\/\/ from the previous homework.\n\/\/TODO: Test each of the functions below\n\/\/NOTE: make sure you test each possible case\nvoid test_unit_to_s() {\n assert(unit_to_s('c') == \"celcius\");\n}\nstring unit_to_s(char unit) {\n return \"celcius\";\n}\n\nvoid test_to_c() {\n assert(to_c('f',32) == 0);\n}\ndouble to_c(char units, double temp) {\n return 0;\n}\n\nvoid test_from_c() {\n assert(from_c('f',0) == 32);\n}\ndouble from_c(char units, double temp){\n return 32;\n}\n\nvoid test_convert() {\n assert(convert('f','c',32) == 0);\n} \ndouble convert(char in, char out, double temp) {\n return 0;\n}\nmodified instructions\/**\n * Instructions:\n * Implement the code, and write comments described in the\n * \/\/TODO:\n * formatted comments. \n *\n * \/\/NOTE:\n * comments clarify parts of the given code.\n * \n * \/\/IGNORE:\n * comments mark code which can be safely ignored.\n **\/\n\n\/\/TODO: Insert your header\n\/\/NOTE: Your header no longer needs to include inputs and outputs\n\n#include \n#include \n#include \n\nusing namespace std;\n\n\/**\n * Function Declarations\n **\/\n\n\/\/IGNORE: You can ignore these functions\nvoid test();\nvoid run_loop();\nvoid run();\nvoid test_unit_to_s();\nvoid test_to_c();\nvoid test_from_c();\nvoid test_convert();\n\n\/\/TODO: Write header comments for each of the following function declarations.\nstring unit_to_s(char unit);\ndouble to_c(char units, double temp);\ndouble from_c(char units, double temp);\ndouble convert(char in, char out, double temp);\n\n\/**\n * Main Function\n **\/\n\n\/\/IGNORE: You may safely ignore the main function.\nint main() {\n char t;\n\n cout << \"Enter [t] to test, or any other character to run.\" << endl;\n cin >> t;\n if(t == 't') {\n test();\n } else {\n run_loop();\n }\n}\n\n\/**\n * Function Definitions\n **\/\n\/\/IGNORE: You may ignore this tester.\nvoid test() {\n test_unit_to_s();\n test_to_c();\n test_from_c();\n test_convert();\n}\n\n\/\/IGNORE: You may ignore this function.\nvoid run_loop() {\n char again = 'y';\n\n while(again == 'y' || again == 'Y') {\n run();\n cout << \"Calculate again?\" << endl;\n cin >> again;\n }\n}\n\/\/NOTE: You do not have to edit this function, but you should use it as a guide\n\/\/ to understand how to implement the functions.\nvoid run() {\n \/\/ Variable Declarations\n char units_in, units_out;\n double temp;\n\n \/\/ Input\n cout << \"Enter the units you'd like to convert from:\" << endl;\n cin >> units_in;\n cout << \"Enter the units you'd like to convert to:\" << endl;\n cin >> units_out;\n cout << \"Enter the temperature in \" << unit_to_s(units_in) << \":\" << endl;\n cin >> temp;\n\n \/\/ Output\n cout << temp << \" \"\n << unit_to_s(units_in) << \" is \"\n << unit_to_s(units_out) << \" \"\n << convert(units_in, units_out, temp) << \".\" << endl;\n}\n\n\/\/TODO: Implement each of the functions below\n\/\/NOTE: You should be able to copy and modify much of your code\n\/\/ from the previous homework.\n\/\/TODO: Test each of the functions below\n\/\/NOTE: make sure you test each possible case\nvoid test_unit_to_s() {\n assert(unit_to_s('c') == \"celcius\");\n}\nstring unit_to_s(char unit) {\n return \"celcius\";\n}\n\nvoid test_to_c() {\n assert(to_c('f',32) == 0);\n}\ndouble to_c(char units, double temp) {\n return 0;\n}\n\nvoid test_from_c() {\n assert(from_c('f',0) == 32);\n}\ndouble from_c(char units, double temp){\n return 32;\n}\n\nvoid test_convert() {\n assert(convert('f','c',32) == 0);\n} \ndouble convert(char in, char out, double temp) {\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"BetaMath.h\"\n\nnamespace RandMath {\n\nlong double logBeta(double a, double b)\n{\n if (a <= 0 || b <= 0)\n return NAN;\n bool aIsInteger = areClose(a, std::round(a));\n bool bIsInteger = areClose(b, std::round(b));\n long double lgammaA = aIsInteger ? lfact(a - 1) : std::lgammal(a);\n long double lgammaB = lgammaA;\n if (a != b)\n lgammaB = bIsInteger ? lfact(b - 1) : std::lgammal(b);\n long double lgammaApB = (bIsInteger && bIsInteger) ? lfact(a + b - 1) : std::lgammal(a + b);\n return lgammaA + lgammaB - lgammaApB;\n}\n\nlong double beta(double a, double b)\n{\n return std::exp(logBeta(a, b));\n}\n\ndouble ibetaPowerSeries1(double x, double a, double b, double logBetaFun, double logX, double log1mX)\n{\n double addon = 1.0, sum = 0.0;\n \/\/\/ avoid underflow\n double u = (x > 1e-5) ? -x \/ (1.0 - x) : -std::exp(logX - log1mX);\n int n = 1;\n do {\n addon *= (n - b) * u \/ (a + n);\n sum += addon;\n ++n;\n } while (std::fabs(addon) > MIN_POSITIVE * std::fabs(sum));\n double y = a * logX;\n y += (b - 1) * log1mX;\n y -= logBetaFun;\n y += std::log1p(sum);\n return std::exp(y) \/ a;\n}\n\ndouble ibetacontinuedFraction1(double x, double a, double b, int number, double logBetaFun, double logX, double log1mX)\n{\n int n = number;\n \/\/\/ avoid underflow\n double u = (x > 1e-5) ? x \/ (1.0 - x) : std::exp(logX - log1mX);\n double frac = 0.0;\n while (n > 1) {\n double cn = (b - n + 1) \/ (a + n - 1) * u;\n frac = cn \/ (1 + cn - frac);\n --n;\n }\n double c1 = b \/ a;\n double F = c1 \/ (1 + c1 - frac);\n double y = a * logX;\n y += (b - 1) * log1mX;\n y -= logBetaFun;\n y = std::exp(y) \/ b;\n y *= F \/ (1.0 - F);\n return y;\n}\n\ndouble ibetaPowerSeries2(double x, double a, double b, double logBetaFun, double logX, double log1mX)\n{\n double addon = 1.0, sum = 0.0;\n int n = 0;\n do {\n addon *= (n + a + b) * x \/ (a + n + 1);\n sum += addon;\n ++n;\n } while (std::fabs(addon) > MIN_POSITIVE * std::fabs(sum));\n double y = a * logX;\n y += b * log1mX;\n y -= logBetaFun;\n y += std::log1p(sum);\n return std::exp(y) \/ a;\n}\n\ndouble ibetaContinuedFraction2(double x, double a, double b, int number, double logBetaFun, double logX, double log1mX)\n{\n int n = number;\n double frac = 0.0;\n while (n > 1) {\n double cn = (a + b + n - 2) \/ (a + n - 1) * x;\n frac = cn \/ (1 + cn - frac);\n --n;\n }\n double c1 = (a + b - 1) \/ a;\n double F = c1 \/ (1 + c1 - frac);\n double y = a * logX;\n y += b * log1mX;\n y -= logBetaFun;\n y = std::exp(y) \/ (a + b - 1);\n y *= F \/ (1.0 - F);\n return y;\n}\n\ndouble ibeta(double x, double a, double b, double logBetaFun, double logX, double log1mX)\n{\n \/\/\/ Check special values\n if (a <= 0 || b <= 0 || x < 0.0 || x > 1.0)\n return NAN;\n if (x == 0.0)\n return 0.0;\n if (x == 1.0)\n return 1.0;\n if (b == 1.0)\n return std::exp(a * logX);\n if (a == 1.0)\n return -std::expm1(b * log1mX);\n\n \/\/\/ If x is larger than mean of Beta distribution,\n \/\/\/ convergence of complementary distribution function is faster\n if (x > a \/ (a + b))\n return 1.0 - ibeta(1.0 - x, b, a);\n\n \/\/\/ We truncate after 0.45 instead of 0.5 here\n \/\/\/ in order to avoid x being too close to 0.5\n if (x < 0.45) {\n if (b < 1)\n return ibetaPowerSeries1(x, a, b, logBetaFun, logX, log1mX);\n double number = std::floor(b);\n \/\/\/ equivalent continued fraction #1\n double ecd = ibetacontinuedFraction1(x, a, b, number, logBetaFun, logX, log1mX);\n double apn = a + number, bmn = b - number;\n double residue = (b == number) ? 0.0 : ibetaPowerSeries1(x, apn, bmn, logBeta(apn, bmn), logX, log1mX);\n return ecd + residue;\n }\n\n if (b < 1)\n return ibetaPowerSeries2(x, a, b, logBetaFun, logX, log1mX);\n double number = std::floor(b);\n \/\/\/ equivalent continued fraction #2\n double ecd = ibetaContinuedFraction2(x, a, b, number, logBetaFun, logX, log1mX);\n double apn = a + number;\n double residue = ibetaPowerSeries2(x, apn, b, logBeta(apn, b), logX, log1mX);\n return ecd + residue;\n}\n\ndouble ibeta(double x, double a, double b)\n{\n \/\/\/ Check special values\n if (a <= 0 || b <= 0 || x < 0.0 || x > 1.0)\n return NAN;\n if (x == 0.0)\n return 0.0;\n if (x == 1.0)\n return 1.0;\n if (b == 1.0)\n return std::pow(x, a);\n if (a == 1.0) {\n double y = b * std::log1p(-x);\n return -std::expm1(y);\n }\n double logBetaFun = logBeta(a, b);\n double logX = std::log(x), log1mX = std::log1p(-x);\n return ibeta(x, a, b, logBetaFun, logX, log1mX);\n}\n\n}\nUpdate BetaMath.cpp#include \"BetaMath.h\"\n\nnamespace RandMath {\n\nlong double logBeta(double a, double b)\n{\n if (a <= 0 || b <= 0)\n return NAN;\n bool aIsInteger = areClose(a, std::round(a));\n bool bIsInteger = areClose(b, std::round(b));\n long double lgammaA = aIsInteger ? lfact(a - 1) : std::lgammal(a);\n long double lgammaB = lgammaA;\n if (a != b)\n lgammaB = bIsInteger ? lfact(b - 1) : std::lgammal(b);\n long double lgammaApB = (aIsInteger && bIsInteger) ? lfact(a + b - 1) : std::lgammal(a + b);\n return lgammaA + lgammaB - lgammaApB;\n}\n\nlong double beta(double a, double b)\n{\n return std::exp(logBeta(a, b));\n}\n\ndouble ibetaPowerSeries1(double x, double a, double b, double logBetaFun, double logX, double log1mX)\n{\n double addon = 1.0, sum = 0.0;\n \/\/\/ avoid underflow\n double u = (x > 1e-5) ? -x \/ (1.0 - x) : -std::exp(logX - log1mX);\n int n = 1;\n do {\n addon *= (n - b) * u \/ (a + n);\n sum += addon;\n ++n;\n } while (std::fabs(addon) > MIN_POSITIVE * std::fabs(sum));\n double y = a * logX;\n y += (b - 1) * log1mX;\n y -= logBetaFun;\n y += std::log1p(sum);\n return std::exp(y) \/ a;\n}\n\ndouble ibetacontinuedFraction1(double x, double a, double b, int number, double logBetaFun, double logX, double log1mX)\n{\n int n = number;\n \/\/\/ avoid underflow\n double u = (x > 1e-5) ? x \/ (1.0 - x) : std::exp(logX - log1mX);\n double frac = 0.0;\n while (n > 1) {\n double cn = (b - n + 1) \/ (a + n - 1) * u;\n frac = cn \/ (1 + cn - frac);\n --n;\n }\n double c1 = b \/ a;\n double F = c1 \/ (1 + c1 - frac);\n double y = a * logX;\n y += (b - 1) * log1mX;\n y -= logBetaFun;\n y = std::exp(y) \/ b;\n y *= F \/ (1.0 - F);\n return y;\n}\n\ndouble ibetaPowerSeries2(double x, double a, double b, double logBetaFun, double logX, double log1mX)\n{\n double addon = 1.0, sum = 0.0;\n int n = 0;\n do {\n addon *= (n + a + b) * x \/ (a + n + 1);\n sum += addon;\n ++n;\n } while (std::fabs(addon) > MIN_POSITIVE * std::fabs(sum));\n double y = a * logX;\n y += b * log1mX;\n y -= logBetaFun;\n y += std::log1p(sum);\n return std::exp(y) \/ a;\n}\n\ndouble ibetaContinuedFraction2(double x, double a, double b, int number, double logBetaFun, double logX, double log1mX)\n{\n int n = number;\n double frac = 0.0;\n while (n > 1) {\n double cn = (a + b + n - 2) \/ (a + n - 1) * x;\n frac = cn \/ (1 + cn - frac);\n --n;\n }\n double c1 = (a + b - 1) \/ a;\n double F = c1 \/ (1 + c1 - frac);\n double y = a * logX;\n y += b * log1mX;\n y -= logBetaFun;\n y = std::exp(y) \/ (a + b - 1);\n y *= F \/ (1.0 - F);\n return y;\n}\n\ndouble ibeta(double x, double a, double b, double logBetaFun, double logX, double log1mX)\n{\n \/\/\/ Check special values\n if (a <= 0 || b <= 0 || x < 0.0 || x > 1.0)\n return NAN;\n if (x == 0.0)\n return 0.0;\n if (x == 1.0)\n return 1.0;\n if (b == 1.0)\n return std::exp(a * logX);\n if (a == 1.0)\n return -std::expm1(b * log1mX);\n\n \/\/\/ If x is larger than mean of Beta distribution,\n \/\/\/ convergence of complementary distribution function is faster\n if (x > a \/ (a + b))\n return 1.0 - ibeta(1.0 - x, b, a);\n\n \/\/\/ We truncate after 0.45 instead of 0.5 here\n \/\/\/ in order to avoid x being too close to 0.5\n if (x < 0.45) {\n if (b < 1)\n return ibetaPowerSeries1(x, a, b, logBetaFun, logX, log1mX);\n double number = std::floor(b);\n \/\/\/ equivalent continued fraction #1\n double ecd = ibetacontinuedFraction1(x, a, b, number, logBetaFun, logX, log1mX);\n double apn = a + number, bmn = b - number;\n double residue = (b == number) ? 0.0 : ibetaPowerSeries1(x, apn, bmn, logBeta(apn, bmn), logX, log1mX);\n return ecd + residue;\n }\n\n if (b < 1)\n return ibetaPowerSeries2(x, a, b, logBetaFun, logX, log1mX);\n double number = std::floor(b);\n \/\/\/ equivalent continued fraction #2\n double ecd = ibetaContinuedFraction2(x, a, b, number, logBetaFun, logX, log1mX);\n double apn = a + number;\n double residue = ibetaPowerSeries2(x, apn, b, logBeta(apn, b), logX, log1mX);\n return ecd + residue;\n}\n\ndouble ibeta(double x, double a, double b)\n{\n \/\/\/ Check special values\n if (a <= 0 || b <= 0 || x < 0.0 || x > 1.0)\n return NAN;\n if (x == 0.0)\n return 0.0;\n if (x == 1.0)\n return 1.0;\n if (b == 1.0)\n return std::pow(x, a);\n if (a == 1.0) {\n double y = b * std::log1p(-x);\n return -std::expm1(y);\n }\n double logBetaFun = logBeta(a, b);\n double logX = std::log(x), log1mX = std::log1p(-x);\n return ibeta(x, a, b, logBetaFun, logX, log1mX);\n}\n\n}\n<|endoftext|>"} {"text":"\/**\n * @file Scalar.hpp\n *\n * Defines conversion of matrix to scalar.\n *\n * @author James Goppert \n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"math.hpp\"\n\nnamespace matrix\n{\n\ntemplate\nclass Scalar\n{\npublic:\n virtual ~Scalar() {};\n\n Scalar() : _value()\n {\n }\n\n Scalar(const Matrix & other)\n {\n _value = other(0,0);\n }\n\n Scalar(Type other)\n {\n _value = other;\n }\n\n operator Type &()\n {\n return _value;\n }\n\n operator Type const &() const\n {\n return _value;\n }\n\n operator Matrix() const {\n Matrix m;\n m(0, 0) = _value;\n return m;\n }\n\nprivate:\n Type _value;\n\n};\n\ntypedef Scalar Scalarf;\n\n} \/\/ namespace matrix\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\nAdded conversion for scalar to vector.\/**\n * @file Scalar.hpp\n *\n * Defines conversion of matrix to scalar.\n *\n * @author James Goppert \n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"math.hpp\"\n\nnamespace matrix\n{\n\ntemplate\nclass Scalar\n{\npublic:\n virtual ~Scalar() {};\n\n Scalar() : _value()\n {\n }\n\n Scalar(const Matrix & other)\n {\n _value = other(0,0);\n }\n\n Scalar(Type other)\n {\n _value = other;\n }\n\n operator Type &()\n {\n return _value;\n }\n\n operator Type const &() const\n {\n return _value;\n }\n\n operator Matrix() const {\n Matrix m;\n m(0, 0) = _value;\n return m;\n }\n\n operator Vector() const {\n Vector m;\n m(0) = _value;\n return m;\n }\n\nprivate:\n Type _value;\n\n};\n\ntypedef Scalar Scalarf;\n\n} \/\/ namespace matrix\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\n<|endoftext|>"} {"text":"\/****************** *****************\n *\n * sonix\n *\n * Original Authors:\n * Kevin Meinert\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \"snx\/ISoundImplementation.h\"\n#include \"snx\/StubSoundImplementation.h\" \/\/ in case lookup fails...\n\n#include \"snx\/SoundFactory.h\" \/\/ my header.\n\n\nnamespace snx\n{\n\n\/**\n * Create the plugin.\n * Symbol name to look up from the shared lib is \"newPlugin\".\n *\/\ntypedef snx::ISoundImplementation* (*newPluginFunc)(void);\n\n\/**\n * Gets the name of the plugin.\n * Symbol name to lookup from the shared lib is \"getName\".\n *\/\ntypedef char* (*getNameFunc)(void);\n\n\/**\n * Get the version of sonix plugin was compiled against.\n * Symbol name to lookup from the shared lib is \"getVersion\".\n *\/\ntypedef char* (*getVersionFunc)(void);\n\nvprSingletonImp(SoundFactory);\n\nSoundFactory::SoundFactory()\n{\n std::vector search_paths;\n\n const std::string envvar(\"SNX_BASE_DIR\");\n std::string dummy_result;\n\n if ( vpr::System::getenv(envvar, dummy_result).failure() )\n {\n vprDEBUG(snxDBG, vprDBG_WARNING_LVL)\n << clrOutBOLD(clrYELLOW, \"WARNING:\")\n << \" SNX_BASE_DIR environment variable not set!\\n\" << vprDEBUG_FLUSH;\n vprDEBUG_NEXT(snxDBG, vprDBG_WARNING_LVL)\n << \"Plug-in loading may fail.\\n\" << vprDEBUG_FLUSH;\n }\n\n#if defined(_ABIN32)\n std::string snx_lib_dir(\"${SNX_BASE_DIR}\/lib32\/snx\/plugins\");\n#elif defined(_ABI64)\n std::string snx_lib_dir(\"${SNX_BASE_DIR}\/lib64\/snx\/plugins\");\n#else\n std::string snx_lib_dir(\"${SNX_BASE_DIR}\/lib\/snx\/plugins\");\n#endif\n\n#ifdef SNX_DEBUG\n snx_lib_dir += std::string(\"\/dbg\");\n#else\n snx_lib_dir += std::string(\"\/opt\");\n#endif\n\n#if defined(VPR_OS_Win32)\n const std::string driver_ext(\"dll\");\n#elif defined(VPR_OS_Darwin)\n const std::string driver_ext(\"dylib\");\n#else\n const std::string driver_ext(\"so\");\n#endif\n\n search_paths.push_back(snx_lib_dir);\n search_paths.push_back( \"${HOME}\/.sonix\/plugins\" );\n\n for (unsigned int x = 0; x < search_paths.size(); ++x)\n {\n search_paths[x] = vpr::replaceEnvVars(search_paths[x]);\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL) << \"Finding plugins in \"\n << search_paths[x] << std::endl\n << vprDEBUG_FLUSH;\n\n boost::filesystem::path dirPath(search_paths[x]);\n if (boost::filesystem::exists(dirPath))\n {\n vpr::LibraryFinder finder(search_paths[x], driver_ext);\n vpr::LibraryFinder::LibraryList libs = finder.getLibraries();\n this->loadPlugins( libs );\n\n#ifdef SNX_DEBUG\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL) << \"filelist:\\n\" << vprDEBUG_FLUSH;\n for ( unsigned int i = 0; i < libs.size(); ++i )\n {\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL) << \"\\t\" << libs[i]\n << std::endl << vprDEBUG_FLUSH;\n }\n#endif\n }\n else\n {\n vprDEBUG(snxDBG, vprDBG_STATE_LVL)\n << \"The directory does not exist: '\" << search_paths[x] << \"'\\n\"\n << vprDEBUG_FLUSH;\n }\n }\n}\n\nvoid SoundFactory::errorOutput(vpr::LibraryPtr lib, const char* test)\n{\n vprDEBUG(snxDBG, vprDBG_WARNING_LVL)\n << \"ERROR: Plugin '\" << lib->getName() << \"' does not export symbol '\"\n << test << \"'\\n\" << vprDEBUG_FLUSH;\n}\n\nbool SoundFactory::isPlugin(vpr::LibraryPtr lib)\n{\n if (lib->findSymbol( \"newPlugin\" ) == NULL)\n {\n errorOutput(lib, \"newPlugin\");\n return false;\n }\n if (lib->findSymbol( \"getVersion\" ) == NULL)\n {\n errorOutput(lib, \"getVersion\");\n return false;\n }\n if (lib->findSymbol( \"getName\" ) == NULL)\n {\n errorOutput(lib, \"getName\");\n return false;\n }\n\n \/\/ @todo give sonix an internal version number string!\n \/\/getVersionFunc getVersion = (getVersionFunc)lib.lookup( \"getVersion\" );\n \/\/if (getVersion != NULL && getVersion() != snx::version) return false;\n vprDEBUG(snxDBG, vprDBG_CONFIG_STATUS_LVL) << \"Plugin '\" << lib->getName()\n << \"' is a valid Sonix plugin.\\n\"\n << vprDEBUG_FLUSH;\n return true;\n}\n\nvoid SoundFactory::loadPlugins( vpr::LibraryFinder::LibraryList libs )\n{\n for (unsigned int x = 0; x < libs.size(); ++x)\n {\n \/\/ open the library\n vpr::ReturnStatus didLoad = libs[x]->load();\n\n if (didLoad == vpr::ReturnStatus::Succeed)\n {\n \/\/If the plug-in implements the nessiasry interface\n if ( this->isPlugin(libs[x]) )\n {\n \/\/ get the name..\n getNameFunc getName = (getNameFunc)libs[x]->findSymbol( \"getName\" );\n std::string name;\n if (getName != NULL)\n {\n name = getName();\n\n \/\/ Check to see it plug-in is already registered\n int pluginsWithName = mRegisteredImplementations.count(name);\n if ( pluginsWithName < 1 )\n {\n \/\/ Keep track of the plug-ins we actual use\n mPlugins.push_back(libs[x]);\n\n vprDEBUG(snxDBG, vprDBG_STATE_LVL)\n << \"Got plug-in '\" << name << \"'--registering\\n\"\n << vprDEBUG_FLUSH;\n\n \/\/ create the implementation\n newPluginFunc newPlugin = (newPluginFunc)libs[x]->findSymbol( \"newPlugin\" );\n ISoundImplementation* si = NULL;\n if (newPlugin != NULL)\n {\n si = newPlugin();\n if (NULL != si)\n {\n this->reg( name, si );\n }\n }\n }\n else\n {\n \/\/Plug in was already registered so we can unload it\n libs[x]->unload();\n }\n }\n }\n }\n else\n {\n \/\/Lib failed to load\n vprDEBUG(snxDBG, vprDBG_WARNING_LVL)\n << \"ERROR: Plugin '\" << libs[x]->getName() << \"' Failed to load\\n\" << vprDEBUG_FLUSH;\n }\n }\n}\n\nvoid SoundFactory::unloadPlugins()\n{\n for (unsigned int x = 0; x < mPlugins.size(); ++x)\n {\n \/\/ get the name..\n getNameFunc getName = (getNameFunc)mPlugins[x]->findSymbol( \"getName\" );\n std::string name;\n ISoundImplementation* impl = NULL;\n if (getName != NULL)\n {\n name = getName();\n impl = mRegisteredImplementations[name];\n\n \/\/ unreg it.\n this->reg( name, NULL );\n }\n\n \/\/ delete the memory using the delete func that comes with the library...\n if ( NULL != impl )\n {\n delete impl;\n }\n\n \/\/ close the library\n mPlugins[x]->unload();\n }\n mPlugins.clear();\n}\n\nvoid SoundFactory::reg(const std::string& apiName,\n snx::ISoundImplementation* impl)\n{\n if (impl != NULL)\n {\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL)\n << \"NOTICE: Registering sound API '\" << apiName << \"'\\n\"\n << vprDEBUG_FLUSH;\n\n impl->setName( apiName );\n mRegisteredImplementations[apiName] = impl;\n }\n else\n {\n mRegisteredImplementations.erase( apiName );\n\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL)\n << \"NOTICE: Unregistered sound API '\" << apiName << \"'\\n\"\n << vprDEBUG_FLUSH;\n }\n}\n\n\/**\n * @input name of api to create\n * @output an implementation is returned for you to use\n * @postconditions if apiName is not known, then a stub implementation is returned\n * @semantics factory function used to create an implementation of a sound API\n *\/\nvoid SoundFactory::createImplementation( const std::string& apiName,\n snx::ISoundImplementation* &mImplementation )\n{\n if (mRegisteredImplementations.count( apiName ) > 0)\n {\n mRegisteredImplementations[apiName]->clone( mImplementation );\n }\n\n else\n {\n mImplementation = new snx::StubSoundImplementation;\n }\n\n \/\/mImplementation->setName( apiName );\n}\n\n} \/\/ end namespace\nCatch exceptions that Boost.Filesystem code might throw, and ensure that native paths can be used when searching for Sonix plug-ins.\/****************** *****************\n *\n * sonix\n *\n * Original Authors:\n * Kevin Meinert\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \"snx\/ISoundImplementation.h\"\n#include \"snx\/StubSoundImplementation.h\" \/\/ in case lookup fails...\n\n#include \"snx\/SoundFactory.h\" \/\/ my header.\n\n\nnamespace snx\n{\n\n\/**\n * Create the plugin.\n * Symbol name to look up from the shared lib is \"newPlugin\".\n *\/\ntypedef snx::ISoundImplementation* (*newPluginFunc)(void);\n\n\/**\n * Gets the name of the plugin.\n * Symbol name to lookup from the shared lib is \"getName\".\n *\/\ntypedef char* (*getNameFunc)(void);\n\n\/**\n * Get the version of sonix plugin was compiled against.\n * Symbol name to lookup from the shared lib is \"getVersion\".\n *\/\ntypedef char* (*getVersionFunc)(void);\n\nvprSingletonImp(SoundFactory);\n\nSoundFactory::SoundFactory()\n{\n std::vector search_paths;\n\n const std::string envvar(\"SNX_BASE_DIR\");\n std::string dummy_result;\n\n if ( vpr::System::getenv(envvar, dummy_result).failure() )\n {\n vprDEBUG(snxDBG, vprDBG_WARNING_LVL)\n << clrOutBOLD(clrYELLOW, \"WARNING:\")\n << \" SNX_BASE_DIR environment variable not set!\\n\" << vprDEBUG_FLUSH;\n vprDEBUG_NEXT(snxDBG, vprDBG_WARNING_LVL)\n << \"Plug-in loading may fail.\\n\" << vprDEBUG_FLUSH;\n }\n\n#if defined(_ABIN32)\n std::string snx_lib_dir(\"${SNX_BASE_DIR}\/lib32\/snx\/plugins\");\n#elif defined(_ABI64)\n std::string snx_lib_dir(\"${SNX_BASE_DIR}\/lib64\/snx\/plugins\");\n#else\n std::string snx_lib_dir(\"${SNX_BASE_DIR}\/lib\/snx\/plugins\");\n#endif\n\n#ifdef SNX_DEBUG\n snx_lib_dir += std::string(\"\/dbg\");\n#else\n snx_lib_dir += std::string(\"\/opt\");\n#endif\n\n#if defined(VPR_OS_Win32)\n const std::string driver_ext(\"dll\");\n#elif defined(VPR_OS_Darwin)\n const std::string driver_ext(\"dylib\");\n#else\n const std::string driver_ext(\"so\");\n#endif\n\n search_paths.push_back(snx_lib_dir);\n search_paths.push_back( \"${HOME}\/.sonix\/plugins\" );\n\n for (unsigned int x = 0; x < search_paths.size(); ++x)\n {\n search_paths[x] = vpr::replaceEnvVars(search_paths[x]);\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL) << \"Finding plugins in \"\n << search_paths[x] << std::endl\n << vprDEBUG_FLUSH;\n\n try\n {\n boost::filesystem::path dirPath(search_paths[x], boost::filesystem::native);\n if (boost::filesystem::exists(dirPath))\n {\n vpr::LibraryFinder finder(search_paths[x], driver_ext);\n vpr::LibraryFinder::LibraryList libs = finder.getLibraries();\n this->loadPlugins( libs );\n\n#ifdef SNX_DEBUG\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL) << \"filelist:\\n\"\n << vprDEBUG_FLUSH;\n for ( unsigned int i = 0; i < libs.size(); ++i )\n {\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL) << \"\\t\" << libs[i]\n << std::endl\n << vprDEBUG_FLUSH;\n }\n#endif\n }\n else\n {\n vprDEBUG(snxDBG, vprDBG_STATE_LVL)\n << \"The directory does not exist: '\" << search_paths[x] << \"'\\n\"\n << vprDEBUG_FLUSH;\n }\n }\n catch (boost::filesystem::filesystem_error& fsEx)\n {\n vprDEBUG(snxDBG, vprDBG_CRITICAL_LVL)\n << clrOutNORM(clrRED, \"ERROR:\")\n << \" File system exception caught: \" << fsEx.what() << std::endl\n << vprDEBUG_FLUSH;\n }\n }\n}\n\nvoid SoundFactory::errorOutput(vpr::LibraryPtr lib, const char* test)\n{\n vprDEBUG(snxDBG, vprDBG_WARNING_LVL)\n << \"ERROR: Plugin '\" << lib->getName() << \"' does not export symbol '\"\n << test << \"'\\n\" << vprDEBUG_FLUSH;\n}\n\nbool SoundFactory::isPlugin(vpr::LibraryPtr lib)\n{\n if (lib->findSymbol( \"newPlugin\" ) == NULL)\n {\n errorOutput(lib, \"newPlugin\");\n return false;\n }\n if (lib->findSymbol( \"getVersion\" ) == NULL)\n {\n errorOutput(lib, \"getVersion\");\n return false;\n }\n if (lib->findSymbol( \"getName\" ) == NULL)\n {\n errorOutput(lib, \"getName\");\n return false;\n }\n\n \/\/ @todo give sonix an internal version number string!\n \/\/getVersionFunc getVersion = (getVersionFunc)lib.lookup( \"getVersion\" );\n \/\/if (getVersion != NULL && getVersion() != snx::version) return false;\n vprDEBUG(snxDBG, vprDBG_CONFIG_STATUS_LVL) << \"Plugin '\" << lib->getName()\n << \"' is a valid Sonix plugin.\\n\"\n << vprDEBUG_FLUSH;\n return true;\n}\n\nvoid SoundFactory::loadPlugins( vpr::LibraryFinder::LibraryList libs )\n{\n for (unsigned int x = 0; x < libs.size(); ++x)\n {\n \/\/ open the library\n vpr::ReturnStatus didLoad = libs[x]->load();\n\n if (didLoad == vpr::ReturnStatus::Succeed)\n {\n \/\/If the plug-in implements the nessiasry interface\n if ( this->isPlugin(libs[x]) )\n {\n \/\/ get the name..\n getNameFunc getName = (getNameFunc)libs[x]->findSymbol( \"getName\" );\n std::string name;\n if (getName != NULL)\n {\n name = getName();\n\n \/\/ Check to see it plug-in is already registered\n int pluginsWithName = mRegisteredImplementations.count(name);\n if ( pluginsWithName < 1 )\n {\n \/\/ Keep track of the plug-ins we actual use\n mPlugins.push_back(libs[x]);\n\n vprDEBUG(snxDBG, vprDBG_STATE_LVL)\n << \"Got plug-in '\" << name << \"'--registering\\n\"\n << vprDEBUG_FLUSH;\n\n \/\/ create the implementation\n newPluginFunc newPlugin = (newPluginFunc)libs[x]->findSymbol( \"newPlugin\" );\n ISoundImplementation* si = NULL;\n if (newPlugin != NULL)\n {\n si = newPlugin();\n if (NULL != si)\n {\n this->reg( name, si );\n }\n }\n }\n else\n {\n \/\/Plug in was already registered so we can unload it\n libs[x]->unload();\n }\n }\n }\n }\n else\n {\n \/\/Lib failed to load\n vprDEBUG(snxDBG, vprDBG_WARNING_LVL)\n << \"ERROR: Plugin '\" << libs[x]->getName() << \"' Failed to load\\n\" << vprDEBUG_FLUSH;\n }\n }\n}\n\nvoid SoundFactory::unloadPlugins()\n{\n for (unsigned int x = 0; x < mPlugins.size(); ++x)\n {\n \/\/ get the name..\n getNameFunc getName = (getNameFunc)mPlugins[x]->findSymbol( \"getName\" );\n std::string name;\n ISoundImplementation* impl = NULL;\n if (getName != NULL)\n {\n name = getName();\n impl = mRegisteredImplementations[name];\n\n \/\/ unreg it.\n this->reg( name, NULL );\n }\n\n \/\/ delete the memory using the delete func that comes with the library...\n if ( NULL != impl )\n {\n delete impl;\n }\n\n \/\/ close the library\n mPlugins[x]->unload();\n }\n mPlugins.clear();\n}\n\nvoid SoundFactory::reg(const std::string& apiName,\n snx::ISoundImplementation* impl)\n{\n if (impl != NULL)\n {\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL)\n << \"NOTICE: Registering sound API '\" << apiName << \"'\\n\"\n << vprDEBUG_FLUSH;\n\n impl->setName( apiName );\n mRegisteredImplementations[apiName] = impl;\n }\n else\n {\n mRegisteredImplementations.erase( apiName );\n\n vprDEBUG(snxDBG, vprDBG_CONFIG_LVL)\n << \"NOTICE: Unregistered sound API '\" << apiName << \"'\\n\"\n << vprDEBUG_FLUSH;\n }\n}\n\n\/**\n * @input name of api to create\n * @output an implementation is returned for you to use\n * @postconditions if apiName is not known, then a stub implementation is returned\n * @semantics factory function used to create an implementation of a sound API\n *\/\nvoid SoundFactory::createImplementation( const std::string& apiName,\n snx::ISoundImplementation* &mImplementation )\n{\n if (mRegisteredImplementations.count( apiName ) > 0)\n {\n mRegisteredImplementations[apiName]->clone( mImplementation );\n }\n\n else\n {\n mImplementation = new snx::StubSoundImplementation;\n }\n\n \/\/mImplementation->setName( apiName );\n}\n\n} \/\/ end namespace\n<|endoftext|>"} {"text":"#include \"menger_sponge.h\"\n#include \"utilities.h\"\n\n#include \n#include \n#include \n#include \n\nstruct Quad\nmake_quad (struct Point a, struct Point b, struct Point c, struct Point d)\n{\n\tstruct Point A = a;\n\tstruct Point B = b;\n\tstruct Point C = c;\n\tstruct Point D = d;\n\n\tA.color = random_color();\n\tB.color = random_color();\n\tC.color = random_color();\n\tD.color = random_color();\n\n\tstruct Normal normal = compute_normal(A - B, B - C);\n\tA.normal = normal;\n\tB.normal = normal;\n\tC.normal = normal;\n\tD.normal = normal;\n\n\tstruct TexCoord tc1 {{0.0, 0.0}};\n\tstruct TexCoord tc2 {{1.0, 0.0}};\n\tstruct TexCoord tc3 {{1.0, 1.0}};\n\tstruct TexCoord tc4 {{0.0, 1.0}};\n\n\tA.tex_coord = tc1;\n\tB.tex_coord = tc2;\n\tC.tex_coord = tc3;\n\tD.tex_coord = tc4;\n\n\tstruct Quad result {A, B, C, D};\n\treturn result;\n}\n\nstruct Cube\ncube_starting_with (int i, int j, int k, struct Point (*cube_points)[4][4])\n{\n\tstruct Cube result {\n\t\tcube_points[i+0][j+0][k+0], \n\t\tcube_points[i+1][j+0][k+0],\n\t\tcube_points[i+1][j+0][k+1], \n\t\tcube_points[i+0][j+0][k+1], \n\n\t\tcube_points[i+0][j+1][k+0], \n\t\tcube_points[i+1][j+1][k+0],\n\t\tcube_points[i+1][j+1][k+1], \n\t\tcube_points[i+0][j+1][k+1], \n\t\t};\n\n\treturn result;\n}\n\nstruct Point\nlin_interpol (struct Point a, struct Point b, GLfloat tx, GLfloat ty, GLfloat\n tz)\n{\n\tGLfloat new_x = a.x + (b.x - a.x) * tx;\t\n\tGLfloat new_y = a.y + (b.y - a.y) * ty;\t\n\tGLfloat new_z = a.z + (b.z - a.z) * tz;\t\n\t\t\t\t\n\tstd::cout << new_x << \" \" << new_y << \" \" << new_z << std::endl;\n\n\tstruct Point result {new_x, new_y, new_z};\n\treturn result;\n}\n\nstd::vector \ncreate_menger_sponge(struct Cube base, unsigned int depth)\n{\n\tstd::stack> stack;\n\tstd::vector result;\n\t\t\n\tstack.push(std::make_pair(base, depth));\n\twhile (!stack.empty())\n\t{\n\t\tstd::pair top = stack.top();\t\n\t\tstack.pop();\n\n\t\tstruct Point a = top.first.points[0];\n\t\tstruct Point b = top.first.points[1];\n\t\tstruct Point c = top.first.points[2];\n\t\tstruct Point d = top.first.points[3];\n\t\tstruct Point e = top.first.points[4];\n\t\tstruct Point f = top.first.points[5];\n\t\tstruct Point g = top.first.points[6];\n\t\tstruct Point h = top.first.points[7];\n\n\t\tif (top.second == 0)\n\t\t{\n\t\t\tresult.push_back(make_quad(a, b, c, d));\n\t\t\tresult.push_back(make_quad(e, f, g, h));\n\t\t\tresult.push_back(make_quad(a, b, f, e));\n\t\t\tresult.push_back(make_quad(c, d, h, g));\n\t\t\tresult.push_back(make_quad(b, c, g, f));\n\t\t\tresult.push_back(make_quad(a, d, h, e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstruct Point cube[4][4][4];\n\t\t\tfor (int i = 0; i < 4; i++)\n\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\tfor (int k = 0; k < 4; k++)\n\t\t\t{\n\t\t\t\tcube[i][j][k] = lin_interpol(a, g, \n\t\t\t\t\t(GLfloat)i\/3.0, \n\t\t\t\t\t(GLfloat)j\/3.0, \n\t\t\t\t\t(GLfloat)k\/3.0);\n\n\t\t\t}\n\n\t\t\t\/\/ cube front face\n\t\t\tstruct Cube cf1 = cube_starting_with(0, 0, 0, cube);\n\t\t\tstruct Cube cf2 = cube_starting_with(1, 0, 0, cube);\n\t\t\tstruct Cube cf3 = cube_starting_with(2, 0, 0, cube);\n\t\t\tstruct Cube cf4 = cube_starting_with(0, 1, 0, cube);\n\t\t\tstruct Cube cf5 = cube_starting_with(2, 1, 0, cube);\n\t\t\tstruct Cube cf6 = cube_starting_with(0, 2, 0, cube);\n\t\t\tstruct Cube cf7 = cube_starting_with(1, 2, 0, cube);\n\t\t\tstruct Cube cf8 = cube_starting_with(2, 2, 0, cube);\n\n\t\t\t\/\/ cube back face\n\t\t\tstruct Cube cb1 = cube_starting_with(0, 0, 2, cube);\n\t\t\tstruct Cube cb2 = cube_starting_with(1, 0, 2, cube);\n\t\t\tstruct Cube cb3 = cube_starting_with(2, 0, 2, cube);\n\t\t\tstruct Cube cb4 = cube_starting_with(0, 1, 2, cube);\n\t\t\tstruct Cube cb5 = cube_starting_with(2, 1, 2, cube);\n\t\t\tstruct Cube cb6 = cube_starting_with(0, 2, 2, cube);\n\t\t\tstruct Cube cb7 = cube_starting_with(1, 2, 2, cube);\n\t\t\tstruct Cube cb8 = cube_starting_with(2, 2, 2, cube);\n\n\t\t\t\/\/ cube side faces\n\t\t\tstruct Cube cs1 = cube_starting_with(2, 0, 1, cube);\n\t\t\tstruct Cube cs2 = cube_starting_with(2, 2, 1, cube);\n\t\t\tstruct Cube cs3 = cube_starting_with(0, 0, 1, cube);\n\t\t\tstruct Cube cs4 = cube_starting_with(0, 2, 1, cube);\n\n\t\t\tstack.push(std::make_pair(cf1, top.second-1));\n\t\t\tstack.push(std::make_pair(cf2, top.second-1));\n\t\t\tstack.push(std::make_pair(cf3, top.second-1));\n\t\t\tstack.push(std::make_pair(cf4, top.second-1));\n\t\t\tstack.push(std::make_pair(cf5, top.second-1));\n\t\t\tstack.push(std::make_pair(cf6, top.second-1));\n\t\t\tstack.push(std::make_pair(cf7, top.second-1));\n\t\t\tstack.push(std::make_pair(cf8, top.second-1));\n\t\t\tstack.push(std::make_pair(cb1, top.second-1));\n\t\t\tstack.push(std::make_pair(cb2, top.second-1));\n\t\t\tstack.push(std::make_pair(cb3, top.second-1));\n\t\t\tstack.push(std::make_pair(cb4, top.second-1));\n\t\t\tstack.push(std::make_pair(cb5, top.second-1));\n\t\t\tstack.push(std::make_pair(cb6, top.second-1));\n\t\t\tstack.push(std::make_pair(cb7, top.second-1));\n\t\t\tstack.push(std::make_pair(cb8, top.second-1));\n\t\t\tstack.push(std::make_pair(cs1, top.second-1));\n\t\t\tstack.push(std::make_pair(cs2, top.second-1));\n\t\t\tstack.push(std::make_pair(cs3, top.second-1));\n\t\t\tstack.push(std::make_pair(cs4, top.second-1));\n\t\t}\n\t}\n\n\treturn result;\n}\n\nRemoved slow printing#include \"menger_sponge.h\"\n#include \"utilities.h\"\n\n#include \n#include \n#include \n#include \n\nstruct Quad\nmake_quad (struct Point a, struct Point b, struct Point c, struct Point d)\n{\n\tstruct Point A = a;\n\tstruct Point B = b;\n\tstruct Point C = c;\n\tstruct Point D = d;\n\n\tA.color = random_color();\n\tB.color = random_color();\n\tC.color = random_color();\n\tD.color = random_color();\n\n\tstruct Normal normal = compute_normal(A - B, B - C);\n\tA.normal = normal;\n\tB.normal = normal;\n\tC.normal = normal;\n\tD.normal = normal;\n\n\tstruct TexCoord tc1 {{0.0, 0.0}};\n\tstruct TexCoord tc2 {{1.0, 0.0}};\n\tstruct TexCoord tc3 {{1.0, 1.0}};\n\tstruct TexCoord tc4 {{0.0, 1.0}};\n\n\tA.tex_coord = tc1;\n\tB.tex_coord = tc2;\n\tC.tex_coord = tc3;\n\tD.tex_coord = tc4;\n\n\tstruct Quad result {A, B, C, D};\n\treturn result;\n}\n\nstruct Cube\ncube_starting_with (int i, int j, int k, struct Point (*cube_points)[4][4])\n{\n\tstruct Cube result {\n\t\tcube_points[i+0][j+0][k+0], \n\t\tcube_points[i+1][j+0][k+0],\n\t\tcube_points[i+1][j+0][k+1], \n\t\tcube_points[i+0][j+0][k+1], \n\n\t\tcube_points[i+0][j+1][k+0], \n\t\tcube_points[i+1][j+1][k+0],\n\t\tcube_points[i+1][j+1][k+1], \n\t\tcube_points[i+0][j+1][k+1], \n\t\t};\n\n\treturn result;\n}\n\nstruct Point\nlin_interpol (struct Point a, struct Point b, GLfloat tx, GLfloat ty, GLfloat\n tz)\n{\n\tGLfloat new_x = a.x + (b.x - a.x) * tx;\t\n\tGLfloat new_y = a.y + (b.y - a.y) * ty;\t\n\tGLfloat new_z = a.z + (b.z - a.z) * tz;\t\n\t\t\t\t\n\tstruct Point result {new_x, new_y, new_z};\n\treturn result;\n}\n\nstd::vector \ncreate_menger_sponge(struct Cube base, unsigned int depth)\n{\n\tstd::stack> stack;\n\tstd::vector result;\n\t\t\n\tstack.push(std::make_pair(base, depth));\n\twhile (!stack.empty())\n\t{\n\t\tstd::pair top = stack.top();\t\n\t\tstack.pop();\n\n\t\tstruct Point a = top.first.points[0];\n\t\tstruct Point b = top.first.points[1];\n\t\tstruct Point c = top.first.points[2];\n\t\tstruct Point d = top.first.points[3];\n\t\tstruct Point e = top.first.points[4];\n\t\tstruct Point f = top.first.points[5];\n\t\tstruct Point g = top.first.points[6];\n\t\tstruct Point h = top.first.points[7];\n\n\t\tif (top.second == 0)\n\t\t{\n\t\t\tresult.push_back(make_quad(a, b, c, d));\n\t\t\tresult.push_back(make_quad(e, f, g, h));\n\t\t\tresult.push_back(make_quad(a, b, f, e));\n\t\t\tresult.push_back(make_quad(c, d, h, g));\n\t\t\tresult.push_back(make_quad(b, c, g, f));\n\t\t\tresult.push_back(make_quad(a, d, h, e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstruct Point cube[4][4][4];\n\t\t\tfor (int i = 0; i < 4; i++)\n\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\tfor (int k = 0; k < 4; k++)\n\t\t\t{\n\t\t\t\tcube[i][j][k] = lin_interpol(a, g, \n\t\t\t\t\t(GLfloat)i\/3.0, \n\t\t\t\t\t(GLfloat)j\/3.0, \n\t\t\t\t\t(GLfloat)k\/3.0);\n\t\t\t}\n\n\t\t\t\/\/ cube front face\n\t\t\tstruct Cube cf1 = cube_starting_with(0, 0, 0, cube);\n\t\t\tstruct Cube cf2 = cube_starting_with(1, 0, 0, cube);\n\t\t\tstruct Cube cf3 = cube_starting_with(2, 0, 0, cube);\n\t\t\tstruct Cube cf4 = cube_starting_with(0, 1, 0, cube);\n\t\t\tstruct Cube cf5 = cube_starting_with(2, 1, 0, cube);\n\t\t\tstruct Cube cf6 = cube_starting_with(0, 2, 0, cube);\n\t\t\tstruct Cube cf7 = cube_starting_with(1, 2, 0, cube);\n\t\t\tstruct Cube cf8 = cube_starting_with(2, 2, 0, cube);\n\n\t\t\t\/\/ cube back face\n\t\t\tstruct Cube cb1 = cube_starting_with(0, 0, 2, cube);\n\t\t\tstruct Cube cb2 = cube_starting_with(1, 0, 2, cube);\n\t\t\tstruct Cube cb3 = cube_starting_with(2, 0, 2, cube);\n\t\t\tstruct Cube cb4 = cube_starting_with(0, 1, 2, cube);\n\t\t\tstruct Cube cb5 = cube_starting_with(2, 1, 2, cube);\n\t\t\tstruct Cube cb6 = cube_starting_with(0, 2, 2, cube);\n\t\t\tstruct Cube cb7 = cube_starting_with(1, 2, 2, cube);\n\t\t\tstruct Cube cb8 = cube_starting_with(2, 2, 2, cube);\n\n\t\t\t\/\/ cube side faces\n\t\t\tstruct Cube cs1 = cube_starting_with(2, 0, 1, cube);\n\t\t\tstruct Cube cs2 = cube_starting_with(2, 2, 1, cube);\n\t\t\tstruct Cube cs3 = cube_starting_with(0, 0, 1, cube);\n\t\t\tstruct Cube cs4 = cube_starting_with(0, 2, 1, cube);\n\n\t\t\tstack.push(std::make_pair(cf1, top.second-1));\n\t\t\tstack.push(std::make_pair(cf2, top.second-1));\n\t\t\tstack.push(std::make_pair(cf3, top.second-1));\n\t\t\tstack.push(std::make_pair(cf4, top.second-1));\n\t\t\tstack.push(std::make_pair(cf5, top.second-1));\n\t\t\tstack.push(std::make_pair(cf6, top.second-1));\n\t\t\tstack.push(std::make_pair(cf7, top.second-1));\n\t\t\tstack.push(std::make_pair(cf8, top.second-1));\n\t\t\tstack.push(std::make_pair(cb1, top.second-1));\n\t\t\tstack.push(std::make_pair(cb2, top.second-1));\n\t\t\tstack.push(std::make_pair(cb3, top.second-1));\n\t\t\tstack.push(std::make_pair(cb4, top.second-1));\n\t\t\tstack.push(std::make_pair(cb5, top.second-1));\n\t\t\tstack.push(std::make_pair(cb6, top.second-1));\n\t\t\tstack.push(std::make_pair(cb7, top.second-1));\n\t\t\tstack.push(std::make_pair(cb8, top.second-1));\n\t\t\tstack.push(std::make_pair(cs1, top.second-1));\n\t\t\tstack.push(std::make_pair(cs2, top.second-1));\n\t\t\tstack.push(std::make_pair(cs3, top.second-1));\n\t\t\tstack.push(std::make_pair(cs4, top.second-1));\n\t\t}\n\t}\n\n\treturn result;\n}\n\n<|endoftext|>"} {"text":":lipstick: Remove unnsessary includes in test.cc<|endoftext|>"} {"text":"Define aliases for items in static_string namespace and rename sss<|endoftext|>"} {"text":"#include \"QZXingImageProvider.h\"\n#include \n#include \n#include \"QZXing.h\"\n\nQZXingImageProvider::QZXingImageProvider() : QQuickImageProvider(QQuickImageProvider::Image)\n{\n}\n\nQImage QZXingImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)\n{\n int slashIndex = id.indexOf('\/');\n if (slashIndex == -1)\n {\n qWarning() << \"Can't parse url\" << id << \". Usage is encode?\/\";\n return QImage();\n }\n\n \/\/Detect operation (ex. encode)\n QString operationName = id.left(slashIndex);\n if(operationName != \"encode\")\n {\n qWarning() << \"Operation not supported: \" << operationName;\n return QImage();\n }\n\n QString data;\n QZXing::EncoderFormat format = QZXing::EncoderFormat_QR_CODE;\n QZXing::EncodeErrorCorrectionLevel correctionLevel = QZXing::EncodeErrorCorrectionLevel_L;\n\n int customSettingsIndex = id.lastIndexOf(QRegExp(\"\\?[cf]\"));\n if(customSettingsIndex >= 0)\n {\n int startOfDataIndex = slashIndex + 1;\n data = id.mid(startOfDataIndex, customSettingsIndex - (startOfDataIndex));\n\n \/\/The dummy option has been added due to a bug(?) of QUrlQuery\n \/\/ it could not recognize the first key-value pair provided\n QUrlQuery optionQuery(\"options?dummy=&\" + id.mid(customSettingsIndex + 1));\n\n if (optionQuery.hasQueryItem(\"format\")) {\n QString formatString = optionQuery.queryItemValue(\"format\");\n if (formatString != \"qrcode\") {\n qWarning() << \"Format not supported: \" << formatString;\n return QImage();\n }\n }\n\n QString correctionLevelString = optionQuery.queryItemValue(\"corretionLevel\");\n if(correctionLevelString == \"H\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_H;\n else if(correctionLevelString == \"Q\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_Q;\n else if(correctionLevelString == \"M\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_M;\n else if(correctionLevelString == \"L\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_L;\n } else\n {\n data = id.mid(slashIndex + 1);\n }\n\n QImage result = QZXing::encodeData(data, format, requestedSize, correctionLevel);\n *size = result.size();\n return result;\n}\nenhance #140 with an even stricter regex expression to minimize possibility of conflict between actual data and encoding options. Fixes #139#include \"QZXingImageProvider.h\"\n#include \n#include \n#include \"QZXing.h\"\n\nQZXingImageProvider::QZXingImageProvider() : QQuickImageProvider(QQuickImageProvider::Image)\n{\n}\n\nQImage QZXingImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)\n{\n int slashIndex = id.indexOf('\/');\n if (slashIndex == -1)\n {\n qWarning() << \"Can't parse url\" << id << \". Usage is encode?\/\";\n return QImage();\n }\n\n \/\/Detect operation (ex. encode)\n QString operationName = id.left(slashIndex);\n if(operationName != \"encode\")\n {\n qWarning() << \"Operation not supported: \" << operationName;\n return QImage();\n }\n\n QString data;\n QZXing::EncoderFormat format = QZXing::EncoderFormat_QR_CODE;\n QZXing::EncodeErrorCorrectionLevel correctionLevel = QZXing::EncodeErrorCorrectionLevel_L;\n\n int customSettingsIndex = id.lastIndexOf(QRegExp(\"\\?(corretionLevel|format)=\"));\n if(customSettingsIndex >= 0)\n {\n int startOfDataIndex = slashIndex + 1;\n data = id.mid(startOfDataIndex, customSettingsIndex - (startOfDataIndex));\n\n \/\/The dummy option has been added due to a bug(?) of QUrlQuery\n \/\/ it could not recognize the first key-value pair provided\n QUrlQuery optionQuery(\"options?dummy=&\" + id.mid(customSettingsIndex + 1));\n\n if (optionQuery.hasQueryItem(\"format\")) {\n QString formatString = optionQuery.queryItemValue(\"format\");\n if (formatString != \"qrcode\") {\n qWarning() << \"Format not supported: \" << formatString;\n return QImage();\n }\n }\n\n QString correctionLevelString = optionQuery.queryItemValue(\"corretionLevel\");\n if(correctionLevelString == \"H\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_H;\n else if(correctionLevelString == \"Q\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_Q;\n else if(correctionLevelString == \"M\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_M;\n else if(correctionLevelString == \"L\")\n correctionLevel = QZXing::EncodeErrorCorrectionLevel_L;\n } else\n {\n data = id.mid(slashIndex + 1);\n }\n\n QImage result = QZXing::encodeData(data, format, requestedSize, correctionLevel);\n *size = result.size();\n return result;\n}\n<|endoftext|>"} {"text":"\/*\n * MIT License\n *\n * Copyright (c) 2016 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \n#include \"RtpBroadCaster.h\"\n#include \"Util\/util.h\"\n#include \"Network\/sockutil.h\"\n\nnamespace ZL {\nnamespace Rtsp {\n\n\nstd::shared_ptr MultiCastAddressMaker::obtain(uint32_t iTry) {\n\tlock_guard lck(m_mtx);\n\tstatic uint32_t addrMin = mINI::Instance()[Config::MultiCast::kAddrMin].as();\n\tstatic uint32_t addrMax = mINI::Instance()[Config::MultiCast::kAddrMax].as();\n\tif(m_iAddr > addrMax){\n\t\tm_iAddr = addrMin;\n\t}\n\tauto iGotAddr = m_iAddr++;\n\tif(m_setBadAddr.find(iGotAddr) != m_setBadAddr.end()){\n\t\t\/\/已经分配过了\n\t\tif(iTry){\n\t\t\treturn obtain(--iTry);\n\t\t}\n\t\t\/\/分配完了,应该不可能到这里\n\t\tFatalL;\n\t\treturn nullptr;\n\t}\n\tm_setBadAddr.emplace(iGotAddr);\n\tstd::shared_ptr ret(new uint32_t(iGotAddr),[](uint32_t *ptr){\n\t\tauto val = *ptr;\n\t\tMultiCastAddressMaker::Instance().release(val);\n\t\tdelete ptr;\n\t});\n\treturn ret;\n}\nvoid MultiCastAddressMaker::release(uint32_t iAddr){\n\tlock_guard lck(m_mtx);\n\tm_setBadAddr.erase(iAddr);\n}\n\n\nrecursive_mutex RtpBroadCaster::g_mtx;\nunordered_map > RtpBroadCaster::g_mapBroadCaster;\n\nvoid RtpBroadCaster::setDetachCB(void* listener, const onDetach& cb) {\n\tlock_guard lck(m_mtx);\n\tif(cb){\n\t\tm_mapDetach.emplace(listener,cb);\n\t}else{\n\t\tm_mapDetach.erase(listener);\n\t}\n}\nRtpBroadCaster::~RtpBroadCaster() {\n\tm_pReader->setReadCB(nullptr);\n\tm_pReader->setDetachCB(nullptr);\n\tDebugL;\n}\nRtpBroadCaster::RtpBroadCaster(const string &strLocalIp,const string &strApp,const string &strStream) {\n\tauto src = RtspMediaSource::find(strApp, strStream);\n\tif(!src){\n\t\tauto strErr = StrPrinter << \"未找到媒体源:\" << strApp << \" \" << strStream << endl;\n\t\tthrow std::runtime_error(strErr);\n\t}\n\tm_multiAddr = MultiCastAddressMaker::Instance().obtain();\n\tfor(auto i = 0; i < 2; i++){\n\t\tm_apUdpSock[i].reset(new Socket());\n\t\tif(!m_apUdpSock[i]->bindUdpSock(0, strLocalIp.data())){\n\t\t\tauto strErr = StrPrinter << \"绑定UDP端口失败:\" << strLocalIp << endl;\n\t\t\tthrow std::runtime_error(strErr);\n\t\t}\n\t\tauto fd = m_apUdpSock[i]->rawFD();\n\t\tstatic uint32_t udpTTL = mINI::Instance()[Config::MultiCast::kUdpTTL].as();\n\t\tSockUtil::setMultiTTL(fd, udpTTL);\n\t\tSockUtil::setMultiLOOP(fd, false);\n\t\tSockUtil::setMultiIF(fd, strLocalIp.data());\n\n\t\tstruct sockaddr_in &peerAddr = m_aPeerUdpAddr[i];\n\t\tpeerAddr.sin_family = AF_INET;\n\t\tpeerAddr.sin_port = htons(m_apUdpSock[i]->get_local_port());\n\t\tpeerAddr.sin_addr.s_addr = htonl(*m_multiAddr);\n\t\tbzero(&(peerAddr.sin_zero), sizeof peerAddr.sin_zero);\n\t}\n\tm_pReader = src->getRing()->attach();\n\tm_pReader->setReadCB([this](const RtpPacket::Ptr &pkt){\n\t\tint i = (pkt->interleaved\/2)%2;\n\t\tauto &pSock = m_apUdpSock[i];\n\t\tauto &peerAddr = m_aPeerUdpAddr[i];\n\t\tpSock->sendTo((char *) pkt->payload + 4, pkt->length - 4,(struct sockaddr *)(&peerAddr));\n\t});\n\tm_pReader->setDetachCB([this](){\n\t\tunordered_map m_mapDetach_copy;\n\t\t{\n\t\t\tlock_guard lck(m_mtx);\n\t\t\tm_mapDetach_copy.swap(m_mapDetach);\n\t\t}\n\t\tfor(auto &pr : m_mapDetach_copy){\n\t\t\tpr.second();\n\t\t}\n\t});\n\tDebugL << MultiCastAddressMaker::toString(*m_multiAddr) << \" \"\n\t\t\t<< m_apUdpSock[0]->get_local_port() << \" \"\n\t\t\t<< m_apUdpSock[1]->get_local_port() << \" \"\n\t\t\t<< strApp << \" \" << strStream;\n}\nuint16_t RtpBroadCaster::getPort(int iTrackId){\n\tint i = iTrackId%2;\n\treturn m_apUdpSock[i]->get_local_port();\n}\nstring RtpBroadCaster::getIP(){\n\treturn inet_ntoa(m_aPeerUdpAddr[0].sin_addr);\n}\nRtpBroadCaster::Ptr RtpBroadCaster::make(const string &strLocalIp,const string &strApp,const string &strStream){\n\ttry{\n\t\tauto ret = Ptr(new RtpBroadCaster(strLocalIp,strApp,strStream));\n\t\tlock_guard lck(g_mtx);\n\t\tstring strKey = StrPrinter << strLocalIp << \" \" << strApp << \" \" << strStream << endl;\n\t\tweak_ptr weakPtr = ret;\n\t\tg_mapBroadCaster.emplace(strKey,weakPtr);\n\t\treturn ret;\n\t}catch (std::exception &ex) {\n\t\tWarnL << ex.what();\n\t\treturn nullptr;\n\t}\n}\n\nRtpBroadCaster::Ptr RtpBroadCaster::get(const string &strLocalIp,const string& strApp, const string& strStream) {\n\tstring strKey = StrPrinter << strLocalIp << \" \" << strApp << \" \" << strStream << endl;\n\tlock_guard lck(g_mtx);\n\tauto it = g_mapBroadCaster.find(strKey);\n\tif (it == g_mapBroadCaster.end()) {\n\t\treturn make(strLocalIp,strApp, strStream);\n\t}\n\tauto ret = it->second.lock();\n\tif (!ret) {\n\t\tg_mapBroadCaster.erase(it);\n\t\treturn make(strLocalIp,strApp, strStream);\n\t}\n\treturn ret;\n}\n\n\n\n} \/* namespace Rtsp *\/\n} \/* namespace ZL *\/\n\n\n修复windows下编译不过的bug\/*\n * MIT License\n *\n * Copyright (c) 2016 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \n#include \n#include \"RtpBroadCaster.h\"\n#include \"Util\/util.h\"\n#include \"Network\/sockutil.h\"\nusing namespace std;\n\nnamespace ZL {\nnamespace Rtsp {\n\n\nstd::shared_ptr MultiCastAddressMaker::obtain(uint32_t iTry) {\n\tlock_guard lck(m_mtx);\n\tstatic uint32_t addrMin = mINI::Instance()[Config::MultiCast::kAddrMin].as();\n\tstatic uint32_t addrMax = mINI::Instance()[Config::MultiCast::kAddrMax].as();\n\tif(m_iAddr > addrMax){\n\t\tm_iAddr = addrMin;\n\t}\n\tauto iGotAddr = m_iAddr++;\n\tif(m_setBadAddr.find(iGotAddr) != m_setBadAddr.end()){\n\t\t\/\/已经分配过了\n\t\tif(iTry){\n\t\t\treturn obtain(--iTry);\n\t\t}\n\t\t\/\/分配完了,应该不可能到这里\n\t\tFatalL;\n\t\treturn nullptr;\n\t}\n\tm_setBadAddr.emplace(iGotAddr);\n\tstd::shared_ptr ret(new uint32_t(iGotAddr),[](uint32_t *ptr){\n\t\tauto val = *ptr;\n\t\tMultiCastAddressMaker::Instance().release(val);\n\t\tdelete ptr;\n\t});\n\treturn ret;\n}\nvoid MultiCastAddressMaker::release(uint32_t iAddr){\n\tlock_guard lck(m_mtx);\n\tm_setBadAddr.erase(iAddr);\n}\n\n\nrecursive_mutex RtpBroadCaster::g_mtx;\nunordered_map > RtpBroadCaster::g_mapBroadCaster;\n\nvoid RtpBroadCaster::setDetachCB(void* listener, const onDetach& cb) {\n\tlock_guard lck(m_mtx);\n\tif(cb){\n\t\tm_mapDetach.emplace(listener,cb);\n\t}else{\n\t\tm_mapDetach.erase(listener);\n\t}\n}\nRtpBroadCaster::~RtpBroadCaster() {\n\tm_pReader->setReadCB(nullptr);\n\tm_pReader->setDetachCB(nullptr);\n\tDebugL;\n}\nRtpBroadCaster::RtpBroadCaster(const string &strLocalIp,const string &strApp,const string &strStream) {\n\tauto src = RtspMediaSource::find(strApp, strStream);\n\tif(!src){\n\t\tauto strErr = StrPrinter << \"未找到媒体源:\" << strApp << \" \" << strStream << endl;\n\t\tthrow std::runtime_error(strErr);\n\t}\n\tm_multiAddr = MultiCastAddressMaker::Instance().obtain();\n\tfor(auto i = 0; i < 2; i++){\n\t\tm_apUdpSock[i].reset(new Socket());\n\t\tif(!m_apUdpSock[i]->bindUdpSock(0, strLocalIp.data())){\n\t\t\tauto strErr = StrPrinter << \"绑定UDP端口失败:\" << strLocalIp << endl;\n\t\t\tthrow std::runtime_error(strErr);\n\t\t}\n\t\tauto fd = m_apUdpSock[i]->rawFD();\n\t\tstatic uint32_t udpTTL = mINI::Instance()[Config::MultiCast::kUdpTTL].as();\n\t\tSockUtil::setMultiTTL(fd, udpTTL);\n\t\tSockUtil::setMultiLOOP(fd, false);\n\t\tSockUtil::setMultiIF(fd, strLocalIp.data());\n\n\t\tstruct sockaddr_in &peerAddr = m_aPeerUdpAddr[i];\n\t\tpeerAddr.sin_family = AF_INET;\n\t\tpeerAddr.sin_port = htons(m_apUdpSock[i]->get_local_port());\n\t\tpeerAddr.sin_addr.s_addr = htonl(*m_multiAddr);\n\t\tbzero(&(peerAddr.sin_zero), sizeof peerAddr.sin_zero);\n\t}\n\tm_pReader = src->getRing()->attach();\n\tm_pReader->setReadCB([this](const RtpPacket::Ptr &pkt){\n\t\tint i = (pkt->interleaved\/2)%2;\n\t\tauto &pSock = m_apUdpSock[i];\n\t\tauto &peerAddr = m_aPeerUdpAddr[i];\n\t\tpSock->sendTo((char *) pkt->payload + 4, pkt->length - 4,(struct sockaddr *)(&peerAddr));\n\t});\n\tm_pReader->setDetachCB([this](){\n\t\tunordered_map m_mapDetach_copy;\n\t\t{\n\t\t\tlock_guard lck(m_mtx);\n\t\t\tm_mapDetach_copy = std::move(m_mapDetach);\n\t\t}\n\t\tfor(auto &pr : m_mapDetach_copy){\n\t\t\tpr.second();\n\t\t}\n\t});\n\tDebugL << MultiCastAddressMaker::toString(*m_multiAddr) << \" \"\n\t\t\t<< m_apUdpSock[0]->get_local_port() << \" \"\n\t\t\t<< m_apUdpSock[1]->get_local_port() << \" \"\n\t\t\t<< strApp << \" \" << strStream;\n}\nuint16_t RtpBroadCaster::getPort(int iTrackId){\n\tint i = iTrackId%2;\n\treturn m_apUdpSock[i]->get_local_port();\n}\nstring RtpBroadCaster::getIP(){\n\treturn inet_ntoa(m_aPeerUdpAddr[0].sin_addr);\n}\nRtpBroadCaster::Ptr RtpBroadCaster::make(const string &strLocalIp,const string &strApp,const string &strStream){\n\ttry{\n\t\tauto ret = Ptr(new RtpBroadCaster(strLocalIp,strApp,strStream));\n\t\tlock_guard lck(g_mtx);\n\t\tstring strKey = StrPrinter << strLocalIp << \" \" << strApp << \" \" << strStream << endl;\n\t\tweak_ptr weakPtr = ret;\n\t\tg_mapBroadCaster.emplace(strKey,weakPtr);\n\t\treturn ret;\n\t}catch (std::exception &ex) {\n\t\tWarnL << ex.what();\n\t\treturn nullptr;\n\t}\n}\n\nRtpBroadCaster::Ptr RtpBroadCaster::get(const string &strLocalIp,const string& strApp, const string& strStream) {\n\tstring strKey = StrPrinter << strLocalIp << \" \" << strApp << \" \" << strStream << endl;\n\tlock_guard lck(g_mtx);\n\tauto it = g_mapBroadCaster.find(strKey);\n\tif (it == g_mapBroadCaster.end()) {\n\t\treturn make(strLocalIp,strApp, strStream);\n\t}\n\tauto ret = it->second.lock();\n\tif (!ret) {\n\t\tg_mapBroadCaster.erase(it);\n\t\treturn make(strLocalIp,strApp, strStream);\n\t}\n\treturn ret;\n}\n\n\n\n} \/* namespace Rtsp *\/\n} \/* namespace ZL *\/\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#define LEATHERMAN_LOGGING_NAMESPACE \"puppetlabs.pxp_agent.external_module\"\n#include \n\n#include \/\/ this_thread::sleep_for\n#include \n\n#include \n#include \n\n#include \n#include \/\/ std::shared_ptr\n#include \/\/ std::move\n\n\/\/ TODO(ale): disable assert() once we're confident with the code...\n\/\/ To disable assert()\n\/\/ #define NDEBUG\n#include \n\nnamespace PXPAgent {\n\nstatic const std::string METADATA_SCHEMA_NAME { \"external_module_metadata\" };\nstatic const std::string ACTION_SCHEMA_NAME { \"action_metadata\" };\n\nstatic const std::string METADATA_CONFIGURATION_ENTRY { \"configuration\" };\nstatic const std::string METADATA_ACTIONS_ENTRY { \"actions\" };\n\nstatic const int EXTERNAL_MODULE_FILE_ERROR_EC { 5 };\n\nnamespace fs = boost::filesystem;\nnamespace lth_exec = leatherman::execution;\nnamespace lth_file = leatherman::file_util;\nnamespace lth_jc = leatherman::json_container;\nnamespace lth_loc = leatherman::locale;\nnamespace pcp_util = PCPClient::Util;\n\n\/\/\n\/\/ Free functions\n\/\/\n\n\/\/ Provides the module metadata validator\nPCPClient::Validator getMetadataValidator()\n{\n \/\/ Metadata schema\n PCPClient::Schema metadata_schema { METADATA_SCHEMA_NAME,\n PCPClient::ContentType::Json };\n using T_C = PCPClient::TypeConstraint;\n metadata_schema.addConstraint(\"description\", T_C::String, true);\n metadata_schema.addConstraint(METADATA_CONFIGURATION_ENTRY, T_C::Object, false);\n metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, T_C::Array, true);\n\n \/\/ 'actions' is an array of actions; define the action sub_schema\n PCPClient::Schema action_schema { ACTION_SCHEMA_NAME,\n PCPClient::ContentType::Json };\n action_schema.addConstraint(\"description\", T_C::String, false);\n action_schema.addConstraint(\"name\", T_C::String, true);\n action_schema.addConstraint(\"input\", T_C::Object, true);\n action_schema.addConstraint(\"results\", T_C::Object, true);\n\n metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, action_schema, false);\n\n PCPClient::Validator validator {};\n validator.registerSchema(metadata_schema);\n return validator;\n}\n\n\/\/\n\/\/ Public interface\n\/\/\n\nExternalModule::ExternalModule(const std::string& path,\n const lth_jc::JsonContainer& config,\n const std::string& spool_dir)\n : path_ { path },\n config_ { config },\n storage_ { spool_dir }\n{\n fs::path module_path { path };\n module_name = module_path.stem().string();\n auto metadata = getModuleMetadata();\n\n try {\n if (metadata.includes(METADATA_CONFIGURATION_ENTRY)) {\n registerConfiguration(\n metadata.get(METADATA_CONFIGURATION_ENTRY));\n } else {\n LOG_DEBUG(\"Found no configuration schema for module '{1}'\", module_name);\n }\n\n registerActions(metadata);\n } catch (lth_jc::data_error& e) {\n LOG_ERROR(\"Failed to retrieve metadata of module {1}: {2}\",\n module_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid metadata of module {1}\", module_name) };\n }\n}\n\nExternalModule::ExternalModule(const std::string& path,\n const std::string& spool_dir)\n : path_ { path },\n config_ { \"{}\" },\n storage_ { spool_dir }\n{\n fs::path module_path { path };\n module_name = module_path.stem().string();\n auto metadata = getModuleMetadata();\n\n try {\n registerActions(metadata);\n } catch (lth_jc::data_error& e) {\n LOG_ERROR(\"Failed to retrieve metadata of module {1}: {2}\",\n module_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid metadata of module {1}\", module_name) };\n }\n}\n\nvoid ExternalModule::validateConfiguration()\n{\n if (config_validator_.includesSchema(module_name)) {\n config_validator_.validate(config_, module_name);\n } else {\n LOG_DEBUG(\"The '{1}' configuration will not be validated; no JSON \"\n \"schema is available\", module_name);\n }\n}\n\n\/\/\n\/\/ Static class members\n\/\/\n\nconst int ExternalModule::OUTPUT_DELAY_MS { 100 };\n\nvoid ExternalModule::processOutputAndUpdateMetadata(ActionResponse& response)\n{\n if (response.output.std_out.empty()) {\n LOG_TRACE(\"Obtained no results on stdout for the {1}\",\n response.prettyRequestLabel());\n } else {\n LOG_TRACE(\"Results on stdout for the {1}: {2}\",\n response.prettyRequestLabel(), response.output.std_out);\n }\n\n if (response.output.exitcode != EXIT_SUCCESS) {\n LOG_TRACE(\"Execution failure (exit code {1}) for the {2}{3}\",\n response.output.exitcode, response.prettyRequestLabel(),\n (response.output.std_err.empty()\n ? \"\"\n : \"; stderr:\\n\" + response.output.std_err));\n } else if (!response.output.std_err.empty()) {\n LOG_TRACE(\"Output on stderr for the {1}:\\n{2}\",\n response.prettyRequestLabel(), response.output.std_err);\n }\n\n try {\n \/\/ Ensure output format is valid JSON by instantiating\n \/\/ JsonContainer (NB: its ctor does not accept empty strings)\n lth_jc::JsonContainer results {\n (response.output.std_out.empty() ? \"null\" : response.output.std_out) };\n response.setValidResultsAndEnd(std::move(results));\n } catch (lth_jc::data_parse_error& e) {\n LOG_DEBUG(\"Obtained invalid JSON on stdout for the {1}; (validation \"\n \"error: {2}); stdout:\\n{3}\",\n response.prettyRequestLabel(), e.what(), response.output.std_out);\n std::string execution_error {\n lth_loc::format(\"The task executed for the {1} returned invalid \"\n \"JSON on stdout - stderr:{2}\",\n response.prettyRequestLabel(),\n (response.output.std_err.empty()\n ? lth_loc::translate(\" (empty)\")\n : \"\\n\" + response.output.std_err)) };\n response.setBadResultsAndEnd(execution_error);\n }\n}\n\n\/\/\n\/\/ Private interface\n\/\/\n\n\/\/ Metadata validator (static member)\nconst PCPClient::Validator ExternalModule::metadata_validator_ {\n getMetadataValidator() };\n\n\/\/ Retrieve and validate the module's metadata\nconst lth_jc::JsonContainer ExternalModule::getModuleMetadata()\n{\n auto exec =\n#ifdef _WIN32\n lth_exec::execute(\"cmd.exe\", { \"\/c\", path_, \"metadata\" },\n#else\n lth_exec::execute(path_, { \"metadata\" },\n#endif\n 0, {lth_exec::execution_options::merge_environment,\n lth_exec::execution_options::inherit_locale});\n\n if (!exec.error.empty()) {\n LOG_ERROR(\"Failed to load the external module metadata from {1}: {2}\",\n path_, exec.error);\n throw Module::LoadingError {\n lth_loc::translate(\"failed to load external module metadata\") };\n }\n\n lth_jc::JsonContainer metadata;\n\n try {\n metadata = lth_jc::JsonContainer { exec.output };\n LOG_DEBUG(\"External module {1}: metadata is valid JSON\", module_name);\n } catch (lth_jc::data_error& e) {\n throw Module::LoadingError {\n lth_loc::format(\"metadata is not in a valid JSON format: {1}\", e.what()) };\n }\n\n try {\n metadata_validator_.validate(metadata, METADATA_SCHEMA_NAME);\n LOG_DEBUG(\"External module {1}: metadata validation OK\", module_name);\n } catch (PCPClient::validation_error& e) {\n throw Module::LoadingError {\n lth_loc::format(\"metadata validation failure: {1}\", e.what()) };\n }\n\n return metadata;\n}\n\nvoid ExternalModule::registerConfiguration(const lth_jc::JsonContainer& config_metadata)\n{\n try {\n PCPClient::Schema configuration_schema { module_name, config_metadata };\n LOG_DEBUG(\"Registering module configuration schema for '{1}'\", module_name);\n config_validator_.registerSchema(configuration_schema);\n } catch (PCPClient::schema_error& e) {\n LOG_ERROR(\"Failed to parse the configuration schema of module '{1}': {2}\",\n module_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid configuration schema of module {1}\", module_name) };\n }\n}\n\nvoid ExternalModule::registerActions(const lth_jc::JsonContainer& metadata)\n{\n for (auto& action\n : metadata.get>(METADATA_ACTIONS_ENTRY))\n registerAction(action);\n}\n\n\/\/ Register the specified action after ensuring that the input and\n\/\/ output schemas are valid JSON (i.e. we can instantiate Schema).\nvoid ExternalModule::registerAction(const lth_jc::JsonContainer& action)\n{\n \/\/ NOTE(ale): name, input, and output are required action entries\n auto action_name = action.get(\"name\");\n LOG_DEBUG(\"Validating action '{1} {2}'\", module_name, action_name);\n\n try {\n auto input_schema_json = action.get(\"input\");\n PCPClient::Schema input_schema { action_name, input_schema_json };\n\n auto results_schema_json = action.get(\"results\");\n PCPClient::Schema results_schema { action_name, results_schema_json };\n\n \/\/ Metadata schemas are valid JSON; store metadata\n LOG_DEBUG(\"Action '{1} {2}' has been validated\", module_name, action_name);\n actions.push_back(action_name);\n input_validator_.registerSchema(input_schema);\n results_validator_.registerSchema(results_schema);\n } catch (PCPClient::schema_error& e) {\n LOG_ERROR(\"Failed to parse metadata schemas of action '{1} {2}': {3}\",\n module_name, action_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid schemas of '{1} {2}'\", module_name, action_name) };\n } catch (lth_jc::data_error& e) {\n LOG_ERROR(\"Failed to retrieve metadata schemas of action '{1} {2}': {3}\",\n module_name, action_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid metadata of '{1} {2}'\", module_name, action_name) };\n }\n}\n\nstd::string ExternalModule::getActionArguments(const ActionRequest& request)\n{\n lth_jc::JsonContainer action_args {};\n action_args.set(\"input\", request.params());\n\n if (!config_.empty())\n action_args.set(\"configuration\", config_);\n\n if (request.type() == RequestType::NonBlocking) {\n fs::path r_d_p { request.resultsDir() };\n lth_jc::JsonContainer output_files {};\n output_files.set(\"stdout\", (r_d_p \/ \"stdout\").string());\n output_files.set(\"stderr\", (r_d_p \/ \"stderr\").string());\n output_files.set(\"exitcode\", (r_d_p \/ \"exitcode\").string());\n action_args.set(\"output_files\", output_files);\n }\n\n return action_args.toString();\n}\n\nActionResponse ExternalModule::callBlockingAction(const ActionRequest& request)\n{\n ActionResponse response { ModuleType::External, request };\n auto action_name = request.action();\n auto action_args = getActionArguments(request);\n\n LOG_INFO(\"Executing the {1}\", request.prettyLabel());\n LOG_TRACE(\"Input for the {1}: {2}\", request.prettyLabel(), action_args);\n\n auto exec = lth_exec::execute(\n#ifdef _WIN32\n \"cmd.exe\", { \"\/c\", path_, action_name },\n#else\n path_, { action_name },\n#endif\n action_args, \/\/ args\n std::map(), \/\/ environment\n 0, \/\/ timeout\n { lth_exec::execution_options::merge_environment,\n lth_exec::execution_options::inherit_locale }); \/\/ options\n\n response.output = ActionOutput { exec.exit_code, exec.output, exec.error };\n ExternalModule::processOutputAndUpdateMetadata(response);\n return response;\n}\n\nActionResponse ExternalModule::callNonBlockingAction(const ActionRequest& request)\n{\n ActionResponse response { ModuleType::External, request };\n auto action_name = request.action();\n auto input_txt = getActionArguments(request);\n fs::path results_dir_path { request.resultsDir() };\n\n LOG_INFO(\"Starting a task for the {1}; stdout and stderr will be stored in {2}\",\n request.prettyLabel(), request.resultsDir());\n LOG_TRACE(\"Input for the {1}: {2}\", request.prettyLabel(), input_txt);\n\n \/\/ NOTE(ale,mruzicka): to avoid terminating the entire process\n \/\/ tree when the pxp-agent service stops, we use the\n \/\/ `create_detached_process` execution option which ensures\n \/\/ the child process is executed in a new process contract\n \/\/ on Solaris and a new process group on Windows\n\n auto exec = lth_exec::execute(\n#ifdef _WIN32\n \"cmd.exe\", { \"\/c\", path_, action_name },\n#else\n path_, { action_name },\n#endif\n input_txt, \/\/ input arguments, passed via stdin\n std::map(), \/\/ environment\n [results_dir_path](size_t pid) {\n auto pid_file = (results_dir_path \/ \"pid\").string();\n lth_file::atomic_write_to_file(std::to_string(pid) + \"\\n\", pid_file);\n }, \/\/ pid callback\n 0, \/\/ timeout\n { lth_exec::execution_options::create_detached_process,\n lth_exec::execution_options::merge_environment,\n lth_exec::execution_options::inherit_locale }); \/\/ options\n\n LOG_INFO(\"The task for the {1} has completed\", request.prettyLabel());\n\n if (exec.exit_code == EXTERNAL_MODULE_FILE_ERROR_EC) {\n \/\/ This is unexpected. The output of the task will not be\n \/\/ available for future transaction status requests; we cannot\n \/\/ provide a reliable ActionResponse.\n std::string empty_label { lth_loc::translate(\"(empty)\") };\n LOG_WARNING(\"The task process failed to write output on file for the {1}; \"\n \"stdout: {2}; stderr: {3}\",\n request.prettyLabel(),\n (exec.output.empty() ? empty_label : exec.output),\n (exec.error.empty() ? empty_label : exec.error));\n throw Module::ProcessingError {\n lth_loc::translate(\"failed to write output on file\") };\n }\n\n \/\/ Wait a bit to relax the requirement for the exitcode file being\n \/\/ written before the output ones, when the process completes\n LOG_TRACE(\"Waiting {1} ms before retrieving the output of {2}\",\n OUTPUT_DELAY_MS, request.prettyLabel());\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::milliseconds(OUTPUT_DELAY_MS));\n\n \/\/ Stdout \/ stderr output should be on file; read it\n response.output = storage_.getOutput(request.transactionId(), exec.exit_code);\n ExternalModule::processOutputAndUpdateMetadata(response);\n return response;\n}\n\nActionResponse ExternalModule::callAction(const ActionRequest& request)\n{\n if (request.type() == RequestType::Blocking) {\n return callBlockingAction(request);\n } else {\n \/\/ Guranteed by Configuration\n assert(!request.resultsDir().empty());\n return callNonBlockingAction(request);\n }\n}\n\n} \/\/ namespace PXPAgent\n(PCP-704) Use fork() to prevent deadlocks#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#define LEATHERMAN_LOGGING_NAMESPACE \"puppetlabs.pxp_agent.external_module\"\n#include \n\n#include \/\/ this_thread::sleep_for\n#include \n\n#include \n#include \n\n#include \n#include \/\/ std::shared_ptr\n#include \/\/ std::move\n\n\/\/ TODO(ale): disable assert() once we're confident with the code...\n\/\/ To disable assert()\n\/\/ #define NDEBUG\n#include \n\nnamespace PXPAgent {\n\nstatic const std::string METADATA_SCHEMA_NAME { \"external_module_metadata\" };\nstatic const std::string ACTION_SCHEMA_NAME { \"action_metadata\" };\n\nstatic const std::string METADATA_CONFIGURATION_ENTRY { \"configuration\" };\nstatic const std::string METADATA_ACTIONS_ENTRY { \"actions\" };\n\nstatic const int EXTERNAL_MODULE_FILE_ERROR_EC { 5 };\n\nnamespace fs = boost::filesystem;\nnamespace lth_exec = leatherman::execution;\nnamespace lth_file = leatherman::file_util;\nnamespace lth_jc = leatherman::json_container;\nnamespace lth_loc = leatherman::locale;\nnamespace pcp_util = PCPClient::Util;\n\n\/\/\n\/\/ Free functions\n\/\/\n\n\/\/ Provides the module metadata validator\nPCPClient::Validator getMetadataValidator()\n{\n \/\/ Metadata schema\n PCPClient::Schema metadata_schema { METADATA_SCHEMA_NAME,\n PCPClient::ContentType::Json };\n using T_C = PCPClient::TypeConstraint;\n metadata_schema.addConstraint(\"description\", T_C::String, true);\n metadata_schema.addConstraint(METADATA_CONFIGURATION_ENTRY, T_C::Object, false);\n metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, T_C::Array, true);\n\n \/\/ 'actions' is an array of actions; define the action sub_schema\n PCPClient::Schema action_schema { ACTION_SCHEMA_NAME,\n PCPClient::ContentType::Json };\n action_schema.addConstraint(\"description\", T_C::String, false);\n action_schema.addConstraint(\"name\", T_C::String, true);\n action_schema.addConstraint(\"input\", T_C::Object, true);\n action_schema.addConstraint(\"results\", T_C::Object, true);\n\n metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, action_schema, false);\n\n PCPClient::Validator validator {};\n validator.registerSchema(metadata_schema);\n return validator;\n}\n\n\/\/\n\/\/ Public interface\n\/\/\n\nExternalModule::ExternalModule(const std::string& path,\n const lth_jc::JsonContainer& config,\n const std::string& spool_dir)\n : path_ { path },\n config_ { config },\n storage_ { spool_dir }\n{\n fs::path module_path { path };\n module_name = module_path.stem().string();\n auto metadata = getModuleMetadata();\n\n try {\n if (metadata.includes(METADATA_CONFIGURATION_ENTRY)) {\n registerConfiguration(\n metadata.get(METADATA_CONFIGURATION_ENTRY));\n } else {\n LOG_DEBUG(\"Found no configuration schema for module '{1}'\", module_name);\n }\n\n registerActions(metadata);\n } catch (lth_jc::data_error& e) {\n LOG_ERROR(\"Failed to retrieve metadata of module {1}: {2}\",\n module_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid metadata of module {1}\", module_name) };\n }\n}\n\nExternalModule::ExternalModule(const std::string& path,\n const std::string& spool_dir)\n : path_ { path },\n config_ { \"{}\" },\n storage_ { spool_dir }\n{\n fs::path module_path { path };\n module_name = module_path.stem().string();\n auto metadata = getModuleMetadata();\n\n try {\n registerActions(metadata);\n } catch (lth_jc::data_error& e) {\n LOG_ERROR(\"Failed to retrieve metadata of module {1}: {2}\",\n module_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid metadata of module {1}\", module_name) };\n }\n}\n\nvoid ExternalModule::validateConfiguration()\n{\n if (config_validator_.includesSchema(module_name)) {\n config_validator_.validate(config_, module_name);\n } else {\n LOG_DEBUG(\"The '{1}' configuration will not be validated; no JSON \"\n \"schema is available\", module_name);\n }\n}\n\n\/\/\n\/\/ Static class members\n\/\/\n\nconst int ExternalModule::OUTPUT_DELAY_MS { 100 };\n\nvoid ExternalModule::processOutputAndUpdateMetadata(ActionResponse& response)\n{\n if (response.output.std_out.empty()) {\n LOG_TRACE(\"Obtained no results on stdout for the {1}\",\n response.prettyRequestLabel());\n } else {\n LOG_TRACE(\"Results on stdout for the {1}: {2}\",\n response.prettyRequestLabel(), response.output.std_out);\n }\n\n if (response.output.exitcode != EXIT_SUCCESS) {\n LOG_TRACE(\"Execution failure (exit code {1}) for the {2}{3}\",\n response.output.exitcode, response.prettyRequestLabel(),\n (response.output.std_err.empty()\n ? \"\"\n : \"; stderr:\\n\" + response.output.std_err));\n } else if (!response.output.std_err.empty()) {\n LOG_TRACE(\"Output on stderr for the {1}:\\n{2}\",\n response.prettyRequestLabel(), response.output.std_err);\n }\n\n try {\n \/\/ Ensure output format is valid JSON by instantiating\n \/\/ JsonContainer (NB: its ctor does not accept empty strings)\n lth_jc::JsonContainer results {\n (response.output.std_out.empty() ? \"null\" : response.output.std_out) };\n response.setValidResultsAndEnd(std::move(results));\n } catch (lth_jc::data_parse_error& e) {\n LOG_DEBUG(\"Obtained invalid JSON on stdout for the {1}; (validation \"\n \"error: {2}); stdout:\\n{3}\",\n response.prettyRequestLabel(), e.what(), response.output.std_out);\n std::string execution_error {\n lth_loc::format(\"The task executed for the {1} returned invalid \"\n \"JSON on stdout - stderr:{2}\",\n response.prettyRequestLabel(),\n (response.output.std_err.empty()\n ? lth_loc::translate(\" (empty)\")\n : \"\\n\" + response.output.std_err)) };\n response.setBadResultsAndEnd(execution_error);\n }\n}\n\n\/\/\n\/\/ Private interface\n\/\/\n\n\/\/ Metadata validator (static member)\nconst PCPClient::Validator ExternalModule::metadata_validator_ {\n getMetadataValidator() };\n\n\/\/ Retrieve and validate the module's metadata\nconst lth_jc::JsonContainer ExternalModule::getModuleMetadata()\n{\n auto exec =\n#ifdef _WIN32\n lth_exec::execute(\"cmd.exe\", { \"\/c\", path_, \"metadata\" },\n#else\n lth_exec::execute(path_, { \"metadata\" },\n#endif\n 0, {lth_exec::execution_options::thread_safe,\n lth_exec::execution_options::merge_environment,\n lth_exec::execution_options::inherit_locale});\n\n if (!exec.error.empty()) {\n LOG_ERROR(\"Failed to load the external module metadata from {1}: {2}\",\n path_, exec.error);\n throw Module::LoadingError {\n lth_loc::translate(\"failed to load external module metadata\") };\n }\n\n lth_jc::JsonContainer metadata;\n\n try {\n metadata = lth_jc::JsonContainer { exec.output };\n LOG_DEBUG(\"External module {1}: metadata is valid JSON\", module_name);\n } catch (lth_jc::data_error& e) {\n throw Module::LoadingError {\n lth_loc::format(\"metadata is not in a valid JSON format: {1}\", e.what()) };\n }\n\n try {\n metadata_validator_.validate(metadata, METADATA_SCHEMA_NAME);\n LOG_DEBUG(\"External module {1}: metadata validation OK\", module_name);\n } catch (PCPClient::validation_error& e) {\n throw Module::LoadingError {\n lth_loc::format(\"metadata validation failure: {1}\", e.what()) };\n }\n\n return metadata;\n}\n\nvoid ExternalModule::registerConfiguration(const lth_jc::JsonContainer& config_metadata)\n{\n try {\n PCPClient::Schema configuration_schema { module_name, config_metadata };\n LOG_DEBUG(\"Registering module configuration schema for '{1}'\", module_name);\n config_validator_.registerSchema(configuration_schema);\n } catch (PCPClient::schema_error& e) {\n LOG_ERROR(\"Failed to parse the configuration schema of module '{1}': {2}\",\n module_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid configuration schema of module {1}\", module_name) };\n }\n}\n\nvoid ExternalModule::registerActions(const lth_jc::JsonContainer& metadata)\n{\n for (auto& action\n : metadata.get>(METADATA_ACTIONS_ENTRY))\n registerAction(action);\n}\n\n\/\/ Register the specified action after ensuring that the input and\n\/\/ output schemas are valid JSON (i.e. we can instantiate Schema).\nvoid ExternalModule::registerAction(const lth_jc::JsonContainer& action)\n{\n \/\/ NOTE(ale): name, input, and output are required action entries\n auto action_name = action.get(\"name\");\n LOG_DEBUG(\"Validating action '{1} {2}'\", module_name, action_name);\n\n try {\n auto input_schema_json = action.get(\"input\");\n PCPClient::Schema input_schema { action_name, input_schema_json };\n\n auto results_schema_json = action.get(\"results\");\n PCPClient::Schema results_schema { action_name, results_schema_json };\n\n \/\/ Metadata schemas are valid JSON; store metadata\n LOG_DEBUG(\"Action '{1} {2}' has been validated\", module_name, action_name);\n actions.push_back(action_name);\n input_validator_.registerSchema(input_schema);\n results_validator_.registerSchema(results_schema);\n } catch (PCPClient::schema_error& e) {\n LOG_ERROR(\"Failed to parse metadata schemas of action '{1} {2}': {3}\",\n module_name, action_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid schemas of '{1} {2}'\", module_name, action_name) };\n } catch (lth_jc::data_error& e) {\n LOG_ERROR(\"Failed to retrieve metadata schemas of action '{1} {2}': {3}\",\n module_name, action_name, e.what());\n throw Module::LoadingError {\n lth_loc::format(\"invalid metadata of '{1} {2}'\", module_name, action_name) };\n }\n}\n\nstd::string ExternalModule::getActionArguments(const ActionRequest& request)\n{\n lth_jc::JsonContainer action_args {};\n action_args.set(\"input\", request.params());\n\n if (!config_.empty())\n action_args.set(\"configuration\", config_);\n\n if (request.type() == RequestType::NonBlocking) {\n fs::path r_d_p { request.resultsDir() };\n lth_jc::JsonContainer output_files {};\n output_files.set(\"stdout\", (r_d_p \/ \"stdout\").string());\n output_files.set(\"stderr\", (r_d_p \/ \"stderr\").string());\n output_files.set(\"exitcode\", (r_d_p \/ \"exitcode\").string());\n action_args.set(\"output_files\", output_files);\n }\n\n return action_args.toString();\n}\n\nActionResponse ExternalModule::callBlockingAction(const ActionRequest& request)\n{\n ActionResponse response { ModuleType::External, request };\n auto action_name = request.action();\n auto action_args = getActionArguments(request);\n\n LOG_INFO(\"Executing the {1}\", request.prettyLabel());\n LOG_TRACE(\"Input for the {1}: {2}\", request.prettyLabel(), action_args);\n\n auto exec = lth_exec::execute(\n#ifdef _WIN32\n \"cmd.exe\", { \"\/c\", path_, action_name },\n#else\n path_, { action_name },\n#endif\n action_args, \/\/ args\n std::map(), \/\/ environment\n 0, \/\/ timeout\n { lth_exec::execution_options::thread_safe,\n lth_exec::execution_options::merge_environment,\n lth_exec::execution_options::inherit_locale }); \/\/ options\n\n response.output = ActionOutput { exec.exit_code, exec.output, exec.error };\n ExternalModule::processOutputAndUpdateMetadata(response);\n return response;\n}\n\nActionResponse ExternalModule::callNonBlockingAction(const ActionRequest& request)\n{\n ActionResponse response { ModuleType::External, request };\n auto action_name = request.action();\n auto input_txt = getActionArguments(request);\n fs::path results_dir_path { request.resultsDir() };\n\n LOG_INFO(\"Starting a task for the {1}; stdout and stderr will be stored in {2}\",\n request.prettyLabel(), request.resultsDir());\n LOG_TRACE(\"Input for the {1}: {2}\", request.prettyLabel(), input_txt);\n\n \/\/ NOTE(ale,mruzicka): to avoid terminating the entire process\n \/\/ tree when the pxp-agent service stops, we use the\n \/\/ `create_detached_process` execution option which ensures\n \/\/ the child process is executed in a new process contract\n \/\/ on Solaris and a new process group on Windows\n\n auto exec = lth_exec::execute(\n#ifdef _WIN32\n \"cmd.exe\", { \"\/c\", path_, action_name },\n#else\n path_, { action_name },\n#endif\n input_txt, \/\/ input arguments, passed via stdin\n std::map(), \/\/ environment\n [results_dir_path](size_t pid) {\n auto pid_file = (results_dir_path \/ \"pid\").string();\n lth_file::atomic_write_to_file(std::to_string(pid) + \"\\n\", pid_file);\n }, \/\/ pid callback\n 0, \/\/ timeout\n { lth_exec::execution_options::thread_safe,\n lth_exec::execution_options::create_detached_process,\n lth_exec::execution_options::merge_environment,\n lth_exec::execution_options::inherit_locale }); \/\/ options\n\n LOG_INFO(\"The task for the {1} has completed\", request.prettyLabel());\n\n if (exec.exit_code == EXTERNAL_MODULE_FILE_ERROR_EC) {\n \/\/ This is unexpected. The output of the task will not be\n \/\/ available for future transaction status requests; we cannot\n \/\/ provide a reliable ActionResponse.\n std::string empty_label { lth_loc::translate(\"(empty)\") };\n LOG_WARNING(\"The task process failed to write output on file for the {1}; \"\n \"stdout: {2}; stderr: {3}\",\n request.prettyLabel(),\n (exec.output.empty() ? empty_label : exec.output),\n (exec.error.empty() ? empty_label : exec.error));\n throw Module::ProcessingError {\n lth_loc::translate(\"failed to write output on file\") };\n }\n\n \/\/ Wait a bit to relax the requirement for the exitcode file being\n \/\/ written before the output ones, when the process completes\n LOG_TRACE(\"Waiting {1} ms before retrieving the output of {2}\",\n OUTPUT_DELAY_MS, request.prettyLabel());\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::milliseconds(OUTPUT_DELAY_MS));\n\n \/\/ Stdout \/ stderr output should be on file; read it\n response.output = storage_.getOutput(request.transactionId(), exec.exit_code);\n ExternalModule::processOutputAndUpdateMetadata(response);\n return response;\n}\n\nActionResponse ExternalModule::callAction(const ActionRequest& request)\n{\n if (request.type() == RequestType::Blocking) {\n return callBlockingAction(request);\n } else {\n \/\/ Guranteed by Configuration\n assert(!request.resultsDir().empty());\n return callNonBlockingAction(request);\n }\n}\n\n} \/\/ namespace PXPAgent\n<|endoftext|>"} {"text":"#include \"image.h\"\n#include \"body.h\"\n#include \"font.h\"\n#include \"units.h\"\n#include \"linkedlist.h\"\n#include \"misc.h\"\n\n#include \n#include \n\nusing namespace std;\n\n\/\/pngwriter png;\n\nImage::Image(string filename, int w, int h, double _scale) {\n\tfileName = filename;\n\twidth = w;\n\theight = h;\n\tscale = _scale;\n\n\tpng = pngwriter(width, height, 0, filename.c_str());\n}\n\nvoid Image::Draw(int x, int y, int r, int g, int b) {\n\tdouble redValue = ((double)r \/ 255.0);\n\tdouble greenValue = ((double)g \/ 255.0);\n\tdouble blueValue = ((double)b \/ 255.0);\n\n\tpng.plot(x, y, redValue, greenValue, blueValue);\n}\n\nvoid Image::DrawLine(int x1, int y1, int x2, int y2, int r, int g, int b) {\n\tdouble redValue = ((double)r \/ 255.0);\n\tdouble greenValue = ((double)g \/ 255.0);\n\tdouble blueValue = ((double)b \/ 255.0);\n\n\tpng.line(x1, height - y1, x2, height - y2, redValue, greenValue, blueValue);\n}\n\nint Image::Scale(double coordinate, double scale) {\n\tint position = (int)(coordinate \/ AU * scale);\n\treturn position;\n}\n\nvoid Image::DrawBody(double x, double y, double radius, int r, int g, int b) {\n\tint xScaled = (width \/ 2) + Scale(x, scale);\n \tint yScaled = (height \/ 2) + Scale(y, scale);\n \tint radiusScaled = Scale(radius, scale);\n\n\tbool xValid = xScaled < width && xScaled >= 0;\n\tbool yValid = yScaled < height && yScaled >= 0;\n\n\tif (xValid && yValid) {\n\t\tdouble redValue = ((double)r \/ 255.0);\n\t\tdouble greenValue = ((double)g \/ 255.0);\n\t\tdouble blueValue = ((double)b \/ 255.0);\n\n\t\tif (radiusScaled == 0) {\n\t\t\tDraw(xScaled, yScaled, 255, 255, 255); \/\/ White pixels show up the best on the screen\n\t\t}\n\t\telse {\n\t\t\tpng.filledcircle(xScaled, yScaled, radiusScaled, redValue, greenValue, blueValue);\n\t\t}\n\n\t\t\/\/Draw(xScaled, yScaled, r, g, b);\n\t}\n}\n\nvoid Image::DrawAllBodies(List bodyList, int r, int g, int b) {\n\tBody * body = bodyList.GetHead();\n\twhile (body != NULL) {\n\t\tDrawBody(body->GetX(), body->GetY(), body->GetRadius(), r, g, b);\n\t\tbody = body->next;\n\t}\n}\n\nvoid Image::DrawTextArray(int textArray [5][5], int xStart, int yStart, int r, int g, int b) {\n\tfor (int y = 0; y < 5; y++)\n\t{\n\t\tfor (int x = 0; x < 5; x++)\n\t\t{\n\t\t\tif (textArray[y][x] == 0)\n\t\t\t{\n\t\t\t\tpng.plot(x + xStart, height - (y + yStart), 0.0, 0.0, 0.0);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpng.plot(x + xStart, height - (y + yStart), ((double)r \/ 255.0), ((double)g \/ 255.0), ((double)b \/ 255.0));\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Image::DrawText(string text, int x, int y, int r, int g, int b) {\n\tfor (size_t i = 0; i < text.length(); i++)\n\t{\n\t\tint c = (int)i;\n\n\t\t\/\/ Handle Alphabet\n\t\tif (tolower(text[c]) >= 97 && tolower(text[c]) <= 122)\n\t\t{\n\t\t\tint index = tolower(text[c]) - 97;\n\t\t\tDrawTextArray(fontAlphabet[index], x, y, r, g, b);\n\t\t}\n\n\t\t\/\/ Handle Numbers\n\t\telse if (tolower(text[c]) >= 48 && tolower(text[c]) <= 57)\n\t\t{\n\t\t\tint index = tolower(text[c]) - 48;\n\t\t\tDrawTextArray(fontNumbers[index], x, y, r, g, b);\n\t\t}\n\n\t\t\/\/ Handle Punctuation\n\t\telse\n\t\t{\n\t\t\tswitch (text[c])\n\t\t\t{\n\t\t\tcase '.':\n\t\t\t\tDrawTextArray(fontPERIOD, x, y, r, g, b);\n\t\t\t\tbreak;\n\t\t\tcase ':':\n\t\t\t\tDrawTextArray(fontCOLON, x, y, r, g, b);\n\t\t\t\tbreak;\n\t\t\tcase '-':\n\t\t\t\tDrawTextArray(fontHYPHEN, x, y, r, g, b);\n\t\t\t\tbreak;\n\t\t\tcase '\/':\n\t\t\t\tDrawTextArray(fontSLASH, x, y, r, g, b);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tx += fontWidth + kerning;\n\t}\n}\n\nvoid Image::DrawScale(double scale, int x, int y, int r, int g, int b) {\n\tif (scale >= 3.0) {\n\t\t\/\/ Long enough to a line\n\t\tdouble distanceOfScale = 1.0;\n\t\tstring scaleString = \"1 AU\";\n\n\t\t\/\/ Check if line + text will fit on screen\n\t\twhile (x + scale + 10 + (6 * scaleString.length()) >= width) {\n\t\t\tscale \/= 10;\n\t\t\tdistanceOfScale \/= 10;\n\t\t\tscaleString = RemoveTrailingZeroes(to_string(distanceOfScale)) + \" AU\";\n\t\t}\n\n\t\tDrawLine(x, y, x + scale, y, r, g, b);\n\t\tDraw(x, height - y + 1, r, g, b);\n\t\tDraw(x + scale, height - y + 1, r, g, b);\n\n\t\tDrawText(scaleString.c_str(), x + scale + 5, y - 2, r, g, b);\n\t}\n\telse {\n\t\t\/\/ Not long enough - just write a message\n\t\tstring scaleText = \"SCALE: \" + to_string(scale) + \" PX\/AU\";\n\t\tDrawText(scaleText.c_str(), x, y - 2, r, g, b);\n\t}\n}\n\nvoid Image::Save() {\n\tpng.close();\n}\nScale line now expands when zooming out#include \"image.h\"\n#include \"body.h\"\n#include \"font.h\"\n#include \"units.h\"\n#include \"linkedlist.h\"\n#include \"misc.h\"\n\n#include \n#include \n\nusing namespace std;\n\n\/\/pngwriter png;\n\nImage::Image(string filename, int w, int h, double _scale) {\n\tfileName = filename;\n\twidth = w;\n\theight = h;\n\tscale = _scale;\n\n\tpng = pngwriter(width, height, 0, filename.c_str());\n}\n\nvoid Image::Draw(int x, int y, int r, int g, int b) {\n\tdouble redValue = ((double)r \/ 255.0);\n\tdouble greenValue = ((double)g \/ 255.0);\n\tdouble blueValue = ((double)b \/ 255.0);\n\n\tpng.plot(x, y, redValue, greenValue, blueValue);\n}\n\nvoid Image::DrawLine(int x1, int y1, int x2, int y2, int r, int g, int b) {\n\tdouble redValue = ((double)r \/ 255.0);\n\tdouble greenValue = ((double)g \/ 255.0);\n\tdouble blueValue = ((double)b \/ 255.0);\n\n\tpng.line(x1, height - y1, x2, height - y2, redValue, greenValue, blueValue);\n}\n\nint Image::Scale(double coordinate, double scale) {\n\tint position = (int)(coordinate \/ AU * scale);\n\treturn position;\n}\n\nvoid Image::DrawBody(double x, double y, double radius, int r, int g, int b) {\n\tint xScaled = (width \/ 2) + Scale(x, scale);\n \tint yScaled = (height \/ 2) + Scale(y, scale);\n \tint radiusScaled = Scale(radius, scale);\n\n\tbool xValid = xScaled < width && xScaled >= 0;\n\tbool yValid = yScaled < height && yScaled >= 0;\n\n\tif (xValid && yValid) {\n\t\tdouble redValue = ((double)r \/ 255.0);\n\t\tdouble greenValue = ((double)g \/ 255.0);\n\t\tdouble blueValue = ((double)b \/ 255.0);\n\n\t\tif (radiusScaled == 0) {\n\t\t\tDraw(xScaled, yScaled, 255, 255, 255); \/\/ White pixels show up the best on the screen\n\t\t}\n\t\telse {\n\t\t\tpng.filledcircle(xScaled, yScaled, radiusScaled, redValue, greenValue, blueValue);\n\t\t}\n\n\t\t\/\/Draw(xScaled, yScaled, r, g, b);\n\t}\n}\n\nvoid Image::DrawAllBodies(List bodyList, int r, int g, int b) {\n\tBody * body = bodyList.GetHead();\n\twhile (body != NULL) {\n\t\tDrawBody(body->GetX(), body->GetY(), body->GetRadius(), r, g, b);\n\t\tbody = body->next;\n\t}\n}\n\nvoid Image::DrawTextArray(int textArray [5][5], int xStart, int yStart, int r, int g, int b) {\n\tfor (int y = 0; y < 5; y++)\n\t{\n\t\tfor (int x = 0; x < 5; x++)\n\t\t{\n\t\t\tif (textArray[y][x] == 0)\n\t\t\t{\n\t\t\t\tpng.plot(x + xStart, height - (y + yStart), 0.0, 0.0, 0.0);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpng.plot(x + xStart, height - (y + yStart), ((double)r \/ 255.0), ((double)g \/ 255.0), ((double)b \/ 255.0));\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Image::DrawText(string text, int x, int y, int r, int g, int b) {\n\tfor (size_t i = 0; i < text.length(); i++)\n\t{\n\t\tint c = (int)i;\n\n\t\t\/\/ Handle Alphabet\n\t\tif (tolower(text[c]) >= 97 && tolower(text[c]) <= 122)\n\t\t{\n\t\t\tint index = tolower(text[c]) - 97;\n\t\t\tDrawTextArray(fontAlphabet[index], x, y, r, g, b);\n\t\t}\n\n\t\t\/\/ Handle Numbers\n\t\telse if (tolower(text[c]) >= 48 && tolower(text[c]) <= 57)\n\t\t{\n\t\t\tint index = tolower(text[c]) - 48;\n\t\t\tDrawTextArray(fontNumbers[index], x, y, r, g, b);\n\t\t}\n\n\t\t\/\/ Handle Punctuation\n\t\telse\n\t\t{\n\t\t\tswitch (text[c])\n\t\t\t{\n\t\t\tcase '.':\n\t\t\t\tDrawTextArray(fontPERIOD, x, y, r, g, b);\n\t\t\t\tbreak;\n\t\t\tcase ':':\n\t\t\t\tDrawTextArray(fontCOLON, x, y, r, g, b);\n\t\t\t\tbreak;\n\t\t\tcase '-':\n\t\t\t\tDrawTextArray(fontHYPHEN, x, y, r, g, b);\n\t\t\t\tbreak;\n\t\t\tcase '\/':\n\t\t\t\tDrawTextArray(fontSLASH, x, y, r, g, b);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tx += fontWidth + kerning;\n\t}\n}\n\nvoid Image::DrawScale(double scale, int x, int y, int r, int g, int b) {\n\tdouble distanceOfScale = 1.0;\n\tstring scaleString = \"1.0 AU\";\n\n\tif (scale >= 3.0) {\n\t\t\/\/ Long enough to a line\n\t\t\/\/ Check if line + text will fit on screen\n\t\twhile (x + scale + 10 + (6 * scaleString.length()) >= width) {\n\t\t\tscale \/= 10;\n\t\t\tdistanceOfScale \/= 10;\n\t\t\tscaleString = RemoveTrailingZeroes(to_string(distanceOfScale)) + \" AU\";\n\t\t}\n\n\t\tDrawLine(x, y, x + scale, y, r, g, b);\n\t\tDraw(x, height - y + 1, r, g, b);\n\t\tDraw(x + scale, height - y + 1, r, g, b);\n\n\t\tDrawText(scaleString.c_str(), x + scale + 5, y - 2, r, g, b);\n\t}\n\telse {\n\t\t\/\/ Too short - must extend to fill screen\n\t\tscale *= 100;\n\t\tdistanceOfScale *= 100;\n\t\tscaleString = RemoveTrailingZeroes(to_string(distanceOfScale)) + \" AU\";\n\n\t\tDrawLine(x, y, x + scale, y, r, g, b);\n\t\tDraw(x, height - y + 1, r, g, b);\n\t\tDraw(x + scale, height - y + 1, r, g, b);\n\n\t\tDrawText(scaleString.c_str(), x + scale + 5, y - 2, r, g, b);\n\t}\n}\n\nvoid Image::Save() {\n\tpng.close();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"Tools\/general_utils.h\"\n#include \"Tools\/Exception\/exception.hpp\"\n\n#include \"general_utils.h\"\n\nstd::vector aff3ct::tools::split(const std::string &s, char delim)\n{\n\tstd::stringstream ss(s);\n\tstd::string item;\n\tstd::vector elems;\n\twhile (std::getline(ss, item, delim))\n\t\telems.push_back(std::move(item));\n\n\treturn elems;\n}\n\nstd::vector aff3ct::tools::split(const std::string &s)\n{\n\tstd::string buf; \/\/ have a buffer string\n\tstd::stringstream ss(s); \/\/ insert the string into a stream\n\tstd::vector tokens; \/\/ create vector to hold our words\n\n\twhile (ss >> buf)\n\t\ttokens.push_back(buf);\n\n\treturn tokens;\n}\n\nvoid aff3ct::tools::getline(std::istream &file, std::string &line)\n{\n\tif (file.eof() || file.fail() || file.bad())\n\t\tthrow runtime_error(__FILE__, __LINE__, __func__, \"Something went wrong when getting a new line.\");\n\n\twhile (std::getline(file, line))\n\t\tif (line[0] != '#' && !std::all_of(line.begin(),line.end(),isspace))\n\t\t\tbreak;\n}\n\ntemplate \nR aff3ct::tools::sigma_to_esn0(const R sigma, const int upsample_factor)\n{\n\tif (upsample_factor <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'upsample_factor' has to be greater than 0 ('upsample_factor' = \" << upsample_factor << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (sigma < (R)0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'sigma' has to be greater than 0 ('sigma' = \" << sigma << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (sigma == (R)0)\n\t{\n\t\tconst auto esn0 = std::numeric_limits::infinity();\n\t\treturn esn0;\n\t}\n\telse\n\t{\n\t\tconst auto esn0 = (R)10 * std::log10((R)upsample_factor \/ (sigma * sigma));\n\t\treturn esn0;\n\t}\n}\n\ntemplate \nR aff3ct::tools::esn0_to_sigma(const R esn0, const int upsample_factor)\n{\n\tif (upsample_factor <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'upsample_factor' has to be greater than 0 ('upsample_factor' = \" << upsample_factor << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tconst auto sigma = std::sqrt((R)upsample_factor \/ ((R)2 * std::pow((R)10, (esn0 \/ (R)10))));\n\treturn sigma;\n}\n\ntemplate \nR aff3ct::tools::esn0_to_ebn0(const R esn0, const R bit_rate, const int bps)\n{\n\tif (bit_rate <= (R)0 || bit_rate > (R)1)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bit_rate' has to be positive and smaller or equal to 1 ('bit_rate' = \" << bit_rate << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (bps <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bps' has to be greater than 0 ('bps' = \" << bps << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tconst auto ebn0 = esn0 - (R)10 * std::log10(bit_rate * (R)bps);\n\treturn ebn0;\n}\n\ntemplate \nR aff3ct::tools::ebn0_to_esn0(const R ebn0, const R bit_rate, const int bps)\n{\n\tif (bit_rate <= (R)0 || bit_rate > (R)1)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bit_rate' has to be positive and smaller or equal to 1 ('bit_rate' = \" << bit_rate << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (bps <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bps' has to be greater than 0 ('bps' = \" << bps << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tconst auto esn0 = ebn0 + (R)10 * std::log10(bit_rate * (R)bps);\n\treturn esn0;\n}\n\ntemplate \nstd::vector aff3ct::tools::generate_range(const std::vector>& range_description, const R default_step)\n{\n\tstd::vector range;\n\n\tfor (auto& s : range_description)\n\t{\n\t\tif (s.size() != 3 && s.size() != 2)\n\t\t{\n\t\t\tstd::stringstream message;\n\t\t\tmessage << \"'s.size()' has to be 2 or 3 ('s.size()' = \" << s.size() << \").\";\n\t\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t\t}\n\n\t\tR step = (s.size() == 3) ? s[1] : default_step;\n\n\t\tfor (R v = s.front(); v <= (s.back() + 0.0001f); v += step) \/\/ 0.0001f is a hack to avoid the miss of the last snr\n\t\t\trange.push_back(v);\n\t}\n\n\treturn range;\n}\n\n\/\/ ==================================================================================== explicit template instantiation\ntemplate float aff3ct::tools::sigma_to_esn0(const float, const int);\ntemplate double aff3ct::tools::sigma_to_esn0(const double, const int);\ntemplate float aff3ct::tools::esn0_to_sigma(const float, const int);\ntemplate double aff3ct::tools::esn0_to_sigma(const double, const int);\ntemplate float aff3ct::tools::esn0_to_ebn0 (const float, const float, const int);\ntemplate double aff3ct::tools::esn0_to_ebn0 (const double, const double, const int);\ntemplate float aff3ct::tools::ebn0_to_esn0 (const float, const float, const int);\ntemplate double aff3ct::tools::ebn0_to_esn0 (const double, const double, const int);\ntemplate std::vector aff3ct::tools::generate_range(const std::vector>&, const float );\ntemplate std::vector aff3ct::tools::generate_range(const std::vector>&, const double);\n\/\/ ==================================================================================== explicit template instantiation\nSort the computed range and parse it to have each SNR only once#include \n#include \n#include \n#include \n\n#include \"Tools\/Math\/utils.h\"\n#include \"Tools\/Exception\/exception.hpp\"\n\n#include \"general_utils.h\"\n\nstd::vector aff3ct::tools::split(const std::string &s, char delim)\n{\n\tstd::stringstream ss(s);\n\tstd::string item;\n\tstd::vector elems;\n\twhile (std::getline(ss, item, delim))\n\t\telems.push_back(std::move(item));\n\n\treturn elems;\n}\n\nstd::vector aff3ct::tools::split(const std::string &s)\n{\n\tstd::string buf; \/\/ have a buffer string\n\tstd::stringstream ss(s); \/\/ insert the string into a stream\n\tstd::vector tokens; \/\/ create vector to hold our words\n\n\twhile (ss >> buf)\n\t\ttokens.push_back(buf);\n\n\treturn tokens;\n}\n\nvoid aff3ct::tools::getline(std::istream &file, std::string &line)\n{\n\tif (file.eof() || file.fail() || file.bad())\n\t\tthrow runtime_error(__FILE__, __LINE__, __func__, \"Something went wrong when getting a new line.\");\n\n\twhile (std::getline(file, line))\n\t\tif (line[0] != '#' && !std::all_of(line.begin(),line.end(),isspace))\n\t\t\tbreak;\n}\n\ntemplate \nR aff3ct::tools::sigma_to_esn0(const R sigma, const int upsample_factor)\n{\n\tif (upsample_factor <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'upsample_factor' has to be greater than 0 ('upsample_factor' = \" << upsample_factor << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (sigma < (R)0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'sigma' has to be greater than 0 ('sigma' = \" << sigma << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (sigma == (R)0)\n\t{\n\t\tconst auto esn0 = std::numeric_limits::infinity();\n\t\treturn esn0;\n\t}\n\telse\n\t{\n\t\tconst auto esn0 = (R)10 * std::log10((R)upsample_factor \/ (sigma * sigma));\n\t\treturn esn0;\n\t}\n}\n\ntemplate \nR aff3ct::tools::esn0_to_sigma(const R esn0, const int upsample_factor)\n{\n\tif (upsample_factor <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'upsample_factor' has to be greater than 0 ('upsample_factor' = \" << upsample_factor << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tconst auto sigma = std::sqrt((R)upsample_factor \/ ((R)2 * std::pow((R)10, (esn0 \/ (R)10))));\n\treturn sigma;\n}\n\ntemplate \nR aff3ct::tools::esn0_to_ebn0(const R esn0, const R bit_rate, const int bps)\n{\n\tif (bit_rate <= (R)0 || bit_rate > (R)1)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bit_rate' has to be positive and smaller or equal to 1 ('bit_rate' = \" << bit_rate << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (bps <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bps' has to be greater than 0 ('bps' = \" << bps << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tconst auto ebn0 = esn0 - (R)10 * std::log10(bit_rate * (R)bps);\n\treturn ebn0;\n}\n\ntemplate \nR aff3ct::tools::ebn0_to_esn0(const R ebn0, const R bit_rate, const int bps)\n{\n\tif (bit_rate <= (R)0 || bit_rate > (R)1)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bit_rate' has to be positive and smaller or equal to 1 ('bit_rate' = \" << bit_rate << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (bps <= 0)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'bps' has to be greater than 0 ('bps' = \" << bps << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tconst auto esn0 = ebn0 + (R)10 * std::log10(bit_rate * (R)bps);\n\treturn esn0;\n}\n\ntemplate \nstd::vector aff3ct::tools::generate_range(const std::vector>& range_description, const R default_step)\n{\n\tstd::vector range;\n\n\tfor (auto& s : range_description)\n\t{\n\t\tif (s.size() != 3 && s.size() != 2)\n\t\t{\n\t\t\tstd::stringstream message;\n\t\t\tmessage << \"'s.size()' has to be 2 or 3 ('s.size()' = \" << s.size() << \").\";\n\t\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t\t}\n\n\t\tR step = (s.size() == 3) ? s[1] : default_step;\n\n\t\tfor (R v = s.front(); v <= (s.back() + 0.0001f); v += step) \/\/ 0.0001f is a hack to avoid the miss of the last snr\n\t\t\trange.push_back(v);\n\t}\n\n\tstd::sort (range.begin(), range.end());\n\tstd::unique(range.begin(), range.end(), comp_equal);\n\n\treturn range;\n}\n\n\/\/ ==================================================================================== explicit template instantiation\ntemplate float aff3ct::tools::sigma_to_esn0(const float, const int);\ntemplate double aff3ct::tools::sigma_to_esn0(const double, const int);\ntemplate float aff3ct::tools::esn0_to_sigma(const float, const int);\ntemplate double aff3ct::tools::esn0_to_sigma(const double, const int);\ntemplate float aff3ct::tools::esn0_to_ebn0 (const float, const float, const int);\ntemplate double aff3ct::tools::esn0_to_ebn0 (const double, const double, const int);\ntemplate float aff3ct::tools::ebn0_to_esn0 (const float, const float, const int);\ntemplate double aff3ct::tools::ebn0_to_esn0 (const double, const double, const int);\ntemplate std::vector aff3ct::tools::generate_range(const std::vector>&, const float );\ntemplate std::vector aff3ct::tools::generate_range(const std::vector>&, const double);\n\/\/ ==================================================================================== explicit template instantiation\n<|endoftext|>"} {"text":"\/\/ \n\/\/ File: map.cc\n\/\/ Author: ruehle\n\/\/\n\/\/ Created on April 13, 2007, 4:41 PM\n\/\/\n\n#include \"map.h\"\n#include \n#include \n\nusing namespace std;\n\nMap::~Map()\n{\n vector::iterator iter;\n for(iter=_maps.begin();iter!=_maps.end();++iter)\n delete (*iter); \n _maps.clear();\n}\n\nvoid Map::Apply(Molecule &in, Molecule &out)\n{\n vector::iterator iter;\n for(iter=_maps.begin();iter!=_maps.end();++iter)\n (*iter)->Apply(in, out);\n}\n\nvoid Map_Sphere::Apply(Molecule &in, Molecule &out)\n{\n vector::iterator iter;\n vec cg(0., 0., 0.), f(0.,0.,0.), vel(0.,0.,0.);\n bool bPos, bVel, bF;\n bPos=bVel=bF=false;\n for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n if(in.getBead((*iter)._in)->HasPos()) {\n cg += (*iter)._weight * in.getBead((*iter)._in)->getPos();\n bPos=true;\n }\n if(in.getBead((*iter)._in)->HasVel()) {\n vel += (*iter)._weight * in.getBead((*iter)._in)->getVel();\n bVel = true;\n }\n if(in.getBead((*iter)._in)->HasF()) {\n \/\/\/ \\todo fix me, right calculation should be F_i = m_cg \/ sum(w_i) * sum(w_i\/m_i*F_i)\n \/\/f += (*iter)._weight * in.getBeadF((*iter)._in);\n f += in.getBead((*iter)._in)->getF();\n bF = true;\n }\n }\n if(bPos)\n out.getBead(_out)->setPos(cg);\n if(bVel)\n out.getBead(_out)->setVel(vel);\n if(bF)\n out.getBead(_out)->setF(f);\n}\n\n\/\/\/ \\todo implement this function\nvoid Map_Ellipsoid::Apply(Molecule &in, Molecule &out)\n{\n vector::iterator iter;\n vec cg(0., 0., 0.), c(0., 0., 0.), f(0.,0.,0.), vel(0.,0.,0.);\n matrix m(0.);\n bool bPos, bVel, bF;\n bPos=bVel=bF=false;\n \n int n;\n n = 0;\n for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n if(in.getBead((*iter)._in)->HasPos()) {\n cg += (*iter)._weight * in.getBead((*iter)._in)->getPos();\n bPos=true;\n }\n if(in.getBead((*iter)._in)->HasVel() == true) {\n vel += (*iter)._weight * in.getBead((*iter)._in)->getVel();\n bVel = true;\n }\n if(in.getBead((*iter)._in)->HasF()) {\n \/\/\/ \\todo fix me, right calculation should be F_i = m_cg \/ sum(w_i) * sum(w_i\/m_i*F_i)\n \/\/f += (*iter)._weight * in.getBeadF((*iter)._in);\n f += in.getBead((*iter)._in)->getF();\n bF = true;\n }\n \n if((*iter)._weight>0) {\n c += in.getBead((*iter)._in)->getPos();\n n++;\n }\n }\n \n if(bPos)\n out.getBead(_out)->setPos(cg);\n if(bVel)\n out.getBead(_out)->setVel(vel);\n if(bF)\n out.getBead(_out)->setF(f);\n \n \/\/ calculate the tensor of gyration\n c=c\/(double)n; \n for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n if((*iter)._weight == 0) continue;\n vec v = (in.getBead((*iter)._in)->getPos() - c);\n \/\/v = vec(1, 0.5, 0) * 0.*(drand48()-0.5)\n \/\/ + vec(0.5, -1, 0) * (drand48()-0.5)\n \/\/ + vec(0, 0, 1) * (drand48()-0.5);\n m[0][0] += v.getX()*v.getX();\n m[0][1] += v.getX()*v.getY();\n m[0][2] += v.getX()*v.getZ(); \n m[1][1] += v.getY()*v.getY();\n m[1][2] += v.getY()*v.getZ();\n m[2][2] += v.getZ()*v.getZ();\n }\n m[1][0] = m[0][1];\n m[2][0] = m[0][2];\n m[2][1] = m[1][2];\n \n \/\/ calculate the eigenvectors\n matrix::eigensystem_t es;\n m.SolveEigensystem(es);\n \n vec u = es.eigenvecs[0];\n vec v = in.getBead(_matrix[1]._in)->getPos() - in.getBead(_matrix[0]._in)->getPos();\n v.normalize();\n \n out.getBead(_out)->setV(v); \n \n vec w = in.getBead(_matrix[2]._in)->getPos() - in.getBead(_matrix[0]._in)->getPos();\n w.normalize();\n if((v^w)*u < 0) u=vec(0.,0.,0.)-u;\n out.getBead(_out)->setU(u); \n \/\/out.BeadV(_out) = v;\n \n \/\/out.BeadW(_out) = es.eigenvecs[2];\n}\nadded --first-frame option map.cc changed to write out w vector as well\/\/ \n\/\/ File: map.cc\n\/\/ Author: ruehle\n\/\/\n\/\/ Created on April 13, 2007, 4:41 PM\n\/\/\n\n#include \"map.h\"\n#include \n#include \n\nusing namespace std;\n\nMap::~Map()\n{\n vector::iterator iter;\n for(iter=_maps.begin();iter!=_maps.end();++iter)\n delete (*iter); \n _maps.clear();\n}\n\nvoid Map::Apply(Molecule &in, Molecule &out)\n{\n vector::iterator iter;\n for(iter=_maps.begin();iter!=_maps.end();++iter)\n (*iter)->Apply(in, out);\n}\n\nvoid Map_Sphere::Apply(Molecule &in, Molecule &out)\n{\n vector::iterator iter;\n vec cg(0., 0., 0.), f(0.,0.,0.), vel(0.,0.,0.);\n bool bPos, bVel, bF;\n bPos=bVel=bF=false;\n for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n if(in.getBead((*iter)._in)->HasPos()) {\n cg += (*iter)._weight * in.getBead((*iter)._in)->getPos();\n bPos=true;\n }\n if(in.getBead((*iter)._in)->HasVel()) {\n vel += (*iter)._weight * in.getBead((*iter)._in)->getVel();\n bVel = true;\n }\n if(in.getBead((*iter)._in)->HasF()) {\n \/\/\/ \\todo fix me, right calculation should be F_i = m_cg \/ sum(w_i) * sum(w_i\/m_i*F_i)\n \/\/f += (*iter)._weight * in.getBeadF((*iter)._in);\n f += in.getBead((*iter)._in)->getF();\n bF = true;\n }\n }\n if(bPos)\n out.getBead(_out)->setPos(cg);\n if(bVel)\n out.getBead(_out)->setVel(vel);\n if(bF)\n out.getBead(_out)->setF(f);\n}\n\n\/\/\/ \\todo implement this function\nvoid Map_Ellipsoid::Apply(Molecule &in, Molecule &out)\n{\n vector::iterator iter;\n vec cg(0., 0., 0.), c(0., 0., 0.), f(0.,0.,0.), vel(0.,0.,0.);\n matrix m(0.);\n bool bPos, bVel, bF;\n bPos=bVel=bF=false;\n \n int n;\n n = 0;\n for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n if(in.getBead((*iter)._in)->HasPos()) {\n cg += (*iter)._weight * in.getBead((*iter)._in)->getPos();\n bPos=true;\n }\n if(in.getBead((*iter)._in)->HasVel() == true) {\n vel += (*iter)._weight * in.getBead((*iter)._in)->getVel();\n bVel = true;\n }\n if(in.getBead((*iter)._in)->HasF()) {\n \/\/\/ \\todo fix me, right calculation should be F_i = m_cg \/ sum(w_i) * sum(w_i\/m_i*F_i)\n \/\/f += (*iter)._weight * in.getBeadF((*iter)._in);\n f += in.getBead((*iter)._in)->getF();\n bF = true;\n }\n \n if((*iter)._weight>0) {\n c += in.getBead((*iter)._in)->getPos();\n n++;\n }\n }\n \n if(bPos)\n out.getBead(_out)->setPos(cg);\n if(bVel)\n out.getBead(_out)->setVel(vel);\n if(bF)\n out.getBead(_out)->setF(f);\n \n \/\/ calculate the tensor of gyration\n c=c\/(double)n; \n for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n if((*iter)._weight == 0) continue;\n vec v = (in.getBead((*iter)._in)->getPos() - c);\n \/\/v = vec(1, 0.5, 0) * 0.*(drand48()-0.5)\n \/\/ + vec(0.5, -1, 0) * (drand48()-0.5)\n \/\/ + vec(0, 0, 1) * (drand48()-0.5);\n m[0][0] += v.getX()*v.getX();\n m[0][1] += v.getX()*v.getY();\n m[0][2] += v.getX()*v.getZ(); \n m[1][1] += v.getY()*v.getY();\n m[1][2] += v.getY()*v.getZ();\n m[2][2] += v.getZ()*v.getZ();\n }\n m[1][0] = m[0][1];\n m[2][0] = m[0][2];\n m[2][1] = m[1][2];\n \n \/\/ calculate the eigenvectors\n matrix::eigensystem_t es;\n m.SolveEigensystem(es);\n \n vec u = es.eigenvecs[0];\n vec v = in.getBead(_matrix[1]._in)->getPos() - in.getBead(_matrix[0]._in)->getPos();\n v.normalize();\n \n out.getBead(_out)->setV(v); \n \n vec w = in.getBead(_matrix[2]._in)->getPos() - in.getBead(_matrix[0]._in)->getPos();\n w.normalize();\n out.getBead(_out)->setW(w);\n \n if((v^w)*u < 0) u=vec(0.,0.,0.)-u;\n out.getBead(_out)->setU(u);\n \n \/\/out.BeadV(_out) = v;\n \n \/\/out.BeadW(_out) = es.eigenvecs[2];\n}\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \"numerics\/unbounded_arrays.hpp\"\n\n#include \n#include \n\n#include \"base\/macros.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n#include \"unbounded_arrays.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace internal_unbounded_arrays {\n\nusing base::uninitialized;\nusing quantities::Sqrt;\n\ntemplate\ntemplate\ninline void uninitialized_allocator::construct(U* const p, Args&&... args) {\n#if PRINCIPIA_COMPILER_CLANG\n ::new ((void*)p) U(std::forward(args)...); \/\/ NOLINT\n#endif\n}\n\ntemplate\nUnboundedVector::UnboundedVector(int const size)\n : data_(size, Scalar{}) {}\n\ntemplate\nUnboundedVector::UnboundedVector(int const size, uninitialized_t)\n : data_(size) {}\n\ntemplate\nUnboundedVector::UnboundedVector(std::initializer_list data)\n : data_(std::move(data)) {}\n\ntemplate\nvoid UnboundedVector::Extend(int const extra_size) {\n DCHECK_LE(0, extra_size);\n data_.resize(data_.size() + extra_size, Scalar{});\n}\n\ntemplate\nvoid UnboundedVector::Extend(int const extra_size, uninitialized_t) {\n DCHECK_LE(0, extra_size);\n data_.resize(data_.size() + extra_size);\n}\n\ntemplate\nvoid UnboundedVector::Extend(std::initializer_list data) {\n std::move(data.begin(), data.end(), std::back_inserter(data_));\n}\n\ntemplate\nvoid UnboundedVector::EraseToEnd(int const begin_index) {\n data_.erase(data_.begin() + begin_index, data_.end());\n}\n\ntemplate\nint UnboundedVector::size() const {\n return data_.size();\n}\n\ntemplate\nbool UnboundedVector::operator==(UnboundedVector const& right) const {\n return data_ == right.data_;\n}\n\ntemplate\nScalar& UnboundedVector::operator[](int const index) {\n return data_[index];\n}\n\ntemplate\nScalar const& UnboundedVector::operator[](int const index) const {\n return data_[index];\n}\n\ntemplate\nUnboundedLowerTriangularMatrix::UnboundedLowerTriangularMatrix(\n int const rows)\n : rows_(rows),\n data_(rows_ * (rows_ + 1) \/ 2, Scalar{}) {}\n\ntemplate\nUnboundedLowerTriangularMatrix::UnboundedLowerTriangularMatrix(\n int const rows,\n uninitialized_t)\n : rows_(rows),\n data_(rows_ * (rows_ + 1) \/ 2) {}\n\ntemplate\nUnboundedLowerTriangularMatrix::UnboundedLowerTriangularMatrix(\n std::initializer_list data)\n : rows_(static_cast(std::lround((-1 + Sqrt(8 * data.size())) * 0.5))),\n data_(std::move(data)) {\n DCHECK_EQ(data_.size(), rows_ * (rows_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::Extend(int const extra_rows) {\n rows_ += extra_rows;\n data_.resize(rows_ * (rows_ + 1) \/ 2, Scalar{});\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::Extend(int const extra_rows,\n uninitialized_t) {\n rows_ += extra_rows;\n data_.resize(rows_ * (rows_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::Extend(\n std::initializer_list data) {\n std::move(data.begin(), data.end(), std::back_inserter(data_));\n rows_ = static_cast(std::lround((-1 + Sqrt(8 * data_.size())) * 0.5));\n DCHECK_EQ(data_.size(), rows_ * (rows_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::EraseToEnd(\n int const begin_row_index) {\n rows_ = begin_row_index;\n data_.erase(data_.begin() + begin_row_index * (begin_row_index + 1) \/ 2,\n data_.end());\n}\n\ntemplate\nUnboundedUpperTriangularMatrix\nUnboundedLowerTriangularMatrix::Transpose() const {\n UnboundedUpperTriangularMatrix u(rows_, uninitialized);\n for (int i = 0; i < rows_; ++i) {\n for (int j = 0; j <= i; ++j) {\n u[j][i] = (*this)[i][j];\n }\n }\n return u;\n}\n\ntemplate\nint UnboundedLowerTriangularMatrix::rows() const {\n return rows_;\n}\n\ntemplate\nint UnboundedLowerTriangularMatrix::dimension() const {\n return data_.size();\n}\n\ntemplate\nbool UnboundedLowerTriangularMatrix::operator==(\n UnboundedLowerTriangularMatrix const& right) const {\n return rows_ == right.rows_ && data_ == right.data_;\n}\n\ntemplate\nScalar* UnboundedLowerTriangularMatrix::operator[](int const index) {\n DCHECK_LT(index, rows_);\n return &data_[index * (index + 1) \/ 2];\n}\n\ntemplate\nScalar const* UnboundedLowerTriangularMatrix::operator[](\n int const index) const {\n DCHECK_LT(index, rows_);\n return &data_[index * (index + 1) \/ 2];\n}\n\ntemplate\nUnboundedUpperTriangularMatrix::UnboundedUpperTriangularMatrix(\n int const columns)\n : columns_(columns),\n data_(columns_ * (columns_ + 1) \/ 2, Scalar{}) {}\n\ntemplate\nUnboundedUpperTriangularMatrix::UnboundedUpperTriangularMatrix(\n int const columns,\n uninitialized_t)\n : columns_(columns),\n data_(columns_ * (columns_ + 1) \/ 2) {}\n\ntemplate\nUnboundedUpperTriangularMatrix::UnboundedUpperTriangularMatrix(\n std::initializer_list const& data)\n : columns_(\n static_cast(std::lround((-1 + Sqrt(8 * data.size())) * 0.5))),\n data_(Transpose(data,\n \/*current_columns=*\/0,\n \/*extra_columns=*\/columns_)) {\n DCHECK_EQ(data_.size(), columns_ * (columns_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::Extend(int const extra_columns) {\n columns_ += extra_columns;\n data_.resize(columns_ * (columns_ + 1) \/ 2, Scalar{});\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::Extend(int const extra_columns,\n uninitialized_t) {\n columns_ += extra_columns;\n data_.resize(columns_ * (columns_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::Extend(\n std::initializer_list const& data) {\n int const new_columns = static_cast(\n std::lround((-1 + Sqrt(8 * (data_.size() + data.size()))) * 0.5));\n auto transposed_data = Transpose(data,\n \/*current_columns=*\/columns_,\n \/*extra_columns=*\/new_columns - columns_);\n columns_ = new_columns;\n std::move(transposed_data.begin(),\n transposed_data.end(),\n std::back_inserter(data_));\n DCHECK_EQ(data_.size(), columns_ * (columns_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::EraseToEnd(\n int const begin_column_index) {\n columns_ = begin_column_index;\n data_.erase(data_.begin() + begin_column_index * (begin_column_index + 1) \/ 2,\n data_.end());\n}\n\ntemplate\nUnboundedLowerTriangularMatrix\nUnboundedUpperTriangularMatrix::Transpose() const {\n UnboundedLowerTriangularMatrix l(columns_, uninitialized);\n for (int i = 0; i < columns_; ++i) {\n for (int j = i; j < columns_; ++j) {\n l[j][i] = (*this)[i][j];\n }\n }\n return l;\n}\n\ntemplate\nint UnboundedUpperTriangularMatrix::columns() const {\n return columns_;\n}\n\ntemplate\nint UnboundedUpperTriangularMatrix::dimension() const {\n return data_.size();\n}\n\ntemplate\nbool UnboundedUpperTriangularMatrix::operator==(\n UnboundedUpperTriangularMatrix const& right) const {\n return columns_ == right.columns_ && data_ == right.data_;\n}\n\ntemplate\ntemplate\nScalar& UnboundedUpperTriangularMatrix::Row::operator[](\n int const column) {\n DCHECK_LT(column, matrix_.columns_);\n auto x = column * (column + 1) \/ 2 + row_;\n Matrix& m = matrix_;\n std::vector>& y = matrix_.data_;\n Scalar& z = y[x];\n return z;\n \/\/return matrix_.data_[column * (column + 1) \/ 2 + row_];\n}\n\ntemplate\ntemplate\nScalar const&\nUnboundedUpperTriangularMatrix::Row::operator[](\n int const column) const {\n DCHECK_LT(column, matrix_.columns_);\n return matrix_.data_[column * (column + 1) \/ 2 + row_];\n}\n\ntemplate\ntemplate\nUnboundedUpperTriangularMatrix::Row::Row(Matrix& matrix,\n int const row)\n : matrix_(const_cast&>(matrix)),\n row_(row) {}\n\ntemplate\nauto UnboundedUpperTriangularMatrix::operator[](int const row)\n -> Row {\n return Row{*this, row};\n}\n\ntemplate\nauto UnboundedUpperTriangularMatrix::operator[](int const row) const\n -> Row {\n return Row{*this, row};\n}\n\ntemplate\nauto\nUnboundedUpperTriangularMatrix::Transpose(\n std::initializer_list const& data,\n int const current_columns,\n int const extra_columns) ->\n std::vector> {\n \/\/ |data| is a trapezoidal slice at the end of the matrix. This is\n \/\/ inconvenient to index, so we start by constructing a rectangular array with\n \/\/ |extra_columns| columns and |current_columns + extra_columns| rows padded\n \/\/ with junk.\n std::vector> padded;\n {\n padded.reserve(2 * data.size()); \/\/ An overestimate.\n int row = 0;\n int column = 0;\n for (auto it = data.begin(); it != data.end();) {\n if (row <= current_columns + column) {\n padded.push_back(*it);\n ++it;\n } else {\n padded.emplace_back();\n }\n ++column;\n if (column == extra_columns) {\n column = 0;\n ++row;\n }\n }\n }\n\n \/\/ Scan the padded array by column and append the part above the diagonal to\n \/\/ the result.\n std::vector> result;\n result.reserve(data.size());\n int const number_of_rows = current_columns + extra_columns;\n for (int column = 0; column < extra_columns; ++column) {\n for (int row = 0; row < number_of_rows; ++row) {\n if (row <= current_columns + column) {\n result.push_back(padded[row * extra_columns + column]);\n }\n }\n }\n\n return result;\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n UnboundedVector const& vector) {\n std::stringstream s;\n for (int i = 0; i < vector.data_.size(); ++i) {\n s << (i == 0 ? \"{\" : \"\") << vector.data_[i]\n << (i == vector.data_.size() - 1 ? \"}\" : \", \");\n }\n out << s.str();\n return out;\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n UnboundedLowerTriangularMatrix const& matrix) {\n std::stringstream s;\n s << \"rows: \" << matrix.rows_ << \"\\n\";\n for (int i = 0; i < matrix.columns(); ++i) {\n out << \"{\";\n for (int j = 0; j <= i; ++j) {\n if (j > i) {\n out << \", \";\n }\n out << matrix[i][j];\n }\n out << \"}\\n\";\n }\n return out;\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n UnboundedUpperTriangularMatrix const& matrix) {\n out << \"columns: \" << matrix.columns_ << \"\\n\";\n for (int i = 0; i < matrix.columns(); ++i) {\n out << \"{\";\n for (int j = i; j < matrix.columns(); ++j) {\n if (j > i) {\n out << \", \";\n }\n out << matrix[i][j];\n }\n out << \"}\\n\";\n }\n return out;\n}\n\n} \/\/ namespace internal_unbounded_arrays\n} \/\/ namespace numerics\n} \/\/ namespace principia\nFix a compilation error.\n#pragma once\n\n#include \"numerics\/unbounded_arrays.hpp\"\n\n#include \n#include \n\n#include \"base\/macros.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n#include \"unbounded_arrays.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace internal_unbounded_arrays {\n\nusing base::uninitialized;\nusing quantities::Sqrt;\n\ntemplate\ntemplate\ninline void uninitialized_allocator::construct(U* const p, Args&&... args) {\n#if PRINCIPIA_COMPILER_CLANG\n ::new ((void*)p) U(std::forward(args)...); \/\/ NOLINT\n#endif\n}\n\ntemplate\nUnboundedVector::UnboundedVector(int const size)\n : data_(size, Scalar{}) {}\n\ntemplate\nUnboundedVector::UnboundedVector(int const size, uninitialized_t)\n : data_(size) {}\n\ntemplate\nUnboundedVector::UnboundedVector(std::initializer_list data)\n : data_(std::move(data)) {}\n\ntemplate\nvoid UnboundedVector::Extend(int const extra_size) {\n DCHECK_LE(0, extra_size);\n data_.resize(data_.size() + extra_size, Scalar{});\n}\n\ntemplate\nvoid UnboundedVector::Extend(int const extra_size, uninitialized_t) {\n DCHECK_LE(0, extra_size);\n data_.resize(data_.size() + extra_size);\n}\n\ntemplate\nvoid UnboundedVector::Extend(std::initializer_list data) {\n std::move(data.begin(), data.end(), std::back_inserter(data_));\n}\n\ntemplate\nvoid UnboundedVector::EraseToEnd(int const begin_index) {\n data_.erase(data_.begin() + begin_index, data_.end());\n}\n\ntemplate\nint UnboundedVector::size() const {\n return data_.size();\n}\n\ntemplate\nbool UnboundedVector::operator==(UnboundedVector const& right) const {\n return data_ == right.data_;\n}\n\ntemplate\nScalar& UnboundedVector::operator[](int const index) {\n return data_[index];\n}\n\ntemplate\nScalar const& UnboundedVector::operator[](int const index) const {\n return data_[index];\n}\n\ntemplate\nUnboundedLowerTriangularMatrix::UnboundedLowerTriangularMatrix(\n int const rows)\n : rows_(rows),\n data_(rows_ * (rows_ + 1) \/ 2, Scalar{}) {}\n\ntemplate\nUnboundedLowerTriangularMatrix::UnboundedLowerTriangularMatrix(\n int const rows,\n uninitialized_t)\n : rows_(rows),\n data_(rows_ * (rows_ + 1) \/ 2) {}\n\ntemplate\nUnboundedLowerTriangularMatrix::UnboundedLowerTriangularMatrix(\n std::initializer_list data)\n : rows_(static_cast(std::lround((-1 + Sqrt(8 * data.size())) * 0.5))),\n data_(std::move(data)) {\n DCHECK_EQ(data_.size(), rows_ * (rows_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::Extend(int const extra_rows) {\n rows_ += extra_rows;\n data_.resize(rows_ * (rows_ + 1) \/ 2, Scalar{});\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::Extend(int const extra_rows,\n uninitialized_t) {\n rows_ += extra_rows;\n data_.resize(rows_ * (rows_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::Extend(\n std::initializer_list data) {\n std::move(data.begin(), data.end(), std::back_inserter(data_));\n rows_ = static_cast(std::lround((-1 + Sqrt(8 * data_.size())) * 0.5));\n DCHECK_EQ(data_.size(), rows_ * (rows_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedLowerTriangularMatrix::EraseToEnd(\n int const begin_row_index) {\n rows_ = begin_row_index;\n data_.erase(data_.begin() + begin_row_index * (begin_row_index + 1) \/ 2,\n data_.end());\n}\n\ntemplate\nUnboundedUpperTriangularMatrix\nUnboundedLowerTriangularMatrix::Transpose() const {\n UnboundedUpperTriangularMatrix u(rows_, uninitialized);\n for (int i = 0; i < rows_; ++i) {\n for (int j = 0; j <= i; ++j) {\n u[j][i] = (*this)[i][j];\n }\n }\n return u;\n}\n\ntemplate\nint UnboundedLowerTriangularMatrix::rows() const {\n return rows_;\n}\n\ntemplate\nint UnboundedLowerTriangularMatrix::dimension() const {\n return data_.size();\n}\n\ntemplate\nbool UnboundedLowerTriangularMatrix::operator==(\n UnboundedLowerTriangularMatrix const& right) const {\n return rows_ == right.rows_ && data_ == right.data_;\n}\n\ntemplate\nScalar* UnboundedLowerTriangularMatrix::operator[](int const index) {\n DCHECK_LT(index, rows_);\n return &data_[index * (index + 1) \/ 2];\n}\n\ntemplate\nScalar const* UnboundedLowerTriangularMatrix::operator[](\n int const index) const {\n DCHECK_LT(index, rows_);\n return &data_[index * (index + 1) \/ 2];\n}\n\ntemplate\nUnboundedUpperTriangularMatrix::UnboundedUpperTriangularMatrix(\n int const columns)\n : columns_(columns),\n data_(columns_ * (columns_ + 1) \/ 2, Scalar{}) {}\n\ntemplate\nUnboundedUpperTriangularMatrix::UnboundedUpperTriangularMatrix(\n int const columns,\n uninitialized_t)\n : columns_(columns),\n data_(columns_ * (columns_ + 1) \/ 2) {}\n\ntemplate\nUnboundedUpperTriangularMatrix::UnboundedUpperTriangularMatrix(\n std::initializer_list const& data)\n : columns_(\n static_cast(std::lround((-1 + Sqrt(8 * data.size())) * 0.5))),\n data_(Transpose(data,\n \/*current_columns=*\/0,\n \/*extra_columns=*\/columns_)) {\n DCHECK_EQ(data_.size(), columns_ * (columns_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::Extend(int const extra_columns) {\n columns_ += extra_columns;\n data_.resize(columns_ * (columns_ + 1) \/ 2, Scalar{});\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::Extend(int const extra_columns,\n uninitialized_t) {\n columns_ += extra_columns;\n data_.resize(columns_ * (columns_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::Extend(\n std::initializer_list const& data) {\n int const new_columns = static_cast(\n std::lround((-1 + Sqrt(8 * (data_.size() + data.size()))) * 0.5));\n auto transposed_data = Transpose(data,\n \/*current_columns=*\/columns_,\n \/*extra_columns=*\/new_columns - columns_);\n columns_ = new_columns;\n std::move(transposed_data.begin(),\n transposed_data.end(),\n std::back_inserter(data_));\n DCHECK_EQ(data_.size(), columns_ * (columns_ + 1) \/ 2);\n}\n\ntemplate\nvoid UnboundedUpperTriangularMatrix::EraseToEnd(\n int const begin_column_index) {\n columns_ = begin_column_index;\n data_.erase(data_.begin() + begin_column_index * (begin_column_index + 1) \/ 2,\n data_.end());\n}\n\ntemplate\nUnboundedLowerTriangularMatrix\nUnboundedUpperTriangularMatrix::Transpose() const {\n UnboundedLowerTriangularMatrix l(columns_, uninitialized);\n for (int i = 0; i < columns_; ++i) {\n for (int j = i; j < columns_; ++j) {\n l[j][i] = (*this)[i][j];\n }\n }\n return l;\n}\n\ntemplate\nint UnboundedUpperTriangularMatrix::columns() const {\n return columns_;\n}\n\ntemplate\nint UnboundedUpperTriangularMatrix::dimension() const {\n return data_.size();\n}\n\ntemplate\nbool UnboundedUpperTriangularMatrix::operator==(\n UnboundedUpperTriangularMatrix const& right) const {\n return columns_ == right.columns_ && data_ == right.data_;\n}\n\ntemplate\ntemplate\nScalar& UnboundedUpperTriangularMatrix::Row::operator[](\n int const column) {\n DCHECK_LT(column, matrix_.columns_);\n auto x = column * (column + 1) \/ 2 + row_;\n Matrix& m = matrix_;\n std::vector>& y = matrix_.data_;\n Scalar& z = y[x];\n return z;\n \/\/return matrix_.data_[column * (column + 1) \/ 2 + row_];\n}\n\ntemplate\ntemplate\nScalar const&\nUnboundedUpperTriangularMatrix::Row::operator[](\n int const column) const {\n DCHECK_LT(column, matrix_.columns_);\n return matrix_.data_[column * (column + 1) \/ 2 + row_];\n}\n\ntemplate\ntemplate\nUnboundedUpperTriangularMatrix::Row::Row(Matrix& matrix,\n int const row)\n : matrix_(const_cast&>(matrix)),\n row_(row) {}\n\ntemplate\nauto UnboundedUpperTriangularMatrix::operator[](int const row)\n -> Row {\n return Row{*this, row};\n}\n\ntemplate\nauto UnboundedUpperTriangularMatrix::operator[](int const row) const\n -> Row {\n return Row{*this, row};\n}\n\ntemplate\nauto\nUnboundedUpperTriangularMatrix::Transpose(\n std::initializer_list const& data,\n int const current_columns,\n int const extra_columns) ->\n std::vector> {\n \/\/ |data| is a trapezoidal slice at the end of the matrix. This is\n \/\/ inconvenient to index, so we start by constructing a rectangular array with\n \/\/ |extra_columns| columns and |current_columns + extra_columns| rows padded\n \/\/ with junk.\n std::vector> padded;\n {\n padded.reserve(2 * data.size()); \/\/ An overestimate.\n int row = 0;\n int column = 0;\n for (auto it = data.begin(); it != data.end();) {\n if (row <= current_columns + column) {\n padded.push_back(*it);\n ++it;\n } else {\n padded.emplace_back();\n }\n ++column;\n if (column == extra_columns) {\n column = 0;\n ++row;\n }\n }\n }\n\n \/\/ Scan the padded array by column and append the part above the diagonal to\n \/\/ the result.\n std::vector> result;\n result.reserve(data.size());\n int const number_of_rows = current_columns + extra_columns;\n for (int column = 0; column < extra_columns; ++column) {\n for (int row = 0; row < number_of_rows; ++row) {\n if (row <= current_columns + column) {\n result.push_back(padded[row * extra_columns + column]);\n }\n }\n }\n\n return result;\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n UnboundedVector const& vector) {\n std::stringstream s;\n for (int i = 0; i < vector.data_.size(); ++i) {\n s << (i == 0 ? \"{\" : \"\") << vector.data_[i]\n << (i == vector.data_.size() - 1 ? \"}\" : \", \");\n }\n out << s.str();\n return out;\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n UnboundedLowerTriangularMatrix const& matrix) {\n std::stringstream s;\n s << \"rows: \" << matrix.rows() << \"\\n\";\n for (int i = 0; i < matrix.rows(); ++i) {\n out << \"{\";\n for (int j = 0; j <= i; ++j) {\n if (j > i) {\n out << \", \";\n }\n out << matrix[i][j];\n }\n out << \"}\\n\";\n }\n return out;\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n UnboundedUpperTriangularMatrix const& matrix) {\n out << \"columns: \" << matrix.columns_ << \"\\n\";\n for (int i = 0; i < matrix.columns(); ++i) {\n out << \"{\";\n for (int j = i; j < matrix.columns(); ++j) {\n if (j > i) {\n out << \", \";\n }\n out << matrix[i][j];\n }\n out << \"}\\n\";\n }\n return out;\n}\n\n} \/\/ namespace internal_unbounded_arrays\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"#include \"broadcastdaemon.h\"\n#ifdef BUILD_PYTHON\n#include \"gil.h\"\n#endif\n#include \n\nnamespace gg\n{\n\nBroadcastDaemon::BroadcastDaemon(IVideoSource * source)\n : _source(source)\n , _running(false)\n{\n if (_source == nullptr)\n throw VideoSourceError(\"Null pointer passed\"\n \" to broadcast daemon\");\n}\n\nBroadcastDaemon::~BroadcastDaemon()\n{\n stop();\n}\n\nvoid BroadcastDaemon::start(float frame_rate)\n{\n if (frame_rate <= 0.0)\n throw VideoSourceError(\"Invalid frame rate\");\n\n {\n std::lock_guard lock_guard(_lock);\n if (_running)\n throw VideoSourceError(\"Broadcast daemon already running\");\n else\n _running = true;\n }\n\n#ifdef BUILD_PYTHON\n ScopedPythonGILRelease gil_release;\n#endif\n\n _thread = std::thread(&BroadcastDaemon::run,\n this,\n 1000.0 \/ frame_rate);\n}\n\nvoid BroadcastDaemon::stop()\n{\n bool stopped = false;\n {\n std::lock_guard lock_guard(_lock);\n if (_running)\n {\n _running = false;\n stopped = true;\n }\n }\n if (stopped)\n _thread.join();\n}\n\nvoid BroadcastDaemon::run(float sleep_duration_ms)\n{\n VideoFrame frame(_source->get_colour(), false);\n \/* in case no frame is obtained, an empty frame is\n * broadcast, to help against potential synchronisation\n * problems\n *\/\n int cols = 1920, rows = 1080; \/\/ default value, in case\n \/\/ something goes wrong\n _source->get_frame_dimensions(cols, rows);\n VideoFrame * fill_frame = new VideoFrame(_source->get_colour(), cols, rows);\n std::chrono::microseconds inter_frame_duration(\n static_cast(1000 * sleep_duration_ms));\n while (_running)\n {\n auto start = std::chrono::high_resolution_clock::now();\n if (_source->get_frame(frame))\n _source->notify(frame);\n else\n {\n _source->get_frame_dimensions(cols, rows);\n if (cols != fill_frame->cols() or rows != fill_frame->rows())\n {\n delete fill_frame;\n fill_frame = new VideoFrame(_source->get_colour(), cols, rows);\n }\n _source->notify(*fill_frame);\n }\n auto end = std::chrono::high_resolution_clock::now();\n std::chrono::microseconds processing_duration =\n std::chrono::duration_cast(\n end - start\n );\n auto sleep_duration = inter_frame_duration - processing_duration;\n if (sleep_duration.count() > 0)\n std::this_thread::sleep_for(sleep_duration);\n }\n delete fill_frame;\n}\n\nBroadcastDaemon::BroadcastDaemon()\n{\n \/\/ nop\n}\n\n}\nIssue #74: BroadcastDaemon mitigates case where frame dimensions are not returned by source, also decreased default frame size from 1920x1080 to 256x64#include \"broadcastdaemon.h\"\n#ifdef BUILD_PYTHON\n#include \"gil.h\"\n#endif\n#include \n\nnamespace gg\n{\n\nBroadcastDaemon::BroadcastDaemon(IVideoSource * source)\n : _source(source)\n , _running(false)\n{\n if (_source == nullptr)\n throw VideoSourceError(\"Null pointer passed\"\n \" to broadcast daemon\");\n}\n\nBroadcastDaemon::~BroadcastDaemon()\n{\n stop();\n}\n\nvoid BroadcastDaemon::start(float frame_rate)\n{\n if (frame_rate <= 0.0)\n throw VideoSourceError(\"Invalid frame rate\");\n\n {\n std::lock_guard lock_guard(_lock);\n if (_running)\n throw VideoSourceError(\"Broadcast daemon already running\");\n else\n _running = true;\n }\n\n#ifdef BUILD_PYTHON\n ScopedPythonGILRelease gil_release;\n#endif\n\n _thread = std::thread(&BroadcastDaemon::run,\n this,\n 1000.0 \/ frame_rate);\n}\n\nvoid BroadcastDaemon::stop()\n{\n bool stopped = false;\n {\n std::lock_guard lock_guard(_lock);\n if (_running)\n {\n _running = false;\n stopped = true;\n }\n }\n if (stopped)\n _thread.join();\n}\n\nvoid BroadcastDaemon::run(float sleep_duration_ms)\n{\n VideoFrame frame(_source->get_colour(), false);\n \/* in case no frame is obtained, an empty frame is\n * broadcast, to help against potential synchronisation\n * problems\n *\/\n int cols = 0, rows = 0;\n if (not _source->get_frame_dimensions(cols, rows))\n {\n \/\/ default values, in case something goes wrong\n cols = 256;\n rows = 64;\n }\n VideoFrame * fill_frame = new VideoFrame(_source->get_colour(), cols, rows);\n std::chrono::microseconds inter_frame_duration(\n static_cast(1000 * sleep_duration_ms));\n while (_running)\n {\n auto start = std::chrono::high_resolution_clock::now();\n if (_source->get_frame(frame))\n _source->notify(frame);\n else\n {\n int old_cols = cols, old_rows = rows;\n if (not _source->get_frame_dimensions(cols, rows))\n {\n cols = old_cols;\n rows = old_rows;\n }\n if (cols != fill_frame->cols() or rows != fill_frame->rows())\n {\n delete fill_frame;\n fill_frame = new VideoFrame(_source->get_colour(), cols, rows);\n }\n _source->notify(*fill_frame);\n }\n auto end = std::chrono::high_resolution_clock::now();\n std::chrono::microseconds processing_duration =\n std::chrono::duration_cast(\n end - start\n );\n auto sleep_duration = inter_frame_duration - processing_duration;\n if (sleep_duration.count() > 0)\n std::this_thread::sleep_for(sleep_duration);\n }\n delete fill_frame;\n}\n\nBroadcastDaemon::BroadcastDaemon()\n{\n \/\/ nop\n}\n\n}\n<|endoftext|>"} {"text":"#include \"tmc.h\"\n\n#include \n#include \n#include \n\n#include \"util.h\"\n\nnamespace redsea {\n\nnamespace tmc {\n\nstd::map g_event_data;\n\nnamespace {\n\nuint16_t popBits(std::deque& bit_deque, int len) {\n uint16_t result = 0x00;\n if ((int)bit_deque.size() >= len) {\n for (int i=0; i>\n getFreeformFields(std::vector parts) {\n\n const std::vector field_size(\n {3, 3, 5, 5, 5, 8, 8, 8, 8, 11, 16, 16, 16, 16, 0, 0});\n\n uint16_t second_gsi = bits(parts[1].data[0], 12, 2);\n\n \/\/ Concatenate freeform data from used message length (derived from\n \/\/ GSI of second group)\n std::deque freeform_data_bits;\n for (int i=0; i<(int)parts.size(); i++) {\n if (!parts[i].is_received)\n break;\n\n if (i <= 1 || i >= (int)parts.size() - second_gsi) {\n for (int b=0; b<12; b++)\n freeform_data_bits.push_back((parts[i].data[0] >> (11-b)) & 0x1);\n for (int b=0; b<16; b++)\n freeform_data_bits.push_back((parts[i].data[1] >> (15-b)) & 0x1);\n }\n }\n\n \/\/ Decode freeform data\n int bits_left = freeform_data_bits.size();\n std::vector> result;\n while (freeform_data_bits.size() > 4) {\n uint16_t label = popBits(freeform_data_bits, 4);\n if ((int)freeform_data_bits.size() < field_size.at(label))\n break;\n\n uint16_t field_data = popBits(freeform_data_bits, field_size.at(label));\n\n result.push_back({label, field_data});\n }\n\n return result;\n}\n\nstd::string timeString(uint16_t field_data) {\n std::string time_string(\"\");\n if (field_data <= 95) {\n char t[6];\n std::snprintf(t, 6, \"%02d:%02d\", field_data\/4, 15*(field_data % 4));\n time_string = t;\n } else if (field_data <= 200) {\n char t[25];\n std::snprintf(t, 25, \"after %d days at %02d:00\", (field_data-96)\/24,\n (field_data-96)%24);\n time_string = t;\n } else if (field_data <= 231) {\n char t[20];\n std::snprintf(t, 20, \"day %d of the month\", field_data-200);\n time_string = t;\n } else {\n int mo = (field_data-232) \/ 2;\n bool end_mid = (field_data-232) % 2;\n std::vector month_names({\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\n \"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"});\n if (mo < 12) {\n time_string = (end_mid ? \"end of \" : \"mid-\") + month_names.at(mo);\n }\n }\n\n return time_string;\n}\n\nstd::string sentence(std::string in) {\n std::string result = in + \".\";\n result[0] = std::toupper(result[0]);\n return result;\n}\n\n} \/\/ namespace\n\nEvent::Event() {\n\n}\n\nEvent::Event(std::string _desc, std::string _desc_q, uint16_t _nature,\n uint16_t _qtype, uint16_t _dur, uint16_t _dir, uint16_t _urg,\n uint16_t _class) : description(_desc), description_with_quantifier(_desc_q),\n nature(_nature), quantifier_type(_qtype), duration_type(_dur),\n directionality(_dir), urgency(_urg), update_class(_class) {\n}\n\nEvent getEvent(uint16_t code) {\n\n if (g_event_data.find(code) != g_event_data.end())\n return g_event_data.find(code)->second;\n else\n return Event();\n\n}\n\nstd::string getSupplInfoString(uint16_t code) {\n std::map suppl_info_list;\n return suppl_info_list[code];\n}\n\n\nvoid loadEventData() {\n std::ifstream in(\"data\/tmc_events.csv\");\n\n if (!in.is_open())\n return;\n\n for (std::string line; std::getline(in, line); ) {\n if (!in.good())\n break;\n\n std::stringstream iss(line);\n uint16_t code;\n std::vector strings(2);\n std::vector nums(6);\n\n for (int col=0; col<9; col++) {\n std::string val;\n std::getline(iss, val, ';');\n if (!iss.good())\n break;\n\n if (col == 0)\n code = std::stoi(val);\n else if (col <= 2)\n strings[col-1] = val;\n else\n nums[col-3] = std::stoi(val);\n }\n\n g_event_data.insert({code, {strings[0], strings[1], nums[0], nums[1],\n nums[2], nums[3], nums[4], nums[5]}});\n\n }\n\n in.close();\n\n}\n\nTMC::TMC() : is_initialized_(false), has_encid_(false), multi_group_buffer_(5),\n ps_(8) {\n\n}\n\nvoid TMC::systemGroup(uint16_t message) {\n\n\n if (bits(message, 14, 1) == 0) {\n printf(\", tmc: { system_info: { \");\n\n if (g_event_data.empty())\n loadEventData();\n\n is_initialized_ = true;\n ltn_ = bits(message, 6, 6);\n is_encrypted_ = (ltn_ == 0);\n\n printf(\"is_encrypted: %s\", is_encrypted_ ? \"true\" : \"false\");\n\n if (!is_encrypted_)\n printf(\", location_table: \\\"0x%02x\\\"\", ltn_);\n\n bool afi = bits(message, 5, 1);\n bool m = bits(message, 4, 1);\n bool mgs_i = bits(message, 3, 1);\n bool mgs_n = bits(message, 2, 1);\n bool mgs_r = bits(message, 1, 1);\n bool mgs_u = bits(message, 0, 1);\n\n printf(\", is_on_alt_freqs: %s\", afi ? \"true\" : \"false\");\n\n std::vector scope;\n if (mgs_i)\n scope.push_back(\"\\\"inter-road\\\"\");\n if (mgs_n)\n scope.push_back(\"\\\"national\\\"\");\n if (mgs_r)\n scope.push_back(\"\\\"regional\\\"\");\n if (mgs_u)\n scope.push_back(\"\\\"urban\\\"\");\n\n printf(\", scope: [ %s ]\", commaJoin(scope).c_str());\n\n printf(\" } }\");\n }\n\n}\n\nvoid TMC::userGroup(uint16_t x, uint16_t y, uint16_t z) {\n\n if (!is_initialized_)\n return;\n\n bool t = bits(x, 4, 1);\n\n \/\/ Encryption administration group\n if (bits(x, 0, 5) == 0x00) {\n sid_ = bits(y, 5, 6);\n encid_ = bits(y, 0, 5);\n ltnbe_ = bits(z, 10, 6);\n has_encid_ = true;\n\n printf(\", tmc: { service_id: \\\"0x%02x\\\", encryption_id: \\\"0x%02x\\\", \"\n \"location_table: \\\"0x%02x\\\" }\", sid_, encid_, ltnbe_);\n\n \/\/ Tuning information\n } else if (t) {\n uint16_t variant = bits(x, 0, 4);\n\n if (variant == 4 || variant == 5) {\n\n int pos = 4 * (variant - 4);\n\n ps_.setAt(pos, bits(y, 8, 8));\n ps_.setAt(pos+1, bits(y, 0, 8));\n ps_.setAt(pos+2, bits(z, 8, 8));\n ps_.setAt(pos+3, bits(z, 0, 8));\n\n if (ps_.isComplete())\n printf(\", tmc: { service_provider: \\\"%s\\\" }\",\n ps_.getLastCompleteString().c_str());\n\n } else {\n printf(\", tmc: { \/* TODO: tuning info variant %d *\/ }\", variant);\n }\n\n \/\/ User message\n } else {\n\n if (is_encrypted_ && !has_encid_)\n return;\n\n bool f = bits(x, 3, 1);\n\n \/\/ Single-group message\n if (f) {\n Message message(false, is_encrypted_, {{true, {x, y, z}}});\n message.print();\n current_ci_ = 0;\n\n \/\/ Part of multi-group message\n } else {\n\n uint16_t ci = bits(x, 0, 3);\n bool fg = bits(y, 15, 1);\n\n if (ci != current_ci_ \/* TODO 15-second limit *\/) {\n Message message(true, is_encrypted_, multi_group_buffer_);\n message.print();\n multi_group_buffer_[0].is_received = false;\n current_ci_ = ci;\n }\n\n int cur_grp;\n\n if (fg)\n cur_grp = 0;\n else if (bits(y, 14, 1))\n cur_grp = 1;\n else\n cur_grp = 4 - bits(y, 12, 2);\n\n multi_group_buffer_.at(cur_grp) = {true, {y, z}};\n\n }\n }\n\n}\n\nMessage::Message(bool is_multi, bool is_loc_encrypted,\n std::vector parts) : is_encrypted(is_loc_encrypted), events() {\n\n \/\/ single-group\n if (!is_multi) {\n duration = bits(parts[0].data[0], 0, 3);\n divertadv = bits(parts[0].data[1], 15, 1);\n direction = bits(parts[0].data[1], 14, 1);\n extent = bits(parts[0].data[1], 11, 3);\n events.push_back(bits(parts[0].data[1], 0, 11));\n location = parts[0].data[2];\n is_complete = true;\n\n \/\/ multi-group\n } else {\n\n \/\/ Need at least the first group\n if (!parts[0].is_received)\n return;\n\n is_complete=true;\n\n \/\/ First group\n direction = bits(parts[0].data[0], 14, 1);\n extent = bits(parts[0].data[0], 11, 3);\n events.push_back(bits(parts[0].data[0], 0, 11));\n location = parts[0].data[1];\n\n \/\/ Subsequent parts\n if (parts[1].is_received) {\n auto freeform = getFreeformFields(parts);\n\n for (auto p : freeform) {\n uint16_t label = p.first;\n uint16_t field_data = p.second;\n \/\/printf (\"tmc: label %04x: field_data %04x\\n\",label,field_data);\n\n \/\/ Duration\n if (label == 0) {\n duration = field_data;\n\n \/\/ Length of route affected\n } else if (label == 2) {\n length_affected = field_data;\n has_length_affected = true;\n\n \/\/ Start \/ stop time\n } else if (label == 7) {\n time_starts = field_data;\n has_time_starts = true;\n } else if (label == 8) {\n time_until = field_data;\n has_time_until = true;\n } else {\n printf(\" \/* TODO label=%d *\/\",label);\n }\n }\n }\n }\n}\n\nvoid Message::print() const {\n printf(\", traffic_message: { \");\n\n if (!is_complete || events.empty()) {\n printf(\"}\\n\");\n return;\n }\n\n if (events.size() > 1) {\n printf(\"events: [ %s ]\", commaJoin(events).c_str());\n } else {\n printf(\"event: { code: %d, description: \\\"%s\\\" }\", events[0],\n sentence(getEvent(events[0]).description).c_str());\n }\n\n printf(\", %slocation: \\\"0x%02x\\\", direction: \\\"%s\\\", extent: %d, \"\n \"diversion_advised: %s\",\n (is_encrypted ? \"encrypted_\" : \"\"), location,\n direction ? \"negative\" : \"positive\",\n extent, divertadv ? \"true\" : \"false\" );\n\n\n if (has_time_starts)\n printf(\", starts: \\\"%s\\\"\", timeString(time_starts).c_str());\n if (has_time_until)\n printf(\", until: \\\"%s\\\"\", timeString(time_until).c_str());\n\n\n printf (\"}\");\n\n}\n\n} \/\/ namespace tmc\n} \/\/ namespace redsea\nunused var#include \"tmc.h\"\n\n#include \n#include \n#include \n\n#include \"util.h\"\n\nnamespace redsea {\n\nnamespace tmc {\n\nstd::map g_event_data;\n\nnamespace {\n\nuint16_t popBits(std::deque& bit_deque, int len) {\n uint16_t result = 0x00;\n if ((int)bit_deque.size() >= len) {\n for (int i=0; i>\n getFreeformFields(std::vector parts) {\n\n const std::vector field_size(\n {3, 3, 5, 5, 5, 8, 8, 8, 8, 11, 16, 16, 16, 16, 0, 0});\n\n uint16_t second_gsi = bits(parts[1].data[0], 12, 2);\n\n \/\/ Concatenate freeform data from used message length (derived from\n \/\/ GSI of second group)\n std::deque freeform_data_bits;\n for (int i=0; i<(int)parts.size(); i++) {\n if (!parts[i].is_received)\n break;\n\n if (i <= 1 || i >= (int)parts.size() - second_gsi) {\n for (int b=0; b<12; b++)\n freeform_data_bits.push_back((parts[i].data[0] >> (11-b)) & 0x1);\n for (int b=0; b<16; b++)\n freeform_data_bits.push_back((parts[i].data[1] >> (15-b)) & 0x1);\n }\n }\n\n \/\/ Decode freeform data\n \/\/int bits_left = freeform_data_bits.size();\n std::vector> result;\n while (freeform_data_bits.size() > 4) {\n uint16_t label = popBits(freeform_data_bits, 4);\n if ((int)freeform_data_bits.size() < field_size.at(label))\n break;\n\n uint16_t field_data = popBits(freeform_data_bits, field_size.at(label));\n\n result.push_back({label, field_data});\n }\n\n return result;\n}\n\nstd::string timeString(uint16_t field_data) {\n std::string time_string(\"\");\n if (field_data <= 95) {\n char t[6];\n std::snprintf(t, 6, \"%02d:%02d\", field_data\/4, 15*(field_data % 4));\n time_string = t;\n } else if (field_data <= 200) {\n char t[25];\n std::snprintf(t, 25, \"after %d days at %02d:00\", (field_data-96)\/24,\n (field_data-96)%24);\n time_string = t;\n } else if (field_data <= 231) {\n char t[20];\n std::snprintf(t, 20, \"day %d of the month\", field_data-200);\n time_string = t;\n } else {\n int mo = (field_data-232) \/ 2;\n bool end_mid = (field_data-232) % 2;\n std::vector month_names({\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\n \"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"});\n if (mo < 12) {\n time_string = (end_mid ? \"end of \" : \"mid-\") + month_names.at(mo);\n }\n }\n\n return time_string;\n}\n\nstd::string sentence(std::string in) {\n std::string result = in + \".\";\n result[0] = std::toupper(result[0]);\n return result;\n}\n\n} \/\/ namespace\n\nEvent::Event() {\n\n}\n\nEvent::Event(std::string _desc, std::string _desc_q, uint16_t _nature,\n uint16_t _qtype, uint16_t _dur, uint16_t _dir, uint16_t _urg,\n uint16_t _class) : description(_desc), description_with_quantifier(_desc_q),\n nature(_nature), quantifier_type(_qtype), duration_type(_dur),\n directionality(_dir), urgency(_urg), update_class(_class) {\n}\n\nEvent getEvent(uint16_t code) {\n\n if (g_event_data.find(code) != g_event_data.end())\n return g_event_data.find(code)->second;\n else\n return Event();\n\n}\n\nstd::string getSupplInfoString(uint16_t code) {\n std::map suppl_info_list;\n return suppl_info_list[code];\n}\n\n\nvoid loadEventData() {\n std::ifstream in(\"data\/tmc_events.csv\");\n\n if (!in.is_open())\n return;\n\n for (std::string line; std::getline(in, line); ) {\n if (!in.good())\n break;\n\n std::stringstream iss(line);\n uint16_t code;\n std::vector strings(2);\n std::vector nums(6);\n\n for (int col=0; col<9; col++) {\n std::string val;\n std::getline(iss, val, ';');\n if (!iss.good())\n break;\n\n if (col == 0)\n code = std::stoi(val);\n else if (col <= 2)\n strings[col-1] = val;\n else\n nums[col-3] = std::stoi(val);\n }\n\n g_event_data.insert({code, {strings[0], strings[1], nums[0], nums[1],\n nums[2], nums[3], nums[4], nums[5]}});\n\n }\n\n in.close();\n\n}\n\nTMC::TMC() : is_initialized_(false), has_encid_(false), multi_group_buffer_(5),\n ps_(8) {\n\n}\n\nvoid TMC::systemGroup(uint16_t message) {\n\n\n if (bits(message, 14, 1) == 0) {\n printf(\", tmc: { system_info: { \");\n\n if (g_event_data.empty())\n loadEventData();\n\n is_initialized_ = true;\n ltn_ = bits(message, 6, 6);\n is_encrypted_ = (ltn_ == 0);\n\n printf(\"is_encrypted: %s\", is_encrypted_ ? \"true\" : \"false\");\n\n if (!is_encrypted_)\n printf(\", location_table: \\\"0x%02x\\\"\", ltn_);\n\n bool afi = bits(message, 5, 1);\n bool m = bits(message, 4, 1);\n bool mgs_i = bits(message, 3, 1);\n bool mgs_n = bits(message, 2, 1);\n bool mgs_r = bits(message, 1, 1);\n bool mgs_u = bits(message, 0, 1);\n\n printf(\", is_on_alt_freqs: %s\", afi ? \"true\" : \"false\");\n\n std::vector scope;\n if (mgs_i)\n scope.push_back(\"\\\"inter-road\\\"\");\n if (mgs_n)\n scope.push_back(\"\\\"national\\\"\");\n if (mgs_r)\n scope.push_back(\"\\\"regional\\\"\");\n if (mgs_u)\n scope.push_back(\"\\\"urban\\\"\");\n\n printf(\", scope: [ %s ]\", commaJoin(scope).c_str());\n\n printf(\" } }\");\n }\n\n}\n\nvoid TMC::userGroup(uint16_t x, uint16_t y, uint16_t z) {\n\n if (!is_initialized_)\n return;\n\n bool t = bits(x, 4, 1);\n\n \/\/ Encryption administration group\n if (bits(x, 0, 5) == 0x00) {\n sid_ = bits(y, 5, 6);\n encid_ = bits(y, 0, 5);\n ltnbe_ = bits(z, 10, 6);\n has_encid_ = true;\n\n printf(\", tmc: { service_id: \\\"0x%02x\\\", encryption_id: \\\"0x%02x\\\", \"\n \"location_table: \\\"0x%02x\\\" }\", sid_, encid_, ltnbe_);\n\n \/\/ Tuning information\n } else if (t) {\n uint16_t variant = bits(x, 0, 4);\n\n if (variant == 4 || variant == 5) {\n\n int pos = 4 * (variant - 4);\n\n ps_.setAt(pos, bits(y, 8, 8));\n ps_.setAt(pos+1, bits(y, 0, 8));\n ps_.setAt(pos+2, bits(z, 8, 8));\n ps_.setAt(pos+3, bits(z, 0, 8));\n\n if (ps_.isComplete())\n printf(\", tmc: { service_provider: \\\"%s\\\" }\",\n ps_.getLastCompleteString().c_str());\n\n } else {\n printf(\", tmc: { \/* TODO: tuning info variant %d *\/ }\", variant);\n }\n\n \/\/ User message\n } else {\n\n if (is_encrypted_ && !has_encid_)\n return;\n\n bool f = bits(x, 3, 1);\n\n \/\/ Single-group message\n if (f) {\n Message message(false, is_encrypted_, {{true, {x, y, z}}});\n message.print();\n current_ci_ = 0;\n\n \/\/ Part of multi-group message\n } else {\n\n uint16_t ci = bits(x, 0, 3);\n bool fg = bits(y, 15, 1);\n\n if (ci != current_ci_ \/* TODO 15-second limit *\/) {\n Message message(true, is_encrypted_, multi_group_buffer_);\n message.print();\n multi_group_buffer_[0].is_received = false;\n current_ci_ = ci;\n }\n\n int cur_grp;\n\n if (fg)\n cur_grp = 0;\n else if (bits(y, 14, 1))\n cur_grp = 1;\n else\n cur_grp = 4 - bits(y, 12, 2);\n\n multi_group_buffer_.at(cur_grp) = {true, {y, z}};\n\n }\n }\n\n}\n\nMessage::Message(bool is_multi, bool is_loc_encrypted,\n std::vector parts) : is_encrypted(is_loc_encrypted), events() {\n\n \/\/ single-group\n if (!is_multi) {\n duration = bits(parts[0].data[0], 0, 3);\n divertadv = bits(parts[0].data[1], 15, 1);\n direction = bits(parts[0].data[1], 14, 1);\n extent = bits(parts[0].data[1], 11, 3);\n events.push_back(bits(parts[0].data[1], 0, 11));\n location = parts[0].data[2];\n is_complete = true;\n\n \/\/ multi-group\n } else {\n\n \/\/ Need at least the first group\n if (!parts[0].is_received)\n return;\n\n is_complete=true;\n\n \/\/ First group\n direction = bits(parts[0].data[0], 14, 1);\n extent = bits(parts[0].data[0], 11, 3);\n events.push_back(bits(parts[0].data[0], 0, 11));\n location = parts[0].data[1];\n\n \/\/ Subsequent parts\n if (parts[1].is_received) {\n auto freeform = getFreeformFields(parts);\n\n for (auto p : freeform) {\n uint16_t label = p.first;\n uint16_t field_data = p.second;\n \/\/printf (\"tmc: label %04x: field_data %04x\\n\",label,field_data);\n\n \/\/ Duration\n if (label == 0) {\n duration = field_data;\n\n \/\/ Length of route affected\n } else if (label == 2) {\n length_affected = field_data;\n has_length_affected = true;\n\n \/\/ Start \/ stop time\n } else if (label == 7) {\n time_starts = field_data;\n has_time_starts = true;\n } else if (label == 8) {\n time_until = field_data;\n has_time_until = true;\n } else {\n printf(\" \/* TODO label=%d *\/\",label);\n }\n }\n }\n }\n}\n\nvoid Message::print() const {\n printf(\", traffic_message: { \");\n\n if (!is_complete || events.empty()) {\n printf(\"}\\n\");\n return;\n }\n\n if (events.size() > 1) {\n printf(\"events: [ %s ]\", commaJoin(events).c_str());\n } else {\n printf(\"event: { code: %d, description: \\\"%s\\\" }\", events[0],\n sentence(getEvent(events[0]).description).c_str());\n }\n\n printf(\", %slocation: \\\"0x%02x\\\", direction: \\\"%s\\\", extent: %d, \"\n \"diversion_advised: %s\",\n (is_encrypted ? \"encrypted_\" : \"\"), location,\n direction ? \"negative\" : \"positive\",\n extent, divertadv ? \"true\" : \"false\" );\n\n\n if (has_time_starts)\n printf(\", starts: \\\"%s\\\"\", timeString(time_starts).c_str());\n if (has_time_until)\n printf(\", until: \\\"%s\\\"\", timeString(time_until).c_str());\n\n\n printf (\"}\");\n\n}\n\n} \/\/ namespace tmc\n} \/\/ namespace redsea\n<|endoftext|>"} {"text":"\/\/ augmentation_widget.cpp\r\n\r\n#include \r\n\r\n#include \"augmentation_widget.h\"\r\n\r\naugmentation_widget::augmentation_widget (QWidget* parent)\r\n: QOpenGLWidget (parent)\r\n, _scale_factor (1.0f)\r\n, _x_pos (0.0f)\r\n, _y_pos (0.0f)\r\n, _x_rot (0)\r\n, _y_rot (0)\r\n, _z_rot (0)\r\n, _cap (0)\r\n, _frame_timer (new QTimer (this)) {\r\n connect (_frame_timer, SIGNAL (timeout ()), this, SLOT (update ()));\r\n _frame_timer->setInterval (1000 \/ _framerate);\r\n _frame_timer->start ();\r\n}\r\n\r\naugmentation_widget::~augmentation_widget () {\r\n delete _frame_timer;\r\n}\r\n\r\nQSize augmentation_widget::minimumSizeHint () const {\r\n return QSize (100, 100);\r\n}\r\n\r\nQSize augmentation_widget::sizeHint () const {\r\n return QSize (500, 500);\r\n}\r\n\r\nstatic void qNormalizeAngle (int& angle) {\r\n while (angle < 0) angle += 360;\r\n while (angle > 360) angle -= 360;\r\n}\r\n\r\nvoid augmentation_widget::setScale (float scale) {\r\n _scale_factor = scale;\r\n \/\/ emit xPositionChanged (location);\r\n}\r\n\r\nvoid augmentation_widget::setXPosition (float location) {\r\n _x_pos = location;\r\n \/\/ emit xPositionChanged (location);\r\n}\r\n\r\nvoid augmentation_widget::setYPosition (float location) {\r\n _y_pos = location;\r\n \/\/ emit yPositionChanged (location);\r\n}\r\n\r\nvoid augmentation_widget::setXRotation (int angle) {\r\n qNormalizeAngle (angle);\r\n _x_rot = angle;\r\n}\r\n\r\nvoid augmentation_widget::setYRotation (int angle) {\r\n qNormalizeAngle (angle);\r\n _y_rot = angle;\r\n}\r\n\r\nvoid augmentation_widget::setZRotation (int angle) {\r\n qNormalizeAngle (angle);\r\n _z_rot = angle;\r\n}\r\n\r\nvoid augmentation_widget::initializeGL () {\r\n initializeOpenGLFunctions ();\r\n\r\n glClearColor (0, 0, 0, 1.0f);\r\n glEnable (GL_DEPTH_TEST);\r\n glEnable (GL_CULL_FACE);\r\n glShadeModel (GL_SMOOTH);\r\n glEnable (GL_LIGHTING);\r\n glEnable (GL_LIGHT0);\r\n glMatrixMode (GL_PROJECTION);\r\n glEnable (GL_TEXTURE_2D);\r\n glGenTextures (1, &_texture_background);\r\n\r\n \/\/ glMatrixMode (GL_MODELVIEW);\r\n \/*static GLfloat lightPosition[4] = { 0, 0, 10, 1.0 };\r\n glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);\r\n glLoadIdentity ();\r\n gluPerspective (33.7, 1.3, 0.1, 100.0);\r\n glMatrixMode (GL_MODELVIEW)*\/\r\n}\r\n\r\nvoid augmentation_widget::resizeGL (int width, int height) {\r\n int side = qMin (width, height);\r\n glViewport ((width - side) \/ 2, (height - side) \/ 2, side, side);\r\n\r\n glMatrixMode (GL_PROJECTION);\r\n glLoadIdentity ();\r\n#ifdef QT_OPENGL_ES_1\r\n glOrthof (-2, +2, -2, +2, 1.0, 15.0);\r\n#else\r\n glOrtho (-2, +2, -2, +2, 1.0, 15.0);\r\n#endif\r\n glMatrixMode (GL_MODELVIEW);\r\n}\r\n\r\nvoid augmentation_widget::paintGL () {\r\n \/\/ QOpenGLFunctions* f = QOpenGLContext::currentContext ()->functions ();\r\n glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n glLoadIdentity ();\r\n\r\n cv::Mat frame;\r\n _cap >> frame;\r\n if (frame.empty ()) {\r\n printf (\"empty video frame\"); \/\/ TODO throw error here\r\n return;\r\n }\r\n \/\/ create background texture\r\n glBindTexture (GL_TEXTURE_2D, _texture_background);\r\n glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\r\n glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\r\n glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, frame.cols, frame.rows, 0, GL_BGR,\r\n GL_UNSIGNED_BYTE, frame.ptr ());\r\n\r\n \/\/ glMatrixMode (GL_MODELVIEW);\r\n\r\n \/\/ draw background\r\n glTranslatef (0.0, 0.0, -10.0);\r\n\r\n glBegin (GL_QUADS);\r\n glTexCoord2f (0.0, 1.0);\r\n glVertex3f (-4.0, -3.0, -2.0);\r\n glTexCoord2f (1.0, 1.0);\r\n glVertex3f (4.0, -3.0, -2.0);\r\n glTexCoord2f (1.0, 0.0);\r\n glVertex3f (4.0, 3.0, -2.0);\r\n glTexCoord2f (0.0, 0.0);\r\n glVertex3f (-4.0, 3.0, -2.0);\r\n glEnd ();\r\n \/\/ glPopMatrix ();\r\n\r\n glPushMatrix ();\r\n glScalef (_scale_factor, _scale_factor, _scale_factor);\r\n glRotatef (_x_rot, 1, 0, 0);\r\n glRotatef (_y_rot, 0, 1, 0);\r\n glRotatef (_z_rot, 0, 0, 1);\r\n glTranslatef (_x_pos, _y_pos, 0);\r\n\r\n glBegin (GL_QUADS);\r\n glNormal3f (0, 0, -1);\r\n glVertex3f (-1, -1, 0);\r\n glVertex3f (-1, 1, 0);\r\n glVertex3f (1, 1, 0);\r\n glVertex3f (1, -1, 0);\r\n glEnd ();\r\n\r\n glBegin (GL_TRIANGLES);\r\n glNormal3f (0, -1, 0.707);\r\n glVertex3f (-1, -1, 0);\r\n glVertex3f (1, -1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glBegin (GL_TRIANGLES);\r\n glNormal3f (1, 0, 0.707);\r\n glVertex3f (1, -1, 0);\r\n glVertex3f (1, 1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glBegin (GL_TRIANGLES);\r\n glNormal3f (0, 1, 0.707);\r\n glVertex3f (1, 1, 0);\r\n glVertex3f (-1, 1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glBegin (GL_TRIANGLES);\r\n glNormal3f (-1, 0, 0.707);\r\n glVertex3f (-1, 1, 0);\r\n glVertex3f (-1, -1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glPopMatrix ();\r\n}\r\nfix augmentatation widget\/\/ augmentation_widget.cpp\r\n\r\n#include \"augmentation_widget.h\"\r\n#include \r\n#include \r\n\r\naugmentation_widget::augmentation_widget (QWidget* parent)\r\n: QOpenGLWidget (parent)\r\n, _scale_factor (1.0f)\r\n, _x_pos (0.0f)\r\n, _y_pos (0.0f)\r\n, _x_rot (0)\r\n, _y_rot (0)\r\n, _z_rot (0)\r\n, _cap (0)\r\n, _frame_timer (new QTimer (this)) {\r\n connect (_frame_timer, SIGNAL (timeout ()), this, SLOT (update ()));\r\n _frame_timer->setInterval (1000 \/ _framerate);\r\n _frame_timer->start ();\r\n}\r\n\r\naugmentation_widget::~augmentation_widget () {\r\n delete _frame_timer;\r\n}\r\n\r\nQSize augmentation_widget::minimumSizeHint () const {\r\n return QSize (100, 100);\r\n}\r\n\r\nQSize augmentation_widget::sizeHint () const {\r\n return QSize (500, 500);\r\n}\r\n\r\nstatic void qNormalizeAngle (int& angle) {\r\n while (angle < 0) angle += 360;\r\n while (angle > 360) angle -= 360;\r\n}\r\n\r\nvoid augmentation_widget::setScale (float scale) {\r\n _scale_factor = scale;\r\n \/\/ emit xPositionChanged (location);\r\n}\r\n\r\nvoid augmentation_widget::setXPosition (float location) {\r\n _x_pos = location;\r\n \/\/ emit xPositionChanged (location);\r\n}\r\n\r\nvoid augmentation_widget::setYPosition (float location) {\r\n _y_pos = location;\r\n \/\/ emit yPositionChanged (location);\r\n}\r\n\r\nvoid augmentation_widget::setXRotation (int angle) {\r\n qNormalizeAngle (angle);\r\n _x_rot = angle;\r\n}\r\n\r\nvoid augmentation_widget::setYRotation (int angle) {\r\n qNormalizeAngle (angle);\r\n _y_rot = angle;\r\n}\r\n\r\nvoid augmentation_widget::setZRotation (int angle) {\r\n qNormalizeAngle (angle);\r\n _z_rot = angle;\r\n}\r\n\r\nvoid augmentation_widget::initializeGL () {\r\n initializeOpenGLFunctions ();\r\n\r\n glClearColor (0, 0, 0, 1.0f);\r\n glEnable (GL_DEPTH_TEST);\r\n glEnable (GL_CULL_FACE);\r\n glShadeModel (GL_SMOOTH);\r\n glEnable (GL_LIGHTING);\r\n glEnable (GL_LIGHT0);\r\n glMatrixMode (GL_PROJECTION);\r\n glEnable (GL_TEXTURE_2D);\r\n glGenTextures (1, &_texture_background);\r\n glEnable (GL_COLOR_MATERIAL);\r\n\r\n glMatrixMode (GL_MODELVIEW);\r\n static GLfloat lightPosition[4] = { 0, 0, 10, 1.0 };\r\n glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);\r\n glLoadIdentity ();\r\n \/\/ gluPerspective (33.7, 1.3, 0.1, 100.0);\r\n glMatrixMode (GL_MODELVIEW);\r\n}\r\n\r\nvoid augmentation_widget::resizeGL (int width, int height) {\r\n int side = qMin (width, height);\r\n glViewport ((width - side) \/ 2, (height - side) \/ 2, side, side);\r\n\r\n glMatrixMode (GL_PROJECTION);\r\n glLoadIdentity ();\r\n#ifdef QT_OPENGL_ES_1\r\n glOrthof (-2, +2, -2, +2, 1.0, 15.0);\r\n#else\r\n glOrtho (-2, +2, -2, +2, 1.0, 15.0);\r\n#endif\r\n glMatrixMode (GL_MODELVIEW);\r\n}\r\n\r\nvoid augmentation_widget::paintGL () {\r\n glMatrixMode (GL_MODELVIEW);\r\n \/\/ QOpenGLFunctions* f = QOpenGLContext::currentContext ()->functions ();\r\n glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n glLoadIdentity ();\r\n\r\n cv::Mat frame;\r\n _cap >> frame;\r\n if (frame.empty ()) {\r\n printf (\"empty video frame\"); \/\/ TODO throw error here\r\n return;\r\n }\r\n \/\/ create background texture\r\n glBindTexture (GL_TEXTURE_2D, _texture_background);\r\n glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\r\n glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\r\n glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, frame.cols, frame.rows, 0, GL_BGR,\r\n GL_UNSIGNED_BYTE, frame.ptr ());\r\n\r\n\r\n \/\/ draw background\r\n glTranslatef (0.0, 0.0, -10.0);\r\n\r\n glBegin (GL_QUADS);\r\n glColor3f (1, 1, 1);\r\n glTexCoord2f (0.0, 1.0);\r\n glVertex3f (-4.0, -3.0, -2.0);\r\n glTexCoord2f (1.0, 1.0);\r\n glVertex3f (4.0, -3.0, -2.0);\r\n glTexCoord2f (1.0, 0.0);\r\n glVertex3f (4.0, 3.0, -2.0);\r\n glTexCoord2f (0.0, 0.0);\r\n glVertex3f (-4.0, 3.0, -2.0);\r\n glEnd ();\r\n\r\n glPushMatrix ();\r\n\r\n \/*GLfloat persp_mat[16] = { 1, 0, -3.845925372767128e-16, 0, 0,\r\n 0.5000000000000003, -5.768888059150692e-16, 0, 0, 0, 1, 0, 0, 0, 0, 1 };\r\n glMultMatrixf (persp_mat);*\/\r\n \/\/[1, 0, -3.845925372767128e-16;\r\n \/\/ 0, 0.3333333333333335, 0.6666666666666663;\r\n \/\/ 0, 0, 1]\r\n\r\n \/\/[1, 0, -3.845925372767128e-16;\r\n \/\/ 0, 0.5000000000000003, -5.768888059150692e-16;\r\n \/\/ 0, 0, 1]\r\n\r\n glTranslatef (_x_pos, _y_pos, 0);\r\n glScalef (_scale_factor, _scale_factor, _scale_factor);\r\n glRotatef (_x_rot, 1, 0, 0);\r\n glRotatef (_y_rot, 0, 1, 0);\r\n glRotatef (_z_rot, 0, 0, 1);\r\n\r\n glBegin (GL_QUADS);\r\n glColor3f (0, 1, 1);\r\n glNormal3f (0, 0, -1);\r\n glVertex3f (-1, -1, 0);\r\n glVertex3f (-1, 1, 0);\r\n glVertex3f (1, 1, 0);\r\n glVertex3f (1, -1, 0);\r\n glEnd ();\r\n\r\n glBegin (GL_TRIANGLES);\r\n glColor3f (1, 0, 0);\r\n glNormal3f (0, -1, 0.707);\r\n glVertex3f (-1, -1, 0);\r\n glVertex3f (1, -1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glBegin (GL_TRIANGLES);\r\n glColor3f (0, 1, 0);\r\n glNormal3f (1, 0, 0.707);\r\n glVertex3f (1, -1, 0);\r\n glVertex3f (1, 1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glBegin (GL_TRIANGLES);\r\n glColor3f (0, 0, 1);\r\n glNormal3f (0, 1, 0.707);\r\n glVertex3f (1, 1, 0);\r\n glVertex3f (-1, 1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glBegin (GL_TRIANGLES);\r\n glColor3f (1, 1, 0);\r\n glNormal3f (-1, 0, 0.707);\r\n glVertex3f (-1, 1, 0);\r\n glVertex3f (-1, -1, 0);\r\n glVertex3f (0, 0, 1.2);\r\n glEnd ();\r\n glPopMatrix ();\r\n}\r\n<|endoftext|>"} {"text":"\/***************************************\n** Tsunagari Tile Engine **\n** gosu-window.cpp **\n** Copyright 2011-2014 Michael Reiley **\n** Copyright 2011-2017 Paul Merrill **\n***************************************\/\n\n\/\/ **********\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/ **********\n\n#include \/\/ for Gosu::Graphics\n#include \n#include \n\n#include \"av\/gosu\/gosu-window.h\"\n\n#include \"core\/client-conf.h\"\n#include \"core\/world.h\"\n\n#define CHECK(x) if (!(x)) { return false; }\n\n\/\/ Garbage collection called every X milliseconds\n#define GC_CALL_PERIOD 10 * 1000\n\n#ifdef BACKEND_GOSU\nstatic GosuGameWindow* globalWindow = nullptr;\n\nGameWindow* GameWindow::create()\n{\n globalWindow = new GosuGameWindow();\n return globalWindow;\n}\n\nGameWindow& GameWindow::instance()\n{\n return *globalWindow;\n}\n\ntime_t GameWindow::time()\n{\n return (time_t)Gosu::milliseconds();\n}\n#endif\n\nnamespace Gosu {\n \/**\n * Enable 1980s-style graphics scaling: nearest-neighbor filtering.\n * Call this function before creating any Gosu::Image.\n *\/\n void enableUndocumentedRetrofication() {\n extern bool undocumented_retrofication;\n undocumented_retrofication = true;\n }\n}\n\nGosuGameWindow::GosuGameWindow()\n \/\/ Gosu emulates the requested screen resolution on fullscreen,\n \/\/ but this breaks our aspect ratio-correcting letterbox.\n \/\/ Ergo we just make a window the size of the screen.\n : Gosu::Window(\n conf.fullscreen ? Gosu::screen_width() :\n (unsigned)conf.windowSize.x,\n conf.fullscreen ? Gosu::screen_height() :\n (unsigned)conf.windowSize.y,\n conf.fullscreen\n ),\n now(this->time()),\n lastGCtime(0)\n{\n Gosu::enableUndocumentedRetrofication();\n\n auto& keys = gosuToTsunagariKey;\n keys[Gosu::ButtonName::KB_ESCAPE] = KBEscape;\n keys[Gosu::ButtonName::KB_LEFT_SHIFT] = KBLeftShift;\n keys[Gosu::ButtonName::KB_RIGHT_SHIFT] = KBRightShift;\n keys[Gosu::ButtonName::KB_LEFT_CONTROL] = KBLeftControl;\n keys[Gosu::ButtonName::KB_RIGHT_CONTROL] = KBRightControl;\n keys[Gosu::ButtonName::KB_SPACE] = KBSpace;\n keys[Gosu::ButtonName::KB_LEFT] = KBLeftArrow;\n keys[Gosu::ButtonName::KB_RIGHT] = KBRightArrow;\n keys[Gosu::ButtonName::KB_UP] = KBUpArrow;\n keys[Gosu::ButtonName::KB_DOWN] = KBDownArrow;\n}\n\nunsigned GosuGameWindow::width() const\n{\n return graphics().width();\n}\n\nunsigned GosuGameWindow::height() const\n{\n return graphics().height();\n}\n\nvoid GosuGameWindow::setCaption(const std::string& caption)\n{\n Gosu::Window::set_caption(caption);\n}\n\nvoid GosuGameWindow::button_down(const Gosu::Button btn)\n{\n now = this->time();\n if (keystates.find(btn) == keystates.end()) {\n keystate& state = keystates[btn];\n state.since = now;\n state.initiallyResolved = false;\n state.consecutive = false;\n }\n\n \/\/ We process the initial buttonDown here so that it\n \/\/ gets handled even if we receive a buttonUp before an\n \/\/ update.\n auto mapped = gosuToTsunagariKey[btn.id()];\n if (mapped) {\n emitKeyDown(mapped);\n }\n}\n\nvoid GosuGameWindow::button_up(const Gosu::Button btn)\n{\n keystates.erase(btn);\n\n auto mapped = gosuToTsunagariKey[btn.id()];\n if (mapped) {\n emitKeyUp(mapped);\n }\n}\n\nvoid GosuGameWindow::draw()\n{\n World::instance().draw();\n}\n\nbool GosuGameWindow::needs_redraw() const\n{\n return World::instance().needsRedraw();\n}\n\nvoid GosuGameWindow::update()\n{\n now = this->time();\n\n if (conf.moveMode == TURN) {\n handleKeyboardInput(now);\n }\n World::instance().update(now);\n\n if (now > lastGCtime + GC_CALL_PERIOD) {\n lastGCtime = now;\n World::instance().garbageCollect();\n }\n}\n\nvoid GosuGameWindow::mainLoop()\n{\n show();\n}\n\nvoid GosuGameWindow::drawRect(double x1, double x2, double y1, double y2,\n uint32_t argb)\n{\n Gosu::Color c(argb);\n double top = std::numeric_limits::max();\n graphics().draw_quad(\n x1, y1, c,\n x2, y1, c,\n x2, y2, c,\n x1, y2, c,\n top\n );\n}\n\nvoid GosuGameWindow::scale(double x, double y, std::function op)\n{\n graphics().transform(Gosu::scale(x, y), op);\n}\n\nvoid GosuGameWindow::translate(double x, double y, std::function op)\n{\n graphics().transform(Gosu::translate(x, y), op);\n}\n\nvoid GosuGameWindow::clip(double x, double y, double width, double height,\n std::function op)\n{\n graphics().clip_to(x, y, width, height, op);\n}\n\nvoid GosuGameWindow::close()\n{\n Gosu::Window::close();\n}\n\n\nvoid GosuGameWindow::handleKeyboardInput(time_t now)\n{\n std::map::iterator it;\n\n \/\/ Persistent input handling code\n for (it = keystates.begin(); it != keystates.end(); it++) {\n Gosu::Button btn = it->first;\n auto mapped = gosuToTsunagariKey[btn.id()];\n keystate& state = it->second;\n\n \/\/ If there is persistCons milliseconds of latency\n \/\/ between when a button is depressed and when we first look at\n \/\/ it here, we'll incorrectly try to fire off a second round of\n \/\/ input.\n \/\/ This can happen if an intermediary function blocks the thread\n \/\/ for a while.\n if (!state.initiallyResolved) {\n state.initiallyResolved = true;\n continue;\n }\n\n time_t delay = state.consecutive ?\n conf.persistCons : conf.persistInit;\n if (now >= state.since + delay) {\n state.since += delay;\n World::instance().buttonDown(mapped);\n state.consecutive = true;\n }\n }\n}\nGosuWindow: Don't initialize unused keys\/***************************************\n** Tsunagari Tile Engine **\n** gosu-window.cpp **\n** Copyright 2011-2014 Michael Reiley **\n** Copyright 2011-2017 Paul Merrill **\n***************************************\/\n\n\/\/ **********\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/ **********\n\n#include \/\/ for Gosu::Graphics\n#include \n#include \n\n#include \"av\/gosu\/gosu-window.h\"\n\n#include \"core\/client-conf.h\"\n#include \"core\/world.h\"\n\n#define CHECK(x) if (!(x)) { return false; }\n\n\/\/ Garbage collection called every X milliseconds\n#define GC_CALL_PERIOD 10 * 1000\n\n#ifdef BACKEND_GOSU\nstatic GosuGameWindow* globalWindow = nullptr;\n\nGameWindow* GameWindow::create()\n{\n globalWindow = new GosuGameWindow();\n return globalWindow;\n}\n\nGameWindow& GameWindow::instance()\n{\n return *globalWindow;\n}\n\ntime_t GameWindow::time()\n{\n return (time_t)Gosu::milliseconds();\n}\n#endif\n\nnamespace Gosu {\n \/**\n * Enable 1980s-style graphics scaling: nearest-neighbor filtering.\n * Call this function before creating any Gosu::Image.\n *\/\n void enableUndocumentedRetrofication() {\n extern bool undocumented_retrofication;\n undocumented_retrofication = true;\n }\n}\n\nGosuGameWindow::GosuGameWindow()\n \/\/ Gosu emulates the requested screen resolution on fullscreen,\n \/\/ but this breaks our aspect ratio-correcting letterbox.\n \/\/ Ergo we just make a window the size of the screen.\n : Gosu::Window(\n conf.fullscreen ? Gosu::screen_width() :\n (unsigned)conf.windowSize.x,\n conf.fullscreen ? Gosu::screen_height() :\n (unsigned)conf.windowSize.y,\n conf.fullscreen\n ),\n now(this->time()),\n lastGCtime(0)\n{\n Gosu::enableUndocumentedRetrofication();\n\n gosuToTsunagariKey.reserve(Gosu::ButtonName::NUM_BUTTONS);\n auto& keys = gosuToTsunagariKey;\n keys[Gosu::ButtonName::KB_ESCAPE] = KBEscape;\n keys[Gosu::ButtonName::KB_LEFT_SHIFT] = KBLeftShift;\n keys[Gosu::ButtonName::KB_RIGHT_SHIFT] = KBRightShift;\n keys[Gosu::ButtonName::KB_LEFT_CONTROL] = KBLeftControl;\n keys[Gosu::ButtonName::KB_RIGHT_CONTROL] = KBRightControl;\n keys[Gosu::ButtonName::KB_SPACE] = KBSpace;\n keys[Gosu::ButtonName::KB_LEFT] = KBLeftArrow;\n keys[Gosu::ButtonName::KB_RIGHT] = KBRightArrow;\n keys[Gosu::ButtonName::KB_UP] = KBUpArrow;\n keys[Gosu::ButtonName::KB_DOWN] = KBDownArrow;\n}\n\nunsigned GosuGameWindow::width() const\n{\n return graphics().width();\n}\n\nunsigned GosuGameWindow::height() const\n{\n return graphics().height();\n}\n\nvoid GosuGameWindow::setCaption(const std::string& caption)\n{\n Gosu::Window::set_caption(caption);\n}\n\nvoid GosuGameWindow::button_down(const Gosu::Button btn)\n{\n now = this->time();\n if (keystates.find(btn) == keystates.end()) {\n keystate& state = keystates[btn];\n state.since = now;\n state.initiallyResolved = false;\n state.consecutive = false;\n }\n\n \/\/ We process the initial buttonDown here so that it\n \/\/ gets handled even if we receive a buttonUp before an\n \/\/ update.\n auto mapped = gosuToTsunagariKey[btn.id()];\n if (mapped) {\n emitKeyDown(mapped);\n }\n}\n\nvoid GosuGameWindow::button_up(const Gosu::Button btn)\n{\n keystates.erase(btn);\n\n auto mapped = gosuToTsunagariKey[btn.id()];\n if (mapped) {\n emitKeyUp(mapped);\n }\n}\n\nvoid GosuGameWindow::draw()\n{\n World::instance().draw();\n}\n\nbool GosuGameWindow::needs_redraw() const\n{\n return World::instance().needsRedraw();\n}\n\nvoid GosuGameWindow::update()\n{\n now = this->time();\n\n if (conf.moveMode == TURN) {\n handleKeyboardInput(now);\n }\n World::instance().update(now);\n\n if (now > lastGCtime + GC_CALL_PERIOD) {\n lastGCtime = now;\n World::instance().garbageCollect();\n }\n}\n\nvoid GosuGameWindow::mainLoop()\n{\n show();\n}\n\nvoid GosuGameWindow::drawRect(double x1, double x2, double y1, double y2,\n uint32_t argb)\n{\n Gosu::Color c(argb);\n double top = std::numeric_limits::max();\n graphics().draw_quad(\n x1, y1, c,\n x2, y1, c,\n x2, y2, c,\n x1, y2, c,\n top\n );\n}\n\nvoid GosuGameWindow::scale(double x, double y, std::function op)\n{\n graphics().transform(Gosu::scale(x, y), op);\n}\n\nvoid GosuGameWindow::translate(double x, double y, std::function op)\n{\n graphics().transform(Gosu::translate(x, y), op);\n}\n\nvoid GosuGameWindow::clip(double x, double y, double width, double height,\n std::function op)\n{\n graphics().clip_to(x, y, width, height, op);\n}\n\nvoid GosuGameWindow::close()\n{\n Gosu::Window::close();\n}\n\n\nvoid GosuGameWindow::handleKeyboardInput(time_t now)\n{\n std::map::iterator it;\n\n \/\/ Persistent input handling code\n for (it = keystates.begin(); it != keystates.end(); it++) {\n Gosu::Button btn = it->first;\n auto mapped = gosuToTsunagariKey[btn.id()];\n keystate& state = it->second;\n\n \/\/ If there is persistCons milliseconds of latency\n \/\/ between when a button is depressed and when we first look at\n \/\/ it here, we'll incorrectly try to fire off a second round of\n \/\/ input.\n \/\/ This can happen if an intermediary function blocks the thread\n \/\/ for a while.\n if (!state.initiallyResolved) {\n state.initiallyResolved = true;\n continue;\n }\n\n time_t delay = state.consecutive ?\n conf.persistCons : conf.persistInit;\n if (now >= state.since + delay) {\n state.since += delay;\n World::instance().buttonDown(mapped);\n state.consecutive = true;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"vm.h\"\n\nconst int STACK_SIZE = 1024;\n\nenum offset {\n\treturn_address = 0,\n\tenclosing_frame = 1,\n\tdeclaration_frame = 2,\n\tlocal = 3\n};\n\nvoid pl0::execute(const bytecode & code, int entry_addr) {\n\tint pc = 0;\n\tint *stack = new int[STACK_SIZE];\n\tint *bp = stack;\n\tint *sp = bp + offset::declaration_frame;\n\n\tauto resolve = [&](int dist) -> int* {\n\t\tint *fp = bp;\n\t\twhile (dist > 0) {\n\t\t\tfp = reinterpret_cast(fp[offset::declaration_frame]);\n\t\t\tdist--;\n\t\t}\n\t\treturn fp;\n\t};\n\t\n\tauto push = [&](auto value) -> void {\n\t\tif constexpr (std::is_pointer_v) {\n\t\t\t*++sp = reinterpret_cast(value);\n\t\t} else {\n\t\t\t*++sp = value;\n\t\t}\n\t};\n\n\tauto pop = [&]() -> int {\n\t\treturn *sp--;\n\t};\n\n\tconst std::unordered_map> bifunctors = {\n\t\t{ opt::ADD, std::plus() },\n\t\t{ opt::SUB, std::minus() },\n\t\t{ opt::DIV, std::divides() },\n\t\t{ opt::MUL, std::multiplies() },\n\t\t{ opt::LE, std::less() },\n\t\t{ opt::LEQ, std::less_equal() },\n\t\t{ opt::GE, std::greater() },\n\t\t{ opt::GEQ, std::greater_equal() },\n\t\t{ opt::EQ, std::equal_to() },\n\t\t{ opt::NEQ, std::not_equal_to() }\n\t};\n\n int codelen = static_cast(code.size());\n\twhile (pc < codelen) {\n\t\tconst instruction & ins = code[pc];\n\t\tpc++;\n\t\tswitch (std::get<0>(ins)) {\n\t\tcase opcode::LIT:\n\t\t\tpush(std::get<2>(ins));\n\t\t\tbreak;\n\t\tcase opcode::LOD:\n\t\t\tpush(resolve(std::get<1>(ins))[offset::local + std::get<2>(ins)]);\n\t\t\tbreak;\n\t\tcase opcode::STO:\n\t\t\tresolve(std::get<1>(ins))[offset::local + std::get<2>(ins)] = pop();\n\t\t\tbreak;\n\t\tcase opcode::CAL:\n\t\t\tpush(pc);\n\t\t\tpush(bp);\n\t\t\tpush(resolve(std::get<1>(ins)));\n\t\t\tbp = sp - 3;\n\t\t\tpc = std::get<2>(ins);\n\t\t\tbreak;\n\t\tcase opcode::INT:\n\t\t\tsp += std::get<2>(ins);\n\t\t\tbreak;\n\t\tcase opcode::JMP:\n\t\t\tpc = std::get<2>(ins);\n\t\t\tbreak;\n\t\tcase opcode::JPC:\n\t\t\tif (pop()) pc = std::get<2>(ins);\n\t\t\tbreak;\n\t\tcase opcode::OPR:\n\t\t\tif (std::get<2>(ins) == *opt::ODD) {\n\t\t\t\tpush(pop() % 2);\n\t\t\t} else if (std::get<2>(ins) == *opt::READ) {\n\t\t\t\tint tmp;\n\t\t\t\tstd::cin >> tmp;\n\t\t\t\tpush(tmp);\n\t\t\t} else if (std::get<2>(ins) == *opt::WRITE) {\n\t\t\t\tstd::cout << pop() << '\\n';\n\t\t\t} else if (std::get<2>(ins) == *opt::RET) {\n\t\t\t\tsp = bp + offset::enclosing_frame;\n\t\t\t\tbp = reinterpret_cast(pop());\n\t\t\t\tpc = pop();\n\t\t\t} else {\n\t\t\t\tint rhs = pop(), lhs = pop();\n\t\t\t\tbifunctors.find(opt(std::get<2>(ins)))->second(lhs, rhs);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\nMake virtual machine works!#include \n#include \n#include \n#include \n#include \n\n#include \"vm.h\"\n\nconst int STACK_SIZE = 1024;\n\nenum offset {\n\treturn_address = 0,\n\tenclosing_frame = 1,\n\tdeclaration_frame = 2,\n\tlocal = 3\n};\n\nvoid pl0::execute(const bytecode & code, int entry_addr) {\n\tint pc = 0;\n\tint *stack = new int[STACK_SIZE];\n\tint *bp = stack;\n\tint *sp = bp;\n\t\n\tauto push = [&](auto value) -> void {\n\t\tif constexpr (std::is_pointer_v) {\n\t\t\t*++sp = reinterpret_cast(value);\n\t\t} else {\n\t\t\t*++sp = value;\n\t\t}\n\t};\n\n\tauto pop = [&]() -> int {\n\t\treturn *sp--;\n\t};\n\n\tconst std::unordered_map> bifunctors = {\n\t\t{ opt::ADD, std::plus() },\n\t\t{ opt::SUB, std::minus() },\n\t\t{ opt::DIV, std::divides() },\n\t\t{ opt::MUL, std::multiplies() },\n\t\t{ opt::LE, std::less() },\n\t\t{ opt::LEQ, std::less_equal() },\n\t\t{ opt::GE, std::greater() },\n\t\t{ opt::GEQ, std::greater_equal() },\n\t\t{ opt::EQ, std::equal_to() },\n\t\t{ opt::NEQ, std::not_equal_to() }\n\t};\n\n int codelen = static_cast(code.size());\n bp[offset::return_address] = codelen;\n\n\twhile (pc < codelen) {\n opcode opc;\n int level, address;\n std::tie(opc, level, address) = code[pc];\n\t\tpc++;\n\n \/* get bp of the frame whose distance from current frame is given *\/\n auto resolve = [&]() -> int* {\n int *fp = bp, dist = level;\n while (dist > 0) {\n fp = reinterpret_cast(fp[offset::declaration_frame]);\n dist--;\n }\n return fp;\n };\n\n\t\tswitch (opc) {\n\t\tcase opcode::LIT:\n\t\t\tpush(address);\n\t\t\tbreak;\n\t\tcase opcode::LOD:\n\t\t\tpush(resolve()[offset::local + address]);\n\t\t\tbreak;\n\t\tcase opcode::STO:\n\t\t\tresolve()[offset::local + address] = pop();\n\t\t\tbreak;\n\t\tcase opcode::CAL:\n \/\/ save context\n sp[0] = pc;\n sp[1] = reinterpret_cast(bp);\n sp[2] = reinterpret_cast(resolve());\n bp = sp;\n\t\t\tpc = address;\n\t\t\tbreak;\n\t\tcase opcode::INT:\n\t\t\tsp += address;\n\t\t\tbreak;\n\t\tcase opcode::JMP:\n\t\t\tpc = address;\n\t\t\tbreak;\n\t\tcase opcode::JPC:\n\t\t\tif (!pop()) pc = address;\n\t\t\tbreak;\n\t\tcase opcode::OPR:\n\t\t\tif (address == *opt::ODD) {\n\t\t\t\tpush(pop() % 2);\n\t\t\t} else if (address == *opt::READ) {\n\t\t\t\tint tmp;\n\t\t\t\tstd::cin >> tmp;\n\t\t\t\tpush(tmp);\n\t\t\t} else if (address == *opt::WRITE) {\n\t\t\t\tstd::cout << pop() << '\\n';\n\t\t\t} else if (address == *opt::RET) {\n \/\/ restore context\n pc = bp[0];\n sp = bp;\n bp = reinterpret_cast(bp[1]);\n\t\t\t} else {\n\t\t\t\tint rhs = pop(), lhs = pop();\n\t\t\t\tauto op = bifunctors.find(opt(address))->second;\n push(op(lhs, rhs));\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n\n#include \n#include \n\n#include \n\nstatic const char *DEFAULT_BENCH_FILTER = \".*\";\n\nstatic void SetupBenchArgs(ArgsManager &argsman) {\n SetupHelpOptions(argsman);\n\n argsman.AddArg(\"-list\", \"List benchmarks without executing them\",\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\"-filter=\",\n strprintf(\"Regular expression filter to select benchmark by \"\n \"name (default: %s)\",\n DEFAULT_BENCH_FILTER),\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\"-asymptote=n1,n2,n3,...\",\n strprintf(\"Test asymptotic growth of the runtime of an \"\n \"algorithm, if supported by the benchmark\"),\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\n \"-output_csv=\",\n \"Generate CSV file with the most important benchmark results.\",\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\"-output_json=\",\n \"Generate JSON file with all benchmark results.\",\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n}\n\n\/\/ parses a comma separated list like \"10,20,30,50\"\nstatic std::vector parseAsymptote(const std::string &str) {\n std::stringstream ss(str);\n std::vector numbers;\n double d;\n char c;\n while (ss >> d) {\n numbers.push_back(d);\n ss >> c;\n }\n return numbers;\n}\n\nint main(int argc, char **argv) {\n ArgsManager argsman;\n SetupBenchArgs(argsman);\n std::string error;\n if (!argsman.ParseParameters(argc, argv, error)) {\n tfm::format(std::cerr, \"Error parsing command line arguments: %s\\n\",\n error);\n return EXIT_FAILURE;\n }\n\n if (HelpRequested(argsman)) {\n std::cout << argsman.GetHelpMessage();\n return EXIT_SUCCESS;\n }\n\n benchmark::Args args;\n args.regex_filter = argsman.GetArg(\"-filter\", DEFAULT_BENCH_FILTER);\n args.is_list_only = argsman.GetBoolArg(\"-list\", false);\n args.asymptote = parseAsymptote(argsman.GetArg(\"-asymptote\", \"\"));\n args.output_csv = argsman.GetArg(\"-output_csv\", \"\");\n args.output_json = argsman.GetArg(\"-output_json\", \"\");\n\n benchmark::BenchRunner::RunAll(args);\n\n return EXIT_SUCCESS;\n}\nCall SHA256AutoDetect in benchmark setup\/\/ Copyright (c) 2015-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nstatic const char *DEFAULT_BENCH_FILTER = \".*\";\n\nstatic void SetupBenchArgs(ArgsManager &argsman) {\n SetupHelpOptions(argsman);\n\n argsman.AddArg(\"-list\", \"List benchmarks without executing them\",\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\"-filter=\",\n strprintf(\"Regular expression filter to select benchmark by \"\n \"name (default: %s)\",\n DEFAULT_BENCH_FILTER),\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\"-asymptote=n1,n2,n3,...\",\n strprintf(\"Test asymptotic growth of the runtime of an \"\n \"algorithm, if supported by the benchmark\"),\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\n \"-output_csv=\",\n \"Generate CSV file with the most important benchmark results.\",\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n argsman.AddArg(\"-output_json=\",\n \"Generate JSON file with all benchmark results.\",\n ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n}\n\n\/\/ parses a comma separated list like \"10,20,30,50\"\nstatic std::vector parseAsymptote(const std::string &str) {\n std::stringstream ss(str);\n std::vector numbers;\n double d;\n char c;\n while (ss >> d) {\n numbers.push_back(d);\n ss >> c;\n }\n return numbers;\n}\n\nint main(int argc, char **argv) {\n ArgsManager argsman;\n SetupBenchArgs(argsman);\n SHA256AutoDetect();\n std::string error;\n if (!argsman.ParseParameters(argc, argv, error)) {\n tfm::format(std::cerr, \"Error parsing command line arguments: %s\\n\",\n error);\n return EXIT_FAILURE;\n }\n\n if (HelpRequested(argsman)) {\n std::cout << argsman.GetHelpMessage();\n return EXIT_SUCCESS;\n }\n\n benchmark::Args args;\n args.regex_filter = argsman.GetArg(\"-filter\", DEFAULT_BENCH_FILTER);\n args.is_list_only = argsman.GetBoolArg(\"-list\", false);\n args.asymptote = parseAsymptote(argsman.GetArg(\"-asymptote\", \"\"));\n args.output_csv = argsman.GetArg(\"-output_csv\", \"\");\n args.output_json = argsman.GetArg(\"-output_json\", \"\");\n\n benchmark::BenchRunner::RunAll(args);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993-2011 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\n\/\/ BZFlag common header\n#include \"common.h\"\n\n#include \n#include \n\n#if defined(_WIN32)\n# include \n# include \n#else\n# include \n# include \n#endif \/* defined(_WIN32) *\/\n\n#include \"clientConfig.h\"\n\n#include \"version.h\"\n#include \"StateDatabase.h\"\n#include \"KeyManager.h\"\n#include \"TextUtils.h\"\n#include \"DirectoryNames.h\"\n#include \"ErrorHandler.h\"\n\nstd::vector configQualityValues;\nstd::vector configViewValues;\n\nvoid initConfigData ( void )\n{\n\tconfigQualityValues.push_back(std::string(\"low\"));\n\tconfigQualityValues.push_back(std::string(\"medium\"));\n\tconfigQualityValues.push_back(std::string(\"high\"));\n\tconfigQualityValues.push_back(std::string(\"experimental\"));\n\n\tconfigViewValues.push_back(std::string(\"normal\"));\n\tconfigViewValues.push_back(std::string(\"stereo\"));\n\tconfigViewValues.push_back(std::string(\"stacked\"));\n\tconfigViewValues.push_back(std::string(\"three\"));\n\tconfigViewValues.push_back(std::string(\"anaglyph\"));\n\tconfigViewValues.push_back(std::string(\"interlaced\"));\n}\n\nstd::string\tgetOldConfigFileName(void)\n{\n#if !defined(_WIN32)\n\n\tstd::string name = getConfigDirName(\"2.0\");\n\tname += \"config.cfg\";\n\n\t\/\/ add in hostname on UNIX\n\tif (getenv(\"HOST\")) {\n\t\tname += \".\";\n\t\tname += getenv(\"HOST\");\n\t}\n\n\treturn name;\n\n#elif defined(_WIN32) \/* !defined(_WIN32) *\/\n\n\tstd::string name(\"C:\");\n\tchar dir[MAX_PATH];\n\tITEMIDLIST* idl;\n\tif (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL , &idl))) {\n\t\tif (SHGetPathFromIDList(idl, dir)) {\n\t\t\tstruct stat statbuf;\n\t\t\tif (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)\n\t\t\t\tname = dir;\n\t\t}\n\n\t\tIMalloc* shalloc;\n\t\tif (SUCCEEDED(SHGetMalloc(&shalloc))) {\n\t\t\tshalloc->Free(idl);\n\t\t\tshalloc->Release();\n\t\t}\n\t}\n\n\tname += \"\\\\My BZFlag Files\\\\2.0\\\\config.cfg\";\n\treturn name;\n\n#endif \/* !defined(_WIN32) *\/\n}\n\n#if !defined(_WIN32)\t\t\/\/ who uses this sucker any more?\nstatic std::string\tgetReallyOldConfigFileName()\n{\n\tstd::string name = getConfigDirName();\n\tname += \"config\";\n\treturn name;\n}\n#endif\n\nstd::string getCurrentConfigFileName(void)\n{\n\tstd::string configFile = BZ_CONFIG_FILE_NAME;\n\n\tstd::string name = getConfigDirName(BZ_CONFIG_DIR_VERSION);\n\tname += configFile;\n\n#if !defined(_WIN32)\n\t\/\/ add in hostname on UNIX\n\tif (getenv(\"HOST\")) {\n\t\tname += \".\";\n\t\tname += getenv(\"HOST\");\n\t}\n#endif\n\treturn name;\n}\n\n#if !defined(_WIN32)\nstatic void copyConfigFile(const char *oldConfigName, std::string configName) {\n\n FILE *fp = fopen(oldConfigName, \"rb\");\n if (!fp)\n return;\n\n \/\/ there is an old config so lets copy it to the new dir and let the\n \/\/ update take care of it.\n mkdir(getConfigDirName(BZ_CONFIG_DIR_VERSION).c_str(), 0755);\n FILE *newFile = fopen(configName.c_str(),\"wb\");\n if (!newFile)\n return;\n\n fseek(fp, 0, SEEK_END);\n const int len = ftell(fp);\n fseek(fp, 0, SEEK_SET);\n\n unsigned char *temp = (unsigned char *)malloc(len);\n if (temp == NULL) {\n printError(\"Unsufficient Memory\");\n fclose(fp);\n return;\n }\n\n size_t items_read = fread(temp, len, 1, fp);\n fclose(fp);\n if (items_read != 1)\n printError(\"Old config file is not readable\");\n\n size_t items_written = fwrite(temp, len, 1, newFile);\n fclose(newFile);\n if (items_written != 1)\n printError(\"New config file is not writable\");\n\n free (temp);\n}\n#endif\n\n\/\/ this function will look for the config, if it's not there,\n\/\/ it will TRY and find an old one and copy it\n\/\/ so that the update function can upgrade it to the current version\n\/\/ the assumption is that there is a unique config per version\nvoid findConfigFile(void)\n{\n\t\/\/ look for the current file\n\tstd::string configName = getCurrentConfigFileName();\n\tFILE *fp = fopen(configName.c_str(), \"rb\");\n\tif (fp) {\n\t\t\/\/ we found the current file, nothing to do, just return\n\t\tfclose(fp);\n\t\treturn;\n\t}\n\n\t\/\/ try and find the old file\n\tstd::string oldConfigName = getOldConfigFileName();\n#if defined(_WIN32)\n\tfp = fopen(oldConfigName.c_str(), \"rb\");\n\tif (fp) {\n\t \/\/ there is an old config so lets copy it to the new dir and\n\t \/\/ let the update take care of it.\n\t fclose(fp);\n\t \/\/ make the dir if we need to\n\t std::string configDir = getConfigDirName(BZ_CONFIG_DIR_VERSION);\n\t mkdir(configDir.c_str());\n\t \/\/ copy the old config to the new dir location with the new name\n\t CopyFile(oldConfigName.c_str(), configName.c_str(),true);\n\t}\n#else\t\/\/ the other OSs should do what they need to do\n\tcopyConfigFile(oldConfigName.c_str(), configName);\n#endif\n\n\t\/\/ try and find the REALLY old file\n\t\/\/ who uses this sucker any more?\n#if !defined(_WIN32)\n\tstd::string realyOldConfigName = getReallyOldConfigFileName();\n\t\/\/ apparently only linux needs this so do the magic\n\tcopyConfigFile(realyOldConfigName.c_str(), configName);\n#endif\n}\n\nvoid updateConfigFile(void)\n{\n\tint\t\tconfigVersion = 0;\n\tif (BZDB.isSet(\"config_version\"))\n\t\tconfigVersion = (int)BZDB.eval(\"config_version\");\n\n\tswitch (configVersion) {\n case 0: \/\/ 1.10-1.12\n\t \/\/ update from old unversioned config\n\t \/\/ roaming fixes - remove keys bound to \"roam translate *\" and \"roam rotate *\"\n\t KEYMGR.unbindCommand(\"roam translate left\");\n\t KEYMGR.unbindCommand(\"roam translate right\");\n\t KEYMGR.unbindCommand(\"roam translate up\");\n\t KEYMGR.unbindCommand(\"roam translate down\");\n\t KEYMGR.unbindCommand(\"roam translate forward\");\n\t KEYMGR.unbindCommand(\"roam translate backward\");\n\t KEYMGR.unbindCommand(\"roam rotate left\");\n\t KEYMGR.unbindCommand(\"roam rotate right\");\n\t KEYMGR.unbindCommand(\"roam rotate up\");\n\t KEYMGR.unbindCommand(\"roam rotate down\");\n\t KEYMGR.unbindCommand(\"roam rotate stop\");\n\n\t \/\/ add new default keybindings if there's no conflict\n\n\t \/\/ iconify\n\t BzfKeyEvent key;\n\t if (KEYMGR.stringToKeyEvent(\"F4\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"iconify\");\n\t \/\/ toggle console & radar\n\t if (KEYMGR.stringToKeyEvent(\"Q\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"toggleRadar\");\n\t if (KEYMGR.stringToKeyEvent(\"W\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"toggleConsole\");\n\t \/\/ controlpanel tabs - all or nothing\n\t if (KEYMGR.stringToKeyEvent(\"Shift+F1\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")\n\t\t && KEYMGR.stringToKeyEvent(\"Shift+F2\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")\n\t\t && KEYMGR.stringToKeyEvent(\"Shift+F3\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")\n\t\t && KEYMGR.stringToKeyEvent(\"Shift+F4\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")) {\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F1\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel all\");\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F2\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel chat\");\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F3\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel server\");\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F4\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel misc\");\n\t\t }\n\n\t\t \/\/ TODO - any other breaking changes from 1.10 to 2.0\n\n case 1: \/\/ 1.11.20\n\t if (KEYMGR.stringToKeyEvent(\"Tab\", key)\n\t\t && (KEYMGR.get(key, false) == \"\"))\n\t\t KEYMGR.bind(key, false, \"jump\");\n\n case 2: \/\/ 2.0\n\t if (KEYMGR.stringToKeyEvent(\"7\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"addhunt\");\n\n case 3: \/\/ Upgrade from 2.0.x to 2.4.x\n\n \/\/ Convert from email to motto\n \n \/\/ If the email is set, see if we should convert it\n if (BZDB.isSet(\"email\")) {\n std::string email = BZDB.get(\"email\");\n \/\/ If the email is set and does not contain an @ sign, move it to motto\n if (!email.empty() && email.find('@') == std::string::npos) {\n\tBZDB.set(\"motto\", email);\n }\n BZDB.unset(\"email\");\t\/\/ discard email string from before version 2.4\n }\n\n if (BZDB.isSet(\"emailDispLen\")) {\n BZDB.set(\"mottoDispLen\", BZDB.get(\"emailDispLen\"));\n BZDB.unset(\"emailDispLen\");\t\/\/ discard setting from before version 2.4\n }\n\n if (BZDB.isSet(\"hideEmails\")) {\n BZDB.setBool(\"hideMottos\", BZDB.isTrue(\"hideEmails\"));\n BZDB.unset(\"hideEmails\");\t\/\/ discard setting from before version 2.4\n }\n\n \/\/ Get rid of geometry and lastScreenshot settings\n BZDB.unset(\"geometry\");\n BZDB.unset(\"lastScreenshot\");\n\n \/\/ Turn off dithering (since none of our automatic performance checks turn it on anymore)\n BZDB.setBool(\"dither\", false);\n \n case 4: \/\/ Upgrade 2.4.0 to 2.4.1\n BZDB.unset(\"displayZoom\");\t\t\/\/ removed in r22109\n BZDB.unset(\"radarShotLineType\");\t\/\/ existed only in r22117\n break;\n\n default: \/\/ hm, we don't know about this one...\n\t printError(TextUtils::format(\"Config file is tagged version \\\"%d\\\", \"\n\t\t \"which was not expected (too new perhaps). \"\n\t\t \"Trying to load anyhow.\", configVersion));\n\t break;\n\t}\n\n\t\/\/ set us as the updated version\n\tconfigVersion = BZ_CONFIG_FILE_VERSION;\n\tBZDB.setInt(\"config_version\", configVersion);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nAvoid resource (file stream) leak when handling errors.\/* bzflag\n * Copyright (c) 1993-2011 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\n\/\/ BZFlag common header\n#include \"common.h\"\n\n#include \n#include \n\n#if defined(_WIN32)\n# include \n# include \n#else\n# include \n# include \n#endif \/* defined(_WIN32) *\/\n\n#include \"clientConfig.h\"\n\n#include \"version.h\"\n#include \"StateDatabase.h\"\n#include \"KeyManager.h\"\n#include \"TextUtils.h\"\n#include \"DirectoryNames.h\"\n#include \"ErrorHandler.h\"\n\nstd::vector configQualityValues;\nstd::vector configViewValues;\n\nvoid initConfigData ( void )\n{\n\tconfigQualityValues.push_back(std::string(\"low\"));\n\tconfigQualityValues.push_back(std::string(\"medium\"));\n\tconfigQualityValues.push_back(std::string(\"high\"));\n\tconfigQualityValues.push_back(std::string(\"experimental\"));\n\n\tconfigViewValues.push_back(std::string(\"normal\"));\n\tconfigViewValues.push_back(std::string(\"stereo\"));\n\tconfigViewValues.push_back(std::string(\"stacked\"));\n\tconfigViewValues.push_back(std::string(\"three\"));\n\tconfigViewValues.push_back(std::string(\"anaglyph\"));\n\tconfigViewValues.push_back(std::string(\"interlaced\"));\n}\n\nstd::string\tgetOldConfigFileName(void)\n{\n#if !defined(_WIN32)\n\n\tstd::string name = getConfigDirName(\"2.0\");\n\tname += \"config.cfg\";\n\n\t\/\/ add in hostname on UNIX\n\tif (getenv(\"HOST\")) {\n\t\tname += \".\";\n\t\tname += getenv(\"HOST\");\n\t}\n\n\treturn name;\n\n#elif defined(_WIN32) \/* !defined(_WIN32) *\/\n\n\tstd::string name(\"C:\");\n\tchar dir[MAX_PATH];\n\tITEMIDLIST* idl;\n\tif (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL , &idl))) {\n\t\tif (SHGetPathFromIDList(idl, dir)) {\n\t\t\tstruct stat statbuf;\n\t\t\tif (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)\n\t\t\t\tname = dir;\n\t\t}\n\n\t\tIMalloc* shalloc;\n\t\tif (SUCCEEDED(SHGetMalloc(&shalloc))) {\n\t\t\tshalloc->Free(idl);\n\t\t\tshalloc->Release();\n\t\t}\n\t}\n\n\tname += \"\\\\My BZFlag Files\\\\2.0\\\\config.cfg\";\n\treturn name;\n\n#endif \/* !defined(_WIN32) *\/\n}\n\n#if !defined(_WIN32)\t\t\/\/ who uses this sucker any more?\nstatic std::string\tgetReallyOldConfigFileName()\n{\n\tstd::string name = getConfigDirName();\n\tname += \"config\";\n\treturn name;\n}\n#endif\n\nstd::string getCurrentConfigFileName(void)\n{\n\tstd::string configFile = BZ_CONFIG_FILE_NAME;\n\n\tstd::string name = getConfigDirName(BZ_CONFIG_DIR_VERSION);\n\tname += configFile;\n\n#if !defined(_WIN32)\n\t\/\/ add in hostname on UNIX\n\tif (getenv(\"HOST\")) {\n\t\tname += \".\";\n\t\tname += getenv(\"HOST\");\n\t}\n#endif\n\treturn name;\n}\n\n#if !defined(_WIN32)\nstatic void copyConfigFile(const char *oldConfigName, std::string configName) {\n\n FILE *fp = fopen(oldConfigName, \"rb\");\n if (!fp)\n return;\n\n \/\/ there is an old config so lets copy it to the new dir and let the\n \/\/ update take care of it.\n mkdir(getConfigDirName(BZ_CONFIG_DIR_VERSION).c_str(), 0755);\n FILE *newFile = fopen(configName.c_str(),\"wb\");\n if (!newFile) {\n fclose(fp);\n return;\n }\n\n fseek(fp, 0, SEEK_END);\n const int len = ftell(fp);\n fseek(fp, 0, SEEK_SET);\n\n unsigned char *temp = (unsigned char *)malloc(len);\n if (temp == NULL) {\n printError(\"Unsufficient Memory\");\n fclose(fp);\n fclose(newFile);\n return;\n }\n\n size_t items_read = fread(temp, len, 1, fp);\n fclose(fp);\n if (items_read != 1)\n printError(\"Old config file is not readable\");\n\n size_t items_written = fwrite(temp, len, 1, newFile);\n fclose(newFile);\n if (items_written != 1)\n printError(\"New config file is not writable\");\n\n free (temp);\n}\n#endif\n\n\/\/ this function will look for the config, if it's not there,\n\/\/ it will TRY and find an old one and copy it\n\/\/ so that the update function can upgrade it to the current version\n\/\/ the assumption is that there is a unique config per version\nvoid findConfigFile(void)\n{\n\t\/\/ look for the current file\n\tstd::string configName = getCurrentConfigFileName();\n\tFILE *fp = fopen(configName.c_str(), \"rb\");\n\tif (fp) {\n\t\t\/\/ we found the current file, nothing to do, just return\n\t\tfclose(fp);\n\t\treturn;\n\t}\n\n\t\/\/ try and find the old file\n\tstd::string oldConfigName = getOldConfigFileName();\n#if defined(_WIN32)\n\tfp = fopen(oldConfigName.c_str(), \"rb\");\n\tif (fp) {\n\t \/\/ there is an old config so lets copy it to the new dir and\n\t \/\/ let the update take care of it.\n\t fclose(fp);\n\t \/\/ make the dir if we need to\n\t std::string configDir = getConfigDirName(BZ_CONFIG_DIR_VERSION);\n\t mkdir(configDir.c_str());\n\t \/\/ copy the old config to the new dir location with the new name\n\t CopyFile(oldConfigName.c_str(), configName.c_str(),true);\n\t}\n#else\t\/\/ the other OSs should do what they need to do\n\tcopyConfigFile(oldConfigName.c_str(), configName);\n#endif\n\n\t\/\/ try and find the REALLY old file\n\t\/\/ who uses this sucker any more?\n#if !defined(_WIN32)\n\tstd::string realyOldConfigName = getReallyOldConfigFileName();\n\t\/\/ apparently only linux needs this so do the magic\n\tcopyConfigFile(realyOldConfigName.c_str(), configName);\n#endif\n}\n\nvoid updateConfigFile(void)\n{\n\tint\t\tconfigVersion = 0;\n\tif (BZDB.isSet(\"config_version\"))\n\t\tconfigVersion = (int)BZDB.eval(\"config_version\");\n\n\tswitch (configVersion) {\n case 0: \/\/ 1.10-1.12\n\t \/\/ update from old unversioned config\n\t \/\/ roaming fixes - remove keys bound to \"roam translate *\" and \"roam rotate *\"\n\t KEYMGR.unbindCommand(\"roam translate left\");\n\t KEYMGR.unbindCommand(\"roam translate right\");\n\t KEYMGR.unbindCommand(\"roam translate up\");\n\t KEYMGR.unbindCommand(\"roam translate down\");\n\t KEYMGR.unbindCommand(\"roam translate forward\");\n\t KEYMGR.unbindCommand(\"roam translate backward\");\n\t KEYMGR.unbindCommand(\"roam rotate left\");\n\t KEYMGR.unbindCommand(\"roam rotate right\");\n\t KEYMGR.unbindCommand(\"roam rotate up\");\n\t KEYMGR.unbindCommand(\"roam rotate down\");\n\t KEYMGR.unbindCommand(\"roam rotate stop\");\n\n\t \/\/ add new default keybindings if there's no conflict\n\n\t \/\/ iconify\n\t BzfKeyEvent key;\n\t if (KEYMGR.stringToKeyEvent(\"F4\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"iconify\");\n\t \/\/ toggle console & radar\n\t if (KEYMGR.stringToKeyEvent(\"Q\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"toggleRadar\");\n\t if (KEYMGR.stringToKeyEvent(\"W\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"toggleConsole\");\n\t \/\/ controlpanel tabs - all or nothing\n\t if (KEYMGR.stringToKeyEvent(\"Shift+F1\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")\n\t\t && KEYMGR.stringToKeyEvent(\"Shift+F2\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")\n\t\t && KEYMGR.stringToKeyEvent(\"Shift+F3\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")\n\t\t && KEYMGR.stringToKeyEvent(\"Shift+F4\", key)\n\t\t && (KEYMGR.get(key, true) == \"\")) {\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F1\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel all\");\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F2\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel chat\");\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F3\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel server\");\n\t\t\t KEYMGR.stringToKeyEvent(\"Shift+F4\", key);\n\t\t\t KEYMGR.bind(key, true, \"messagepanel misc\");\n\t\t }\n\n\t\t \/\/ TODO - any other breaking changes from 1.10 to 2.0\n\n case 1: \/\/ 1.11.20\n\t if (KEYMGR.stringToKeyEvent(\"Tab\", key)\n\t\t && (KEYMGR.get(key, false) == \"\"))\n\t\t KEYMGR.bind(key, false, \"jump\");\n\n case 2: \/\/ 2.0\n\t if (KEYMGR.stringToKeyEvent(\"7\", key)\n\t\t && (KEYMGR.get(key, true) == \"\"))\n\t\t KEYMGR.bind(key, true, \"addhunt\");\n\n case 3: \/\/ Upgrade from 2.0.x to 2.4.x\n\n \/\/ Convert from email to motto\n \n \/\/ If the email is set, see if we should convert it\n if (BZDB.isSet(\"email\")) {\n std::string email = BZDB.get(\"email\");\n \/\/ If the email is set and does not contain an @ sign, move it to motto\n if (!email.empty() && email.find('@') == std::string::npos) {\n\tBZDB.set(\"motto\", email);\n }\n BZDB.unset(\"email\");\t\/\/ discard email string from before version 2.4\n }\n\n if (BZDB.isSet(\"emailDispLen\")) {\n BZDB.set(\"mottoDispLen\", BZDB.get(\"emailDispLen\"));\n BZDB.unset(\"emailDispLen\");\t\/\/ discard setting from before version 2.4\n }\n\n if (BZDB.isSet(\"hideEmails\")) {\n BZDB.setBool(\"hideMottos\", BZDB.isTrue(\"hideEmails\"));\n BZDB.unset(\"hideEmails\");\t\/\/ discard setting from before version 2.4\n }\n\n \/\/ Get rid of geometry and lastScreenshot settings\n BZDB.unset(\"geometry\");\n BZDB.unset(\"lastScreenshot\");\n\n \/\/ Turn off dithering (since none of our automatic performance checks turn it on anymore)\n BZDB.setBool(\"dither\", false);\n \n case 4: \/\/ Upgrade 2.4.0 to 2.4.1\n BZDB.unset(\"displayZoom\");\t\t\/\/ removed in r22109\n BZDB.unset(\"radarShotLineType\");\t\/\/ existed only in r22117\n break;\n\n default: \/\/ hm, we don't know about this one...\n\t printError(TextUtils::format(\"Config file is tagged version \\\"%d\\\", \"\n\t\t \"which was not expected (too new perhaps). \"\n\t\t \"Trying to load anyhow.\", configVersion));\n\t break;\n\t}\n\n\t\/\/ set us as the updated version\n\tconfigVersion = BZ_CONFIG_FILE_VERSION;\n\tBZDB.setInt(\"config_version\", configVersion);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/\/---------------------------------------------------------- -*- Mode: C++ -*-\n\/\/ $Id$\n\/\/\n\/\/ \\brief Properties implementation.\n\/\/\n\/\/ Created 2004\/05\/05\n\/\/\n\/\/ Copyright 2008-2012 Quantcast Corp.\n\/\/ Copyright 2006-2008 Kosmix Corp.\n\/\/\n\/\/ This file is part of Kosmos File System (KFS).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \"Properties.h\"\n#include \"RequestParser.h\"\n\nnamespace KFS\n{\n\nusing std::string;\nusing std::istream;\nusing std::ifstream;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\n\ninline static int\nAsciiCharToLower(int c)\n{\n return ((c >= 'A' && c <= 'Z') ? 'a' + (c - 'A') : c);\n}\n\ntemplate inline static void\nremoveLTSpaces(const string& str, string::size_type start,\n string::size_type end, T& outStr, bool asciiToLower = false)\n{\n char const* const delims = \" \\t\\r\\n\";\n\n if (start >= str.length()) {\n outStr.clear();\n return;\n }\n string::size_type const first = str.find_first_not_of(delims, start);\n if (end <= first || first == string::npos) {\n outStr.clear();\n return;\n }\n string::size_type const last = str.find_last_not_of(\n delims, end == string::npos ? string::npos : end - 1);\n if (asciiToLower) {\n outStr.clear();\n for (const char* p = str.data() + first,\n * e = str.data() +\n (last == string::npos ? str.size() : last + 1);\n p < e;\n ++p) {\n outStr.Append(AsciiCharToLower(*p & 0xFF));\n }\n return;\n }\n outStr.Copy(str.c_str() + first,\n (last == string::npos ? str.size() : last + 1) - first);\n}\n\n\/* static *\/ string\nProperties::AsciiToLower(const string& str)\n{\n string s(str);\n for (string::iterator i = s.begin(); i != s.end(); ++i) {\n const int c = AsciiCharToLower(*i & 0xFF);\n if (c != *i) {\n *i = c;\n }\n }\n return s;\n}\n\ninline Properties::iterator\nProperties::find(const Properties::String& key) const\n{\n return propmap.find(key);\n}\n\nProperties::Properties(int base)\n : intbase(base),\n propmap()\n{\n}\n\nProperties::Properties(const Properties &p)\n : intbase(p.intbase),\n propmap(p.propmap)\n{\n}\n\nProperties::~Properties()\n{\n}\n\nint\nProperties::loadProperties(\n const char* fileName,\n char delimiter,\n bool verbose \/* = false *\/,\n bool multiline \/* =false *\/,\n bool keysAsciiToLower \/* = false *\/)\n{\n ifstream input(fileName);\n if(! input.is_open()) {\n cerr << \"Properties::loadProperties() failed to open the file:\" <<\n fileName << endl;\n return(-1);\n }\n loadProperties(input, delimiter, verbose, multiline, keysAsciiToLower);\n input.close();\n return 0;\n}\n\nint\nProperties::loadProperties(\n istream& ist,\n char delimiter,\n bool verbose,\n bool multiline \/* = false *\/,\n bool keysAsciiToLower \/* = false *\/)\n{\n string line;\n String key;\n String val;\n if (ist) {\n line.reserve(512);\n }\n while (ist) {\n getline(ist, line); \/\/read one line at a time\n if (line.empty() || line[0] == '#') {\n continue; \/\/ ignore comments\n }\n \/\/ find the delimiter\n string::size_type const pos = line.find(delimiter);\n if (pos == string::npos) {\n continue; \/\/ ignore if no delimiter is found\n }\n removeLTSpaces(line, 0, pos, key, keysAsciiToLower);\n removeLTSpaces(line, pos + 1, string::npos, val);\n if (multiline) {\n \/\/ allow properties to span across multiple lines\n propmap[key].Append(val);\n } else {\n propmap[key] = val;\n }\n if (verbose) {\n cout << \"Loading key \" << key <<\n \" with value \" << propmap[key] << endl;\n }\n }\n return 0;\n}\n\nint\nProperties::loadProperties(\n const char* buf,\n size_t len,\n char delimiter,\n ostream* verbose \/* = 0 *\/,\n bool multiline \/* = false *\/,\n bool keysAsciiToLower \/* = false *\/)\n{\n PropertiesTokenizer tokenizer(buf, len);\n if (keysAsciiToLower) {\n String lkey;\n while (tokenizer.Next(delimiter)) {\n const PropertiesTokenizer::Token& key = tokenizer.GetKey();\n const PropertiesTokenizer::Token& val = tokenizer.GetValue();\n lkey.clear();\n for (const char* p = key.mPtr, * e = p + key.mLen; p < e; ++p) {\n lkey.Append(AsciiCharToLower(*p & 0xFF));\n }\n if (multiline) {\n propmap[lkey].Append(val.mPtr, val.mLen);\n } else {\n propmap[lkey].Copy(val.mPtr, val.mLen);\n }\n if (verbose) {\n (*verbose) << \"Loading key \";\n verbose->write(key.mPtr, key.mLen);\n (*verbose) << \" with value \";\n verbose->write(val.mPtr, val.mLen);\n (*verbose) << endl;\n }\n }\n } else {\n while (tokenizer.Next(delimiter)) {\n const PropertiesTokenizer::Token& key = tokenizer.GetKey();\n const PropertiesTokenizer::Token& val = tokenizer.GetValue();\n if (multiline) {\n propmap[String(key.mPtr, key.mLen)].Append(val.mPtr, val.mLen);\n } else {\n propmap[String(key.mPtr, key.mLen)].Copy(val.mPtr, val.mLen);\n }\n if (verbose) {\n (*verbose) << \"Loading key \";\n verbose->write(key.mPtr, key.mLen);\n (*verbose) << \" with value \";\n verbose->write(val.mPtr, val.mLen);\n (*verbose) << endl;\n }\n }\n }\n return 0;\n}\n\nvoid\nProperties::setValue(const string& key, const string& value)\n{\n String kstr;\n if (key.length() > size_t(kStringBufSize)) {\n kstr = key;\n } else {\n kstr.Copy(key.data(), key.size());\n }\n if (value.length() > size_t(kStringBufSize)) {\n propmap[kstr] = value;\n } else {\n propmap[kstr].Copy(value.data(), value.size());\n }\n}\n\nvoid\nProperties::setValue(const Properties::String& key, const string& value)\n{\n if (value.length() > size_t(kStringBufSize)) {\n propmap[key] = value;\n } else {\n propmap[key].Copy(value.data(), value.size());\n }\n}\n\nstring\nProperties::getValueSelf(const Properties::String& key, const string& def) const\n{\n PropMap::const_iterator const i = find(key);\n if (i == propmap.end()) {\n return def;\n }\n if (i->second.size() > size_t(kStringBufSize)) {\n return i->second.GetStr();\n }\n return string(i->second.data(), i->second.size());\n}\n\nconst char*\nProperties::getValueSelf(const Properties::String& key, const char* def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : i->second.c_str());\n}\n\nint\nProperties::getValueSelf(const Properties::String& key, int def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def :\n (int)strtol(i->second.c_str(), 0, intbase));\n}\n\nunsigned int\nProperties::getValueSelf(const Properties::String& key, unsigned int def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def :\n (unsigned int)strtoul(i->second.c_str(), 0, intbase));\n}\n\nlong\nProperties::getValueSelf(const Properties::String& key, long def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtol(i->second.c_str(), 0, intbase));\n}\n\nunsigned long\nProperties::getValueSelf(const Properties::String& key, unsigned long def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtoul(i->second.c_str(), 0, intbase));\n}\n\nlong long\nProperties::getValueSelf(const Properties::String& key, long long def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtoll(i->second.c_str(), 0, intbase));\n}\n\nunsigned long long\nProperties::getValueSelf(const Properties::String& key, unsigned long long def)\n const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtoull(i->second.c_str(), 0, intbase));\n}\n\ndouble\nProperties::getValueSelf(const Properties::String& key, double def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : atof(i->second.c_str()));\n}\n\nbool\nProperties::remove(const Properties::String& key)\n{\n return (propmap.erase(key) > 0);\n}\n\nvoid\nProperties::getList(string& outBuf,\n const string& linePrefix, const string& lineSuffix) const\n{\n PropMap::const_iterator iter;\n for (iter = propmap.begin(); iter != propmap.end(); iter++) {\n if (iter->first.size() > 0) {\n outBuf += linePrefix;\n outBuf.append(iter->first.data(), iter->first.size());\n outBuf += '=';\n outBuf.append(iter->second.data(), iter->second.size());\n outBuf += lineSuffix;\n }\n }\n return;\n}\n\nvoid\nProperties::copyWithPrefix(const string& prefix, Properties& props) const\n{\n const size_t prefixSize = prefix.size();\n PropMap::const_iterator iter;\n for (iter = propmap.begin(); iter != propmap.end(); iter++) {\n const String& key = iter->first;\n if (key.size() >= prefixSize &&\n prefix.compare(0, prefixSize, key.c_str()) == 0) {\n props.propmap[key] = iter->second;\n }\n }\n}\n\n} \/\/ namespace KFS\nCommon lib: fix Properties::copyWithPrefix().\/\/---------------------------------------------------------- -*- Mode: C++ -*-\n\/\/ $Id$\n\/\/\n\/\/ \\brief Properties implementation.\n\/\/\n\/\/ Created 2004\/05\/05\n\/\/\n\/\/ Copyright 2008-2012 Quantcast Corp.\n\/\/ Copyright 2006-2008 Kosmix Corp.\n\/\/\n\/\/ This file is part of Kosmos File System (KFS).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \"Properties.h\"\n#include \"RequestParser.h\"\n\nnamespace KFS\n{\n\nusing std::string;\nusing std::istream;\nusing std::ifstream;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\n\ninline static int\nAsciiCharToLower(int c)\n{\n return ((c >= 'A' && c <= 'Z') ? 'a' + (c - 'A') : c);\n}\n\ntemplate inline static void\nremoveLTSpaces(const string& str, string::size_type start,\n string::size_type end, T& outStr, bool asciiToLower = false)\n{\n char const* const delims = \" \\t\\r\\n\";\n\n if (start >= str.length()) {\n outStr.clear();\n return;\n }\n string::size_type const first = str.find_first_not_of(delims, start);\n if (end <= first || first == string::npos) {\n outStr.clear();\n return;\n }\n string::size_type const last = str.find_last_not_of(\n delims, end == string::npos ? string::npos : end - 1);\n if (asciiToLower) {\n outStr.clear();\n for (const char* p = str.data() + first,\n * e = str.data() +\n (last == string::npos ? str.size() : last + 1);\n p < e;\n ++p) {\n outStr.Append(AsciiCharToLower(*p & 0xFF));\n }\n return;\n }\n outStr.Copy(str.c_str() + first,\n (last == string::npos ? str.size() : last + 1) - first);\n}\n\n\/* static *\/ string\nProperties::AsciiToLower(const string& str)\n{\n string s(str);\n for (string::iterator i = s.begin(); i != s.end(); ++i) {\n const int c = AsciiCharToLower(*i & 0xFF);\n if (c != *i) {\n *i = c;\n }\n }\n return s;\n}\n\ninline Properties::iterator\nProperties::find(const Properties::String& key) const\n{\n return propmap.find(key);\n}\n\nProperties::Properties(int base)\n : intbase(base),\n propmap()\n{\n}\n\nProperties::Properties(const Properties &p)\n : intbase(p.intbase),\n propmap(p.propmap)\n{\n}\n\nProperties::~Properties()\n{\n}\n\nint\nProperties::loadProperties(\n const char* fileName,\n char delimiter,\n bool verbose \/* = false *\/,\n bool multiline \/* =false *\/,\n bool keysAsciiToLower \/* = false *\/)\n{\n ifstream input(fileName);\n if(! input.is_open()) {\n cerr << \"Properties::loadProperties() failed to open the file:\" <<\n fileName << endl;\n return(-1);\n }\n loadProperties(input, delimiter, verbose, multiline, keysAsciiToLower);\n input.close();\n return 0;\n}\n\nint\nProperties::loadProperties(\n istream& ist,\n char delimiter,\n bool verbose,\n bool multiline \/* = false *\/,\n bool keysAsciiToLower \/* = false *\/)\n{\n string line;\n String key;\n String val;\n if (ist) {\n line.reserve(512);\n }\n while (ist) {\n getline(ist, line); \/\/read one line at a time\n if (line.empty() || line[0] == '#') {\n continue; \/\/ ignore comments\n }\n \/\/ find the delimiter\n string::size_type const pos = line.find(delimiter);\n if (pos == string::npos) {\n continue; \/\/ ignore if no delimiter is found\n }\n removeLTSpaces(line, 0, pos, key, keysAsciiToLower);\n removeLTSpaces(line, pos + 1, string::npos, val);\n if (multiline) {\n \/\/ allow properties to span across multiple lines\n propmap[key].Append(val);\n } else {\n propmap[key] = val;\n }\n if (verbose) {\n cout << \"Loading key \" << key <<\n \" with value \" << propmap[key] << endl;\n }\n }\n return 0;\n}\n\nint\nProperties::loadProperties(\n const char* buf,\n size_t len,\n char delimiter,\n ostream* verbose \/* = 0 *\/,\n bool multiline \/* = false *\/,\n bool keysAsciiToLower \/* = false *\/)\n{\n PropertiesTokenizer tokenizer(buf, len);\n if (keysAsciiToLower) {\n String lkey;\n while (tokenizer.Next(delimiter)) {\n const PropertiesTokenizer::Token& key = tokenizer.GetKey();\n const PropertiesTokenizer::Token& val = tokenizer.GetValue();\n lkey.clear();\n for (const char* p = key.mPtr, * e = p + key.mLen; p < e; ++p) {\n lkey.Append(AsciiCharToLower(*p & 0xFF));\n }\n if (multiline) {\n propmap[lkey].Append(val.mPtr, val.mLen);\n } else {\n propmap[lkey].Copy(val.mPtr, val.mLen);\n }\n if (verbose) {\n (*verbose) << \"Loading key \";\n verbose->write(key.mPtr, key.mLen);\n (*verbose) << \" with value \";\n verbose->write(val.mPtr, val.mLen);\n (*verbose) << endl;\n }\n }\n } else {\n while (tokenizer.Next(delimiter)) {\n const PropertiesTokenizer::Token& key = tokenizer.GetKey();\n const PropertiesTokenizer::Token& val = tokenizer.GetValue();\n if (multiline) {\n propmap[String(key.mPtr, key.mLen)].Append(val.mPtr, val.mLen);\n } else {\n propmap[String(key.mPtr, key.mLen)].Copy(val.mPtr, val.mLen);\n }\n if (verbose) {\n (*verbose) << \"Loading key \";\n verbose->write(key.mPtr, key.mLen);\n (*verbose) << \" with value \";\n verbose->write(val.mPtr, val.mLen);\n (*verbose) << endl;\n }\n }\n }\n return 0;\n}\n\nvoid\nProperties::setValue(const string& key, const string& value)\n{\n String kstr;\n if (key.length() > size_t(kStringBufSize)) {\n kstr = key;\n } else {\n kstr.Copy(key.data(), key.size());\n }\n if (value.length() > size_t(kStringBufSize)) {\n propmap[kstr] = value;\n } else {\n propmap[kstr].Copy(value.data(), value.size());\n }\n}\n\nvoid\nProperties::setValue(const Properties::String& key, const string& value)\n{\n if (value.length() > size_t(kStringBufSize)) {\n propmap[key] = value;\n } else {\n propmap[key].Copy(value.data(), value.size());\n }\n}\n\nstring\nProperties::getValueSelf(const Properties::String& key, const string& def) const\n{\n PropMap::const_iterator const i = find(key);\n if (i == propmap.end()) {\n return def;\n }\n if (i->second.size() > size_t(kStringBufSize)) {\n return i->second.GetStr();\n }\n return string(i->second.data(), i->second.size());\n}\n\nconst char*\nProperties::getValueSelf(const Properties::String& key, const char* def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : i->second.c_str());\n}\n\nint\nProperties::getValueSelf(const Properties::String& key, int def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def :\n (int)strtol(i->second.c_str(), 0, intbase));\n}\n\nunsigned int\nProperties::getValueSelf(const Properties::String& key, unsigned int def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def :\n (unsigned int)strtoul(i->second.c_str(), 0, intbase));\n}\n\nlong\nProperties::getValueSelf(const Properties::String& key, long def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtol(i->second.c_str(), 0, intbase));\n}\n\nunsigned long\nProperties::getValueSelf(const Properties::String& key, unsigned long def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtoul(i->second.c_str(), 0, intbase));\n}\n\nlong long\nProperties::getValueSelf(const Properties::String& key, long long def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtoll(i->second.c_str(), 0, intbase));\n}\n\nunsigned long long\nProperties::getValueSelf(const Properties::String& key, unsigned long long def)\n const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : strtoull(i->second.c_str(), 0, intbase));\n}\n\ndouble\nProperties::getValueSelf(const Properties::String& key, double def) const\n{\n PropMap::const_iterator const i = find(key);\n return (i == propmap.end() ? def : atof(i->second.c_str()));\n}\n\nbool\nProperties::remove(const Properties::String& key)\n{\n return (propmap.erase(key) > 0);\n}\n\nvoid\nProperties::getList(string& outBuf,\n const string& linePrefix, const string& lineSuffix) const\n{\n PropMap::const_iterator iter;\n for (iter = propmap.begin(); iter != propmap.end(); iter++) {\n if (iter->first.size() > 0) {\n outBuf += linePrefix;\n outBuf.append(iter->first.data(), iter->first.size());\n outBuf += '=';\n outBuf.append(iter->second.data(), iter->second.size());\n outBuf += lineSuffix;\n }\n }\n return;\n}\n\nvoid\nProperties::copyWithPrefix(const string& prefix, Properties& props) const\n{\n const size_t prefixSize = prefix.size();\n PropMap::const_iterator iter;\n for (iter = propmap.begin(); iter != propmap.end(); iter++) {\n const String& key = iter->first;\n if (key.size() >= prefixSize &&\n prefix.compare(0, prefixSize, key.c_str(), prefixSize) == 0) {\n props.propmap[key] = iter->second;\n }\n }\n}\n\n} \/\/ namespace KFS\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/search_engine_manager_handler.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/callback.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/search_engines\/keyword_editor_controller.h\"\n#include \"chrome\/browser\/search_engines\/template_url_table_model.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\nSearchEngineManagerHandler::SearchEngineManagerHandler() {\n}\n\nSearchEngineManagerHandler::~SearchEngineManagerHandler() {\n if (controller_.get() && controller_->table_model())\n controller_->table_model()->SetObserver(NULL);\n}\n\nvoid SearchEngineManagerHandler::Initialize() {\n controller_.reset(new KeywordEditorController(dom_ui_->GetProfile()));\n controller_->table_model()->SetObserver(this);\n}\n\nvoid SearchEngineManagerHandler::GetLocalizedValues(\n DictionaryValue* localized_strings) {\n DCHECK(localized_strings);\n\n localized_strings->SetString(\"searchEngineManagerPage\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_WINDOW_TITLE));\n localized_strings->SetString(\"searchEngineTableNameHeader\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN));\n localized_strings->SetString(\"searchEngineTableKeywordHeader\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN));\n localized_strings->SetString(\"addSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_NEW_BUTTON));\n localized_strings->SetString(\"removeSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_REMOVE_BUTTON));\n localized_strings->SetString(\"editSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_EDIT_BUTTON));\n localized_strings->SetString(\"makeDefaultSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAKE_DEFAULT_BUTTON));\n}\n\nvoid SearchEngineManagerHandler::RegisterMessages() {\n dom_ui_->RegisterMessageCallback(\n \"managerSetDefaultSearchEngine\",\n NewCallback(this, &SearchEngineManagerHandler::SetDefaultSearchEngine));\n dom_ui_->RegisterMessageCallback(\n \"removeSearchEngine\",\n NewCallback(this, &SearchEngineManagerHandler::RemoveSearchEngine));\n}\n\nvoid SearchEngineManagerHandler::OnModelChanged() {\n ListValue engine_list;\n\n \/\/ Find the default engine.\n const TemplateURL* default_engine =\n controller_->url_model()->GetDefaultSearchProvider();\n int default_index = controller_->table_model()->IndexOfTemplateURL(\n default_engine);\n\n \/\/ Add the first group (default search engine options).\n engine_list.Append(CreateDictionaryForHeading(0));\n int last_default_engine_index =\n controller_->table_model()->last_search_engine_index();\n for (int i = 0; i < last_default_engine_index; ++i) {\n engine_list.Append(CreateDictionaryForEngine(i, i == default_index));\n }\n\n \/\/ Add the second group (other search templates).\n engine_list.Append(CreateDictionaryForHeading(1));\n if (last_default_engine_index < 0)\n last_default_engine_index = 0;\n int engine_count = controller_->table_model()->RowCount();\n for (int i = last_default_engine_index; i < engine_count; ++i) {\n engine_list.Append(CreateDictionaryForEngine(i, i == default_index));\n }\n\n dom_ui_->CallJavascriptFunction(L\"SearchEngineManager.updateSearchEngineList\",\n engine_list);\n}\n\nvoid SearchEngineManagerHandler::OnItemsChanged(int start, int length) {\n OnModelChanged();\n}\n\nvoid SearchEngineManagerHandler::OnItemsAdded(int start, int length) {\n OnModelChanged();\n}\n\nvoid SearchEngineManagerHandler::OnItemsRemoved(int start, int length) {\n OnModelChanged();\n}\n\nDictionaryValue* SearchEngineManagerHandler::CreateDictionaryForHeading(\n int group_index) {\n TableModel::Groups groups = controller_->table_model()->GetGroups();\n\n DictionaryValue* dict = new DictionaryValue();\n dict->SetString(\"heading\", WideToUTF16Hack(groups[group_index].title));\n return dict;\n}\n\nDictionaryValue* SearchEngineManagerHandler::CreateDictionaryForEngine(\n int index, bool is_default) {\n TemplateURLTableModel* table_model = controller_->table_model();\n\n DictionaryValue* dict = new DictionaryValue();\n dict->SetString(\"name\", WideToUTF16Hack(table_model->GetText(\n index, IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN)));\n dict->SetString(\"keyword\", WideToUTF16Hack(table_model->GetText(\n index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN)));\n const TemplateURL* template_url = controller_->GetTemplateURL(index);\n GURL icon_url = template_url->GetFavIconURL();\n if (icon_url.is_valid())\n dict->SetString(\"iconURL\", icon_url.spec());\n dict->SetString(\"modelIndex\", base::IntToString(index));\n\n if (controller_->CanRemove(template_url))\n dict->SetString(\"canBeRemoved\", \"1\");\n if (controller_->CanMakeDefault(template_url))\n dict->SetString(\"canBeDefault\", \"1\");\n if (is_default)\n dict->SetString(\"default\", \"1\");\n\n return dict;\n}\n\nvoid SearchEngineManagerHandler::SetDefaultSearchEngine(const ListValue* args) {\n int index;\n if (!ExtractIntegerValue(args, &index)) {\n NOTREACHED();\n return;\n }\n if (index < 0 || index >= controller_->table_model()->RowCount())\n return;\n\n controller_->MakeDefaultTemplateURL(index);\n}\n\nvoid SearchEngineManagerHandler::RemoveSearchEngine(const ListValue* args) {\n int index;\n if (!ExtractIntegerValue(args, &index)) {\n NOTREACHED();\n return;\n }\n if (index < 0 || index >= controller_->table_model()->RowCount())\n return;\n\n if (controller_->CanRemove(controller_->GetTemplateURL(index)))\n controller_->RemoveTemplateURL(index);\n}\nDOMUI prefs: Fix a race condition in pushing search engine information to DOMUI\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/search_engine_manager_handler.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/callback.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/search_engines\/keyword_editor_controller.h\"\n#include \"chrome\/browser\/search_engines\/template_url_table_model.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\nSearchEngineManagerHandler::SearchEngineManagerHandler() {\n}\n\nSearchEngineManagerHandler::~SearchEngineManagerHandler() {\n if (controller_.get() && controller_->table_model())\n controller_->table_model()->SetObserver(NULL);\n}\n\nvoid SearchEngineManagerHandler::Initialize() {\n controller_.reset(new KeywordEditorController(dom_ui_->GetProfile()));\n if (controller_.get()) {\n controller_->table_model()->SetObserver(this);\n OnModelChanged();\n }\n}\n\nvoid SearchEngineManagerHandler::GetLocalizedValues(\n DictionaryValue* localized_strings) {\n DCHECK(localized_strings);\n\n localized_strings->SetString(\"searchEngineManagerPage\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_WINDOW_TITLE));\n localized_strings->SetString(\"searchEngineTableNameHeader\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN));\n localized_strings->SetString(\"searchEngineTableKeywordHeader\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN));\n localized_strings->SetString(\"addSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_NEW_BUTTON));\n localized_strings->SetString(\"removeSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_REMOVE_BUTTON));\n localized_strings->SetString(\"editSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_EDIT_BUTTON));\n localized_strings->SetString(\"makeDefaultSearchEngineButton\",\n l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAKE_DEFAULT_BUTTON));\n}\n\nvoid SearchEngineManagerHandler::RegisterMessages() {\n dom_ui_->RegisterMessageCallback(\n \"managerSetDefaultSearchEngine\",\n NewCallback(this, &SearchEngineManagerHandler::SetDefaultSearchEngine));\n dom_ui_->RegisterMessageCallback(\n \"removeSearchEngine\",\n NewCallback(this, &SearchEngineManagerHandler::RemoveSearchEngine));\n}\n\nvoid SearchEngineManagerHandler::OnModelChanged() {\n if (!controller_->loaded())\n return;\n\n ListValue engine_list;\n\n \/\/ Find the default engine.\n const TemplateURL* default_engine =\n controller_->url_model()->GetDefaultSearchProvider();\n int default_index = controller_->table_model()->IndexOfTemplateURL(\n default_engine);\n\n \/\/ Add the first group (default search engine options).\n engine_list.Append(CreateDictionaryForHeading(0));\n int last_default_engine_index =\n controller_->table_model()->last_search_engine_index();\n for (int i = 0; i < last_default_engine_index; ++i) {\n engine_list.Append(CreateDictionaryForEngine(i, i == default_index));\n }\n\n \/\/ Add the second group (other search templates).\n engine_list.Append(CreateDictionaryForHeading(1));\n if (last_default_engine_index < 0)\n last_default_engine_index = 0;\n int engine_count = controller_->table_model()->RowCount();\n for (int i = last_default_engine_index; i < engine_count; ++i) {\n engine_list.Append(CreateDictionaryForEngine(i, i == default_index));\n }\n\n dom_ui_->CallJavascriptFunction(L\"SearchEngineManager.updateSearchEngineList\",\n engine_list);\n}\n\nvoid SearchEngineManagerHandler::OnItemsChanged(int start, int length) {\n OnModelChanged();\n}\n\nvoid SearchEngineManagerHandler::OnItemsAdded(int start, int length) {\n OnModelChanged();\n}\n\nvoid SearchEngineManagerHandler::OnItemsRemoved(int start, int length) {\n OnModelChanged();\n}\n\nDictionaryValue* SearchEngineManagerHandler::CreateDictionaryForHeading(\n int group_index) {\n TableModel::Groups groups = controller_->table_model()->GetGroups();\n\n DictionaryValue* dict = new DictionaryValue();\n dict->SetString(\"heading\", WideToUTF16Hack(groups[group_index].title));\n return dict;\n}\n\nDictionaryValue* SearchEngineManagerHandler::CreateDictionaryForEngine(\n int index, bool is_default) {\n TemplateURLTableModel* table_model = controller_->table_model();\n\n DictionaryValue* dict = new DictionaryValue();\n dict->SetString(\"name\", WideToUTF16Hack(table_model->GetText(\n index, IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN)));\n dict->SetString(\"keyword\", WideToUTF16Hack(table_model->GetText(\n index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN)));\n const TemplateURL* template_url = controller_->GetTemplateURL(index);\n GURL icon_url = template_url->GetFavIconURL();\n if (icon_url.is_valid())\n dict->SetString(\"iconURL\", icon_url.spec());\n dict->SetString(\"modelIndex\", base::IntToString(index));\n\n if (controller_->CanRemove(template_url))\n dict->SetString(\"canBeRemoved\", \"1\");\n if (controller_->CanMakeDefault(template_url))\n dict->SetString(\"canBeDefault\", \"1\");\n if (is_default)\n dict->SetString(\"default\", \"1\");\n\n return dict;\n}\n\nvoid SearchEngineManagerHandler::SetDefaultSearchEngine(const ListValue* args) {\n int index;\n if (!ExtractIntegerValue(args, &index)) {\n NOTREACHED();\n return;\n }\n if (index < 0 || index >= controller_->table_model()->RowCount())\n return;\n\n controller_->MakeDefaultTemplateURL(index);\n}\n\nvoid SearchEngineManagerHandler::RemoveSearchEngine(const ListValue* args) {\n int index;\n if (!ExtractIntegerValue(args, &index)) {\n NOTREACHED();\n return;\n }\n if (index < 0 || index >= controller_->table_model()->RowCount())\n return;\n\n if (controller_->CanRemove(controller_->GetTemplateURL(index)))\n controller_->RemoveTemplateURL(index);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(TOOLKIT_VIEWS)\n#define MAYBE_Infobars Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n\/\/ Temporarily marked as DISABLED on OSX too. See http:\/\/crbug.com\/60990 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\nMarking ExtensionApiTest, Infobars as DISABLED on everything but Windows.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(OS_WIN)\n#define MAYBE_Infobars Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n\/\/ Temporarily marked as DISABLED on OSX too. See http:\/\/crbug.com\/60990 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/async_resource_handler.h\"\n\n#include \"base\/hash_tables.h\"\n#include \"base\/logging.h\"\n#include \"base\/process.h\"\n#include \"base\/shared_memory.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/net\/chrome_net_log.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/net\/load_timing_observer.h\"\n#include \"chrome\/browser\/renderer_host\/global_request_id.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/base\/net_log.h\"\n#include \"webkit\/glue\/resource_loader_bridge.h\"\n\nusing base::Time;\nusing base::TimeTicks;\n\nnamespace {\n\n\/\/ When reading, we don't know if we are going to get EOF (0 bytes read), so\n\/\/ we typically have a buffer that we allocated but did not use. We keep\n\/\/ this buffer around for the next read as a small optimization.\nSharedIOBuffer* g_spare_read_buffer = NULL;\n\n\/\/ The initial size of the shared memory buffer. (32 kilobytes).\nconst int kInitialReadBufSize = 32768;\n\n\/\/ The maximum size of the shared memory buffer. (512 kilobytes).\nconst int kMaxReadBufSize = 524288;\n\n} \/\/ namespace\n\n\/\/ Our version of IOBuffer that uses shared memory.\nclass SharedIOBuffer : public net::IOBuffer {\n public:\n explicit SharedIOBuffer(int buffer_size)\n : net::IOBuffer(),\n ok_(false),\n buffer_size_(buffer_size) {}\n\n bool Init() {\n if (shared_memory_.Create(std::wstring(), false, false, buffer_size_) &&\n shared_memory_.Map(buffer_size_)) {\n data_ = reinterpret_cast(shared_memory_.memory());\n \/\/ TODO(hawk): Remove after debugging bug 16371.\n CHECK(data_);\n ok_ = true;\n }\n return ok_;\n }\n\n base::SharedMemory* shared_memory() { return &shared_memory_; }\n bool ok() { return ok_; }\n int buffer_size() { return buffer_size_; }\n\n private:\n ~SharedIOBuffer() {\n \/\/ TODO(willchan): Remove after debugging bug 16371.\n CHECK(g_spare_read_buffer != this);\n data_ = NULL;\n }\n\n base::SharedMemory shared_memory_;\n bool ok_;\n int buffer_size_;\n};\n\nAsyncResourceHandler::AsyncResourceHandler(\n ResourceDispatcherHost::Receiver* receiver,\n int process_id,\n int routing_id,\n base::ProcessHandle process_handle,\n const GURL& url,\n ResourceDispatcherHost* resource_dispatcher_host)\n : receiver_(receiver),\n process_id_(process_id),\n routing_id_(routing_id),\n process_handle_(process_handle),\n rdh_(resource_dispatcher_host),\n next_buffer_size_(kInitialReadBufSize) {\n}\n\nAsyncResourceHandler::~AsyncResourceHandler() {\n}\n\nvoid AsyncResourceHandler::PopulateTimingInfo(URLRequest* request,\n ResourceResponse* response) {\n if (!(request->load_flags() & net::LOAD_ENABLE_LOAD_TIMING))\n return;\n\n ChromeNetLog* chrome_net_log = static_cast(\n request->net_log().net_log());\n if (chrome_net_log == NULL)\n return;\n\n uint32 source_id = request->net_log().source().id;\n LoadTimingObserver* observer = chrome_net_log->load_timing_observer();\n LoadTimingObserver::URLRequestRecord* record =\n observer->GetURLRequestRecord(source_id);\n if (record) {\n response->response_head.connection_id = record->socket_log_id;\n response->response_head.connection_reused = record->socket_reused;\n response->response_head.load_timing = record->timing;\n }\n}\n\nbool AsyncResourceHandler::OnUploadProgress(int request_id,\n uint64 position,\n uint64 size) {\n return receiver_->Send(new ViewMsg_Resource_UploadProgress(routing_id_,\n request_id,\n position, size));\n}\n\nbool AsyncResourceHandler::OnRequestRedirected(int request_id,\n const GURL& new_url,\n ResourceResponse* response,\n bool* defer) {\n *defer = true;\n URLRequest* request = rdh_->GetURLRequest(\n GlobalRequestID(process_id_, request_id));\n PopulateTimingInfo(request, response);\n return receiver_->Send(new ViewMsg_Resource_ReceivedRedirect(\n routing_id_, request_id, new_url, response->response_head));\n}\n\nbool AsyncResourceHandler::OnResponseStarted(int request_id,\n ResourceResponse* response) {\n \/\/ For changes to the main frame, inform the renderer of the new URL's\n \/\/ per-host settings before the request actually commits. This way the\n \/\/ renderer will be able to set these precisely at the time the\n \/\/ request commits, avoiding the possibility of e.g. zooming the old content\n \/\/ or of having to layout the new content twice.\n URLRequest* request = rdh_->GetURLRequest(\n GlobalRequestID(process_id_, request_id));\n\n PopulateTimingInfo(request, response);\n\n ResourceDispatcherHostRequestInfo* info = rdh_->InfoForRequest(request);\n if (info->resource_type() == ResourceType::MAIN_FRAME) {\n GURL request_url(request->url());\n ChromeURLRequestContext* context =\n static_cast(request->context());\n if (context) {\n receiver_->Send(new ViewMsg_SetContentSettingsForLoadingURL(\n info->route_id(), request_url,\n context->host_content_settings_map()->GetContentSettings(\n request_url)));\n receiver_->Send(new ViewMsg_SetZoomLevelForLoadingURL(info->route_id(),\n request_url, context->host_zoom_map()->GetZoomLevel(request_url)));\n }\n }\n\n receiver_->Send(new ViewMsg_Resource_ReceivedResponse(\n routing_id_, request_id, response->response_head));\n\n if (request->response_info().metadata) {\n std::vector copy(request->response_info().metadata->data(),\n request->response_info().metadata->data() +\n request->response_info().metadata->size());\n receiver_->Send(new ViewMsg_Resource_ReceivedCachedMetadata(\n routing_id_, request_id, copy));\n }\n\n return true;\n}\n\nbool AsyncResourceHandler::OnWillStart(int request_id,\n const GURL& url,\n bool* defer) {\n return true;\n}\n\nbool AsyncResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf,\n int* buf_size, int min_size) {\n DCHECK(min_size == -1);\n\n if (g_spare_read_buffer) {\n DCHECK(!read_buffer_);\n read_buffer_.swap(&g_spare_read_buffer);\n \/\/ TODO(willchan): Remove after debugging bug 16371.\n CHECK(read_buffer_->data());\n\n *buf = read_buffer_.get();\n *buf_size = read_buffer_->buffer_size();\n } else {\n read_buffer_ = new SharedIOBuffer(next_buffer_size_);\n if (!read_buffer_->Init()) {\n DLOG(ERROR) << \"Couldn't allocate shared io buffer\";\n read_buffer_ = NULL;\n return false;\n }\n \/\/ TODO(willchan): Remove after debugging bug 16371.\n CHECK(read_buffer_->data());\n *buf = read_buffer_.get();\n *buf_size = next_buffer_size_;\n }\n\n return true;\n}\n\nbool AsyncResourceHandler::OnReadCompleted(int request_id, int* bytes_read) {\n if (!*bytes_read)\n return true;\n DCHECK(read_buffer_.get());\n\n if (read_buffer_->buffer_size() == *bytes_read) {\n \/\/ The network layer has saturated our buffer. Next time, we should give it\n \/\/ a bigger buffer for it to fill, to minimize the number of round trips we\n \/\/ do with the renderer process.\n next_buffer_size_ = std::min(next_buffer_size_ * 2, kMaxReadBufSize);\n }\n\n if (!rdh_->WillSendData(process_id_, request_id)) {\n \/\/ We should not send this data now, we have too many pending requests.\n return true;\n }\n\n base::SharedMemoryHandle handle;\n if (!read_buffer_->shared_memory()->GiveToProcess(process_handle_, &handle)) {\n \/\/ We wrongfully incremented the pending data count. Fake an ACK message\n \/\/ to fix this. We can't move this call above the WillSendData because\n \/\/ it's killing our read_buffer_, and we don't want that when we pause\n \/\/ the request.\n rdh_->DataReceivedACK(process_id_, request_id);\n \/\/ We just unmapped the memory.\n read_buffer_ = NULL;\n return false;\n }\n \/\/ We just unmapped the memory.\n read_buffer_ = NULL;\n\n receiver_->Send(new ViewMsg_Resource_DataReceived(\n routing_id_, request_id, handle, *bytes_read));\n\n return true;\n}\n\nbool AsyncResourceHandler::OnResponseCompleted(\n int request_id,\n const URLRequestStatus& status,\n const std::string& security_info) {\n receiver_->Send(new ViewMsg_Resource_RequestComplete(routing_id_,\n request_id,\n status,\n security_info));\n\n \/\/ If we still have a read buffer, then see about caching it for later...\n if (g_spare_read_buffer) {\n read_buffer_ = NULL;\n } else if (read_buffer_.get()) {\n \/\/ TODO(willchan): Remove after debugging bug 16371.\n CHECK(read_buffer_->data());\n read_buffer_.swap(&g_spare_read_buffer);\n }\n return true;\n}\n\nvoid AsyncResourceHandler::OnRequestClosed() {\n}\n\n\/\/ static\nvoid AsyncResourceHandler::GlobalCleanup() {\n if (g_spare_read_buffer) {\n \/\/ Avoid the CHECK in SharedIOBuffer::~SharedIOBuffer().\n SharedIOBuffer* tmp = g_spare_read_buffer;\n g_spare_read_buffer = NULL;\n tmp->Release();\n }\n}\nAsyncResourceHandler: When a URLRequest is canceled, the network code may complete the request with a CANCELED status but hold on to the actual buffer that was used for the operation (that's the whole point about using IOBuffers instead of a plain, non-refcounted buffer).\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/async_resource_handler.h\"\n\n#include \"base\/hash_tables.h\"\n#include \"base\/logging.h\"\n#include \"base\/process.h\"\n#include \"base\/shared_memory.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/net\/chrome_net_log.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/net\/load_timing_observer.h\"\n#include \"chrome\/browser\/renderer_host\/global_request_id.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/base\/net_log.h\"\n#include \"webkit\/glue\/resource_loader_bridge.h\"\n\nusing base::Time;\nusing base::TimeTicks;\n\nnamespace {\n\n\/\/ When reading, we don't know if we are going to get EOF (0 bytes read), so\n\/\/ we typically have a buffer that we allocated but did not use. We keep\n\/\/ this buffer around for the next read as a small optimization.\nSharedIOBuffer* g_spare_read_buffer = NULL;\n\n\/\/ The initial size of the shared memory buffer. (32 kilobytes).\nconst int kInitialReadBufSize = 32768;\n\n\/\/ The maximum size of the shared memory buffer. (512 kilobytes).\nconst int kMaxReadBufSize = 524288;\n\n} \/\/ namespace\n\n\/\/ Our version of IOBuffer that uses shared memory.\nclass SharedIOBuffer : public net::IOBuffer {\n public:\n explicit SharedIOBuffer(int buffer_size)\n : net::IOBuffer(),\n ok_(false),\n buffer_size_(buffer_size) {}\n\n bool Init() {\n if (shared_memory_.Create(std::wstring(), false, false, buffer_size_) &&\n shared_memory_.Map(buffer_size_)) {\n data_ = reinterpret_cast(shared_memory_.memory());\n DCHECK(data_);\n ok_ = true;\n }\n return ok_;\n }\n\n base::SharedMemory* shared_memory() { return &shared_memory_; }\n bool ok() { return ok_; }\n int buffer_size() { return buffer_size_; }\n\n private:\n ~SharedIOBuffer() {\n DCHECK(g_spare_read_buffer != this);\n data_ = NULL;\n }\n\n base::SharedMemory shared_memory_;\n bool ok_;\n int buffer_size_;\n};\n\nAsyncResourceHandler::AsyncResourceHandler(\n ResourceDispatcherHost::Receiver* receiver,\n int process_id,\n int routing_id,\n base::ProcessHandle process_handle,\n const GURL& url,\n ResourceDispatcherHost* resource_dispatcher_host)\n : receiver_(receiver),\n process_id_(process_id),\n routing_id_(routing_id),\n process_handle_(process_handle),\n rdh_(resource_dispatcher_host),\n next_buffer_size_(kInitialReadBufSize) {\n}\n\nAsyncResourceHandler::~AsyncResourceHandler() {\n}\n\nvoid AsyncResourceHandler::PopulateTimingInfo(URLRequest* request,\n ResourceResponse* response) {\n if (!(request->load_flags() & net::LOAD_ENABLE_LOAD_TIMING))\n return;\n\n ChromeNetLog* chrome_net_log = static_cast(\n request->net_log().net_log());\n if (chrome_net_log == NULL)\n return;\n\n uint32 source_id = request->net_log().source().id;\n LoadTimingObserver* observer = chrome_net_log->load_timing_observer();\n LoadTimingObserver::URLRequestRecord* record =\n observer->GetURLRequestRecord(source_id);\n if (record) {\n response->response_head.connection_id = record->socket_log_id;\n response->response_head.connection_reused = record->socket_reused;\n response->response_head.load_timing = record->timing;\n }\n}\n\nbool AsyncResourceHandler::OnUploadProgress(int request_id,\n uint64 position,\n uint64 size) {\n return receiver_->Send(new ViewMsg_Resource_UploadProgress(routing_id_,\n request_id,\n position, size));\n}\n\nbool AsyncResourceHandler::OnRequestRedirected(int request_id,\n const GURL& new_url,\n ResourceResponse* response,\n bool* defer) {\n *defer = true;\n URLRequest* request = rdh_->GetURLRequest(\n GlobalRequestID(process_id_, request_id));\n PopulateTimingInfo(request, response);\n return receiver_->Send(new ViewMsg_Resource_ReceivedRedirect(\n routing_id_, request_id, new_url, response->response_head));\n}\n\nbool AsyncResourceHandler::OnResponseStarted(int request_id,\n ResourceResponse* response) {\n \/\/ For changes to the main frame, inform the renderer of the new URL's\n \/\/ per-host settings before the request actually commits. This way the\n \/\/ renderer will be able to set these precisely at the time the\n \/\/ request commits, avoiding the possibility of e.g. zooming the old content\n \/\/ or of having to layout the new content twice.\n URLRequest* request = rdh_->GetURLRequest(\n GlobalRequestID(process_id_, request_id));\n\n PopulateTimingInfo(request, response);\n\n ResourceDispatcherHostRequestInfo* info = rdh_->InfoForRequest(request);\n if (info->resource_type() == ResourceType::MAIN_FRAME) {\n GURL request_url(request->url());\n ChromeURLRequestContext* context =\n static_cast(request->context());\n if (context) {\n receiver_->Send(new ViewMsg_SetContentSettingsForLoadingURL(\n info->route_id(), request_url,\n context->host_content_settings_map()->GetContentSettings(\n request_url)));\n receiver_->Send(new ViewMsg_SetZoomLevelForLoadingURL(info->route_id(),\n request_url, context->host_zoom_map()->GetZoomLevel(request_url)));\n }\n }\n\n receiver_->Send(new ViewMsg_Resource_ReceivedResponse(\n routing_id_, request_id, response->response_head));\n\n if (request->response_info().metadata) {\n std::vector copy(request->response_info().metadata->data(),\n request->response_info().metadata->data() +\n request->response_info().metadata->size());\n receiver_->Send(new ViewMsg_Resource_ReceivedCachedMetadata(\n routing_id_, request_id, copy));\n }\n\n return true;\n}\n\nbool AsyncResourceHandler::OnWillStart(int request_id,\n const GURL& url,\n bool* defer) {\n return true;\n}\n\nbool AsyncResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf,\n int* buf_size, int min_size) {\n DCHECK_EQ(-1, min_size);\n\n if (g_spare_read_buffer) {\n DCHECK(!read_buffer_);\n read_buffer_.swap(&g_spare_read_buffer);\n DCHECK(read_buffer_->data());\n\n *buf = read_buffer_.get();\n *buf_size = read_buffer_->buffer_size();\n } else {\n read_buffer_ = new SharedIOBuffer(next_buffer_size_);\n if (!read_buffer_->Init()) {\n DLOG(ERROR) << \"Couldn't allocate shared io buffer\";\n read_buffer_ = NULL;\n return false;\n }\n DCHECK(read_buffer_->data());\n *buf = read_buffer_.get();\n *buf_size = next_buffer_size_;\n }\n\n return true;\n}\n\nbool AsyncResourceHandler::OnReadCompleted(int request_id, int* bytes_read) {\n if (!*bytes_read)\n return true;\n DCHECK(read_buffer_.get());\n\n if (read_buffer_->buffer_size() == *bytes_read) {\n \/\/ The network layer has saturated our buffer. Next time, we should give it\n \/\/ a bigger buffer for it to fill, to minimize the number of round trips we\n \/\/ do with the renderer process.\n next_buffer_size_ = std::min(next_buffer_size_ * 2, kMaxReadBufSize);\n }\n\n if (!rdh_->WillSendData(process_id_, request_id)) {\n \/\/ We should not send this data now, we have too many pending requests.\n return true;\n }\n\n base::SharedMemoryHandle handle;\n if (!read_buffer_->shared_memory()->GiveToProcess(process_handle_, &handle)) {\n \/\/ We wrongfully incremented the pending data count. Fake an ACK message\n \/\/ to fix this. We can't move this call above the WillSendData because\n \/\/ it's killing our read_buffer_, and we don't want that when we pause\n \/\/ the request.\n rdh_->DataReceivedACK(process_id_, request_id);\n \/\/ We just unmapped the memory.\n read_buffer_ = NULL;\n return false;\n }\n \/\/ We just unmapped the memory.\n read_buffer_ = NULL;\n\n receiver_->Send(new ViewMsg_Resource_DataReceived(\n routing_id_, request_id, handle, *bytes_read));\n\n return true;\n}\n\nbool AsyncResourceHandler::OnResponseCompleted(\n int request_id,\n const URLRequestStatus& status,\n const std::string& security_info) {\n receiver_->Send(new ViewMsg_Resource_RequestComplete(routing_id_,\n request_id,\n status,\n security_info));\n\n \/\/ If we still have a read buffer, then see about caching it for later...\n \/\/ Note that we have to make sure the buffer is not still being used, so we\n \/\/ have to perform an explicit check on the status code.\n if (g_spare_read_buffer || URLRequestStatus::SUCCESS != status.status()) {\n read_buffer_ = NULL;\n } else if (read_buffer_.get()) {\n DCHECK(read_buffer_->data());\n read_buffer_.swap(&g_spare_read_buffer);\n }\n return true;\n}\n\nvoid AsyncResourceHandler::OnRequestClosed() {\n}\n\n\/\/ static\nvoid AsyncResourceHandler::GlobalCleanup() {\n if (g_spare_read_buffer) {\n \/\/ Avoid the CHECK in SharedIOBuffer::~SharedIOBuffer().\n SharedIOBuffer* tmp = g_spare_read_buffer;\n g_spare_read_buffer = NULL;\n tmp->Release();\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/glue\/extension_change_processor.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/sync\/engine\/syncapi.h\"\n#include \"chrome\/browser\/sync\/glue\/extension_model_associator.h\"\n#include \"chrome\/browser\/sync\/glue\/extension_util.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_source.h\"\n\ntypedef sync_api::SyncManager::ExtraExtensionChangeRecordData\n ExtraExtensionChangeRecordData;\n\nnamespace browser_sync {\n\nExtensionChangeProcessor::ExtensionChangeProcessor(\n UnrecoverableErrorHandler* error_handler,\n ExtensionModelAssociator* extension_model_associator)\n : ChangeProcessor(error_handler),\n extension_model_associator_(extension_model_associator),\n profile_(NULL) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(error_handler);\n DCHECK(extension_model_associator_);\n}\n\nExtensionChangeProcessor::~ExtensionChangeProcessor() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n}\n\n\/\/ TODO(akalin): We need to make sure events we receive from either\n\/\/ the browser or the syncapi are done in order; this is tricky since\n\/\/ some events (e.g., extension installation) are done asynchronously.\n\nvoid ExtensionChangeProcessor::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(running());\n DCHECK(profile_);\n switch (type.value) {\n case NotificationType::EXTENSION_LOADED:\n case NotificationType::EXTENSION_UNLOADED: {\n DCHECK_EQ(Source(source).ptr(), profile_);\n Extension* extension = Details(details).ptr();\n CHECK(extension);\n if (!IsExtensionSyncable(*extension)) {\n return;\n }\n const std::string& id = extension->id();\n LOG(INFO) << \"Got change notification of type \" << type.value\n << \" for extension \" << id;\n if (!extension_model_associator_->OnClientUpdate(id)) {\n std::string error = std::string(\"Client update failed for \") + id;\n error_handler()->OnUnrecoverableError(FROM_HERE, error);\n return;\n }\n break;\n }\n default:\n LOG(DFATAL) << \"Received unexpected notification of type \"\n << type.value;\n break;\n }\n}\n\nvoid ExtensionChangeProcessor::ApplyChangesFromSyncModel(\n const sync_api::BaseTransaction* trans,\n const sync_api::SyncManager::ChangeRecord* changes,\n int change_count) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (!running()) {\n return;\n }\n for (int i = 0; i < change_count; ++i) {\n const sync_api::SyncManager::ChangeRecord& change = changes[i];\n switch (change.action) {\n case sync_api::SyncManager::ChangeRecord::ACTION_ADD:\n case sync_api::SyncManager::ChangeRecord::ACTION_UPDATE: {\n sync_api::ReadNode node(trans);\n if (!node.InitByIdLookup(change.id)) {\n std::stringstream error;\n error << \"Extension node lookup failed for change \" << change.id\n << \" of action type \" << change.action;\n error_handler()->OnUnrecoverableError(FROM_HERE, error.str());\n return;\n }\n DCHECK_EQ(node.GetModelType(), syncable::EXTENSIONS);\n const sync_pb::ExtensionSpecifics& specifics =\n node.GetExtensionSpecifics();\n if (!IsExtensionSpecificsValid(specifics)) {\n std::string error =\n std::string(\"Invalid server specifics: \") +\n ExtensionSpecificsToString(specifics);\n error_handler()->OnUnrecoverableError(FROM_HERE, error);\n return;\n }\n StopObserving();\n extension_model_associator_->OnServerUpdate(specifics);\n StartObserving();\n break;\n }\n case sync_api::SyncManager::ChangeRecord::ACTION_DELETE: {\n StopObserving();\n scoped_ptr\n data(static_cast(change.extra));\n if (data.get()) {\n extension_model_associator_->OnServerRemove(data->extension_id);\n } else {\n std::stringstream error;\n error << \"Could not get extension ID for deleted node \"\n << change.id;\n error_handler()->OnUnrecoverableError(FROM_HERE, error.str());\n LOG(DFATAL) << error.str();\n }\n StartObserving();\n break;\n }\n }\n }\n}\n\nvoid ExtensionChangeProcessor::StartImpl(Profile* profile) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(profile);\n profile_ = profile;\n StartObserving();\n}\n\nvoid ExtensionChangeProcessor::StopImpl() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n StopObserving();\n profile_ = NULL;\n}\n\nvoid ExtensionChangeProcessor::StartObserving() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(profile_);\n LOG(INFO) << \"Observing EXTENSION_LOADED and EXTENSION_UNLOADED\";\n \/\/ TODO(akalin): We miss notifications when we uninstall a disabled\n \/\/ extension since EXTENSION_UNLOADED isn't sent in that case. Add\n \/\/ an EXTENSION_UNINSTALLED notification and listen to it.\n notification_registrar_.Add(\n this, NotificationType::EXTENSION_LOADED,\n Source(profile_));\n notification_registrar_.Add(\n this, NotificationType::EXTENSION_UNLOADED,\n Source(profile_));\n}\n\nvoid ExtensionChangeProcessor::StopObserving() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(profile_);\n LOG(INFO) << \"Unobserving all notifications\";\n notification_registrar_.RemoveAll();\n}\n\n} \/\/ namespace browser_sync\nMake extension sync change processor listen to events for disabled extensions.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/glue\/extension_change_processor.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/sync\/engine\/syncapi.h\"\n#include \"chrome\/browser\/sync\/glue\/extension_model_associator.h\"\n#include \"chrome\/browser\/sync\/glue\/extension_util.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_source.h\"\n\ntypedef sync_api::SyncManager::ExtraExtensionChangeRecordData\n ExtraExtensionChangeRecordData;\n\nnamespace browser_sync {\n\nExtensionChangeProcessor::ExtensionChangeProcessor(\n UnrecoverableErrorHandler* error_handler,\n ExtensionModelAssociator* extension_model_associator)\n : ChangeProcessor(error_handler),\n extension_model_associator_(extension_model_associator),\n profile_(NULL) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(error_handler);\n DCHECK(extension_model_associator_);\n}\n\nExtensionChangeProcessor::~ExtensionChangeProcessor() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n}\n\n\/\/ TODO(akalin): We need to make sure events we receive from either\n\/\/ the browser or the syncapi are done in order; this is tricky since\n\/\/ some events (e.g., extension installation) are done asynchronously.\n\nvoid ExtensionChangeProcessor::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(running());\n DCHECK(profile_);\n switch (type.value) {\n case NotificationType::EXTENSION_LOADED:\n case NotificationType::EXTENSION_UPDATE_DISABLED:\n case NotificationType::EXTENSION_UNLOADED:\n case NotificationType::EXTENSION_UNLOADED_DISABLED: {\n DCHECK_EQ(Source(source).ptr(), profile_);\n Extension* extension = Details(details).ptr();\n CHECK(extension);\n if (!IsExtensionSyncable(*extension)) {\n return;\n }\n const std::string& id = extension->id();\n LOG(INFO) << \"Got change notification of type \" << type.value\n << \" for extension \" << id;\n if (!extension_model_associator_->OnClientUpdate(id)) {\n std::string error = std::string(\"Client update failed for \") + id;\n error_handler()->OnUnrecoverableError(FROM_HERE, error);\n return;\n }\n break;\n }\n default:\n LOG(DFATAL) << \"Received unexpected notification of type \"\n << type.value;\n break;\n }\n}\n\nvoid ExtensionChangeProcessor::ApplyChangesFromSyncModel(\n const sync_api::BaseTransaction* trans,\n const sync_api::SyncManager::ChangeRecord* changes,\n int change_count) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (!running()) {\n return;\n }\n for (int i = 0; i < change_count; ++i) {\n const sync_api::SyncManager::ChangeRecord& change = changes[i];\n switch (change.action) {\n case sync_api::SyncManager::ChangeRecord::ACTION_ADD:\n case sync_api::SyncManager::ChangeRecord::ACTION_UPDATE: {\n sync_api::ReadNode node(trans);\n if (!node.InitByIdLookup(change.id)) {\n std::stringstream error;\n error << \"Extension node lookup failed for change \" << change.id\n << \" of action type \" << change.action;\n error_handler()->OnUnrecoverableError(FROM_HERE, error.str());\n return;\n }\n DCHECK_EQ(node.GetModelType(), syncable::EXTENSIONS);\n const sync_pb::ExtensionSpecifics& specifics =\n node.GetExtensionSpecifics();\n if (!IsExtensionSpecificsValid(specifics)) {\n std::string error =\n std::string(\"Invalid server specifics: \") +\n ExtensionSpecificsToString(specifics);\n error_handler()->OnUnrecoverableError(FROM_HERE, error);\n return;\n }\n StopObserving();\n extension_model_associator_->OnServerUpdate(specifics);\n StartObserving();\n break;\n }\n case sync_api::SyncManager::ChangeRecord::ACTION_DELETE: {\n StopObserving();\n scoped_ptr\n data(static_cast(change.extra));\n if (data.get()) {\n extension_model_associator_->OnServerRemove(data->extension_id);\n } else {\n std::stringstream error;\n error << \"Could not get extension ID for deleted node \"\n << change.id;\n error_handler()->OnUnrecoverableError(FROM_HERE, error.str());\n LOG(DFATAL) << error.str();\n }\n StartObserving();\n break;\n }\n }\n }\n}\n\nvoid ExtensionChangeProcessor::StartImpl(Profile* profile) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(profile);\n profile_ = profile;\n StartObserving();\n}\n\nvoid ExtensionChangeProcessor::StopImpl() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n StopObserving();\n profile_ = NULL;\n}\n\nvoid ExtensionChangeProcessor::StartObserving() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(profile_);\n LOG(INFO) << \"Observing EXTENSION_LOADED, EXTENSION_UPDATE_DISABLED, \"\n << \"EXTENSION_UNLOADED, and EXTENSION_UNLOADED_DISABLED\";\n notification_registrar_.Add(\n this, NotificationType::EXTENSION_LOADED,\n Source(profile_));\n \/\/ Despite the name, this notification is exactly like\n \/\/ EXTENSION_LOADED but with an initial state of DISABLED.\n \/\/\n \/\/ TODO(akalin): See if the themes change processor needs to listen\n \/\/ to any of these, too.\n notification_registrar_.Add(\n this, NotificationType::EXTENSION_UPDATE_DISABLED,\n Source(profile_));\n notification_registrar_.Add(\n this, NotificationType::EXTENSION_UNLOADED,\n Source(profile_));\n notification_registrar_.Add(\n this, NotificationType::EXTENSION_UNLOADED_DISABLED,\n Source(profile_));\n}\n\nvoid ExtensionChangeProcessor::StopObserving() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n DCHECK(profile_);\n LOG(INFO) << \"Unobserving all notifications\";\n notification_registrar_.RemoveAll();\n}\n\n} \/\/ namespace browser_sync\n<|endoftext|>"} {"text":"\/**\n * Copyright 2013 Da Zheng\n *\n * This file is part of SAFSlib.\n *\n * SAFSlib is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SAFSlib is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SAFSlib. If not, see .\n *\/\n\n#include \n#include \n#include \n\n#include \n\n#include \"io_interface.h\"\n#include \"native_file.h\"\n#include \"safs_file.h\"\n\nconst int BUF_SIZE = 1024 * 64 * PAGE_SIZE;\nconst size_t DATA_SIZE = 10L * 1024 * 1024 * 1024;\n\nssize_t complete_read(int fd, char *buf, size_t count)\n{\n\tssize_t bytes = 0;\n\tdo {\n\t\tssize_t ret = read(fd, buf, count);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t\tif (ret == 0)\n\t\t\treturn bytes;\n\t\tbytes += ret;\n\t\tcount -= ret;\n\t\tbuf += ret;\n\t} while (count > 0);\n\treturn bytes;\n}\n\nint verify_bytes(const char *bs1, const char *bs2, int size)\n{\n\tfor (int i = 0; i < size; i++) {\n\t\tassert(bs1[i] == bs2[i]);\n\t}\n\treturn 0;\n}\n\nclass data_source\n{\npublic:\n\tvirtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0;\n\tvirtual size_t get_size() const = 0;\n};\n\nclass file_data_source: public data_source\n{\n\tint fd;\n\tsize_t file_size;\npublic:\n\tfile_data_source(const std::string &ext_file) {\n\t\tfd = open(ext_file.c_str(), O_RDONLY);\n\t\tif (fd < 0) {\n\t\t\tperror(\"open\");\n\t\t\texit(-1);\n\t\t}\n\t\tnative_file f(ext_file);\n\t\tfile_size = f.get_size();\n\t}\n\n\tvirtual ssize_t get_data(off_t off, size_t size, char *buf) const {\n\t\tlong new_off = lseek(fd, off, SEEK_SET);\n\t\tassert(new_off == off);\n\t\tssize_t ret = complete_read(fd, buf, size);\n\t\tif (ret < 0) {\n\t\t\tperror(\"complete_read\");\n\t\t\texit(-1);\n\t\t}\n\t\treturn ret;\n\t}\n\n\tvirtual size_t get_size() const {\n\t\treturn file_size;\n\t}\n};\n\nclass synthetic_data_source: public data_source\n{\n\tsize_t size;\npublic:\n\tsynthetic_data_source(size_t size) {\n\t\tthis->size = size;\n\t}\n\n\tvirtual ssize_t get_data(off_t off, size_t size, char *buf) const {\n\t\toff_t *long_pointer = (off_t *) buf;\n\t\tint num_longs = size \/ sizeof(off_t);\n\t\tlong value = off \/ sizeof(off_t);\n\t\tfor (int i = 0; i < num_longs; i++, value++) {\n\t\t\tlong_pointer[i] = value;\n\t\t}\n\t\treturn size;\n\t}\n\n\tvirtual size_t get_size() const {\n\t\treturn size;\n\t}\n};\n\nclass verify_callback: public callback\n{\n\tchar *orig_buf;\n\tdata_source *source;\n\tsize_t verified_bytes;\npublic:\n\tverify_callback(data_source *source) {\n\t\tthis->source = source;\n\t\torig_buf = (char *) malloc(BUF_SIZE);\n\t\tverified_bytes = 0;\n\t}\n\n\t~verify_callback() {\n\t\tfree(orig_buf);\n\t}\n\n\tint invoke(io_request *rqs[], int num) {\n\t\tsize_t read_bytes = min(rqs[0]->get_size(),\n\t\t\t\tsource->get_size() - rqs[0]->get_offset());\n\t\tassert(read_bytes > 0);\n\t\tsize_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf);\n\t\tfprintf(stderr, \"verify block %lx of %ld bytes\\n\", rqs[0]->get_offset(), read_bytes);\n\t\tassert(ret == read_bytes);\n\t\tverified_bytes += read_bytes;\n\t\tverify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes);\n\t}\n\n\tsize_t get_verified_bytes() const {\n\t\treturn verified_bytes;\n\t}\n};\n\nvoid comm_verify_file(int argc, char *argv[])\n{\n\tif (argc < 1) {\n\t\tfprintf(stderr, \"verify file_name [ext_file]\");\n\t\tfprintf(stderr, \"file_name is the file name in the SA-FS file system\\n\");\n\t\tfprintf(stderr, \"ext_file is the file in the external file system\\n\");\n\t\texit(-1);\n\t}\n\n\tstd::string int_file_name = argv[0];\n\tstd::string ext_file;\n\tif (argc >= 2)\n\t\text_file = argv[1];\n\n\tfile_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);\n\tthread *curr_thread = thread::represent_thread(0);\n\tio_interface *io = factory->create_io(curr_thread);\n\tdata_source *source;\n\tif (ext_file.empty())\n\t\tsource = new synthetic_data_source(DATA_SIZE);\n\telse\n\t\tsource = new file_data_source(ext_file);\n\tverify_callback *cb = new verify_callback(source);\n\tio->set_callback(cb);\n\n\tsize_t file_size = source->get_size();\n\tassert(factory->get_file_size() >= file_size);\n\tfile_size = ROUNDUP(file_size, BUF_SIZE);\n\tchar *buf = (char *) valloc(BUF_SIZE);\n\tfor (off_t off = 0; off < file_size; off += BUF_SIZE) {\n\t\tio_request req(buf, off, BUF_SIZE, READ, io, 0);\n\t\tio->access(&req, 1);\n\t\tio->wait4complete(1);\n\t}\n\tprintf(\"verify %ld bytes\\n\", cb->get_verified_bytes());\n\t\n\tio->cleanup();\n\tdelete io->get_callback();\n\tfactory->destroy_io(io);\n}\n\nvoid comm_load_file2fs(int argc, char *argv[])\n{\n\tif (argc < 1) {\n\t\tfprintf(stderr, \"load file_name [ext_file]\\n\");\n\t\tfprintf(stderr, \"file_name is the file name in the SA-FS file system\\n\");\n\t\tfprintf(stderr, \"ext_file is the file in the external file system\\n\");\n\t\texit(-1);\n\t}\n\n\tstd::string int_file_name = argv[0];\n\tstd::string ext_file;\n\tif (argc >= 2)\n\t\text_file = argv[1];\n\n\tfile_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);\n\tthread *curr_thread = thread::represent_thread(0);\n\tio_interface *io = factory->create_io(curr_thread);\n\n\tdata_source *source;\n\tif (ext_file.empty()) {\n\t\tprintf(\"use synthetic data\\n\");\n\t\tsource = new synthetic_data_source(DATA_SIZE);\n\t}\n\telse {\n\t\tprintf(\"use file %s\\n\", ext_file.c_str());\n\t\tsource = new file_data_source(ext_file);\n\t}\n\tassert(factory->get_file_size() >= source->get_size());\n\tprintf(\"source size: %ld\\n\", source->get_size());\n\n\tchar *buf = (char *) valloc(BUF_SIZE);\n\toff_t off = 0;\n\n\twhile (off < source->get_size()) {\n\t\tsize_t size = min(BUF_SIZE, source->get_size() - off);\n\t\tsize_t ret = source->get_data(off, size, buf);\n\t\tassert(ret == size);\n\t\tssize_t write_bytes = ROUNDUP(ret, 512);\n\t\tio_request req(buf, off, write_bytes, WRITE, io, 0);\n\t\tio->access(&req, 1);\n\t\tio->wait4complete(1);\n\t\toff += write_bytes;\n\t}\n\tprintf(\"write all data\\n\");\n\t\n\tio->cleanup();\n\tfactory->destroy_io(io);\n}\n\nvoid comm_create_file(int argc, char *argv[])\n{\n\tif (argc < 2) {\n\t\tfprintf(stderr, \"create file_name size\\n\");\n\t\tfprintf(stderr, \"file_name is the file name in the SA-FS file system\\n\");\n\t\texit(-1);\n\t}\n\n\tstd::string file_name = argv[0];\n\tsize_t file_size = str2size(argv[1]);\n\tsafs_file file(get_sys_RAID_conf(), file_name);\n\tfile.create_file(file_size);\n\tprintf(\"create file %s of %ld bytes\\n\", file_name.c_str(),\n\t\t\tfile.get_file_size());\n}\n\ntypedef void (*command_func_t)(int argc, char *argv[]);\n\nstruct command\n{\n\tstd::string name;\n\tcommand_func_t func;\n\tstd::string help_info;\n};\n\nstruct command commands[] = {\n\t{\"create\", comm_create_file,\n\t\t\"create file_name size: create a file with the specified size\"},\n\t{\"load\", comm_load_file2fs,\n\t\t\"load file_name [ext_file]: load data to the file\"},\n\t{\"verify\", comm_verify_file,\n\t\t\"verify file_name [ext_file]: verify data in the file\"},\n};\n\nint get_num_commands()\n{\n\treturn sizeof(commands) \/ sizeof(commands[0]);\n}\n\nconst command *get_command(const std::string &name)\n{\n\tint num_comms = get_num_commands();\n\tfor (int i = 0; i < num_comms; i++) {\n\t\tif (commands[i].name == name)\n\t\t\treturn &commands[i];\n\t}\n\treturn NULL;\n}\n\nvoid print_help()\n{\n\tprintf(\"SAFS-util conf_file command ...\\n\");\n\tprintf(\"The supported commands are\\n\");\n\tint num_commands = get_num_commands();\n\tfor (int i =0; i < num_commands; i++) {\n\t\tprintf(\"\\t%s\\n\", commands[i].help_info.c_str());\n\t}\n}\n\n\/**\n * This is a utility tool for the SA-FS.\n *\/\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 3) {\n\t\tprint_help();\n\t\texit(-1);\n\t}\n\n\tstd::string conf_file = argv[1];\n\tstd::string command = argv[2];\n\n\tconfig_map configs(conf_file);\n\tinit_io_system(configs);\n\n\tconst struct command *comm = get_command(command);\n\tif (comm == NULL) {\n\t\tfprintf(stderr, \"wrong command %s\\n\", comm->name.c_str());\n\t\tprint_help();\n\t\treturn -1;\n\t}\n\tcomm->func(argc - 3, argv + 3);\n}\n[SAFS]: add command help and list in SAFS-util.\/**\n * Copyright 2013 Da Zheng\n *\n * This file is part of SAFSlib.\n *\n * SAFSlib is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SAFSlib is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SAFSlib. If not, see .\n *\/\n\n#include \n#include \n#include \n\n#include \n\n#include \"io_interface.h\"\n#include \"native_file.h\"\n#include \"safs_file.h\"\n\nconst int BUF_SIZE = 1024 * 64 * PAGE_SIZE;\nconst size_t DATA_SIZE = 10L * 1024 * 1024 * 1024;\n\nssize_t complete_read(int fd, char *buf, size_t count)\n{\n\tssize_t bytes = 0;\n\tdo {\n\t\tssize_t ret = read(fd, buf, count);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t\tif (ret == 0)\n\t\t\treturn bytes;\n\t\tbytes += ret;\n\t\tcount -= ret;\n\t\tbuf += ret;\n\t} while (count > 0);\n\treturn bytes;\n}\n\nint verify_bytes(const char *bs1, const char *bs2, int size)\n{\n\tfor (int i = 0; i < size; i++) {\n\t\tassert(bs1[i] == bs2[i]);\n\t}\n\treturn 0;\n}\n\nclass data_source\n{\npublic:\n\tvirtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0;\n\tvirtual size_t get_size() const = 0;\n};\n\nclass file_data_source: public data_source\n{\n\tint fd;\n\tsize_t file_size;\npublic:\n\tfile_data_source(const std::string &ext_file) {\n\t\tfd = open(ext_file.c_str(), O_RDONLY);\n\t\tif (fd < 0) {\n\t\t\tperror(\"open\");\n\t\t\texit(-1);\n\t\t}\n\t\tnative_file f(ext_file);\n\t\tfile_size = f.get_size();\n\t}\n\n\tvirtual ssize_t get_data(off_t off, size_t size, char *buf) const {\n\t\tlong new_off = lseek(fd, off, SEEK_SET);\n\t\tassert(new_off == off);\n\t\tssize_t ret = complete_read(fd, buf, size);\n\t\tif (ret < 0) {\n\t\t\tperror(\"complete_read\");\n\t\t\texit(-1);\n\t\t}\n\t\treturn ret;\n\t}\n\n\tvirtual size_t get_size() const {\n\t\treturn file_size;\n\t}\n};\n\nclass synthetic_data_source: public data_source\n{\n\tsize_t size;\npublic:\n\tsynthetic_data_source(size_t size) {\n\t\tthis->size = size;\n\t}\n\n\tvirtual ssize_t get_data(off_t off, size_t size, char *buf) const {\n\t\toff_t *long_pointer = (off_t *) buf;\n\t\tint num_longs = size \/ sizeof(off_t);\n\t\tlong value = off \/ sizeof(off_t);\n\t\tfor (int i = 0; i < num_longs; i++, value++) {\n\t\t\tlong_pointer[i] = value;\n\t\t}\n\t\treturn size;\n\t}\n\n\tvirtual size_t get_size() const {\n\t\treturn size;\n\t}\n};\n\nclass verify_callback: public callback\n{\n\tchar *orig_buf;\n\tdata_source *source;\n\tsize_t verified_bytes;\npublic:\n\tverify_callback(data_source *source) {\n\t\tthis->source = source;\n\t\torig_buf = (char *) malloc(BUF_SIZE);\n\t\tverified_bytes = 0;\n\t}\n\n\t~verify_callback() {\n\t\tfree(orig_buf);\n\t}\n\n\tint invoke(io_request *rqs[], int num) {\n\t\tsize_t read_bytes = min(rqs[0]->get_size(),\n\t\t\t\tsource->get_size() - rqs[0]->get_offset());\n\t\tassert(read_bytes > 0);\n\t\tsize_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf);\n\t\tfprintf(stderr, \"verify block %lx of %ld bytes\\n\", rqs[0]->get_offset(), read_bytes);\n\t\tassert(ret == read_bytes);\n\t\tverified_bytes += read_bytes;\n\t\tverify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes);\n\t}\n\n\tsize_t get_verified_bytes() const {\n\t\treturn verified_bytes;\n\t}\n};\n\nvoid comm_verify_file(int argc, char *argv[])\n{\n\tif (argc < 1) {\n\t\tfprintf(stderr, \"verify file_name [ext_file]\");\n\t\tfprintf(stderr, \"file_name is the file name in the SA-FS file system\\n\");\n\t\tfprintf(stderr, \"ext_file is the file in the external file system\\n\");\n\t\texit(-1);\n\t}\n\n\tstd::string int_file_name = argv[0];\n\tstd::string ext_file;\n\tif (argc >= 2)\n\t\text_file = argv[1];\n\n\tfile_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);\n\tthread *curr_thread = thread::represent_thread(0);\n\tio_interface *io = factory->create_io(curr_thread);\n\tdata_source *source;\n\tif (ext_file.empty())\n\t\tsource = new synthetic_data_source(DATA_SIZE);\n\telse\n\t\tsource = new file_data_source(ext_file);\n\tverify_callback *cb = new verify_callback(source);\n\tio->set_callback(cb);\n\n\tsize_t file_size = source->get_size();\n\tassert(factory->get_file_size() >= file_size);\n\tfile_size = ROUNDUP(file_size, BUF_SIZE);\n\tchar *buf = (char *) valloc(BUF_SIZE);\n\tfor (off_t off = 0; off < file_size; off += BUF_SIZE) {\n\t\tio_request req(buf, off, BUF_SIZE, READ, io, 0);\n\t\tio->access(&req, 1);\n\t\tio->wait4complete(1);\n\t}\n\tprintf(\"verify %ld bytes\\n\", cb->get_verified_bytes());\n\t\n\tio->cleanup();\n\tdelete io->get_callback();\n\tfactory->destroy_io(io);\n}\n\nvoid comm_load_file2fs(int argc, char *argv[])\n{\n\tif (argc < 1) {\n\t\tfprintf(stderr, \"load file_name [ext_file]\\n\");\n\t\tfprintf(stderr, \"file_name is the file name in the SA-FS file system\\n\");\n\t\tfprintf(stderr, \"ext_file is the file in the external file system\\n\");\n\t\texit(-1);\n\t}\n\n\tstd::string int_file_name = argv[0];\n\tstd::string ext_file;\n\tif (argc >= 2)\n\t\text_file = argv[1];\n\n\tfile_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);\n\tthread *curr_thread = thread::represent_thread(0);\n\tio_interface *io = factory->create_io(curr_thread);\n\n\tdata_source *source;\n\tif (ext_file.empty()) {\n\t\tprintf(\"use synthetic data\\n\");\n\t\tsource = new synthetic_data_source(DATA_SIZE);\n\t}\n\telse {\n\t\tprintf(\"use file %s\\n\", ext_file.c_str());\n\t\tsource = new file_data_source(ext_file);\n\t}\n\tassert(factory->get_file_size() >= source->get_size());\n\tprintf(\"source size: %ld\\n\", source->get_size());\n\n\tchar *buf = (char *) valloc(BUF_SIZE);\n\toff_t off = 0;\n\n\twhile (off < source->get_size()) {\n\t\tsize_t size = min(BUF_SIZE, source->get_size() - off);\n\t\tsize_t ret = source->get_data(off, size, buf);\n\t\tassert(ret == size);\n\t\tssize_t write_bytes = ROUNDUP(ret, 512);\n\t\tio_request req(buf, off, write_bytes, WRITE, io, 0);\n\t\tio->access(&req, 1);\n\t\tio->wait4complete(1);\n\t\toff += write_bytes;\n\t}\n\tprintf(\"write all data\\n\");\n\t\n\tio->cleanup();\n\tfactory->destroy_io(io);\n}\n\nvoid comm_create_file(int argc, char *argv[])\n{\n\tif (argc < 2) {\n\t\tfprintf(stderr, \"create file_name size\\n\");\n\t\tfprintf(stderr, \"file_name is the file name in the SA-FS file system\\n\");\n\t\texit(-1);\n\t}\n\n\tstd::string file_name = argv[0];\n\tsize_t file_size = str2size(argv[1]);\n\tsafs_file file(get_sys_RAID_conf(), file_name);\n\tfile.create_file(file_size);\n\tprintf(\"create file %s of %ld bytes\\n\", file_name.c_str(),\n\t\t\tfile.get_file_size());\n}\n\nvoid print_help();\n\nvoid comm_help(int argc, char *argv[])\n{\n\tprint_help();\n}\n\nvoid comm_list(int argc, char *argv[])\n{\n\tstd::set files;\n\tconst RAID_config &conf = get_sys_RAID_conf();\n\n\t\/\/ First find all individual file names in the root directories.\n\tfor (int i = 0; i < conf.get_num_disks(); i++) {\n\t\tstd::string dir_name = conf.get_disk(i).name;\n\t\tnative_dir dir(dir_name);\n\t\tstd::vector file_names;\n\t\tdir.read_all_files(file_names);\n\t\tfiles.insert(file_names.begin(), file_names.end());\n\t}\n\n\tfor (std::set::const_iterator it = files.begin();\n\t\t\tit != files.end(); it++) {\n\t\tsafs_file file(conf, *it);\n\t\tif (file.exist()) {\n\t\t\tprintf(\"%s: %ld bytes\\n\", file.get_name().c_str(),\n\t\t\t\t\tfile.get_file_size());\n\t\t}\n\t\telse {\n\t\t\tprintf(\"%s is corrupted\\n\", file.get_name().c_str());\n\t\t}\n\t}\n}\n\ntypedef void (*command_func_t)(int argc, char *argv[]);\n\nstruct command\n{\n\tstd::string name;\n\tcommand_func_t func;\n\tstd::string help_info;\n};\n\nstruct command commands[] = {\n\t{\"create\", comm_create_file,\n\t\t\"create file_name size: create a file with the specified size\"},\n\t{\"help\", comm_help,\n\t\t\"help: print the help info\"},\n\t{\"list\", comm_list, \"list: list existing files in SAFS\"},\n\t{\"load\", comm_load_file2fs,\n\t\t\"load file_name [ext_file]: load data to the file\"},\n\t{\"verify\", comm_verify_file,\n\t\t\"verify file_name [ext_file]: verify data in the file\"},\n};\n\nint get_num_commands()\n{\n\treturn sizeof(commands) \/ sizeof(commands[0]);\n}\n\nconst command *get_command(const std::string &name)\n{\n\tint num_comms = get_num_commands();\n\tfor (int i = 0; i < num_comms; i++) {\n\t\tif (commands[i].name == name)\n\t\t\treturn &commands[i];\n\t}\n\treturn NULL;\n}\n\nvoid print_help()\n{\n\tprintf(\"SAFS-util conf_file command ...\\n\");\n\tprintf(\"The supported commands are\\n\");\n\tint num_commands = get_num_commands();\n\tfor (int i =0; i < num_commands; i++) {\n\t\tprintf(\"\\t%s\\n\", commands[i].help_info.c_str());\n\t}\n}\n\n\/**\n * This is a utility tool for the SA-FS.\n *\/\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 3) {\n\t\tprint_help();\n\t\texit(-1);\n\t}\n\n\tstd::string conf_file = argv[1];\n\tstd::string command = argv[2];\n\n\tconfig_map configs(conf_file);\n\tinit_io_system(configs);\n\n\tconst struct command *comm = get_command(command);\n\tif (comm == NULL) {\n\t\tfprintf(stderr, \"wrong command %s\\n\", comm->name.c_str());\n\t\tprint_help();\n\t\treturn -1;\n\t}\n\tcomm->func(argc - 3, argv + 3);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"platform.h\"\n\n#include \"base_swapchain.h\"\n\nnamespace swapchain {\n\nnamespace {\nVkResult createSemaphore(const DeviceData *device_functions, VkDevice device,\n const VkAllocationCallbacks *pAllocator,\n VkSemaphore *pSem) {\n VkSemaphoreCreateInfo createInfo = {\n VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, \/\/ sType\n nullptr, \/\/ pNext\n 0, \/\/ flags\n };\n return device_functions->vkCreateSemaphore(device, &createInfo, pAllocator,\n pSem);\n}\nVkResult createSemaphores(const DeviceData *device_functions, VkDevice device,\n const VkAllocationCallbacks *pAllocator, size_t count,\n std::vector &sems) {\n sems.resize(count);\n for (VkSemaphore &sem : sems) {\n VkResult res;\n if ((res = createSemaphore(device_functions, device, pAllocator, &sem)) !=\n VK_SUCCESS) {\n return res;\n }\n }\n return VK_SUCCESS;\n}\n\nvoid destroySemaphores(const DeviceData *device_functions, VkDevice device,\n const VkAllocationCallbacks *pAllocator,\n std::vector &sems) {\n for (VkSemaphore sem : sems) {\n device_functions->vkDestroySemaphore(device, sem, pAllocator);\n }\n sems.clear();\n}\n} \/\/ namespace\n\nBaseSwapchain::BaseSwapchain(VkInstance instance, VkDevice device,\n uint32_t queue, VkCommandPool command_pool,\n uint32_t num_images,\n const InstanceData *instance_functions,\n const DeviceData *device_functions,\n const VkSwapchainCreateInfoKHR *swapchain_info,\n const VkAllocationCallbacks *pAllocator,\n const void *platform_info)\n : instance_(instance),\n device_(device),\n instance_functions_(instance_functions),\n device_functions_(device_functions),\n swapchain_info_(*swapchain_info) {\n if (platform_info == nullptr) {\n return;\n }\n\n CreateSurface(instance_functions, instance, platform_info, pAllocator,\n &surface_);\n if (surface_ == 0) {\n \/\/ Surface creation failed\n return;\n }\n\n {\n \/\/ Create the swapchain\n VkSwapchainCreateInfoKHR createInfo = {\n VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, \/\/ sType\n nullptr, \/\/ pNext\n 0, \/\/ flags\n surface_, \/\/ surface\n num_images, \/\/ minImageCount\n swapchain_info_.imageFormat, \/\/ imageFormat\n swapchain_info_.imageColorSpace, \/\/ imageColorSpace\n swapchain_info_.imageExtent, \/\/ imageExtent\n swapchain_info_.imageArrayLayers, \/\/ arrayLayers\n VK_IMAGE_USAGE_TRANSFER_DST_BIT, \/\/ imageUsage\n VK_SHARING_MODE_EXCLUSIVE, \/\/ imageSharingMode,\n 0, \/\/ queueFamilyIndexCount\n nullptr, \/\/ pQueueFamilyIndices\n swapchain_info_.preTransform, \/\/ preTransform\n swapchain_info_.compositeAlpha, \/\/ compositeAlpha\n VK_PRESENT_MODE_FIFO_KHR, \/\/ presentMode\n VK_TRUE, \/\/ clipped\n 0, \/\/ oldSwapchain\n };\n if (device_functions_->vkCreateSwapchainKHR(\n device_, &createInfo, pAllocator, &swapchain_) != VK_SUCCESS) {\n \/\/ Creating swapchain failed\n swapchain_ = 0;\n return;\n }\n }\n\n uint32_t num_base_images = 0;\n device_functions_->vkGetSwapchainImagesKHR(device, swapchain_,\n &num_base_images, nullptr);\n images_.resize(num_base_images);\n device_functions_->vkGetSwapchainImagesKHR(device, swapchain_,\n &num_base_images, images_.data());\n\n \/\/ Create a command buffer for each virtual image to blit from\n VkCommandBufferAllocateInfo command_buffer_info = {\n VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, \/\/ sType\n nullptr, \/\/ pNext\n command_pool, \/\/ commandPool\n VK_COMMAND_BUFFER_LEVEL_PRIMARY, \/\/ level\n num_images, \/\/ commandBufferCount\n };\n command_buffers_.resize(num_images);\n if (device_functions_->vkAllocateCommandBuffers(device, &command_buffer_info,\n command_buffers_.data()) !=\n VK_SUCCESS) {\n return;\n }\n for (VkCommandBuffer cmdbuf : command_buffers_) {\n set_dispatch_from_parent(cmdbuf, device);\n }\n\n if (createSemaphore(device_functions_, device_, pAllocator,\n &acquire_semaphore_) != VK_SUCCESS) {\n return;\n }\n if (createSemaphores(device_functions_, device_, pAllocator, num_images,\n blit_semaphores_) != VK_SUCCESS) {\n return;\n }\n if (createSemaphores(device_functions_, device_, pAllocator, num_images,\n present_semaphores_) != VK_SUCCESS) {\n return;\n }\n\n is_pending_.resize(num_images);\n}\n\nvoid BaseSwapchain::Destroy(const VkAllocationCallbacks *pAllocator) {\n device_functions_->vkDestroySemaphore(device_, acquire_semaphore_,\n pAllocator);\n acquire_semaphore_ = VK_NULL_HANDLE;\n\n destroySemaphores(device_functions_, device_, pAllocator, blit_semaphores_);\n destroySemaphores(device_functions_, device_, pAllocator,\n present_semaphores_);\n\n device_functions_->vkDestroySwapchainKHR(device_, swapchain_, pAllocator);\n swapchain_ = VK_NULL_HANDLE;\n\n instance_functions_->vkDestroySurfaceKHR(instance_, surface_, pAllocator);\n surface_ = VK_NULL_HANDLE;\n\n images_.clear();\n\n is_pending_.clear();\n command_buffers_.clear();\n}\n\nVkResult BaseSwapchain::PresentFrom(VkQueue queue, size_t index,\n VkImage image) {\n std::unique_lock guard(present_lock_);\n VkResult res;\n uint32_t base_index = 0;\n \/\/ TODO: the error return values here aren't necessarily valid return values\n \/\/ for VkQueueSubmit\n if ((res = device_functions_->vkAcquireNextImageKHR(\n device_, swapchain_, 0, acquire_semaphore_, VK_NULL_HANDLE,\n &base_index)) != VK_SUCCESS) {\n return res;\n }\n\n VkCommandBuffer cmdbuf = command_buffers_[index];\n if ((res = device_functions_->vkResetCommandBuffer(cmdbuf, 0)) !=\n VK_SUCCESS) {\n return res;\n }\n VkCommandBufferBeginInfo beginInfo = {\n VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, \/\/ sType\n 0, \/\/ pNext\n VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, \/\/ flags\n nullptr, \/\/ pInheritanceInfo\n };\n if ((res = device_functions_->vkBeginCommandBuffer(cmdbuf, &beginInfo)) !=\n VK_SUCCESS) {\n return res;\n }\n\n \/\/ The source image is already in VK_IMAGE_LAYOUT_TRANSFER_SRC, we need to\n \/\/ transition our image between VK_IMAGE_LAYOUT_TRANSFER_DST and\n \/\/ VK_IMAGE_LAYOUT_SHADER_PRESENT_KHR\n VkImageMemoryBarrier initialBarrier = {\n VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, \/\/ sType\n nullptr, \/\/ pNext\n 0, \/\/ srcAccessFlags\n VK_ACCESS_TRANSFER_WRITE_BIT, \/\/ dstAccessFlags\n VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, \/\/ oldLayout\n VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, \/\/ newLayout\n VK_QUEUE_FAMILY_IGNORED, \/\/ srcQueueFamilyIndex\n VK_QUEUE_FAMILY_IGNORED, \/\/ dstQueueFamilyIndex\n images_[base_index], \/\/ image\n VkImageSubresourceRange{\n VK_IMAGE_ASPECT_COLOR_BIT, \/\/ aspectMask\n 0, \/\/ baseMipLevel\n 1, \/\/ levelCount\n 0, \/\/ baseArrayLayer\n swapchain_info_.imageArrayLayers, \/\/ layerCount\n }, \/\/ subresourceRange\n };\n\n device_functions_->vkCmdPipelineBarrier(\n cmdbuf,\n 0, \/\/ srcStageMask\n VK_PIPELINE_STAGE_TRANSFER_BIT, \/\/ dstStageMask\n 0, \/\/ dependencyFlags\n 0, \/\/ memoryBarrierCount\n nullptr, \/\/ pMemoryBarriers\n 0, \/\/ bufferMemoryBarrierCount\n nullptr, \/\/ pBufferMemoryBarriers\n 1, \/\/ imageMemoryBarrierCount\n &initialBarrier \/\/ pImageMemoryBarriers\n );\n\n VkImageSubresourceLayers subresource = {\n VK_IMAGE_ASPECT_COLOR_BIT, \/\/ aspectMask\n 0, \/\/ mipLevel\n 0, \/\/ baseArrayLayer\n swapchain_info_.imageArrayLayers, \/\/ layerCount\n };\n VkOffset3D offsets[2] = {\n {\n 0,\n 0,\n 0,\n },\n {\n (int32_t)swapchain_info_.imageExtent.width,\n (int32_t)swapchain_info_.imageExtent.height,\n 1,\n },\n };\n VkImageBlit blit = {\n subresource,\n {offsets[0], offsets[1]},\n subresource,\n {offsets[0], offsets[1]},\n };\n device_functions_->vkCmdBlitImage(\n cmdbuf,\n image, \/\/ srcImage\n VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, \/\/ srcImageLayout\n images_[base_index], \/\/ dstImage\n VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, \/\/ dstImageLayout\n 1, \/\/ regionCount\n &blit, \/\/ pRegions\n VK_FILTER_NEAREST \/\/ filter\n );\n\n VkImageMemoryBarrier finalBarrier = initialBarrier;\n finalBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n finalBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;\n finalBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;\n finalBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;\n\n device_functions_->vkCmdPipelineBarrier(\n cmdbuf,\n VK_PIPELINE_STAGE_TRANSFER_BIT, \/\/ srcStageMask\n 0, \/\/ dstStageMask\n 0, \/\/ dependencyFlags\n 0, \/\/ memoryBarrierCount\n nullptr, \/\/ pMemoryBarriers\n 0, \/\/ bufferMemoryBarrierCount\n nullptr, \/\/ pBufferMemoryBarriers\n 1, \/\/ imageMemoryBarrierCount\n &finalBarrier \/\/ pImageMemoryBarriers\n );\n\n if ((res = device_functions_->vkEndCommandBuffer(cmdbuf)) != VK_SUCCESS) {\n return res;\n }\n\n VkSemaphore signal_semaphores[] = {blit_semaphores_[index],\n present_semaphores_[index]};\n VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_TRANSFER_BIT;\n VkSubmitInfo submitInfo = {\n VK_STRUCTURE_TYPE_SUBMIT_INFO, \/\/ sType\n 0, \/\/ pNext\n 1, \/\/ waitSemaphoreCount\n &acquire_semaphore_, \/\/ pWaitSemaphores\n &waitStage, \/\/ pWaitDstStageMask\n 1, \/\/ commandBufferCount\n &cmdbuf, \/\/ pCommandBuffers\n 2, \/\/ signalSemaphoreCount\n signal_semaphores, \/\/ pSignalSemaphores\n };\n auto queue_functions = GetGlobalContext().GetQueueData(queue);\n if ((res = queue_functions->vkQueueSubmit(queue, 1, &submitInfo,\n VK_NULL_HANDLE)) != VK_SUCCESS) {\n return res;\n }\n is_pending_[index] = true;\n\n VkPresentInfoKHR presentInfo = {\n VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, \/\/ sType\n 0, \/\/ pNext\n 1, \/\/ waitSemaphoreCount\n &present_semaphores_[index], \/\/ waitSemaphores\n 1, \/\/ swapchainCount\n &swapchain_, \/\/ pSwapchains,\n &base_index, \/\/ pImageIndices\n nullptr, \/\/ pResults\n };\n if ((res = queue_functions->vkQueuePresentKHR(queue, &presentInfo)) !=\n VK_SUCCESS) {\n return res;\n }\n return VK_SUCCESS;\n}\n\nVkSemaphore BaseSwapchain::BlitWaitSemaphore(size_t index) {\n if (!is_pending_[index]) {\n return VK_NULL_HANDLE;\n }\n is_pending_[index] = false;\n return blit_semaphores_[index];\n}\n} \/\/ namespace swapchain\nFix incorrect image blitting layout\/*\n * Copyright (C) 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"platform.h\"\n\n#include \"base_swapchain.h\"\n\nnamespace swapchain {\n\nnamespace {\nVkResult createSemaphore(const DeviceData *device_functions, VkDevice device,\n const VkAllocationCallbacks *pAllocator,\n VkSemaphore *pSem) {\n VkSemaphoreCreateInfo createInfo = {\n VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, \/\/ sType\n nullptr, \/\/ pNext\n 0, \/\/ flags\n };\n return device_functions->vkCreateSemaphore(device, &createInfo, pAllocator,\n pSem);\n}\nVkResult createSemaphores(const DeviceData *device_functions, VkDevice device,\n const VkAllocationCallbacks *pAllocator, size_t count,\n std::vector &sems) {\n sems.resize(count);\n for (VkSemaphore &sem : sems) {\n VkResult res;\n if ((res = createSemaphore(device_functions, device, pAllocator, &sem)) !=\n VK_SUCCESS) {\n return res;\n }\n }\n return VK_SUCCESS;\n}\n\nvoid destroySemaphores(const DeviceData *device_functions, VkDevice device,\n const VkAllocationCallbacks *pAllocator,\n std::vector &sems) {\n for (VkSemaphore sem : sems) {\n device_functions->vkDestroySemaphore(device, sem, pAllocator);\n }\n sems.clear();\n}\n} \/\/ namespace\n\nBaseSwapchain::BaseSwapchain(VkInstance instance, VkDevice device,\n uint32_t queue, VkCommandPool command_pool,\n uint32_t num_images,\n const InstanceData *instance_functions,\n const DeviceData *device_functions,\n const VkSwapchainCreateInfoKHR *swapchain_info,\n const VkAllocationCallbacks *pAllocator,\n const void *platform_info)\n : instance_(instance),\n device_(device),\n instance_functions_(instance_functions),\n device_functions_(device_functions),\n swapchain_info_(*swapchain_info) {\n if (platform_info == nullptr) {\n return;\n }\n\n CreateSurface(instance_functions, instance, platform_info, pAllocator,\n &surface_);\n if (surface_ == 0) {\n \/\/ Surface creation failed\n return;\n }\n\n {\n \/\/ Create the swapchain\n VkSwapchainCreateInfoKHR createInfo = {\n VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, \/\/ sType\n nullptr, \/\/ pNext\n 0, \/\/ flags\n surface_, \/\/ surface\n num_images, \/\/ minImageCount\n swapchain_info_.imageFormat, \/\/ imageFormat\n swapchain_info_.imageColorSpace, \/\/ imageColorSpace\n swapchain_info_.imageExtent, \/\/ imageExtent\n swapchain_info_.imageArrayLayers, \/\/ arrayLayers\n VK_IMAGE_USAGE_TRANSFER_DST_BIT, \/\/ imageUsage\n VK_SHARING_MODE_EXCLUSIVE, \/\/ imageSharingMode,\n 0, \/\/ queueFamilyIndexCount\n nullptr, \/\/ pQueueFamilyIndices\n swapchain_info_.preTransform, \/\/ preTransform\n swapchain_info_.compositeAlpha, \/\/ compositeAlpha\n VK_PRESENT_MODE_FIFO_KHR, \/\/ presentMode\n VK_TRUE, \/\/ clipped\n 0, \/\/ oldSwapchain\n };\n if (device_functions_->vkCreateSwapchainKHR(\n device_, &createInfo, pAllocator, &swapchain_) != VK_SUCCESS) {\n \/\/ Creating swapchain failed\n swapchain_ = 0;\n return;\n }\n }\n\n uint32_t num_base_images = 0;\n device_functions_->vkGetSwapchainImagesKHR(device, swapchain_,\n &num_base_images, nullptr);\n images_.resize(num_base_images);\n device_functions_->vkGetSwapchainImagesKHR(device, swapchain_,\n &num_base_images, images_.data());\n\n \/\/ Create a command buffer for each virtual image to blit from\n VkCommandBufferAllocateInfo command_buffer_info = {\n VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, \/\/ sType\n nullptr, \/\/ pNext\n command_pool, \/\/ commandPool\n VK_COMMAND_BUFFER_LEVEL_PRIMARY, \/\/ level\n num_images, \/\/ commandBufferCount\n };\n command_buffers_.resize(num_images);\n if (device_functions_->vkAllocateCommandBuffers(device, &command_buffer_info,\n command_buffers_.data()) !=\n VK_SUCCESS) {\n return;\n }\n for (VkCommandBuffer cmdbuf : command_buffers_) {\n set_dispatch_from_parent(cmdbuf, device);\n }\n\n if (createSemaphore(device_functions_, device_, pAllocator,\n &acquire_semaphore_) != VK_SUCCESS) {\n return;\n }\n if (createSemaphores(device_functions_, device_, pAllocator, num_images,\n blit_semaphores_) != VK_SUCCESS) {\n return;\n }\n if (createSemaphores(device_functions_, device_, pAllocator, num_images,\n present_semaphores_) != VK_SUCCESS) {\n return;\n }\n\n is_pending_.resize(num_images);\n}\n\nvoid BaseSwapchain::Destroy(const VkAllocationCallbacks *pAllocator) {\n device_functions_->vkDestroySemaphore(device_, acquire_semaphore_,\n pAllocator);\n acquire_semaphore_ = VK_NULL_HANDLE;\n\n destroySemaphores(device_functions_, device_, pAllocator, blit_semaphores_);\n destroySemaphores(device_functions_, device_, pAllocator,\n present_semaphores_);\n\n device_functions_->vkDestroySwapchainKHR(device_, swapchain_, pAllocator);\n swapchain_ = VK_NULL_HANDLE;\n\n instance_functions_->vkDestroySurfaceKHR(instance_, surface_, pAllocator);\n surface_ = VK_NULL_HANDLE;\n\n images_.clear();\n\n is_pending_.clear();\n command_buffers_.clear();\n}\n\nVkResult BaseSwapchain::PresentFrom(VkQueue queue, size_t index,\n VkImage image) {\n std::unique_lock guard(present_lock_);\n VkResult res;\n uint32_t base_index = 0;\n \/\/ TODO: the error return values here aren't necessarily valid return values\n \/\/ for VkQueueSubmit\n if ((res = device_functions_->vkAcquireNextImageKHR(\n device_, swapchain_, 0, acquire_semaphore_, VK_NULL_HANDLE,\n &base_index)) != VK_SUCCESS) {\n return res;\n }\n\n VkCommandBuffer cmdbuf = command_buffers_[index];\n if ((res = device_functions_->vkResetCommandBuffer(cmdbuf, 0)) !=\n VK_SUCCESS) {\n return res;\n }\n VkCommandBufferBeginInfo beginInfo = {\n VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, \/\/ sType\n 0, \/\/ pNext\n VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, \/\/ flags\n nullptr, \/\/ pInheritanceInfo\n };\n if ((res = device_functions_->vkBeginCommandBuffer(cmdbuf, &beginInfo)) !=\n VK_SUCCESS) {\n return res;\n }\n\n \/\/ The source image is already in VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, we\n \/\/ need to transition our image between VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL\n \/\/ and VK_IMAGE_LAYOUT_PRESENT_SRC_KHR\n VkImageMemoryBarrier initialBarrier = {\n VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, \/\/ sType\n nullptr, \/\/ pNext\n 0, \/\/ srcAccessFlags\n VK_ACCESS_TRANSFER_WRITE_BIT, \/\/ dstAccessFlags\n VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, \/\/ oldLayout\n VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, \/\/ newLayout\n VK_QUEUE_FAMILY_IGNORED, \/\/ srcQueueFamilyIndex\n VK_QUEUE_FAMILY_IGNORED, \/\/ dstQueueFamilyIndex\n images_[base_index], \/\/ image\n VkImageSubresourceRange{\n VK_IMAGE_ASPECT_COLOR_BIT, \/\/ aspectMask\n 0, \/\/ baseMipLevel\n 1, \/\/ levelCount\n 0, \/\/ baseArrayLayer\n swapchain_info_.imageArrayLayers, \/\/ layerCount\n }, \/\/ subresourceRange\n };\n\n device_functions_->vkCmdPipelineBarrier(\n cmdbuf,\n 0, \/\/ srcStageMask\n VK_PIPELINE_STAGE_TRANSFER_BIT, \/\/ dstStageMask\n 0, \/\/ dependencyFlags\n 0, \/\/ memoryBarrierCount\n nullptr, \/\/ pMemoryBarriers\n 0, \/\/ bufferMemoryBarrierCount\n nullptr, \/\/ pBufferMemoryBarriers\n 1, \/\/ imageMemoryBarrierCount\n &initialBarrier \/\/ pImageMemoryBarriers\n );\n\n VkImageSubresourceLayers subresource = {\n VK_IMAGE_ASPECT_COLOR_BIT, \/\/ aspectMask\n 0, \/\/ mipLevel\n 0, \/\/ baseArrayLayer\n swapchain_info_.imageArrayLayers, \/\/ layerCount\n };\n VkOffset3D offsets[2] = {\n {\n 0,\n 0,\n 0,\n },\n {\n (int32_t)swapchain_info_.imageExtent.width,\n (int32_t)swapchain_info_.imageExtent.height,\n 1,\n },\n };\n VkImageBlit blit = {\n subresource,\n {offsets[0], offsets[1]},\n subresource,\n {offsets[0], offsets[1]},\n };\n device_functions_->vkCmdBlitImage(\n cmdbuf,\n image, \/\/ srcImage\n VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, \/\/ srcImageLayout\n images_[base_index], \/\/ dstImage\n VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, \/\/ dstImageLayout\n 1, \/\/ regionCount\n &blit, \/\/ pRegions\n VK_FILTER_NEAREST \/\/ filter\n );\n\n VkImageMemoryBarrier finalBarrier = initialBarrier;\n finalBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n finalBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;\n finalBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;\n finalBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;\n\n device_functions_->vkCmdPipelineBarrier(\n cmdbuf,\n VK_PIPELINE_STAGE_TRANSFER_BIT, \/\/ srcStageMask\n 0, \/\/ dstStageMask\n 0, \/\/ dependencyFlags\n 0, \/\/ memoryBarrierCount\n nullptr, \/\/ pMemoryBarriers\n 0, \/\/ bufferMemoryBarrierCount\n nullptr, \/\/ pBufferMemoryBarriers\n 1, \/\/ imageMemoryBarrierCount\n &finalBarrier \/\/ pImageMemoryBarriers\n );\n\n if ((res = device_functions_->vkEndCommandBuffer(cmdbuf)) != VK_SUCCESS) {\n return res;\n }\n\n VkSemaphore signal_semaphores[] = {blit_semaphores_[index],\n present_semaphores_[index]};\n VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_TRANSFER_BIT;\n VkSubmitInfo submitInfo = {\n VK_STRUCTURE_TYPE_SUBMIT_INFO, \/\/ sType\n 0, \/\/ pNext\n 1, \/\/ waitSemaphoreCount\n &acquire_semaphore_, \/\/ pWaitSemaphores\n &waitStage, \/\/ pWaitDstStageMask\n 1, \/\/ commandBufferCount\n &cmdbuf, \/\/ pCommandBuffers\n 2, \/\/ signalSemaphoreCount\n signal_semaphores, \/\/ pSignalSemaphores\n };\n auto queue_functions = GetGlobalContext().GetQueueData(queue);\n if ((res = queue_functions->vkQueueSubmit(queue, 1, &submitInfo,\n VK_NULL_HANDLE)) != VK_SUCCESS) {\n return res;\n }\n is_pending_[index] = true;\n\n VkPresentInfoKHR presentInfo = {\n VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, \/\/ sType\n 0, \/\/ pNext\n 1, \/\/ waitSemaphoreCount\n &present_semaphores_[index], \/\/ waitSemaphores\n 1, \/\/ swapchainCount\n &swapchain_, \/\/ pSwapchains,\n &base_index, \/\/ pImageIndices\n nullptr, \/\/ pResults\n };\n if ((res = queue_functions->vkQueuePresentKHR(queue, &presentInfo)) !=\n VK_SUCCESS) {\n return res;\n }\n return VK_SUCCESS;\n}\n\nVkSemaphore BaseSwapchain::BlitWaitSemaphore(size_t index) {\n if (!is_pending_[index]) {\n return VK_NULL_HANDLE;\n }\n is_pending_[index] = false;\n return blit_semaphores_[index];\n}\n} \/\/ namespace swapchain\n<|endoftext|>"} {"text":"SingleSelectQueryComposer: the name of a non-SELECT column is its \"real\" name<|endoftext|>"} {"text":"\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::map;\nusing std::string;\nusing std::vector;\n\nnamespace process {\n\nusing InputFileDescriptors = Subprocess::IO::InputFileDescriptors;\nusing OutputFileDescriptors = Subprocess::IO::OutputFileDescriptors;\n\n\nSubprocess::IO Subprocess::PIPE()\n{\n return Subprocess::IO(\n []() -> Try {\n int pipefd[2];\n if (::pipe(pipefd) == -1) {\n return ErrnoError(\"Failed to create pipe\");\n }\n\n InputFileDescriptors fds;\n fds.read = pipefd[0];\n fds.write = pipefd[1];\n return fds;\n },\n []() -> Try {\n int pipefd[2];\n if (::pipe(pipefd) == -1) {\n return ErrnoError(\"Failed to create pipe\");\n }\n\n OutputFileDescriptors fds;\n fds.read = pipefd[0];\n fds.write = pipefd[1];\n return fds;\n });\n}\n\n\nSubprocess::IO Subprocess::PATH(const string& path)\n{\n return Subprocess::IO(\n [path]() -> Try {\n Try open = os::open(path, O_RDONLY | O_CLOEXEC);\n if (open.isError()) {\n return Error(\"Failed to open '\" + path + \"': \" + open.error());\n }\n\n InputFileDescriptors fds;\n fds.read = open.get();\n return fds;\n },\n [path]() -> Try {\n Try open = os::open(\n path,\n O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC,\n S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n\n if (open.isError()) {\n return Error(\"Failed to open '\" + path + \"': \" + open.error());\n }\n\n OutputFileDescriptors fds;\n fds.write = open.get();\n return fds;\n });\n}\n\n} \/\/ namespace process {\nUpdated the ::pipe() system calls to pipe2 in posix subprocess.\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::array;\nusing std::map;\nusing std::string;\nusing std::vector;\n\nnamespace process {\n\nusing InputFileDescriptors = Subprocess::IO::InputFileDescriptors;\nusing OutputFileDescriptors = Subprocess::IO::OutputFileDescriptors;\n\n\nSubprocess::IO Subprocess::PIPE()\n{\n return Subprocess::IO(\n []() -> Try {\n Try> pipefd = os::pipe();\n if (pipefd.isError()) {\n return Error(pipefd.error());\n }\n\n InputFileDescriptors fds;\n fds.read = pipefd->at(0);\n fds.write = pipefd->at(1);\n return fds;\n },\n []() -> Try {\n Try> pipefd = os::pipe();\n if (pipefd.isError()) {\n return Error(pipefd.error());\n }\n\n OutputFileDescriptors fds;\n fds.read = pipefd->at(0);\n fds.write = pipefd->at(1);\n return fds;\n });\n}\n\n\nSubprocess::IO Subprocess::PATH(const string& path)\n{\n return Subprocess::IO(\n [path]() -> Try {\n Try open = os::open(path, O_RDONLY | O_CLOEXEC);\n if (open.isError()) {\n return Error(\"Failed to open '\" + path + \"': \" + open.error());\n }\n\n InputFileDescriptors fds;\n fds.read = open.get();\n return fds;\n },\n [path]() -> Try {\n Try open = os::open(\n path,\n O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC,\n S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n\n if (open.isError()) {\n return Error(\"Failed to open '\" + path + \"': \" + open.error());\n }\n\n OutputFileDescriptors fds;\n fds.write = open.get();\n return fds;\n });\n}\n\n} \/\/ namespace process {\n<|endoftext|>"} {"text":"BZOJ 2629<|endoftext|>"} {"text":"\/* MicroFlo - Flow-Based Programming for microcontrollers\n * Copyright (c) 2016 Jon Nordby \n * MicroFlo may be freely distributed under the MIT license\n *\/\n\n\/\/ MQTT and MsgFlo.org support, at least for embedded Linux\n\n#include \"mosquitto.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef DEBUG\n#define LOG(...) do { printf(__VA_ARGS__); } while (0)\n#else\n#define LOG(...)\n#endif\n\nclass MqttMount;\n\nstruct Port {\n MicroFlo::NodeId node;\n MicroFlo::PortId port;\n std::string topic;\n std::string name;\n\n Port(std::string t, MicroFlo::NodeId n, MicroFlo::PortId p, std::string na)\n : node(n)\n , port(p)\n , topic(t)\n , name(na)\n {\n\n }\n};\n\nstd::string\ntoTopic(std::string role, std::string portName) {\n return \"\/\" + role + \"\/\" + portName;\n}\n\nstruct ParticipantInfo {\n std::vector inports;\n std::vector outports;\n std::string role;\n std::string id;\n std::string component;\n\n ParticipantInfo *addInport(std::string name, MicroFlo::NodeId n, MicroFlo::PortId p) {\n Port port(toTopic(role, name), n, p, name);\n inports.push_back(port);\n return this;\n }\n ParticipantInfo *addOutport(std::string name, MicroFlo::NodeId n, MicroFlo::PortId p) {\n Port port(toTopic(role, name), n, p, name);\n outports.push_back(port);\n return this;\n }\n};\n\n#define JSON_ATTR_STRING(name, value) \\\n +std::string(\" \\\"\") +name+std::string(\"\\\": \\\"\") + value + std::string(\"\\\",\\n\")\n#define JSON_ATTR_ARRAY(name, value) \\\n +std::string(\" \\\"\") +name+std::string(\"\\\": [\") + value + std::string(\"],\\n\")\n#define JSON_ATTR_ENDNULL(name) \\\n +std::string(\" \\\"\") +name+std::string(\"\\\": \") + \"null\" + std::string(\"\\n\")\n\nstd::string msgfloPorts(const std::vector &ports) {\n std::string str;\n \/\/ TODO: specify datatype on ports\n\n for (int i=0; i<(int)ports.size(); i++) {\n const Port &port = ports[i];\n str += \"\\n {\\n\"\n JSON_ATTR_STRING(\"id\", port.name)\n JSON_ATTR_STRING(\"queue\", port.topic)\n JSON_ATTR_STRING(\"type\", \"any\")\n JSON_ATTR_ENDNULL(\"_\")\n + \" }\";\n if (i < (int)ports.size()-1) {\n str =+ \",\";\n }\n }\n return str;\n}\n\nstd::string msgfloDiscoveryMessage(const ParticipantInfo *info) {\n \/\/ TODO: add label\n \/\/ TODO: add icon\n std::string inports = msgfloPorts(info->inports);\n std::string outports = msgfloPorts(info->outports);\n\n std::string msg = \"{\\n\"\n JSON_ATTR_STRING(\"id\", info->id)\n JSON_ATTR_STRING(\"role\", info->role)\n JSON_ATTR_STRING(\"component\", info->component)\n JSON_ATTR_ARRAY(\"inports\", inports)\n JSON_ATTR_ARRAY(\"outports\", outports)\n JSON_ATTR_ENDNULL(\"label\")\n + \"}\";\n return msg;\n}\n\n\nstruct MqttOptions {\n int brokerPort;\n char * brokerHostname;\n int keepaliveSeconds;\n char * clientId;\n ParticipantInfo info;\n};\n\n\nconst Port *\nfindPortByTopic(const std::vector &ports, char *topic) {\n for (std::vector::const_iterator it = ports.begin() ; it != ports.end(); ++it) {\n const Port *port = &(*it);\n if (port->topic == std::string(topic)) {\n return port;\n }\n }\n return NULL;\n}\n\nconst Port *\nfindPortByEdge(const std::vector &ports, MicroFlo::NodeId node, MicroFlo::PortId portId) {\n for (std::vector::const_iterator it = ports.begin() ; it != ports.end(); ++it) {\n const Port *port = &(*it);\n if (port->node == node && port->port == portId) {\n return port;\n }\n }\n return NULL;\n}\n\n\/\/ FIXME: write automated test\nclass MqttMount : public NetworkNotificationHandler {\n\npublic:\n static bool runForever(MqttMount *mount) {\n const int timeoutMs = 10;\n\n while(1){\n const int status = mosquitto_loop(mount->connection, timeoutMs, 1);\n if (status == MOSQ_ERR_CONN_LOST) {\n mount->connect();\n } else if (status == MOSQ_ERR_SUCCESS) {\n \/\/ Run MicroFlo network\n for (int i=0; i<20; i++) {\n mount->network->runTick();\n }\n } else {\n LOG(\"mosquitto loop error: %s\\n\", mosquitto_strerror(status));\n }\n }\n }\n\npublic:\n MqttMount(Network *net, const MqttOptions &o)\n : network(net)\n , options(o)\n , connection(NULL)\n {\n network->setNotificationHandler(this);\n }\n\n ~MqttMount() {\n mosquitto_destroy(this->connection);\n this->connection = NULL;\n (void)mosquitto_lib_cleanup();\n }\n\n bool connect() {\n struct mosquitto *m = mosquitto_new(options.clientId, true, this);\n this->connection = m;\n\n mosquitto_connect_callback_set(m, on_connect);\n mosquitto_publish_callback_set(m, on_publish);\n mosquitto_subscribe_callback_set(m, on_subscribe);\n mosquitto_message_callback_set(m, on_message);\n\n const int res = mosquitto_connect(m, options.brokerHostname, options.brokerPort,\n options.keepaliveSeconds);\n return res == MOSQ_ERR_SUCCESS;\n }\n void disconnect() {} \/\/ TODO: implement\n\npublic:\n \/\/ Not really public, used by C trampolines\n void onConnect(int status) {\n const bool connected = status == 0;\n if (connected) {\n subscribePorts();\n sendDiscovery();\n }\n }\n\n void onMessage(const struct mosquitto_message *msg) {\n\n const Port *port = findPortByTopic(options.info.inports, msg->topic);\n if (port) {\n LOG(\"processing, sending to %d %d \\n\", port->node, port->port);\n\n \/\/ FIXME: parse out data from input message\n Packet pkg = Packet((long)msg->payloadlen);\n network->sendMessageTo(port->node, port->port, pkg);\n\n LOG(\"processing done\\n\");\n } else {\n LOG(\"Failed to find port for MQTT topic: %s\", msg->topic);\n }\n }\n\n \/\/ implements NetworkNotificationHandler\n virtual void nodeAdded(Component *c, MicroFlo::NodeId parentId) {}\n virtual void nodesConnected(Component *src, MicroFlo::PortId srcPort,\n Component *target, MicroFlo::PortId targetPort) {}\n virtual void networkStateChanged(Network::State s) {}\n virtual void emitDebug(DebugLevel level, DebugId id) {}\n virtual void debugChanged(DebugLevel level) {}\n virtual void portSubscriptionChanged(MicroFlo::NodeId nodeId, MicroFlo::PortId portId, bool enable) {}\n virtual void subgraphConnected(bool isOutput, MicroFlo::NodeId subgraphNode,\n MicroFlo::PortId subgraphPort, MicroFlo::NodeId childNode, MicroFlo::PortId childPort) {}\n\n virtual void packetSent(const Message &m, const Component *sender, MicroFlo::PortId senderPort) {\n const MicroFlo::NodeId senderId = sender->id();\n LOG(\"packet sent %d\\n\", senderId);\n\n const Port * port = findPortByEdge(options.info.outports, senderId, senderPort);\n if (port) {\n const char *outTopic = port->topic.c_str();\n LOG(\"sending on MQTT topic %s\\n\", outTopic);\n\n \/\/ FIXME: determine sane serialization\n size_t payload_sz = 32;\n char payload[payload_sz];\n size_t payloadlen = 0;\n payloadlen = snprintf(payload, payload_sz, \"tock %d\", (int)m.pkg.asInteger());\n if (payload_sz < payloadlen) {\n \/\/die(\"snprintf\\n\");\n }\n\n const int res = mosquitto_publish(this->connection, NULL, outTopic, payloadlen, payload, 0, false);\n if (res != MOSQ_ERR_SUCCESS) {\n \/\/die(\"publish\\n\");\n }\n } else {\n LOG(\"no MQTT topic associated\\n\");\n }\n }\n\nprivate:\n void subscribePorts() {\n for (std::vector::iterator it = options.info.inports.begin() ; it != options.info.inports.end(); ++it) {\n const Port &port = *it;\n const char *pattern = port.topic.c_str();\n mosquitto_subscribe(this->connection, NULL, pattern, 0);\n LOG(\"subscribed inport to MQTT topic: %s\\n\", pattern);\n }\n for (std::vector::iterator it = options.info.outports.begin() ; it != options.info.outports.end(); ++it) {\n const Port &port = *it;\n network->subscribeToPort(port.node, port.port, true);\n LOG(\"setup outport to MQTT topic: %s\\n\", port.topic.c_str());\n }\n }\n\n void sendDiscovery() {\n const std::string msgfloDiscoveryTopic = \"fbp\";\n publish(msgfloDiscoveryTopic, msgfloDiscoveryMessage(&options.info));\n LOG(\"sent MsgFlo discovery message\\n\");\n }\n\n void publish(std::string topic, std::string payload) {\n const int res = mosquitto_publish(this->connection, NULL,\n topic.c_str(), payload.size(), payload.c_str(), 0, false);\n if (res != MOSQ_ERR_SUCCESS) {\n \/\/die(\"publish\\n\");\n }\n }\n\nprivate:\n \/\/ mosquitto callback trampolines\n static void on_connect(struct mosquitto *m, void *udata, int res) {\n MqttMount *self = (MqttMount *)udata;\n self->onConnect(res);\n }\n\n static void on_message(struct mosquitto *m, void *udata,\n const struct mosquitto_message *msg) {\n if (msg == NULL) {\n return;\n }\n LOG(\"-- got message @ %s: (%d, QoS %d, %s) '%s'\\n\",\n msg->topic, msg->payloadlen, msg->qos, msg->retain ? \"R\" : \"!r\", (char *)msg->payload);\n MqttMount *self = (MqttMount *)udata;\n self->onMessage(msg);\n }\n\n static void on_subscribe(struct mosquitto *m, void *udata, int mid,\n int qos_count, const int *granted_qos) {\n LOG(\"-- subscribed successfully\\n\");\n }\n\n static void on_publish(struct mosquitto *m, void *udata, int m_id) {\n LOG(\"-- published successfully\\n\");\n }\n\nprivate:\n Network *network;\n MqttOptions options;\n struct mosquitto *connection;\n};\n\nbool parse_brokerurl(MqttOptions *options, const char *url) {\n if (!url) {\n return true;\n }\n\n int *ip = &options->brokerPort;\n char *host = options->brokerHostname;\n if (sscanf(url, \"mqtt:\/\/%99[^:]:%i[^\\n]\", host, ip) == 2) {\n return true;\n } else if (sscanf(url, \"mqtt:\/\/%99[^\\n]\", host) == 1) {\n return true;\n } else {\n return false;\n }\n}\n\nbool mqttParseOptions(MqttOptions *options, int argc, char **argv) {\n\n \/\/ defaults\n options->brokerHostname = strndup(\"localhost\", 99);\n options->brokerPort = 1883;\n options->keepaliveSeconds = 60;\n options->clientId = NULL; \/\/ MQTT will autogenerate\n options->info.role = \"micro\";\n options->info.component = \"microflo\/Component\"; \/\/ FIXME: take from graph\n\n if (argc > 1) {\n options->info.role = std::string(argv[1]);\n }\n\n options->info.id = options->info.role + std::to_string(rand());\n\n char* broker = getenv(\"MSGFLO_BROKER\");\n return parse_brokerurl(options, broker);\n}\nmqtt: Always return value from runForever()\/* MicroFlo - Flow-Based Programming for microcontrollers\n * Copyright (c) 2016 Jon Nordby \n * MicroFlo may be freely distributed under the MIT license\n *\/\n\n\/\/ MQTT and MsgFlo.org support, at least for embedded Linux\n\n#include \"mosquitto.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef DEBUG\n#define LOG(...) do { printf(__VA_ARGS__); } while (0)\n#else\n#define LOG(...)\n#endif\n\nclass MqttMount;\n\nstruct Port {\n MicroFlo::NodeId node;\n MicroFlo::PortId port;\n std::string topic;\n std::string name;\n\n Port(std::string t, MicroFlo::NodeId n, MicroFlo::PortId p, std::string na)\n : node(n)\n , port(p)\n , topic(t)\n , name(na)\n {\n\n }\n};\n\nstd::string\ntoTopic(std::string role, std::string portName) {\n return \"\/\" + role + \"\/\" + portName;\n}\n\nstruct ParticipantInfo {\n std::vector inports;\n std::vector outports;\n std::string role;\n std::string id;\n std::string component;\n\n ParticipantInfo *addInport(std::string name, MicroFlo::NodeId n, MicroFlo::PortId p) {\n Port port(toTopic(role, name), n, p, name);\n inports.push_back(port);\n return this;\n }\n ParticipantInfo *addOutport(std::string name, MicroFlo::NodeId n, MicroFlo::PortId p) {\n Port port(toTopic(role, name), n, p, name);\n outports.push_back(port);\n return this;\n }\n};\n\n#define JSON_ATTR_STRING(name, value) \\\n +std::string(\" \\\"\") +name+std::string(\"\\\": \\\"\") + value + std::string(\"\\\",\\n\")\n#define JSON_ATTR_ARRAY(name, value) \\\n +std::string(\" \\\"\") +name+std::string(\"\\\": [\") + value + std::string(\"],\\n\")\n#define JSON_ATTR_ENDNULL(name) \\\n +std::string(\" \\\"\") +name+std::string(\"\\\": \") + \"null\" + std::string(\"\\n\")\n\nstd::string msgfloPorts(const std::vector &ports) {\n std::string str;\n \/\/ TODO: specify datatype on ports\n\n for (int i=0; i<(int)ports.size(); i++) {\n const Port &port = ports[i];\n str += \"\\n {\\n\"\n JSON_ATTR_STRING(\"id\", port.name)\n JSON_ATTR_STRING(\"queue\", port.topic)\n JSON_ATTR_STRING(\"type\", \"any\")\n JSON_ATTR_ENDNULL(\"_\")\n + \" }\";\n if (i < (int)ports.size()-1) {\n str =+ \",\";\n }\n }\n return str;\n}\n\nstd::string msgfloDiscoveryMessage(const ParticipantInfo *info) {\n \/\/ TODO: add label\n \/\/ TODO: add icon\n std::string inports = msgfloPorts(info->inports);\n std::string outports = msgfloPorts(info->outports);\n\n std::string msg = \"{\\n\"\n JSON_ATTR_STRING(\"id\", info->id)\n JSON_ATTR_STRING(\"role\", info->role)\n JSON_ATTR_STRING(\"component\", info->component)\n JSON_ATTR_ARRAY(\"inports\", inports)\n JSON_ATTR_ARRAY(\"outports\", outports)\n JSON_ATTR_ENDNULL(\"label\")\n + \"}\";\n return msg;\n}\n\n\nstruct MqttOptions {\n int brokerPort;\n char * brokerHostname;\n int keepaliveSeconds;\n char * clientId;\n ParticipantInfo info;\n};\n\n\nconst Port *\nfindPortByTopic(const std::vector &ports, char *topic) {\n for (std::vector::const_iterator it = ports.begin() ; it != ports.end(); ++it) {\n const Port *port = &(*it);\n if (port->topic == std::string(topic)) {\n return port;\n }\n }\n return NULL;\n}\n\nconst Port *\nfindPortByEdge(const std::vector &ports, MicroFlo::NodeId node, MicroFlo::PortId portId) {\n for (std::vector::const_iterator it = ports.begin() ; it != ports.end(); ++it) {\n const Port *port = &(*it);\n if (port->node == node && port->port == portId) {\n return port;\n }\n }\n return NULL;\n}\n\n\/\/ FIXME: write automated test\nclass MqttMount : public NetworkNotificationHandler {\n\npublic:\n static bool runForever(MqttMount *mount) {\n const int timeoutMs = 10;\n\n while(1){\n const int status = mosquitto_loop(mount->connection, timeoutMs, 1);\n if (status == MOSQ_ERR_CONN_LOST) {\n mount->connect();\n } else if (status == MOSQ_ERR_SUCCESS) {\n \/\/ Run MicroFlo network\n for (int i=0; i<20; i++) {\n mount->network->runTick();\n }\n } else {\n LOG(\"mosquitto loop error: %s\\n\", mosquitto_strerror(status));\n return false;\n }\n }\n return true;\n }\n\npublic:\n MqttMount(Network *net, const MqttOptions &o)\n : network(net)\n , options(o)\n , connection(NULL)\n {\n network->setNotificationHandler(this);\n }\n\n ~MqttMount() {\n mosquitto_destroy(this->connection);\n this->connection = NULL;\n (void)mosquitto_lib_cleanup();\n }\n\n bool connect() {\n struct mosquitto *m = mosquitto_new(options.clientId, true, this);\n this->connection = m;\n\n mosquitto_connect_callback_set(m, on_connect);\n mosquitto_publish_callback_set(m, on_publish);\n mosquitto_subscribe_callback_set(m, on_subscribe);\n mosquitto_message_callback_set(m, on_message);\n\n const int res = mosquitto_connect(m, options.brokerHostname, options.brokerPort,\n options.keepaliveSeconds);\n return res == MOSQ_ERR_SUCCESS;\n }\n void disconnect() {} \/\/ TODO: implement\n\npublic:\n \/\/ Not really public, used by C trampolines\n void onConnect(int status) {\n const bool connected = status == 0;\n if (connected) {\n subscribePorts();\n sendDiscovery();\n }\n }\n\n void onMessage(const struct mosquitto_message *msg) {\n\n const Port *port = findPortByTopic(options.info.inports, msg->topic);\n if (port) {\n LOG(\"processing, sending to %d %d \\n\", port->node, port->port);\n\n \/\/ FIXME: parse out data from input message\n Packet pkg = Packet((long)msg->payloadlen);\n network->sendMessageTo(port->node, port->port, pkg);\n\n LOG(\"processing done\\n\");\n } else {\n LOG(\"Failed to find port for MQTT topic: %s\", msg->topic);\n }\n }\n\n \/\/ implements NetworkNotificationHandler\n virtual void nodeAdded(Component *c, MicroFlo::NodeId parentId) {}\n virtual void nodesConnected(Component *src, MicroFlo::PortId srcPort,\n Component *target, MicroFlo::PortId targetPort) {}\n virtual void networkStateChanged(Network::State s) {}\n virtual void emitDebug(DebugLevel level, DebugId id) {}\n virtual void debugChanged(DebugLevel level) {}\n virtual void portSubscriptionChanged(MicroFlo::NodeId nodeId, MicroFlo::PortId portId, bool enable) {}\n virtual void subgraphConnected(bool isOutput, MicroFlo::NodeId subgraphNode,\n MicroFlo::PortId subgraphPort, MicroFlo::NodeId childNode, MicroFlo::PortId childPort) {}\n\n virtual void packetSent(const Message &m, const Component *sender, MicroFlo::PortId senderPort) {\n const MicroFlo::NodeId senderId = sender->id();\n LOG(\"packet sent %d\\n\", senderId);\n\n const Port * port = findPortByEdge(options.info.outports, senderId, senderPort);\n if (port) {\n const char *outTopic = port->topic.c_str();\n LOG(\"sending on MQTT topic %s\\n\", outTopic);\n\n \/\/ FIXME: determine sane serialization\n size_t payload_sz = 32;\n char payload[payload_sz];\n size_t payloadlen = 0;\n payloadlen = snprintf(payload, payload_sz, \"tock %d\", (int)m.pkg.asInteger());\n if (payload_sz < payloadlen) {\n \/\/die(\"snprintf\\n\");\n }\n\n const int res = mosquitto_publish(this->connection, NULL, outTopic, payloadlen, payload, 0, false);\n if (res != MOSQ_ERR_SUCCESS) {\n \/\/die(\"publish\\n\");\n }\n } else {\n LOG(\"no MQTT topic associated\\n\");\n }\n }\n\nprivate:\n void subscribePorts() {\n for (std::vector::iterator it = options.info.inports.begin() ; it != options.info.inports.end(); ++it) {\n const Port &port = *it;\n const char *pattern = port.topic.c_str();\n mosquitto_subscribe(this->connection, NULL, pattern, 0);\n LOG(\"subscribed inport to MQTT topic: %s\\n\", pattern);\n }\n for (std::vector::iterator it = options.info.outports.begin() ; it != options.info.outports.end(); ++it) {\n const Port &port = *it;\n network->subscribeToPort(port.node, port.port, true);\n LOG(\"setup outport to MQTT topic: %s\\n\", port.topic.c_str());\n }\n }\n\n void sendDiscovery() {\n const std::string msgfloDiscoveryTopic = \"fbp\";\n publish(msgfloDiscoveryTopic, msgfloDiscoveryMessage(&options.info));\n LOG(\"sent MsgFlo discovery message\\n\");\n }\n\n void publish(std::string topic, std::string payload) {\n const int res = mosquitto_publish(this->connection, NULL,\n topic.c_str(), payload.size(), payload.c_str(), 0, false);\n if (res != MOSQ_ERR_SUCCESS) {\n \/\/die(\"publish\\n\");\n }\n }\n\nprivate:\n \/\/ mosquitto callback trampolines\n static void on_connect(struct mosquitto *m, void *udata, int res) {\n MqttMount *self = (MqttMount *)udata;\n self->onConnect(res);\n }\n\n static void on_message(struct mosquitto *m, void *udata,\n const struct mosquitto_message *msg) {\n if (msg == NULL) {\n return;\n }\n LOG(\"-- got message @ %s: (%d, QoS %d, %s) '%s'\\n\",\n msg->topic, msg->payloadlen, msg->qos, msg->retain ? \"R\" : \"!r\", (char *)msg->payload);\n MqttMount *self = (MqttMount *)udata;\n self->onMessage(msg);\n }\n\n static void on_subscribe(struct mosquitto *m, void *udata, int mid,\n int qos_count, const int *granted_qos) {\n LOG(\"-- subscribed successfully\\n\");\n }\n\n static void on_publish(struct mosquitto *m, void *udata, int m_id) {\n LOG(\"-- published successfully\\n\");\n }\n\nprivate:\n Network *network;\n MqttOptions options;\n struct mosquitto *connection;\n};\n\nbool parse_brokerurl(MqttOptions *options, const char *url) {\n if (!url) {\n return true;\n }\n\n int *ip = &options->brokerPort;\n char *host = options->brokerHostname;\n if (sscanf(url, \"mqtt:\/\/%99[^:]:%i[^\\n]\", host, ip) == 2) {\n return true;\n } else if (sscanf(url, \"mqtt:\/\/%99[^\\n]\", host) == 1) {\n return true;\n } else {\n return false;\n }\n}\n\nbool mqttParseOptions(MqttOptions *options, int argc, char **argv) {\n\n \/\/ defaults\n options->brokerHostname = strndup(\"localhost\", 99);\n options->brokerPort = 1883;\n options->keepaliveSeconds = 60;\n options->clientId = NULL; \/\/ MQTT will autogenerate\n options->info.role = \"micro\";\n options->info.component = \"microflo\/Component\"; \/\/ FIXME: take from graph\n\n if (argc > 1) {\n options->info.role = std::string(argv[1]);\n }\n\n options->info.id = options->info.role + std::to_string(rand());\n\n char* broker = getenv(\"MSGFLO_BROKER\");\n return parse_brokerurl(options, broker);\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n#include \n#include \n\nusing namespace fnord;\n\nnamespace csql {\n\nCSTableScan::CSTableScan(\n RefPtr stmt,\n cstable::CSTableReader&& cstable) :\n cstable_(std::move(cstable)),\n colindex_(0),\n flat_(false) {\n\n Set column_names;\n for (const auto& expr : stmt->selectList()) {\n findColumns(expr, &column_names);\n }\n\n for (const auto& col : column_names) {\n columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));\n }\n\n for (auto& expr : stmt->selectList()) {\n resolveColumns(expr);\n }\n\n \/\/fnord::iputs(\"all cols: $0\", column_names);\n\n DefaultRuntime runtime;\n\n for (const auto& expr : stmt->selectList()) {\n select_list_.emplace_back(\n findMaxRepetitionLevel(expr),\n runtime.compiler()->compile(expr),\n &scratch_);\n }\n}\n\nvoid CSTableScan::execute(Function fn) {\n uint64_t select_level = 0;\n uint64_t fetch_level = 0;\n\n Vector in_row(colindex_, SValue{});\n Vector out_row(select_list_.size(), SValue{});\n\n size_t num_records = 0;\n size_t total_records = cstable_.numRecords();\n while (num_records < total_records) {\n uint64_t next_level = 0;\n\n if (fetch_level == 0) {\n ++num_records;\n }\n\n for (auto& col : columns_) {\n if (col.second.reader->nextRepetitionLevel() >= fetch_level) {\n auto& reader = col.second.reader;\n\n uint64_t r;\n uint64_t d;\n void* data;\n size_t size;\n reader->next(&r, &d, &data, &size);\n\n switch (col.second.reader->type()) {\n\n case msg::FieldType::STRING:\n in_row[col.second.index] =\n SValue(SValue::StringType((char*) data, size));\n break;\n\n case msg::FieldType::UINT32:\n case msg::FieldType::UINT64:\n switch (size) {\n case sizeof(uint32_t):\n in_row[col.second.index] =\n SValue(SValue::IntegerType(*((uint32_t*) data)));\n break;\n case sizeof(uint64_t):\n in_row[col.second.index] =\n SValue(SValue::IntegerType(*((uint64_t*) data)));\n break;\n case 0:\n in_row[col.second.index] = SValue(SValue::IntegerType(0));\n break;\n }\n break;\n\n case msg::FieldType::BOOLEAN:\n switch (size) {\n case sizeof(uint32_t):\n in_row[col.second.index] =\n SValue(SValue::BoolType(*((uint32_t*) data) > 0));\n break;\n case sizeof(uint64_t):\n in_row[col.second.index] =\n SValue(SValue::BoolType(*((uint64_t*) data) > 0));\n break;\n case 0:\n in_row[col.second.index] = SValue(SValue::BoolType(false));\n break;\n }\n break;\n\n case msg::FieldType::OBJECT:\n RAISE(kIllegalStateError);\n\n }\n\n }\n\n next_level = std::max(next_level, col.second.reader->nextRepetitionLevel());\n }\n\n fetch_level = next_level;\n\n if (true) { \/\/ where clause\n for (int i = 0; i < select_list_.size(); ++i) {\n if (select_list_[i].rep_level >= select_level) {\n \/\/select_level_[i].compiled.accumulate();\n }\n }\n\n if (!flat_ || next_level == 0) {\n for (int i = 0; i < select_list_.size(); ++i) {\n select_list_[i].compiled->evaluate(\n &select_list_[i].instance,\n in_row.size(),\n in_row.data(),\n &out_row[i]);\n }\n }\n\n if (!fn(out_row.size(), out_row.data())) {\n return;\n }\n\n select_level = fetch_level;\n } else {\n select_level = std::min(select_level, fetch_level);\n }\n }\n}\n\nvoid CSTableScan::findColumns(\n RefPtr expr,\n Set* column_names) const {\n auto fieldref = dynamic_cast(expr.get());\n if (fieldref != nullptr) {\n column_names->emplace(fieldref->fieldName());\n }\n\n for (const auto& e : expr->arguments()) {\n findColumns(e, column_names);\n }\n}\n\nvoid CSTableScan::resolveColumns(RefPtr expr) const {\n auto fieldref = dynamic_cast(expr.get());\n if (fieldref != nullptr) {\n auto col = columns_.find(fieldref->fieldName());\n if (col == columns_.end()) {\n RAISE(kIllegalStateError);\n }\n\n fieldref->setColumnIndex(col->second.index);\n }\n\n for (const auto& e : expr->arguments()) {\n resolveColumns(e);\n }\n}\n\nuint64_t CSTableScan::findMaxRepetitionLevel(\n RefPtr expr) const {\n uint64_t max_level = 0;\n\n auto fieldref = dynamic_cast(expr.get());\n if (fieldref != nullptr) {\n auto col = columns_.find(fieldref->fieldName());\n if (col == columns_.end()) {\n RAISE(kIllegalStateError);\n }\n\n auto col_level = col->second.reader->maxRepetitionLevel();\n if (col_level > max_level) {\n max_level = col_level;\n }\n }\n\n for (const auto& e : expr->arguments()) {\n auto e_level = findMaxRepetitionLevel(e);\n if (e_level > max_level) {\n max_level = e_level;\n }\n }\n\n return max_level;\n}\n\nCSTableScan::ColumnRef::ColumnRef(\n RefPtr r,\n size_t i) :\n reader(r),\n index(i) {}\n\nCSTableScan::ExpressionRef::ExpressionRef(\n size_t _rep_level,\n ScopedPtr _compiled,\n ScratchMemory* smem) :\n rep_level(_rep_level),\n compiled(std::move(_compiled)),\n instance(compiled->allocInstance(smem)) {}\n\nCSTableScan::ExpressionRef::ExpressionRef(\n ExpressionRef&& other) :\n rep_level(other.rep_level),\n compiled(std::move(other.compiled)),\n instance(other.instance) {\n other.instance.scratch = nullptr;\n}\n\nCSTableScan::ExpressionRef::~ExpressionRef() {\n if (instance.scratch) {\n compiled->freeInstance(&instance);\n }\n}\n\n} \/\/ namespace csql\ncall accumulate\/reset\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n#include \n#include \n\nusing namespace fnord;\n\nnamespace csql {\n\nCSTableScan::CSTableScan(\n RefPtr stmt,\n cstable::CSTableReader&& cstable) :\n cstable_(std::move(cstable)),\n colindex_(0),\n flat_(false) {\n\n Set column_names;\n for (const auto& expr : stmt->selectList()) {\n findColumns(expr, &column_names);\n }\n\n for (const auto& col : column_names) {\n columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));\n }\n\n for (auto& expr : stmt->selectList()) {\n resolveColumns(expr);\n }\n\n \/\/fnord::iputs(\"all cols: $0\", column_names);\n\n DefaultRuntime runtime;\n\n for (const auto& expr : stmt->selectList()) {\n select_list_.emplace_back(\n findMaxRepetitionLevel(expr),\n runtime.compiler()->compile(expr),\n &scratch_);\n }\n}\n\nvoid CSTableScan::execute(Function fn) {\n uint64_t select_level = 0;\n uint64_t fetch_level = 0;\n\n Vector in_row(colindex_, SValue{});\n Vector out_row(select_list_.size(), SValue{});\n\n size_t num_records = 0;\n size_t total_records = cstable_.numRecords();\n while (num_records < total_records) {\n uint64_t next_level = 0;\n\n if (fetch_level == 0) {\n ++num_records;\n }\n\n for (auto& col : columns_) {\n if (col.second.reader->nextRepetitionLevel() >= fetch_level) {\n auto& reader = col.second.reader;\n\n uint64_t r;\n uint64_t d;\n void* data;\n size_t size;\n reader->next(&r, &d, &data, &size);\n\n switch (col.second.reader->type()) {\n\n case msg::FieldType::STRING:\n in_row[col.second.index] =\n SValue(SValue::StringType((char*) data, size));\n break;\n\n case msg::FieldType::UINT32:\n case msg::FieldType::UINT64:\n switch (size) {\n case sizeof(uint32_t):\n in_row[col.second.index] =\n SValue(SValue::IntegerType(*((uint32_t*) data)));\n break;\n case sizeof(uint64_t):\n in_row[col.second.index] =\n SValue(SValue::IntegerType(*((uint64_t*) data)));\n break;\n case 0:\n in_row[col.second.index] = SValue(SValue::IntegerType(0));\n break;\n }\n break;\n\n case msg::FieldType::BOOLEAN:\n switch (size) {\n case sizeof(uint32_t):\n in_row[col.second.index] =\n SValue(SValue::BoolType(*((uint32_t*) data) > 0));\n break;\n case sizeof(uint64_t):\n in_row[col.second.index] =\n SValue(SValue::BoolType(*((uint64_t*) data) > 0));\n break;\n case 0:\n in_row[col.second.index] = SValue(SValue::BoolType(false));\n break;\n }\n break;\n\n case msg::FieldType::OBJECT:\n RAISE(kIllegalStateError);\n\n }\n\n }\n\n next_level = std::max(next_level, col.second.reader->nextRepetitionLevel());\n }\n\n fetch_level = next_level;\n\n if (true) { \/\/ where clause\n for (int i = 0; i < select_list_.size(); ++i) {\n if (select_list_[i].rep_level >= select_level) {\n select_list_[i].compiled->accumulate(\n &select_list_[i].instance,\n in_row.size(),\n in_row.data());\n }\n }\n\n if (!flat_ || next_level == 0) {\n for (int i = 0; i < select_list_.size(); ++i) {\n select_list_[i].compiled->evaluate(\n &select_list_[i].instance,\n in_row.size(),\n in_row.data(),\n &out_row[i]);\n\n select_list_[i].compiled->reset(&select_list_[i].instance);\n }\n }\n\n if (!fn(out_row.size(), out_row.data())) {\n return;\n }\n\n select_level = fetch_level;\n } else {\n select_level = std::min(select_level, fetch_level);\n }\n }\n}\n\nvoid CSTableScan::findColumns(\n RefPtr expr,\n Set* column_names) const {\n auto fieldref = dynamic_cast(expr.get());\n if (fieldref != nullptr) {\n column_names->emplace(fieldref->fieldName());\n }\n\n for (const auto& e : expr->arguments()) {\n findColumns(e, column_names);\n }\n}\n\nvoid CSTableScan::resolveColumns(RefPtr expr) const {\n auto fieldref = dynamic_cast(expr.get());\n if (fieldref != nullptr) {\n auto col = columns_.find(fieldref->fieldName());\n if (col == columns_.end()) {\n RAISE(kIllegalStateError);\n }\n\n fieldref->setColumnIndex(col->second.index);\n }\n\n for (const auto& e : expr->arguments()) {\n resolveColumns(e);\n }\n}\n\nuint64_t CSTableScan::findMaxRepetitionLevel(\n RefPtr expr) const {\n uint64_t max_level = 0;\n\n auto fieldref = dynamic_cast(expr.get());\n if (fieldref != nullptr) {\n auto col = columns_.find(fieldref->fieldName());\n if (col == columns_.end()) {\n RAISE(kIllegalStateError);\n }\n\n auto col_level = col->second.reader->maxRepetitionLevel();\n if (col_level > max_level) {\n max_level = col_level;\n }\n }\n\n for (const auto& e : expr->arguments()) {\n auto e_level = findMaxRepetitionLevel(e);\n if (e_level > max_level) {\n max_level = e_level;\n }\n }\n\n return max_level;\n}\n\nCSTableScan::ColumnRef::ColumnRef(\n RefPtr r,\n size_t i) :\n reader(r),\n index(i) {}\n\nCSTableScan::ExpressionRef::ExpressionRef(\n size_t _rep_level,\n ScopedPtr _compiled,\n ScratchMemory* smem) :\n rep_level(_rep_level),\n compiled(std::move(_compiled)),\n instance(compiled->allocInstance(smem)) {}\n\nCSTableScan::ExpressionRef::ExpressionRef(\n ExpressionRef&& other) :\n rep_level(other.rep_level),\n compiled(std::move(other.compiled)),\n instance(other.instance) {\n other.instance.scratch = nullptr;\n}\n\nCSTableScan::ExpressionRef::~ExpressionRef() {\n if (instance.scratch) {\n compiled->freeInstance(&instance);\n }\n}\n\n} \/\/ namespace csql\n<|endoftext|>"} {"text":"#pragma once\n\ntemplate \nvoid allocate2D(const int Nx,\n const int Ny,\n T**& ptr) {\n ptr = new T* [Nx];\n ptr[0] = new T[Nx * Ny];\n for (int i = 1; i < Nx; i++) ptr[i] = ptr[0] + i * Ny;\n}\n\ntemplate \nvoid deallocate2D(T**& ptr) {\n delete [] ptr[0];\n delete [] ptr;\n ptr = nullptr;\n}\nアラインメントを指定する関数を追加#pragma once\n\n#include \n#include \n\ntemplate \nvoid allocate2D_aligend(const int Nx,\n const int Ny,\n T**& ptr) {\n ptr = static_cast(malloc(Nx * sizeof(T*)));\n const auto stat = posix_memalign(reinterpret_cast(ptr),\n alignment,\n sizeof(T) * Nx * Ny);\n if (stat) {\n std::cerr << \"error occurs at allocate2D_aligend\\n\";\n std::exit(1);\n }\n for (int i = 1; i < Nx; i++) ptr[i] = ptr[0] + i * Ny;\n}\n\ntemplate \nvoid deallocate2D_aligend(T**& ptr) {\n free(ptr[0]);\n free(ptr);\n ptr = nullptr;\n}\n\ntemplate \nvoid allocate2D(const int Nx,\n const int Ny,\n T**& ptr) {\n ptr = new T* [Nx];\n ptr[0] = new T[Nx * Ny];\n for (int i = 1; i < Nx; i++) ptr[i] = ptr[0] + i * Ny;\n}\n\ntemplate \nvoid deallocate2D(T**& ptr) {\n delete [] ptr[0];\n delete [] ptr;\n ptr = nullptr;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"circuit.h\"\n\n#include \"..\/benchmark_util.h\"\n\nBENCHMARK(circuit_parse) {\n Circuit c;\n benchmark_go([&]() {\n c = Circuit::from_text(R\"input(\nH 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\nCNOT 4 5 6 7\nM 1 2 3 4 5 6 7 8 9 10 11\n )input\");\n }).goal_nanos(950);\n if (c.num_qubits == 0) {\n std::cerr << \"impossible\";\n }\n}\n\nBENCHMARK(circuit_parse_sparse) {\n Circuit c;\n for (auto k = 0; k < 1000; k++) {\n c.append_op(\"H\", {0});\n c.append_op(\"CNOT\", {1, 2});\n c.append_op(\"M\", {0});\n }\n auto text = c.str();\n benchmark_go([&]() {\n c = Circuit::from_text(text);\n }).goal_micros(150);\n if (c.num_qubits == 0) {\n std::cerr << \"impossible\";\n }\n}\nRestore CI checks\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"circuit.h\"\n\n#include \"..\/benchmark_util.h\"\n\nBENCHMARK(circuit_parse) {\n Circuit c;\n benchmark_go([&]() {\n c = Circuit::from_text(R\"input(\nH 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\nCNOT 4 5 6 7\nM 1 2 3 4 5 6 7 8 9 10 11\n )input\");\n }).goal_nanos(950);\n if (c.num_qubits == 0) {\n std::cerr << \"impossible\";\n }\n}\n\nBENCHMARK(circuit_parse_sparse) {\n Circuit c;\n for (auto k = 0; k < 1000; k++) {\n c.append_op(\"H\", {0});\n c.append_op(\"CNOT\", {1, 2});\n c.append_op(\"M\", {0});\n }\n auto text = c.str();\n benchmark_go([&]() {\n c = Circuit::from_text(text.data());\n }).goal_micros(150);\n if (c.num_qubits == 0) {\n std::cerr << \"impossible\";\n }\n}\n<|endoftext|>"} {"text":"\/*\n The MIT License (MIT)\n\n Copyright (c) [2016] [BTC.COM]\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"zmq.hpp\"\n\n#include \"Utils.h\"\n#include \"ShareLogParser.h\"\n\nusing namespace std;\nusing namespace libconfig;\n\nstd::shared_ptr gShareLogParserServer = nullptr;\n\nvoid handler(int sig) {\n if (gShareLogParserServer) {\n gShareLogParserServer->stop();\n }\n}\n\nvoid usage() {\n fprintf(stderr, \"Usage:\\n\\tslparser -c \\\"slparser.cfg\\\" -l \\\"log_dir\\\"\\n\");\n fprintf(stderr, \"\\tslparser -c \\\"slparser.cfg\\\" -l \\\"log_dir2\\\" -d \\\"20160830\\\"\\n\");\n fprintf(stderr, \"\\tslparser -c \\\"slparser.cfg\\\" -l \\\"log_dir3\\\" -d \\\"20160830\\\" -u \\\"puid(0: dump all, >0: someone's)\\\"\\n\");\n}\n\nstd::shared_ptr newShareLogDumper(const string &chainType, const string &dataDir,\n time_t timestamp, const std::set &uids)\n{\n if (chainType == \"BTC\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, uids);\n }\n else if (chainType == \"ETH\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, uids);\n }\n else if (chainType == \"BTM\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, uids); \n }\n else {\n LOG(FATAL) << \"newShareLogDumper: unknown chain type \" << chainType;\n return nullptr;\n }\n}\n\nstd::shared_ptr newShareLogParser(const string &chainType, const string &dataDir,\n time_t timestamp, const MysqlConnectInfo &poolDBInfo,\n const int dupShareTrackingHeight)\n{\n if (chainType == \"BTC\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, poolDBInfo, nullptr);\n }\n else if (chainType == \"ETH\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, poolDBInfo,\n std::make_shared(dupShareTrackingHeight));\n }\n else if (chainType == \"BTM\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, poolDBInfo,\n std::make_shared(dupShareTrackingHeight));\n }\n else {\n LOG(FATAL) << \"newShareLogParser: unknown chain type \" << chainType;\n return nullptr;\n }\n}\n\nstd::shared_ptr newShareLogParserServer(const string &chainType, const string &dataDir,\n const string &httpdHost, unsigned short httpdPort,\n const MysqlConnectInfo &poolDBInfo,\n const uint32_t kFlushDBInterval,\n const int dupShareTrackingHeight)\n{\n if (chainType == \"BTC\") {\n return std::make_shared(chainType.c_str(), dataDir,\n httpdHost, httpdPort,\n poolDBInfo, kFlushDBInterval, nullptr);\n }\n else if (chainType == \"ETH\") {\n return std::make_shared(chainType.c_str(), dataDir,\n httpdHost, httpdPort,\n poolDBInfo, kFlushDBInterval,\n std::make_shared(dupShareTrackingHeight));\n }\n else if (chainType == \"ETH\") {\n return std::make_shared(chainType.c_str(), dataDir,\n httpdHost, httpdPort,\n poolDBInfo, kFlushDBInterval,\n std::make_shared(dupShareTrackingHeight));\n }\n else {\n LOG(FATAL) << \"newShareLogParserServer: unknown chain type \" << chainType;\n return nullptr;\n }\n}\n\nint main(int argc, char **argv) {\n char *optLogDir = NULL;\n char *optConf = NULL;\n int32_t optDate = 0;\n int32_t optPUID = -1; \/\/ pool user id\n int c;\n\n if (argc <= 1) {\n usage();\n return 1;\n }\n while ((c = getopt(argc, argv, \"c:l:d:u:h\")) != -1) {\n switch (c) {\n case 'c':\n optConf = optarg;\n break;\n case 'l':\n optLogDir = optarg;\n break;\n case 'd':\n optDate = atoi(optarg);\n break;\n case 'u':\n optPUID = atoi(optarg);\n break;\n case 'h': default:\n usage();\n exit(0);\n }\n }\n\n \/\/ Initialize Google's logging library.\n google::InitGoogleLogging(argv[0]);\n FLAGS_log_dir = string(optLogDir);\n \/\/ Log messages at a level >= this flag are automatically sent to\n \/\/ stderr in addition to log files.\n FLAGS_stderrthreshold = 3; \/\/ 3: FATAL\n FLAGS_max_log_size = 100; \/\/ max log file size 100 MB\n FLAGS_logbuflevel = -1; \/\/ don't buffer logs\n FLAGS_stop_logging_if_full_disk = true;\n\n \/\/ Read the file. If there is an error, report it and exit.\n libconfig::Config cfg;\n try\n {\n cfg.readFile(optConf);\n } catch(const FileIOException &fioex) {\n std::cerr << \"I\/O error while reading file.\" << std::endl;\n return(EXIT_FAILURE);\n } catch(const ParseException &pex) {\n std::cerr << \"Parse error at \" << pex.getFile() << \":\" << pex.getLine()\n << \" - \" << pex.getError() << std::endl;\n return(EXIT_FAILURE);\n }\n\n try {\n \/\/ check if we are using testnet3\n bool isTestnet3 = false;\n cfg.lookupValue(\"testnet\", isTestnet3);\n if (isTestnet3) {\n SelectParams(CBaseChainParams::TESTNET);\n LOG(WARNING) << \"using bitcoin testnet3\";\n } else {\n SelectParams(CBaseChainParams::MAIN);\n }\n\n \/\/ DB info\n MysqlConnectInfo *poolDBInfo = nullptr;\n {\n int32_t poolDBPort = 3306;\n cfg.lookupValue(\"pooldb.port\", poolDBPort);\n poolDBInfo = new MysqlConnectInfo(cfg.lookup(\"pooldb.host\"), poolDBPort,\n cfg.lookup(\"pooldb.username\"),\n cfg.lookup(\"pooldb.password\"),\n cfg.lookup(\"pooldb.dbname\"));\n }\n\n \/\/ chain type\n string chainType = cfg.lookup(\"sharelog.chain_type\");\n \/\/ Track duplicate shares within N blocks.\n int32_t dupShareTrackingHeight = 3;\n cfg.lookupValue(\"dup_share_checker.tracking_height_number\", dupShareTrackingHeight);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ dump shares to stdout\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (optDate != 0 && optPUID != -1) {\n const string tsStr = Strings::Format(\"%04d-%02d-%02d 00:00:00\",\n optDate\/10000,\n optDate\/100 % 100, optDate % 100);\n const time_t ts = str2time(tsStr.c_str(), \"%F %T\");\n std::set uids;\n if (optPUID > 0)\n uids.insert(optPUID);\n\n std::shared_ptr sldumper = newShareLogDumper(chainType, cfg.lookup(\"sharelog.data_dir\"), ts, uids);\n sldumper->dump2stdout();\n\n google::ShutdownGoogleLogging();\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ re-run someday's share bin log\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (optDate != 0) {\n const string tsStr = Strings::Format(\"%04d-%02d-%02d 00:00:00\",\n optDate\/10000,\n optDate\/100 % 100, optDate % 100);\n const time_t ts = str2time(tsStr.c_str(), \"%F %T\");\n\n std::shared_ptr slparser = newShareLogParser(chainType,\n cfg.lookup(\"sharelog.data_dir\"),\n ts, *poolDBInfo,\n dupShareTrackingHeight);\n do {\n if (slparser->init() == false) {\n LOG(ERROR) << \"init failure\";\n break;\n }\n if (!slparser->processUnchangedShareLog()) {\n LOG(ERROR) << \"processUnchangedShareLog fail\";\n break;\n }\n if (!slparser->flushToDB()) {\n LOG(ERROR) << \"processUnchangedShareLog fail\";\n break;\n }\n } while (0);\n\n google::ShutdownGoogleLogging();\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ lock cfg file:\n \/\/ you can't run more than one process with the same config file\n boost::interprocess::file_lock pidFileLock(optConf);\n if (pidFileLock.try_lock() == false) {\n LOG(FATAL) << \"lock cfg file fail\";\n return(EXIT_FAILURE);\n }\n\n signal(SIGTERM, handler);\n signal(SIGINT, handler);\n\n int32_t port = 8081;\n cfg.lookupValue(\"slparserhttpd.port\", port);\n uint32_t kFlushDBInterval = 20;\n cfg.lookupValue(\"slparserhttpd.flush_db_interval\", kFlushDBInterval);\n gShareLogParserServer = newShareLogParserServer(chainType,\n cfg.lookup(\"sharelog.data_dir\"),\n cfg.lookup(\"slparserhttpd.ip\"),\n port, *poolDBInfo,\n kFlushDBInterval,\n dupShareTrackingHeight);\n gShareLogParserServer->run();\n }\n catch (std::exception & e) {\n LOG(FATAL) << \"exception: \" << e.what();\n return 1;\n }\n\n google::ShutdownGoogleLogging();\n return 0;\n}\nfix bug ShareLogParser creation for Bytom\/*\n The MIT License (MIT)\n\n Copyright (c) [2016] [BTC.COM]\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"zmq.hpp\"\n\n#include \"Utils.h\"\n#include \"ShareLogParser.h\"\n\nusing namespace std;\nusing namespace libconfig;\n\nstd::shared_ptr gShareLogParserServer = nullptr;\n\nvoid handler(int sig) {\n if (gShareLogParserServer) {\n gShareLogParserServer->stop();\n }\n}\n\nvoid usage() {\n fprintf(stderr, \"Usage:\\n\\tslparser -c \\\"slparser.cfg\\\" -l \\\"log_dir\\\"\\n\");\n fprintf(stderr, \"\\tslparser -c \\\"slparser.cfg\\\" -l \\\"log_dir2\\\" -d \\\"20160830\\\"\\n\");\n fprintf(stderr, \"\\tslparser -c \\\"slparser.cfg\\\" -l \\\"log_dir3\\\" -d \\\"20160830\\\" -u \\\"puid(0: dump all, >0: someone's)\\\"\\n\");\n}\n\nstd::shared_ptr newShareLogDumper(const string &chainType, const string &dataDir,\n time_t timestamp, const std::set &uids)\n{\n if (chainType == \"BTC\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, uids);\n }\n else if (chainType == \"ETH\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, uids);\n }\n else if (chainType == \"BTM\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, uids); \n }\n else {\n LOG(FATAL) << \"newShareLogDumper: unknown chain type \" << chainType;\n return nullptr;\n }\n}\n\nstd::shared_ptr newShareLogParser(const string &chainType, const string &dataDir,\n time_t timestamp, const MysqlConnectInfo &poolDBInfo,\n const int dupShareTrackingHeight)\n{\n if (chainType == \"BTC\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, poolDBInfo, nullptr);\n }\n else if (chainType == \"ETH\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, poolDBInfo,\n std::make_shared(dupShareTrackingHeight));\n }\n else if (chainType == \"BTM\") {\n return std::make_shared(chainType.c_str(), dataDir, timestamp, poolDBInfo,\n std::make_shared(dupShareTrackingHeight));\n }\n else {\n LOG(FATAL) << \"newShareLogParser: unknown chain type \" << chainType;\n return nullptr;\n }\n}\n\nstd::shared_ptr newShareLogParserServer(const string &chainType, const string &dataDir,\n const string &httpdHost, unsigned short httpdPort,\n const MysqlConnectInfo &poolDBInfo,\n const uint32_t kFlushDBInterval,\n const int dupShareTrackingHeight)\n{\n if (chainType == \"BTC\") {\n return std::make_shared(chainType.c_str(), dataDir,\n httpdHost, httpdPort,\n poolDBInfo, kFlushDBInterval, nullptr);\n }\n else if (chainType == \"ETH\") {\n return std::make_shared(chainType.c_str(), dataDir,\n httpdHost, httpdPort,\n poolDBInfo, kFlushDBInterval,\n std::make_shared(dupShareTrackingHeight));\n }\n else if (chainType == \"BTM\") {\n return std::make_shared(chainType.c_str(), dataDir,\n httpdHost, httpdPort,\n poolDBInfo, kFlushDBInterval,\n std::make_shared(dupShareTrackingHeight));\n }\n else {\n LOG(FATAL) << \"newShareLogParserServer: unknown chain type \" << chainType;\n return nullptr;\n }\n}\n\nint main(int argc, char **argv) {\n char *optLogDir = NULL;\n char *optConf = NULL;\n int32_t optDate = 0;\n int32_t optPUID = -1; \/\/ pool user id\n int c;\n\n if (argc <= 1) {\n usage();\n return 1;\n }\n while ((c = getopt(argc, argv, \"c:l:d:u:h\")) != -1) {\n switch (c) {\n case 'c':\n optConf = optarg;\n break;\n case 'l':\n optLogDir = optarg;\n break;\n case 'd':\n optDate = atoi(optarg);\n break;\n case 'u':\n optPUID = atoi(optarg);\n break;\n case 'h': default:\n usage();\n exit(0);\n }\n }\n\n \/\/ Initialize Google's logging library.\n google::InitGoogleLogging(argv[0]);\n FLAGS_log_dir = string(optLogDir);\n \/\/ Log messages at a level >= this flag are automatically sent to\n \/\/ stderr in addition to log files.\n FLAGS_stderrthreshold = 3; \/\/ 3: FATAL\n FLAGS_max_log_size = 100; \/\/ max log file size 100 MB\n FLAGS_logbuflevel = -1; \/\/ don't buffer logs\n FLAGS_stop_logging_if_full_disk = true;\n\n \/\/ Read the file. If there is an error, report it and exit.\n libconfig::Config cfg;\n try\n {\n cfg.readFile(optConf);\n } catch(const FileIOException &fioex) {\n std::cerr << \"I\/O error while reading file.\" << std::endl;\n return(EXIT_FAILURE);\n } catch(const ParseException &pex) {\n std::cerr << \"Parse error at \" << pex.getFile() << \":\" << pex.getLine()\n << \" - \" << pex.getError() << std::endl;\n return(EXIT_FAILURE);\n }\n\n try {\n \/\/ check if we are using testnet3\n bool isTestnet3 = false;\n cfg.lookupValue(\"testnet\", isTestnet3);\n if (isTestnet3) {\n SelectParams(CBaseChainParams::TESTNET);\n LOG(WARNING) << \"using bitcoin testnet3\";\n } else {\n SelectParams(CBaseChainParams::MAIN);\n }\n\n \/\/ DB info\n MysqlConnectInfo *poolDBInfo = nullptr;\n {\n int32_t poolDBPort = 3306;\n cfg.lookupValue(\"pooldb.port\", poolDBPort);\n poolDBInfo = new MysqlConnectInfo(cfg.lookup(\"pooldb.host\"), poolDBPort,\n cfg.lookup(\"pooldb.username\"),\n cfg.lookup(\"pooldb.password\"),\n cfg.lookup(\"pooldb.dbname\"));\n }\n\n \/\/ chain type\n string chainType = cfg.lookup(\"sharelog.chain_type\");\n \/\/ Track duplicate shares within N blocks.\n int32_t dupShareTrackingHeight = 3;\n cfg.lookupValue(\"dup_share_checker.tracking_height_number\", dupShareTrackingHeight);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ dump shares to stdout\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (optDate != 0 && optPUID != -1) {\n const string tsStr = Strings::Format(\"%04d-%02d-%02d 00:00:00\",\n optDate\/10000,\n optDate\/100 % 100, optDate % 100);\n const time_t ts = str2time(tsStr.c_str(), \"%F %T\");\n std::set uids;\n if (optPUID > 0)\n uids.insert(optPUID);\n\n std::shared_ptr sldumper = newShareLogDumper(chainType, cfg.lookup(\"sharelog.data_dir\"), ts, uids);\n sldumper->dump2stdout();\n\n google::ShutdownGoogleLogging();\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ re-run someday's share bin log\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (optDate != 0) {\n const string tsStr = Strings::Format(\"%04d-%02d-%02d 00:00:00\",\n optDate\/10000,\n optDate\/100 % 100, optDate % 100);\n const time_t ts = str2time(tsStr.c_str(), \"%F %T\");\n\n std::shared_ptr slparser = newShareLogParser(chainType,\n cfg.lookup(\"sharelog.data_dir\"),\n ts, *poolDBInfo,\n dupShareTrackingHeight);\n do {\n if (slparser->init() == false) {\n LOG(ERROR) << \"init failure\";\n break;\n }\n if (!slparser->processUnchangedShareLog()) {\n LOG(ERROR) << \"processUnchangedShareLog fail\";\n break;\n }\n if (!slparser->flushToDB()) {\n LOG(ERROR) << \"processUnchangedShareLog fail\";\n break;\n }\n } while (0);\n\n google::ShutdownGoogleLogging();\n return 0;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ lock cfg file:\n \/\/ you can't run more than one process with the same config file\n boost::interprocess::file_lock pidFileLock(optConf);\n if (pidFileLock.try_lock() == false) {\n LOG(FATAL) << \"lock cfg file fail\";\n return(EXIT_FAILURE);\n }\n\n signal(SIGTERM, handler);\n signal(SIGINT, handler);\n\n int32_t port = 8081;\n cfg.lookupValue(\"slparserhttpd.port\", port);\n uint32_t kFlushDBInterval = 20;\n cfg.lookupValue(\"slparserhttpd.flush_db_interval\", kFlushDBInterval);\n gShareLogParserServer = newShareLogParserServer(chainType,\n cfg.lookup(\"sharelog.data_dir\"),\n cfg.lookup(\"slparserhttpd.ip\"),\n port, *poolDBInfo,\n kFlushDBInterval,\n dupShareTrackingHeight);\n gShareLogParserServer->run();\n }\n catch (std::exception & e) {\n LOG(FATAL) << \"exception: \" << e.what();\n return 1;\n }\n\n google::ShutdownGoogleLogging();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\r\n * Copyright 2013 Research In Motion Limited.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"gsecrypto.hpp\"\r\n#include \"gsecryptojs.hpp\"\r\n#include \"util\/util.hpp\"\r\n\r\nclass GSECryptoJS;\r\n\r\nnamespace webworks {\r\n\r\nGSECrypto::GSECrypto(GSECryptoJS *owner) {\r\n\tparent = owner;\r\n\r\n\tsbCtx = NULL;\r\n\r\n\ttry {\r\n\t\tint error = hu_GlobalCtxCreateDefault(&sbCtx);\r\n\t\tif (error != SB_SUCCESS) {\r\n\t\t\tthrow \"Failed to create global context\";\r\n\t\t}\r\n\r\n\t\terror = hu_RegisterSbg56(sbCtx);\r\n\t\tif (error != SB_SUCCESS) {\r\n\t\t\tthrow \"Failed to register sbg 5.6\";\r\n\t\t}\r\n\r\n\t\terror = hu_InitSbg56(sbCtx);\r\n\t\tif (error != SB_SUCCESS) {\r\n\t\t\tthrow \"Failed to init sbg 5.6\";\r\n\t\t}\r\n\t} catch (const char * message) {\r\n\t\tlastError = message;\r\n\t}\r\n}\r\n\r\nGSECrypto::~GSECrypto() {\r\n\tif (sbCtx != NULL) {\r\n\t\thu_GlobalCtxDestroy(&sbCtx);\r\n\t\tsbCtx = NULL;\r\n\t}\r\n}\r\n\r\nclass DataTracker {\r\npublic:\r\n\tDataTracker() :\r\n\t\t\tdata(0), dataLen(0) {\r\n\t}\r\n\t;\r\n\tvirtual ~DataTracker() {\r\n\t\tcleanUp();\r\n\t}\r\n\tvoid cleanUp() {\r\n\t\tif (data != NULL) {\r\n\t\t\tdelete[] data;\r\n\t\t\tdata = NULL;\r\n\t\t\tdataLen = 0;\r\n\t\t}\r\n\t}\r\n\tvoid setData(std::string in) {\r\n\t\tcleanUp();\r\n\t\tdataLen = in.length();\r\n\t\tdata = new unsigned char[dataLen + 1];\r\n\t\tstrcpy((char*) data, in.data());\r\n\t}\r\n\tunsigned char * data;\r\n\tsize_t dataLen;\r\n};\r\n\r\n\/\/ Take in input and return a value\r\nstd::string GSECrypto::hash(const std::string& inputString) {\r\n\tDataTracker data;\r\n\tstd::string toReturn;\r\n\r\n\ttry {\r\n\r\n\t\tJson::Value args;\r\n\t\tJson::Reader reader;\r\n\t\tif (!reader.parse(inputString, args, 0)) {\r\n\t\t\tthrow \"Input is not decodable Json\";\r\n\t\t}\r\n\r\n\t\tif (args.isMember(\"hex\")) {\r\n\t\t\tgsecrypto::util::fromHex(args[\"hex\"].asString(), data.data, data.dataLen);\r\n\t\t} else if (args.isMember(\"b64\")) {\r\n\t\t\tgsecrypto::util::fromB64(args[\"b64\"].asString(), data.data, data.dataLen);\r\n\t\t} else if (args.isMember(\"raw\")) {\r\n\t\t\tdata.setData(args[\"raw\"].asString());\r\n\t\t} else {\r\n\t\t\tthrow \"Input must have one of hex,b64,raw\";\r\n\t\t}\r\n\r\n\t\tstd::string alg = args.get(\"alg\", \"SHA1\").asString();\r\n\t\tstd::transform(alg.begin(), alg.end(), alg.begin(), tolower);\r\n\r\n\t\tsize_t digestLen = 0;\r\n\r\n\t\tint (*algFunc)(size_t, sb_YieldCtx, size_t, const unsigned char *,\r\n\t\t\t\tunsigned char *, sb_GlobalCtx) = NULL;\r\n\r\n\t\tif (alg == \"sha1\") {\r\n\t\t\tdigestLen = SB_SHA1_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA1Msg;\r\n\t\t} else if (alg == \"sha224\") {\r\n\t\t\tdigestLen = SB_SHA224_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA224Msg;\r\n\t\t} else if (alg == \"sha256\") {\r\n\t\t\tdigestLen = SB_SHA256_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA256Msg;\r\n\t\t} else if (alg == \"sha384\") {\r\n\t\t\tdigestLen = SB_SHA384_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA384Msg;\r\n\t\t} else if (alg == \"sha512\") {\r\n\t\t\tdigestLen = SB_SHA512_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA512Msg;\r\n\t\t} else {\r\n\t\t\tthrow \"Unknown SHA operation\";\r\n\t\t}\r\n\r\n\t\tlastMessage = \"\";\r\n\t\tstd::stringstream tmp;\r\n\t\ttmp << \"dataLength: \" << data.dataLen << \" data: \";\r\n\t\tfor (size_t i = 0; i < data.dataLen; ++i) {\r\n\t\t\ttmp << data.data[i];\r\n\t\t}\r\n\t\ttmp << \"\\n\";\r\n\t\ttmp << \"Input: \" << inputString;\r\n\t\tlastMessage = tmp.str();\r\n\r\n\t\tunsigned char digest[digestLen];\r\n\t\tfor (size_t i = 0; i < digestLen; ++i) {\r\n\t\t\tdigest[i] = i;\r\n\t\t}\r\n\t\tif (SB_SUCCESS\r\n\t\t\t\t!= algFunc(digestLen, NULL, data.dataLen, data.data, digest,\r\n\t\t\t\t\t\tsbCtx)) {\r\n\t\t\tthrow \"Could not call hash function\";\r\n\t\t}\r\n\r\n\t\ttoReturn = toString(digest, digestLen);\r\n\t} catch (const char * error) {\r\n\t\tJson::Value errorJ;\r\n\t\tJson::FastWriter writer;\r\n\t\terrorJ[\"error\"] = error;\r\n\t\treturn writer.write(errorJ);\r\n\t}\r\n\r\n\treturn toReturn;\r\n}\r\n\r\nstd::string GSECrypto::toString(unsigned char * data, size_t dataLen) {\r\n\tJson::Value toReturn;\r\n\tJson::FastWriter writer;\r\n\ttoReturn[\"hex\"] = gsecrypto::util::toHex(data, dataLen);\r\n\ttoReturn[\"b64\"] = gsecrypto::util::toB64(data, dataLen);\r\n\tif (lastMessage.length() != 0) {\r\n\t\ttoReturn[\"lastMessage\"] = lastMessage;\r\n\t\tlastMessage = \"\";\r\n\t}\r\n\r\n\treturn writer.write(toReturn);\r\n}\r\n\r\n} \/* namespace webworks *\/\r\nAdded code to ignore - in the alg name\/*\r\n * Copyright 2013 Research In Motion Limited.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"gsecrypto.hpp\"\r\n#include \"gsecryptojs.hpp\"\r\n#include \"util\/util.hpp\"\r\n\r\nclass GSECryptoJS;\r\n\r\nnamespace webworks {\r\n\r\nGSECrypto::GSECrypto(GSECryptoJS *owner) {\r\n\tparent = owner;\r\n\r\n\tsbCtx = NULL;\r\n\r\n\ttry {\r\n\t\tint error = hu_GlobalCtxCreateDefault(&sbCtx);\r\n\t\tif (error != SB_SUCCESS) {\r\n\t\t\tthrow \"Failed to create global context\";\r\n\t\t}\r\n\r\n\t\terror = hu_RegisterSbg56(sbCtx);\r\n\t\tif (error != SB_SUCCESS) {\r\n\t\t\tthrow \"Failed to register sbg 5.6\";\r\n\t\t}\r\n\r\n\t\terror = hu_InitSbg56(sbCtx);\r\n\t\tif (error != SB_SUCCESS) {\r\n\t\t\tthrow \"Failed to init sbg 5.6\";\r\n\t\t}\r\n\t} catch (const char * message) {\r\n\t\tlastError = message;\r\n\t}\r\n}\r\n\r\nGSECrypto::~GSECrypto() {\r\n\tif (sbCtx != NULL) {\r\n\t\thu_GlobalCtxDestroy(&sbCtx);\r\n\t\tsbCtx = NULL;\r\n\t}\r\n}\r\n\r\nclass DataTracker {\r\npublic:\r\n\tDataTracker() :\r\n\t\t\tdata(0), dataLen(0) {\r\n\t}\r\n\t;\r\n\tvirtual ~DataTracker() {\r\n\t\tcleanUp();\r\n \t}\r\n\tvoid cleanUp() {\r\n\t\tif (data != NULL) {\r\n\t\t\tdelete[] data;\r\n\t\t\tdata = NULL;\r\n\t\t\tdataLen = 0;\r\n\t\t}\r\n\t}\r\n\tvoid setData(std::string in) {\r\n\t\tcleanUp();\r\n\t\tdataLen = in.length();\r\n\t\tdata = new unsigned char[dataLen + 1];\r\n\t\tstrcpy((char*) data, in.data());\r\n\t}\r\n\tunsigned char * data;\r\n\tsize_t dataLen;\r\n};\r\n\r\n\/\/ Take in input and return a value\r\nstd::string GSECrypto::hash(const std::string& inputString) {\r\n\tDataTracker data;\r\n\tstd::string toReturn;\r\n\r\n\ttry {\r\n\r\n\t\tJson::Value args;\r\n\t\tJson::Reader reader;\r\n\t\tif (!reader.parse(inputString, args, 0)) {\r\n\t\t\tthrow \"Input is not decodable Json\";\r\n\t\t}\r\n\r\n\t\tif (args.isMember(\"hex\")) {\r\n\t\t\tgsecrypto::util::fromHex(args[\"hex\"].asString(), data.data, data.dataLen);\r\n\t\t} else if (args.isMember(\"b64\")) {\r\n\t\t\tgsecrypto::util::fromB64(args[\"b64\"].asString(), data.data, data.dataLen);\r\n\t\t} else if (args.isMember(\"raw\")) {\r\n\t\t\tdata.setData(args[\"raw\"].asString());\r\n\t\t} else {\r\n\t\t\tthrow \"Input must have one of hex,b64,raw\";\r\n\t\t}\r\n\r\n\t\tstd::string alg = args.get(\"alg\", \"SHA1\").asString();\r\n\t\tstd::transform(alg.begin(), alg.end(), alg.begin(), tolower);\r\n\t\talg.erase(std::remove(alg.begin(), alg.end(), '-'), alg.end());\r\n\r\n\r\n\t\tsize_t digestLen = 0;\r\n\r\n\t\tint (*algFunc)(size_t, sb_YieldCtx, size_t, const unsigned char *,\r\n\t\t\t\tunsigned char *, sb_GlobalCtx) = NULL;\r\n\r\n\t\tif (alg == \"sha1\") {\r\n\t\t\tdigestLen = SB_SHA1_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA1Msg;\r\n\t\t} else if (alg == \"sha224\") {\r\n\t\t\tdigestLen = SB_SHA224_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA224Msg;\r\n\t\t} else if (alg == \"sha256\") {\r\n\t\t\tdigestLen = SB_SHA256_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA256Msg;\r\n\t\t} else if (alg == \"sha384\") {\r\n\t\t\tdigestLen = SB_SHA384_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA384Msg;\r\n\t\t} else if (alg == \"sha512\") {\r\n\t\t\tdigestLen = SB_SHA512_DIGEST_LEN;\r\n\t\t\talgFunc = hu_SHA512Msg;\r\n\t\t} else {\r\n\t\t\tthrow \"Unknown SHA operation\";\r\n\t\t}\r\n\r\n\t\tlastMessage = \"\";\r\n\t\tstd::stringstream tmp;\r\n\t\ttmp << \"dataLength: \" << data.dataLen << \" data: \";\r\n\t\tfor (size_t i = 0; i < data.dataLen; ++i) {\r\n\t\t\ttmp << data.data[i];\r\n\t\t}\r\n\t\ttmp << \"\\n\";\r\n\t\ttmp << \"Input: \" << inputString;\r\n\t\tlastMessage = tmp.str();\r\n\r\n\t\tunsigned char digest[digestLen];\r\n\t\tfor (size_t i = 0; i < digestLen; ++i) {\r\n\t\t\tdigest[i] = i;\r\n\t\t}\r\n\t\tif (SB_SUCCESS\r\n\t\t\t\t!= algFunc(digestLen, NULL, data.dataLen, data.data, digest,\r\n\t\t\t\t\t\tsbCtx)) {\r\n\t\t\tthrow \"Could not call hash function\";\r\n\t\t}\r\n\r\n\t\ttoReturn = toString(digest, digestLen);\r\n\t} catch (const char * error) {\r\n\t\tJson::Value errorJ;\r\n\t\tJson::FastWriter writer;\r\n\t\terrorJ[\"error\"] = error;\r\n\t\treturn writer.write(errorJ);\r\n\t}\r\n\r\n\treturn toReturn;\r\n}\r\n\r\nstd::string GSECrypto::toString(unsigned char * data, size_t dataLen) {\r\n\tJson::Value toReturn;\r\n\tJson::FastWriter writer;\r\n\ttoReturn[\"hex\"] = gsecrypto::util::toHex(data, dataLen);\r\n\ttoReturn[\"b64\"] = gsecrypto::util::toB64(data, dataLen);\r\n\tif (lastMessage.length() != 0) {\r\n\t\ttoReturn[\"lastMessage\"] = lastMessage;\r\n\t\tlastMessage = \"\";\r\n\t}\r\n\r\n\treturn writer.write(toReturn);\r\n}\r\n\r\n} \/* namespace webworks *\/\r\n<|endoftext|>"} {"text":"\/\/ Copyright [2014] \n\/\/=====================================================================================\n\/\/\n\/\/ Filename: cmdRemove.cpp\n\/\/\n\/\/ Description: 删除命令\n\/\/\n\/\/ Version: 1.0\n\/\/ Created: 2014年12月25日 10时44分35秒\n\/\/ Revision: none\n\/\/ Compiler: gcc\n\/\/\n\/\/ Author: lgb (LiuGuangBao), easyeagel@gmx.com\n\/\/ Organization: ezbty.org\n\/\/\n\/\/=====================================================================================\n\/\/\n\n#include\"option.hpp\"\n#include\"fileset.hpp\"\n\nnamespace ezsh\n{\n\nnamespace bf=boost::filesystem;\n\nclass CmdRemove:public CmdBaseT>\n{\n typedef CmdBaseT BaseThis;\npublic:\n CmdRemove()\n :BaseThis(\"remove - remove file or dir\")\n {\n opt_.add_options()\n (\"force,f\", \"ignore nonexistent files and arguments\")\n ;\n }\n\n static const char* nameGet()\n {\n return \"remove\";\n }\n\n MainReturn doit() override\n {\n const auto& vm=mapGet();\n auto& files=fileGet();\n\n files.init(vm);\n\n const bool force=vm.count(\"force\") ? true : false;\n for(const auto& file: files.setGet())\n {\n if(!file.isExist())\n {\n if(force)\n continue;\n stdErr() << file.total << \": not exist\" << std::endl;\n continue;\n }\n\n boost::system::error_code ec;\n if(!file.isDir())\n {\n bf::remove(file.total, ec);\n if(ec && !force)\n stdErr() << file.total << \": \" << ec.message() << std::endl;\n continue;\n }\n\n if(files.isRecursive())\n {\n bf::remove_all(file.total, ec);\n if(ec && !force)\n stdErr() << file.total << \": \" << ec.message() << std::endl;\n continue;\n }\n\n bf::remove(file.total, ec);\n if(ec && !force)\n stdErr() << file.total << \": \" << ec.message() << std::endl;\n }\n\n return MainReturn::eGood;\n }\n\n};\n\nnamespace\n{\nstatic CmdRegisterT gsRegister;\n}\n\n\n}\n\n在扫描的过程中删除文件是危险的\/\/ Copyright [2014] \n\/\/=====================================================================================\n\/\/\n\/\/ Filename: cmdRemove.cpp\n\/\/\n\/\/ Description: 删除命令\n\/\/\n\/\/ Version: 1.0\n\/\/ Created: 2014年12月25日 10时44分35秒\n\/\/ Revision: none\n\/\/ Compiler: gcc\n\/\/\n\/\/ Author: lgb (LiuGuangBao), easyeagel@gmx.com\n\/\/ Organization: ezbty.org\n\/\/\n\/\/=====================================================================================\n\/\/\n\n#include\"option.hpp\"\n#include\"fileset.hpp\"\n\nnamespace ezsh\n{\n\nnamespace bf=boost::filesystem;\n\nclass CmdRemove:public CmdBaseT>\n{\n typedef CmdBaseT BaseThis;\npublic:\n CmdRemove()\n :BaseThis(\"remove - remove file or dir\")\n {\n opt_.add_options()\n (\"force,f\", \"ignore nonexistent files and arguments\")\n ;\n }\n\n static const char* nameGet()\n {\n return \"remove\";\n }\n\n MainReturn doit() override\n {\n auto& files=fileGet();\n const auto& vm=mapGet();\n\n files.init(vm);\n files.scan();\n const bool force=vm.count(\"force\") ? true : false;\n for(const auto& file: files.setGet())\n fileRemove(file, force);\n return MainReturn::eGood;\n }\n\nprivate:\n void fileRemove(const FileUnit& file, bool force)\n {\n if(!file.isExist())\n {\n if(!force)\n stdErr() << file.total << \": not exist\" << std::endl;\n return;\n }\n\n boost::system::error_code ec;\n if(!file.isDir())\n {\n bf::remove(file.total, ec);\n if(ec && !force)\n stdErr() << file.total << \": \" << ec.message() << std::endl;\n return;\n }\n\n if(fileGet().isRecursive())\n {\n bf::remove_all(file.total, ec);\n if(ec && !force)\n stdErr() << file.total << \": \" << ec.message() << std::endl;\n return;\n }\n\n bf::remove(file.total, ec);\n if(ec && !force)\n stdErr() << file.total << \": \" << ec.message() << std::endl;\n }\n};\n\nnamespace\n{\nstatic CmdRegisterT gsRegister;\n}\n\n\n}\n\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2014 by Marcin Ziemiński *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2.1 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n#include \"otr-message.h\"\n\nnamespace OTR\n{\n Message::Message()\n : dir(MessageDirection::TO_PEER)\n {\n message << Tp::MessagePart() << Tp::MessagePart();\n setType(Tp::ChannelTextMessageTypeNormal);\n }\n\n Message::Message(const Tp::MessagePartList &message)\n : dir(MessageDirection::TO_PEER),\n message(message)\n {\n while(this->message.size() < 2) {\n this->message << Tp::MessagePart();\n }\n if(!this->message[0].contains(QLatin1String(\"message-type\"))) {\n setType(Tp::ChannelTextMessageTypeNormal);\n }\n }\n\n const Tp::MessagePartList& Message::parts() const\n {\n return message;\n }\n\n QString Message::text() const\n {\n auto it = message[1].find(QLatin1String(\"content\"));\n if(it == message[1].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setText(const QString &text, const QString &contentType)\n {\n message[1].insert(QLatin1String(\"content-type\"),\n QDBusVariant(contentType));\n message[1].insert(QLatin1String(\"content\"), QDBusVariant(text));\n }\n\n QString Message::contentType() const\n {\n auto it = message[1].find(QLatin1String(\"content-type\"));\n if(it == message[1].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setType(Tp::ChannelTextMessageType msgType)\n {\n message[0].insert(QLatin1String(\"message-type\"), QDBusVariant(msgType));\n }\n\n Tp::ChannelTextMessageType Message::type() const\n {\n return static_cast(message[0][QLatin1String(\"message-type\")].variant().toUInt(nullptr));\n }\n\n bool Message::isOTRmessage() const\n {\n return otrl_proto_message_type(text().toLocal8Bit()) != OTRL_MSGTYPE_NOTOTR;\n }\n\n MessageDirection Message::direction() const\n {\n return dir;\n }\n\n void Message::setDirection(MessageDirection direction)\n {\n dir = direction;\n }\n\n bool Message::isOTRevent() const\n {\n return message[0].contains(QLatin1String(\"otr-message-event\"));\n }\n\n void Message::setOTRevent(OtrlMessageEvent msgEvent)\n {\n message[0].insert(QLatin1String(\"otr-message-event\"), QDBusVariant(static_cast(msgEvent)));\n }\n\n OtrlMessageEvent Message::getOTRevent() const\n {\n return static_cast(message[0][QLatin1String(\"otr-message-event\")].variant().toUInt(nullptr));\n }\n\n void Message::setOTRheader(const QString &header, const QString &text)\n {\n message[0].insert(header, QDBusVariant(text));\n }\n\n QString Message::getOTRheader(const QString &header)\n {\n auto it = message[0].find(header);\n if(it == message[0].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setTimestamp(qint64 timestamp)\n {\n message[0].insert(QLatin1String(\"message-sent\"), QDBusVariant(timestamp));\n }\n\n qint64 Message::getTimestamp() const\n {\n auto it = message[0].find(QLatin1String(\"message-sent\"));\n if(it == message[0].end()) {\n return 0;\n } else {\n return it->variant().toLongLong(NULL);\n }\n }\n\n void Message::setSenderId(const QString &senderId)\n {\n message[0].insert(QLatin1String(\"message-sender-id\"), QDBusVariant(senderId));\n }\n\n QString Message::getSenderId() const\n {\n auto it = message[0].find(QLatin1String(\"message-sender-id\"));\n if(it == message[0].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setSender(uint sender)\n {\n message[0].insert(QLatin1String(\"message-sender\"), QDBusVariant(sender));\n }\n\n uint Message::getSender() const\n {\n auto it = message[0].find(QLatin1String(\"message-sender\"));\n if(it == message[0].end()) {\n return 0;\n } else {\n return it->variant().toUInt(NULL);\n }\n }\n\n void Message::setToken(const QString &token)\n {\n message[0].insert(QLatin1String(\"message-token\"), QDBusVariant(token));\n }\n\n QString Message::getToken() const\n {\n auto it = message[0].find(QLatin1String(\"message-sender\"));\n if(it == message[0].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n} \/* namespace OTR *\/\nReturn default OtrlMessageEvent in the Message\/***************************************************************************\n * Copyright (C) 2014 by Marcin Ziemiński *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2.1 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n#include \"otr-message.h\"\n\nnamespace OTR\n{\n Message::Message()\n : dir(MessageDirection::TO_PEER)\n {\n message << Tp::MessagePart() << Tp::MessagePart();\n setType(Tp::ChannelTextMessageTypeNormal);\n }\n\n Message::Message(const Tp::MessagePartList &message)\n : dir(MessageDirection::TO_PEER),\n message(message)\n {\n while(this->message.size() < 2) {\n this->message << Tp::MessagePart();\n }\n if(!this->message[0].contains(QLatin1String(\"message-type\"))) {\n setType(Tp::ChannelTextMessageTypeNormal);\n }\n }\n\n const Tp::MessagePartList& Message::parts() const\n {\n return message;\n }\n\n QString Message::text() const\n {\n auto it = message[1].find(QLatin1String(\"content\"));\n if(it == message[1].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setText(const QString &text, const QString &contentType)\n {\n message[1].insert(QLatin1String(\"content-type\"),\n QDBusVariant(contentType));\n message[1].insert(QLatin1String(\"content\"), QDBusVariant(text));\n }\n\n QString Message::contentType() const\n {\n auto it = message[1].find(QLatin1String(\"content-type\"));\n if(it == message[1].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setType(Tp::ChannelTextMessageType msgType)\n {\n message[0].insert(QLatin1String(\"message-type\"), QDBusVariant(msgType));\n }\n\n Tp::ChannelTextMessageType Message::type() const\n {\n return static_cast(message[0][QLatin1String(\"message-type\")].variant().toUInt(nullptr));\n }\n\n bool Message::isOTRmessage() const\n {\n return otrl_proto_message_type(text().toLocal8Bit()) != OTRL_MSGTYPE_NOTOTR;\n }\n\n MessageDirection Message::direction() const\n {\n return dir;\n }\n\n void Message::setDirection(MessageDirection direction)\n {\n dir = direction;\n }\n\n bool Message::isOTRevent() const\n {\n return message[0].contains(QLatin1String(\"otr-message-event\"));\n }\n\n void Message::setOTRevent(OtrlMessageEvent msgEvent)\n {\n message[0].insert(QLatin1String(\"otr-message-event\"), QDBusVariant(static_cast(msgEvent)));\n }\n\n OtrlMessageEvent Message::getOTRevent() const\n {\n if(isOTRevent()) {\n return static_cast(message[0][QLatin1String(\"otr-message-event\")].variant().toUInt(nullptr));\n } else {\n return OTRL_MSGEVENT_NONE;\n }\n }\n\n void Message::setOTRheader(const QString &header, const QString &text)\n {\n message[0].insert(header, QDBusVariant(text));\n }\n\n QString Message::getOTRheader(const QString &header)\n {\n auto it = message[0].find(header);\n if(it == message[0].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setTimestamp(qint64 timestamp)\n {\n message[0].insert(QLatin1String(\"message-sent\"), QDBusVariant(timestamp));\n }\n\n qint64 Message::getTimestamp() const\n {\n auto it = message[0].find(QLatin1String(\"message-sent\"));\n if(it == message[0].end()) {\n return 0;\n } else {\n return it->variant().toLongLong(NULL);\n }\n }\n\n void Message::setSenderId(const QString &senderId)\n {\n message[0].insert(QLatin1String(\"message-sender-id\"), QDBusVariant(senderId));\n }\n\n QString Message::getSenderId() const\n {\n auto it = message[0].find(QLatin1String(\"message-sender-id\"));\n if(it == message[0].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n void Message::setSender(uint sender)\n {\n message[0].insert(QLatin1String(\"message-sender\"), QDBusVariant(sender));\n }\n\n uint Message::getSender() const\n {\n auto it = message[0].find(QLatin1String(\"message-sender\"));\n if(it == message[0].end()) {\n return 0;\n } else {\n return it->variant().toUInt(NULL);\n }\n }\n\n void Message::setToken(const QString &token)\n {\n message[0].insert(QLatin1String(\"message-token\"), QDBusVariant(token));\n }\n\n QString Message::getToken() const\n {\n auto it = message[0].find(QLatin1String(\"message-sender\"));\n if(it == message[0].end()) {\n return QLatin1String(\"\");\n } else {\n return it->variant().toString();\n }\n }\n\n} \/* namespace OTR *\/\n<|endoftext|>"} {"text":"\/\/ Time: O(logn)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n int findMin(vector& nums) {\n int left = 0, right = nums.size() - 1;\n\n \/\/ Find min left s.t. nums[left] < nums[left'].\n while (left < right && nums[left] >= nums[right]) {\n int mid = left + (right - left) \/ 2;\n if (nums[mid] < nums[left]) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n return nums[left];\n\n }\n};\nUpdate find-minimum-in-rotated-sorted-array.cpp\/\/ Time: O(logn)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n int findMin(vector& nums) {\n int left = 0, right = nums.size() - 1;\n\n \/\/ Find min left s.t. nums[left] < nums[left'].\n while (left < right && nums[left] >= nums[right]) {\n int mid = left + (right - left) \/ 2;\n if (nums[mid] < nums[left]) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n return nums[left];\n }\n};\n<|endoftext|>"} {"text":"#define BOOST_TEST_MODULE \"Number_of_Islands_test\"\n#include \n\n#include \"test_common.hpp\"\n#include \"read_test_case.hpp\"\n#include \"solution.hpp\"\n\n#include \n#include \n\ntemplate<> const pretty_print::delimiters_values pretty_print::delimiters>, char>::values = { \"||\\n \", \" :\\n \", \" \\n||\" };\n\nBOOST_DATA_TEST_CASE(\n test1,\n (make_tests(&read_input, &read_output)),\n \/\/ ^ bdata::make( { 1, 2, 3, 5, 8, 13, 21, 35, 56 } ),\n island_map, expected)\n{\n auto filepaths = get_all_test_filepaths();\n for (const auto& f : filepaths) {\n cout << f << '\\n';\n }\n cout << \"island map is \" << island_map << '\\n';\n Solution sol;\n int actual = sol.numIslands(island_map);\n BOOST_CHECK_EQUAL(actual, expected);\n}\n\n\/\/BOOST_AUTO_TEST_CASE(FailTest) {\n\/\/ BOOST_FAIL(\"\");\n\/\/}\nNumber of Islands with test implemented#define BOOST_TEST_MODULE \"Number_of_Islands_test\"\n#include \n\n#include \"test_common.hpp\"\n#include \"read_test_case.hpp\"\n#include \"solution.hpp\"\n\n#include \n#include \n\ntemplate<> const pretty_print::delimiters_values pretty_print::delimiters>, char>::values = { \"||\\n \", \" :\\n \", \" \\n||\" };\n\nBOOST_DATA_TEST_CASE(\n test1,\n (make_tests(&read_input, &read_output)),\n \/\/ ^ bdata::make( { 1, 2, 3, 5, 8, 13, 21, 35, 56 } ),\n island_map, expected)\n{\n \/\/ auto filepaths = get_all_test_filepaths();\n \/\/ for (const auto& f : filepaths) {\n \/\/ cout << f << '\\n';\n \/\/ }\n \/\/ cout << \"island map is \" << island_map << '\\n';\n Solution sol;\n int actual = sol.numIslands(island_map);\n BOOST_CHECK_EQUAL(actual, expected);\n}\n<|endoftext|>"} {"text":"#include \n#include \n\nusing namespace std;\n\n\/\/Global Variables\nconst double pi = 3.14159;\n\/\/Classes\nclass railroad_car{\n\tpublic:\n\t\t\/\/Default constructor\n\t\trailroad_car(){}\n\t\t\/\/Functions\n\t\tvirtual void display_name(){}\n\t\tvirtual void display_capacity(){}\n};\n\nclass box{\n\tpublic:\n\t\t\/\/Default constructor\n\t\tbox(){}\n\t\t\/\/Argument-bearing constructor\n\t\tbox(double h, double w, double l){\n\t\t\theight = h; width = w; length = l;\n\t\t}\n\t\t\/\/Functions\n\t\tdouble volume(){return height*width*length; }\n\t\t\/\/Variables\n\t\tdouble height, width, length;\n};\n\n\n\nclass box_car : public railroad_car, protected box{\n\tpublic:\n\t\t\/\/Default constructor\n\t\tbox_car() : box(10.5,9.5,40.0) {}\n\t\tvirtual void display_height(){cout << height << endl;}\n\t\tvirtual void display_name(){cout << \"box_car\";}\n\t\tvirtual void display_capacity(){cout << volume();}\n};\nint main(){\n\tbox_car example;\n\t\/\/cout << example.height<< endl; DOES NOT WORK\n\texample.display_height();\n\tbox b;\n\tcout << b.height << endl; \/\/Does work, however since box has no default constructor, return random number\n\treturn 0;\n}\n\t\t\t\t\n\t\t\t\t\nUpdate S9_Protected_classes.cpp#include \n#include \n\nusing namespace std;\n\n\/\/Global Variables\nconst double pi = 3.14159;\n\/\/Classes\nclass railroad_car{\n\tpublic:\n\t\t\/\/Default constructor\n\t\trailroad_car(){}\n\t\t\/\/Functions\n\t\tvirtual void display_name(){}\n\t\tvirtual void display_capacity(){}\n};\n\nclass box{\n\tpublic:\n\t\t\/\/Default constructor\n\t\tbox(){}\n\t\t\/\/Argument-bearing constructor\n\t\tbox(double h, double w, double l){\n\t\t\theight = h; width = w; length = l;\n\t\t}\n\t\t\/\/Functions\n\t\tdouble volume(){return height*width*length; }\n\t\t\/\/Variables\n\t\tdouble height, width, length;\n};\n\n\/\/Box car class that inherits railraod_car as well as protected box\nclass box_car : public railroad_car, protected box{\n\tpublic:\n\t\t\/\/Default constructor\n\t\tbox_car() : box(10.5,9.5,40.0) {}\n\t\tvirtual void display_height(){cout << height << endl;}\n\t\tvirtual void display_name(){cout << \"box_car\";}\n\t\tvirtual void display_capacity(){cout << volume();}\n};\nint main(){\n\t\/\/A box car\n\tbox_car example;\n\t\/\/Showing how a protected inheritance limits the classes access\n\t\n\t\/\/cout << example.height<< endl; DOES NOT WORK\n\t\n\texample.display_height();\n\tbox b;\n\tcout << b.height << endl; \/\/Does work, however since box has no default constructor, return random number\n\treturn 0;\n}\n\t\t\t\t\n\t\t\t\t\n<|endoftext|>"} {"text":"\/**\n * @file\n * exercise_03_15.cpp\n * @author\n * Henrik Samuelsson, henrik.samuelsson(at)gmail.com\n *\/\n#include \n#include \n#include \n\nusing std::cin;\nusing std::string;\nusing std::vector;\n\nint main() {\n vector ivec;\n string temp;\n \n while (cin >> temp) {\n ivec.push_back(temp);\n }\n \n return 0;\n}\nBetter variable name.\/**\n * @file\n * exercise_03_15.cpp\n * @author\n * Henrik Samuelsson, henrik.samuelsson(at)gmail.com\n *\/\n#include \n#include \n#include \n\nusing std::cin;\nusing std::string;\nusing std::vector;\n\nint main() {\n vector s_vec;\n string temp;\n \n while (cin >> temp) {\n s_vec.push_back(temp);\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n\n Copyright Eli Dupree and Isaac Dupree, 2011, 2012\n\n This file is part of Lasercake.\n\n Lasercake is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Lasercake is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with Lasercake. If not, see .\n\n*\/\n\n#ifndef LASERCAKE_BORROWED_BITSET_HPP__\n#define LASERCAKE_BORROWED_BITSET_HPP__\n\n#include \n#include \n#include \n#include \n\n#include \"..\/utils.hpp\"\n#if 0 && !LASERCAKE_NO_THREADS\n#include \n#endif\n\ntypedef uint64_t bit_index_type;\n\nnamespace borrowed_bitset_impl {\n\n\/\/ Noncopying singly linked list that owns its members unless you pop them.\ntemplate\nstruct liststack_node : boost::noncopyable {\n liststack_node* next;\n T here;\n\n liststack_node() : next(nullptr), here() {}\n template\n explicit liststack_node(Arg const& arg, liststack_node* next = nullptr)\n : next(next), here(arg) {}\n ~liststack_node() { delete next; }\n};\n\ntemplate\nstruct liststack : boost::noncopyable {\n typedef borrowed_bitset_impl::liststack_node liststack_node;\n liststack_node* next;\n\n liststack() : next(nullptr) {}\n explicit liststack(liststack_node* next) : next(next) {}\n ~liststack() { delete next; }\n\n liststack_node* pop() {\n liststack_node* result = next;\n next = result->next;\n \/\/ for clarity:\n result->next = nullptr;\n return result;\n }\n void push(liststack_node* add) {\n add->next = next;\n next = add;\n }\n bool empty() {\n return next == nullptr;\n }\n};\n\n \nstruct zeroable_bitset {\n \/\/ until this implementation becomes profile-measurable, it's good enough.\n bit_index_type num_bits;\n boost::dynamic_bitset<> bits;\n std::vector bits_to_clear;\n\n zeroable_bitset(bit_index_type num_bits)\n : num_bits(num_bits), bits(num_bits), bits_to_clear() {}\n};\n\ntypedef liststack zeroable_bitset_list;\n\/\/ node\/iterator\/such\ntypedef liststack_node zeroable_bitset_node;\n\nstatic const size_t array_of_bitset_lists_len = 40;\nstatic const size_t bit_to_min_size_exponent = 6;\n\/\/ if we track 4-8byteses individually, this exponent would be smaller.\nstatic const size_t bit_exponent_below_which_its_worth_tracking_bits_individually = 8;\n\n\/\/ array of array_of_bitset_lists_len sizes, from 2**bit_to_min_size_exponent bits up.\ntypedef zeroable_bitset_list* zeroable_bitset_array;\n\nextern thread_local zeroable_bitset_array array_of_bitset_lists;\n\ninline\nvoid delete_array_of_bitset_lists() { delete[] array_of_bitset_lists; }\n\ninline\nzeroable_bitset_array get_this_thread_array_of_bitset_lists() {\n if(array_of_bitset_lists == nullptr) {\n array_of_bitset_lists = new zeroable_bitset_list[array_of_bitset_lists_len];\n #if 0 && !LASERCAKE_NO_THREADS\n \/\/ No Boost.Thread for now; fewer deps.\n \/\/ Currently, the borrowed_bitset won't leak memory in Lasercake\n \/\/ because we only create a small, finite number of threads.\n \/\/ We'll use some better solution if that changes (TODO).\n try {\n \/\/ (note, if we use forcible thread cancelation, this won't run)\n \/\/ Also, donating them to another thread might be more useful\n \/\/ than deleting them.\n boost::this_thread::at_thread_exit(delete_array_of_bitset_lists);\n }\n catch(...) {\n delete array_of_bitset_lists;\n array_of_bitset_lists = nullptr;\n throw;\n }\n #endif\n }\n return array_of_bitset_lists;\n};\n\ninline size_t which_bitset_index_is_size(bit_index_type num_bits) {\n if(num_bits == 0) return 0;\n const bit_index_type max_bit_index = num_bits - 1;\n const bit_index_type max_8byte_index = max_bit_index >> bit_to_min_size_exponent;\n caller_error_if(max_8byte_index != size_t(max_8byte_index), \"More bits requested than your architecture can handle!\");\n const size_t which_bitset_size_index = num_bits_in_integer_that_are_not_leading_zeroes(max_8byte_index);\n caller_error_if(which_bitset_size_index >= array_of_bitset_lists_len, \"More bits requested than we support!\");\n return which_bitset_size_index;\n}\n\ninline bit_index_type how_many_bits_at_bitset_index(size_t bitset_index) {\n return bit_index_type(1) << (bitset_index + bit_to_min_size_exponent);\n}\n\ninline\nzeroable_bitset_node* borrow_bitset(bit_index_type num_bits_desired) {\n zeroable_bitset_array array_of_bitset_lists = get_this_thread_array_of_bitset_lists();\n const size_t which_bitset_size_index = which_bitset_index_is_size(num_bits_desired);\n const bit_index_type actual_bits = how_many_bits_at_bitset_index(which_bitset_size_index);\n assert(actual_bits >= num_bits_desired);\n assert(actual_bits < num_bits_desired*2 || actual_bits == (1<here.num_bits == actual_bits);\n return result;\n }\n else {\n return new zeroable_bitset_node(actual_bits);\n }\n}\n\ninline void return_bitset(zeroable_bitset_node* node) BOOST_NOEXCEPT {\n zeroable_bitset_array array_of_bitset_lists;\n try {\n array_of_bitset_lists = get_this_thread_array_of_bitset_lists();\n }\n catch(std::exception const&) {\n \/\/ This function is called from destructors so it must be nothrow.\n \/\/ In particular, this may happen if the destructor is called in a different\n \/\/ thread than the constructor was (std::bad_alloc or similar).\n delete node;\n return;\n }\n const size_t which_bitset_size_index = which_bitset_index_is_size(node->here.num_bits);\n array_of_bitset_lists[which_bitset_size_index].push(node);\n}\n\n\n\n\n\/\/ borrowed_bitset(n) borrows an array of zero bits of size n (rounded\n\/\/ up to something), and when destructed it restores the zeroes and returns\n\/\/ that array. (There's a dynamically allocated pool of arrays of zeroes\n\/\/ waiting to be borrowed; if none are available, borrowed_bitset allocates\n\/\/ a new one, which it will return to the pool when destructed.)\n\/\/\n\/\/ If there aren't too many borrowed_bitsets at once and program runs for\n\/\/ a while, borrowed_bitset() effectively has O(1) construction, and\n\/\/ destruction time <= the number of operations performed on it (so no worse\n\/\/ than a constant factor). This is pretty good for something this much\n\/\/ faster at uniquing than an unordered_set.\nclass borrowed_bitset : boost::noncopyable {\npublic:\n explicit borrowed_bitset(bit_index_type num_bits_desired) : bs_(borrow_bitset(num_bits_desired)) {}\n borrowed_bitset() : bs_(nullptr) {} \/\/default-constructing invalid bitsets is okay\n borrowed_bitset(borrowed_bitset&& other) { bs_ = other.bs_; other.bs_ = nullptr; }\n bool test(bit_index_type which)const {\n caller_correct_if(which < size(), \"borrowed_bitset bounds overflow\");\n return bs_->here.bits.test(which);\n }\n bool set(bit_index_type which) {\n bool was_already_set = test(which);\n if(!was_already_set && tracking_bits_individually_()) {\n bs_->here.bits_to_clear.push_back(which);\n }\n bs_->here.bits.set(which);\n return was_already_set;\n }\n bit_index_type size()const {\n \/\/ Implementation detail: this number might be greater than the number\n \/\/ requested by the constructor. We could store the requested number,\n \/\/ but is it important to?\n return bs_->here.num_bits;\n }\n ~borrowed_bitset() {\n if(!bs_) return;\n if(tracking_bits_individually_()) {\n for(bit_index_type which : bs_->here.bits_to_clear) {\n bs_->here.bits.reset(which);\n }\n }\n else {\n bs_->here.bits.reset();\n }\n bs_->here.bits_to_clear.clear();\n return_bitset(bs_);\n }\nprivate:\n bool tracking_bits_individually_() const {\n return bs_->here.bits_to_clear.size()\n < (bs_->here.num_bits >> bit_exponent_below_which_its_worth_tracking_bits_individually);\n }\n zeroable_bitset_node* bs_;\n};\n\n\n\/\/ If you know ahead of time that you're going to set most of the bits,\n\/\/ this will give a small constant-factor speed improvement over\n\/\/ borrowed_bitset.\nclass borrowed_bitset_that_always_clears_using_memset : boost::noncopyable {\npublic:\n explicit borrowed_bitset_that_always_clears_using_memset(bit_index_type num_bits_desired)\n : bs_(borrow_bitset(num_bits_desired)) {}\n borrowed_bitset_that_always_clears_using_memset()\n : bs_(nullptr) {} \/\/default-constructing invalid bitsets is okay\n borrowed_bitset_that_always_clears_using_memset(borrowed_bitset_that_always_clears_using_memset&& other)\n { bs_ = other.bs_; other.bs_ = nullptr; }\n bool test(bit_index_type which)const {\n caller_correct_if(which < size(), \"borrowed_bitset bounds overflow\");\n return bs_->here.bits.test(which);\n }\n bool set(bit_index_type which) {\n bool was_already_set = test(which);\n bs_->here.bits.set(which);\n return was_already_set;\n }\n bit_index_type size()const {\n \/\/ Implementation detail: this number might be greater than the number\n \/\/ requested by the constructor. We could store the requested number,\n \/\/ but is it important to?\n return bs_->here.num_bits;\n }\n ~borrowed_bitset_that_always_clears_using_memset() {\n if(!bs_) return;\n bs_->here.bits.reset();\n return_bitset(bs_);\n }\nprivate:\n zeroable_bitset_node* bs_;\n};\n\n\n}\n\nusing borrowed_bitset_impl::borrowed_bitset;\nusing borrowed_bitset_impl::borrowed_bitset_that_always_clears_using_memset;\n\n#endif\n\nreplace borrowed_bitset's use of dynamic_bitset with custom bitbuffer\/*\n\n Copyright Eli Dupree and Isaac Dupree, 2011, 2012\n\n This file is part of Lasercake.\n\n Lasercake is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Lasercake is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with Lasercake. If not, see .\n\n*\/\n\n#ifndef LASERCAKE_BORROWED_BITSET_HPP__\n#define LASERCAKE_BORROWED_BITSET_HPP__\n\n#include \n#include \n#include \n#include \/\/ for memset\n\n#include \"..\/utils.hpp\"\n#if 0 && !LASERCAKE_NO_THREADS\n#include \n#endif\n\ntypedef uint64_t bit_index_type;\n\nnamespace borrowed_bitset_impl {\n\n\/\/ Noncopying singly linked list that owns its members unless you pop them.\ntemplate\nstruct liststack_node : boost::noncopyable {\n liststack_node* next;\n T here;\n\n liststack_node() : next(nullptr), here() {}\n template\n explicit liststack_node(Arg const& arg, liststack_node* next = nullptr)\n : next(next), here(arg) {}\n ~liststack_node() { delete next; }\n};\n\ntemplate\nstruct liststack : boost::noncopyable {\n typedef borrowed_bitset_impl::liststack_node liststack_node;\n liststack_node* next;\n\n liststack() : next(nullptr) {}\n explicit liststack(liststack_node* next) : next(next) {}\n ~liststack() { delete next; }\n\n liststack_node* pop() {\n liststack_node* result = next;\n next = result->next;\n \/\/ for clarity:\n result->next = nullptr;\n return result;\n }\n void push(liststack_node* add) {\n add->next = next;\n next = add;\n }\n bool empty() {\n return next == nullptr;\n }\n};\n\n\/\/ reminiscent of boost::dynamic_bitset\n\/\/ should Block be a union instead?\n\/\/ There is no checking for invalid indexes.\n\/\/ In fact, after construction, it doesn't even *know* how large it is.\n\/\/ It's for the other parts of the code to keep track of which parts of that\n\/\/ they want to.\n\/\/\n\/\/ For bitset operations, on x86_64,\n\/\/ uint32_t appeared a bit faster than uint64_t as block-size for this.\ntemplate \nstruct bitbuffer : boost::noncopyable {\n typedef Block block_type;\n typedef ::bit_index_type bit_index_type;\n typedef size_t block_index_type;\n typedef int32_t block_width_type;\n static const block_width_type bits_per_block = std::numeric_limits::digits;\n block_type* buffer;\n bitbuffer() : buffer(nullptr) {}\n bitbuffer(bitbuffer&& other) {\n buffer = other.buffer;\n other.buffer = nullptr;\n }\n bitbuffer& operator=(bitbuffer&& other) {\n buffer = other.buffer;\n other.buffer = nullptr;\n }\n\n void new_zeroed_buffer_with_num_blocks(block_index_type num_blocks) {\n buffer = new block_type[num_blocks];\n reset_block_range(0, num_blocks);\n }\n void delete_buffer() {\n if(buffer) {delete[] buffer;}\n buffer = nullptr;\n }\n ~bitbuffer() {\n delete_buffer();\n }\n\n void reset_block_range(block_index_type begin, block_index_type count) {\n memset(buffer + begin, 0, count * sizeof(block_type));\n }\n\n void set_bit(bit_index_type pos) {\n buffer[block_index(pos)] |= bit_mask(pos);\n }\n void reset_bit(bit_index_type pos) {\n buffer[block_index(pos)] &= ~bit_mask(pos);\n }\n void set_bit(bit_index_type pos, bool val) {\n buffer[block_index(pos)] |= bit_mask_if(pos, val);\n buffer[block_index(pos)] &= ~bit_mask_if(pos, !val);\n }\n void flip_bit(bit_index_type pos) {\n buffer[block_index(pos)] ^= bit_mask(pos);\n }\n bool test_bit(bit_index_type pos)const {\n return bool(buffer[block_index(pos)] & bit_mask(pos));\n }\n\n void set_block(block_index_type pos, block_type val) {\n buffer[pos] = val;\n }\n void get_block(block_index_type pos)const {\n return buffer[pos];\n }\n\n static block_index_type block_index(bit_index_type pos) {\n return pos \/ bits_per_block;\n\n }\n static block_width_type bit_index(bit_index_type pos) {\n return static_cast(pos % bits_per_block);\n }\n static block_type bit_mask(bit_index_type pos) {\n return block_type(1) << bit_index(pos);\n }\n static block_type bit_mask_if(bit_index_type pos, bool val) {\n return block_type(val) << bit_index(pos);\n }\n};\n\nstruct zeroable_bitset {\n typedef bitbuffer<> bitbuffer_type;\n bit_index_type num_bits;\n bitbuffer_type bits;\n std::vector bits_to_clear;\n\n zeroable_bitset(bit_index_type num_bits) : num_bits(num_bits) {\n bits.new_zeroed_buffer_with_num_blocks(num_blocks_allocated());\n }\n size_t num_blocks_allocated()const {\n \/\/ Divide rounding up.\n return (num_bits + (bitbuffer_type::bits_per_block - 1)) \/ bitbuffer_type::bits_per_block;\n }\n};\n\ntypedef liststack zeroable_bitset_list;\n\/\/ node\/iterator\/such\ntypedef liststack_node zeroable_bitset_node;\n\nstatic const size_t array_of_bitset_lists_len = 40;\nstatic const size_t bit_to_min_size_exponent = 6;\n\/\/ if we track 4-8byteses individually, this exponent would be smaller.\nstatic const size_t bit_exponent_below_which_its_worth_tracking_bits_individually = 8;\n\n\/\/ array of array_of_bitset_lists_len sizes, from 2**bit_to_min_size_exponent bits up.\ntypedef zeroable_bitset_list* zeroable_bitset_array;\n\nextern thread_local zeroable_bitset_array array_of_bitset_lists;\n\ninline\nvoid delete_array_of_bitset_lists() { delete[] array_of_bitset_lists; }\n\ninline\nzeroable_bitset_array get_this_thread_array_of_bitset_lists() {\n if(array_of_bitset_lists == nullptr) {\n array_of_bitset_lists = new zeroable_bitset_list[array_of_bitset_lists_len];\n #if 0 && !LASERCAKE_NO_THREADS\n \/\/ No Boost.Thread for now; fewer deps.\n \/\/ Currently, the borrowed_bitset won't leak memory in Lasercake\n \/\/ because we only create a small, finite number of threads.\n \/\/ We'll use some better solution if that changes (TODO).\n try {\n \/\/ (note, if we use forcible thread cancelation, this won't run)\n \/\/ Also, donating them to another thread might be more useful\n \/\/ than deleting them.\n boost::this_thread::at_thread_exit(delete_array_of_bitset_lists);\n }\n catch(...) {\n delete array_of_bitset_lists;\n array_of_bitset_lists = nullptr;\n throw;\n }\n #endif\n }\n return array_of_bitset_lists;\n};\n\ninline size_t which_bitset_index_is_size(bit_index_type num_bits) {\n if(num_bits == 0) return 0;\n const bit_index_type max_bit_index = num_bits - 1;\n const bit_index_type max_8byte_index = max_bit_index >> bit_to_min_size_exponent;\n caller_error_if(max_8byte_index != size_t(max_8byte_index), \"More bits requested than your architecture can handle!\");\n const size_t which_bitset_size_index = num_bits_in_integer_that_are_not_leading_zeroes(max_8byte_index);\n caller_error_if(which_bitset_size_index >= array_of_bitset_lists_len, \"More bits requested than we support!\");\n return which_bitset_size_index;\n}\n\ninline bit_index_type how_many_bits_at_bitset_index(size_t bitset_index) {\n return bit_index_type(1) << (bitset_index + bit_to_min_size_exponent);\n}\n\ninline\nzeroable_bitset_node* borrow_bitset(bit_index_type num_bits_desired) {\n zeroable_bitset_array array_of_bitset_lists = get_this_thread_array_of_bitset_lists();\n const size_t which_bitset_size_index = which_bitset_index_is_size(num_bits_desired);\n const bit_index_type actual_bits = how_many_bits_at_bitset_index(which_bitset_size_index);\n assert(actual_bits >= num_bits_desired);\n assert(actual_bits < num_bits_desired*2 || actual_bits == (1<here.num_bits == actual_bits);\n return result;\n }\n else {\n return new zeroable_bitset_node(actual_bits);\n }\n}\n\ninline void return_bitset(zeroable_bitset_node* node) BOOST_NOEXCEPT {\n zeroable_bitset_array array_of_bitset_lists;\n try {\n array_of_bitset_lists = get_this_thread_array_of_bitset_lists();\n }\n catch(std::exception const&) {\n \/\/ This function is called from destructors so it must be nothrow.\n \/\/ In particular, this may happen if the destructor is called in a different\n \/\/ thread than the constructor was (std::bad_alloc or similar).\n delete node;\n return;\n }\n const size_t which_bitset_size_index = which_bitset_index_is_size(node->here.num_bits);\n array_of_bitset_lists[which_bitset_size_index].push(node);\n}\n\n\n\n\n\/\/ borrowed_bitset(n) borrows an array of zero bits of size n (rounded\n\/\/ up to something), and when destructed it restores the zeroes and returns\n\/\/ that array. (There's a dynamically allocated pool of arrays of zeroes\n\/\/ waiting to be borrowed; if none are available, borrowed_bitset allocates\n\/\/ a new one, which it will return to the pool when destructed.)\n\/\/\n\/\/ If there aren't too many borrowed_bitsets at once and program runs for\n\/\/ a while, borrowed_bitset() effectively has O(1) construction, and\n\/\/ destruction time <= the number of operations performed on it (so no worse\n\/\/ than a constant factor). This is pretty good for something this much\n\/\/ faster at uniquing than an unordered_set.\nclass borrowed_bitset : boost::noncopyable {\npublic:\n explicit borrowed_bitset(bit_index_type num_bits_desired) : bs_(borrow_bitset(num_bits_desired)) {}\n borrowed_bitset() : bs_(nullptr) {} \/\/default-constructing invalid bitsets is okay\n borrowed_bitset(borrowed_bitset&& other) { bs_ = other.bs_; other.bs_ = nullptr; }\n bool test(bit_index_type which)const {\n caller_correct_if(which < size(), \"borrowed_bitset bounds overflow\");\n return bs_->here.bits.test_bit(which);\n }\n bool set(bit_index_type which) {\n bool was_already_set = test(which);\n if(!was_already_set && tracking_bits_individually_()) {\n bs_->here.bits_to_clear.push_back(which);\n }\n bs_->here.bits.set_bit(which);\n return was_already_set;\n }\n bit_index_type size()const {\n \/\/ Implementation detail: this number might be greater than the number\n \/\/ requested by the constructor. We could store the requested number,\n \/\/ but is it important to?\n return bs_->here.num_bits;\n }\n ~borrowed_bitset() {\n if(!bs_) return;\n if(tracking_bits_individually_()) {\n for(bit_index_type which : bs_->here.bits_to_clear) {\n bs_->here.bits.reset_bit(which);\n }\n }\n else {\n \/\/ TODO optimization: store size of *this* buffer and only clear *that*.\n bs_->here.bits.reset_block_range(0, bs_->here.num_blocks_allocated());\n }\n bs_->here.bits_to_clear.clear();\n return_bitset(bs_);\n }\nprivate:\n bool tracking_bits_individually_() const {\n return bs_->here.bits_to_clear.size()\n < (bs_->here.num_bits >> bit_exponent_below_which_its_worth_tracking_bits_individually);\n }\n zeroable_bitset_node* bs_;\n};\n\n\n\/\/ If you know ahead of time that you're going to set most of the bits,\n\/\/ this will give a small constant-factor speed improvement over\n\/\/ borrowed_bitset.\nclass borrowed_bitset_that_always_clears_using_memset : boost::noncopyable {\npublic:\n explicit borrowed_bitset_that_always_clears_using_memset(bit_index_type num_bits_desired)\n : bs_(borrow_bitset(num_bits_desired)) {}\n borrowed_bitset_that_always_clears_using_memset()\n : bs_(nullptr) {} \/\/default-constructing invalid bitsets is okay\n borrowed_bitset_that_always_clears_using_memset(borrowed_bitset_that_always_clears_using_memset&& other)\n { bs_ = other.bs_; other.bs_ = nullptr; }\n bool test(bit_index_type which)const {\n caller_correct_if(which < size(), \"borrowed_bitset bounds overflow\");\n return bs_->here.bits.test_bit(which);\n }\n bool set(bit_index_type which) {\n bool was_already_set = test(which);\n bs_->here.bits.set_bit(which);\n return was_already_set;\n }\n bit_index_type size()const {\n \/\/ Implementation detail: this number might be greater than the number\n \/\/ requested by the constructor. We could store the requested number,\n \/\/ but is it important to?\n return bs_->here.num_bits;\n }\n ~borrowed_bitset_that_always_clears_using_memset() {\n if(!bs_) return;\n bs_->here.bits.reset_block_range(0, bs_->here.num_blocks_allocated());\n return_bitset(bs_);\n }\nprivate:\n zeroable_bitset_node* bs_;\n};\n\n\n}\n\nusing borrowed_bitset_impl::borrowed_bitset;\nusing borrowed_bitset_impl::borrowed_bitset_that_always_clears_using_memset;\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nBOOST_FIXTURE_TEST_SUITE(policyestimator_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(BlockPolicyEstimates)\n{\n CBlockPolicyEstimator feeEst;\n CTxMemPool mpool(&feeEst);\n LOCK2(cs_main, mpool.cs);\n TestMemPoolEntryHelper entry;\n CAmount basefee(2000);\n CAmount deltaFee(100);\n std::vector feeV;\n\n \/\/ Populate vectors of increasing fees\n for (int j = 0; j < 10; j++) {\n feeV.push_back(basefee * (j+1));\n }\n\n \/\/ Store the hashes of transactions that have been\n \/\/ added to the mempool by their associate fee\n \/\/ txHashes[j] is populated with transactions either of\n \/\/ fee = basefee * (j+1)\n std::vector txHashes[10];\n\n \/\/ Create a transaction template\n CScript garbage;\n for (unsigned int i = 0; i < 128; i++)\n garbage.push_back('X');\n CMutableTransaction tx;\n tx.vin.resize(1);\n tx.vin[0].scriptSig = garbage;\n tx.vout.resize(1);\n tx.vout[0].nValue=0LL;\n CFeeRate baseRate(basefee, GetVirtualTransactionSize(CTransaction(tx)));\n\n \/\/ Create a fake block\n std::vector block;\n int blocknum = 0;\n\n \/\/ Loop through 200 blocks\n \/\/ At a decay .9952 and 4 fee transactions per block\n \/\/ This makes the tx count about 2.5 per bucket, well above the 0.1 threshold\n while (blocknum < 200) {\n for (int j = 0; j < 10; j++) { \/\/ For each fee\n for (int k = 0; k < 4; k++) { \/\/ add 4 fee txs\n tx.vin[0].prevout.n = 10000*blocknum+100*j+k; \/\/ make transaction unique\n uint256 hash = tx.GetHash();\n mpool.addUnchecked(entry.Fee(feeV[j]).Time(GetTime()).Height(blocknum).FromTx(tx));\n txHashes[j].push_back(hash);\n }\n }\n \/\/Create blocks where higher fee txs are included more often\n for (int h = 0; h <= blocknum%10; h++) {\n \/\/ 10\/10 blocks add highest fee transactions\n \/\/ 9\/10 blocks add 2nd highest and so on until ...\n \/\/ 1\/10 blocks add lowest fee transactions\n while (txHashes[9-h].size()) {\n CTransactionRef ptx = mpool.get(txHashes[9-h].back());\n if (ptx)\n block.push_back(ptx);\n txHashes[9-h].pop_back();\n }\n }\n mpool.removeForBlock(block, ++blocknum);\n block.clear();\n \/\/ Check after just a few txs that combining buckets works as expected\n if (blocknum == 3) {\n \/\/ At this point we should need to combine 3 buckets to get enough data points\n \/\/ So estimateFee(1) should fail and estimateFee(2) should return somewhere around\n \/\/ 9*baserate. estimateFee(2) %'s are 100,100,90 = average 97%\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n BOOST_CHECK(feeEst.estimateFee(2).GetFeePerK() < 9*baseRate.GetFeePerK() + deltaFee);\n BOOST_CHECK(feeEst.estimateFee(2).GetFeePerK() > 9*baseRate.GetFeePerK() - deltaFee);\n }\n }\n\n std::vector origFeeEst;\n \/\/ Highest feerate is 10*baseRate and gets in all blocks,\n \/\/ second highest feerate is 9*baseRate and gets in 9\/10 blocks = 90%,\n \/\/ third highest feerate is 8*base rate, and gets in 8\/10 blocks = 80%,\n \/\/ so estimateFee(1) would return 10*baseRate but is hardcoded to return failure\n \/\/ Second highest feerate has 100% chance of being included by 2 blocks,\n \/\/ so estimateFee(2) should return 9*baseRate etc...\n for (int i = 1; i < 10;i++) {\n origFeeEst.push_back(feeEst.estimateFee(i).GetFeePerK());\n if (i > 2) { \/\/ Fee estimates should be monotonically decreasing\n BOOST_CHECK(origFeeEst[i-1] <= origFeeEst[i-2]);\n }\n int mult = 11-i;\n if (i % 2 == 0) { \/\/At scale 2, test logic is only correct for even targets\n BOOST_CHECK(origFeeEst[i-1] < mult*baseRate.GetFeePerK() + deltaFee);\n BOOST_CHECK(origFeeEst[i-1] > mult*baseRate.GetFeePerK() - deltaFee);\n }\n }\n \/\/ Fill out rest of the original estimates\n for (int i = 10; i <= 48; i++) {\n origFeeEst.push_back(feeEst.estimateFee(i).GetFeePerK());\n }\n\n \/\/ Mine 50 more blocks with no transactions happening, estimates shouldn't change\n \/\/ We haven't decayed the moving average enough so we still have enough data points in every bucket\n while (blocknum < 250)\n mpool.removeForBlock(block, ++blocknum);\n\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n for (int i = 2; i < 10;i++) {\n BOOST_CHECK(feeEst.estimateFee(i).GetFeePerK() < origFeeEst[i-1] + deltaFee);\n BOOST_CHECK(feeEst.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);\n }\n\n\n \/\/ Mine 15 more blocks with lots of transactions happening and not getting mined\n \/\/ Estimates should go up\n while (blocknum < 265) {\n for (int j = 0; j < 10; j++) { \/\/ For each fee multiple\n for (int k = 0; k < 4; k++) { \/\/ add 4 fee txs\n tx.vin[0].prevout.n = 10000*blocknum+100*j+k;\n uint256 hash = tx.GetHash();\n mpool.addUnchecked(entry.Fee(feeV[j]).Time(GetTime()).Height(blocknum).FromTx(tx));\n txHashes[j].push_back(hash);\n }\n }\n mpool.removeForBlock(block, ++blocknum);\n }\n\n for (int i = 1; i < 10;i++) {\n BOOST_CHECK(feeEst.estimateFee(i) == CFeeRate(0) || feeEst.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);\n }\n\n \/\/ Mine all those transactions\n \/\/ Estimates should still not be below original\n for (int j = 0; j < 10; j++) {\n while(txHashes[j].size()) {\n CTransactionRef ptx = mpool.get(txHashes[j].back());\n if (ptx)\n block.push_back(ptx);\n txHashes[j].pop_back();\n }\n }\n mpool.removeForBlock(block, 266);\n block.clear();\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n for (int i = 2; i < 10;i++) {\n BOOST_CHECK(feeEst.estimateFee(i) == CFeeRate(0) || feeEst.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);\n }\n\n \/\/ Mine 400 more blocks where everything is mined every block\n \/\/ Estimates should be below original estimates\n while (blocknum < 665) {\n for (int j = 0; j < 10; j++) { \/\/ For each fee multiple\n for (int k = 0; k < 4; k++) { \/\/ add 4 fee txs\n tx.vin[0].prevout.n = 10000*blocknum+100*j+k;\n uint256 hash = tx.GetHash();\n mpool.addUnchecked(entry.Fee(feeV[j]).Time(GetTime()).Height(blocknum).FromTx(tx));\n CTransactionRef ptx = mpool.get(hash);\n if (ptx)\n block.push_back(ptx);\n\n }\n }\n mpool.removeForBlock(block, ++blocknum);\n block.clear();\n }\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n for (int i = 2; i < 9; i++) { \/\/ At 9, the original estimate was already at the bottom (b\/c scale = 2)\n BOOST_CHECK(feeEst.estimateFee(i).GetFeePerK() < origFeeEst[i-1] - deltaFee);\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\ntest\/policyestimator: Use ChainTestingSetup's CTxMemPool\/\/ Copyright (c) 2011-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nBOOST_FIXTURE_TEST_SUITE(policyestimator_tests, ChainTestingSetup)\n\nBOOST_AUTO_TEST_CASE(BlockPolicyEstimates)\n{\n CBlockPolicyEstimator& feeEst = *Assert(m_node.fee_estimator);\n CTxMemPool& mpool = *Assert(m_node.mempool);\n LOCK2(cs_main, mpool.cs);\n TestMemPoolEntryHelper entry;\n CAmount basefee(2000);\n CAmount deltaFee(100);\n std::vector feeV;\n\n \/\/ Populate vectors of increasing fees\n for (int j = 0; j < 10; j++) {\n feeV.push_back(basefee * (j+1));\n }\n\n \/\/ Store the hashes of transactions that have been\n \/\/ added to the mempool by their associate fee\n \/\/ txHashes[j] is populated with transactions either of\n \/\/ fee = basefee * (j+1)\n std::vector txHashes[10];\n\n \/\/ Create a transaction template\n CScript garbage;\n for (unsigned int i = 0; i < 128; i++)\n garbage.push_back('X');\n CMutableTransaction tx;\n tx.vin.resize(1);\n tx.vin[0].scriptSig = garbage;\n tx.vout.resize(1);\n tx.vout[0].nValue=0LL;\n CFeeRate baseRate(basefee, GetVirtualTransactionSize(CTransaction(tx)));\n\n \/\/ Create a fake block\n std::vector block;\n int blocknum = 0;\n\n \/\/ Loop through 200 blocks\n \/\/ At a decay .9952 and 4 fee transactions per block\n \/\/ This makes the tx count about 2.5 per bucket, well above the 0.1 threshold\n while (blocknum < 200) {\n for (int j = 0; j < 10; j++) { \/\/ For each fee\n for (int k = 0; k < 4; k++) { \/\/ add 4 fee txs\n tx.vin[0].prevout.n = 10000*blocknum+100*j+k; \/\/ make transaction unique\n uint256 hash = tx.GetHash();\n mpool.addUnchecked(entry.Fee(feeV[j]).Time(GetTime()).Height(blocknum).FromTx(tx));\n txHashes[j].push_back(hash);\n }\n }\n \/\/Create blocks where higher fee txs are included more often\n for (int h = 0; h <= blocknum%10; h++) {\n \/\/ 10\/10 blocks add highest fee transactions\n \/\/ 9\/10 blocks add 2nd highest and so on until ...\n \/\/ 1\/10 blocks add lowest fee transactions\n while (txHashes[9-h].size()) {\n CTransactionRef ptx = mpool.get(txHashes[9-h].back());\n if (ptx)\n block.push_back(ptx);\n txHashes[9-h].pop_back();\n }\n }\n mpool.removeForBlock(block, ++blocknum);\n block.clear();\n \/\/ Check after just a few txs that combining buckets works as expected\n if (blocknum == 3) {\n \/\/ At this point we should need to combine 3 buckets to get enough data points\n \/\/ So estimateFee(1) should fail and estimateFee(2) should return somewhere around\n \/\/ 9*baserate. estimateFee(2) %'s are 100,100,90 = average 97%\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n BOOST_CHECK(feeEst.estimateFee(2).GetFeePerK() < 9*baseRate.GetFeePerK() + deltaFee);\n BOOST_CHECK(feeEst.estimateFee(2).GetFeePerK() > 9*baseRate.GetFeePerK() - deltaFee);\n }\n }\n\n std::vector origFeeEst;\n \/\/ Highest feerate is 10*baseRate and gets in all blocks,\n \/\/ second highest feerate is 9*baseRate and gets in 9\/10 blocks = 90%,\n \/\/ third highest feerate is 8*base rate, and gets in 8\/10 blocks = 80%,\n \/\/ so estimateFee(1) would return 10*baseRate but is hardcoded to return failure\n \/\/ Second highest feerate has 100% chance of being included by 2 blocks,\n \/\/ so estimateFee(2) should return 9*baseRate etc...\n for (int i = 1; i < 10;i++) {\n origFeeEst.push_back(feeEst.estimateFee(i).GetFeePerK());\n if (i > 2) { \/\/ Fee estimates should be monotonically decreasing\n BOOST_CHECK(origFeeEst[i-1] <= origFeeEst[i-2]);\n }\n int mult = 11-i;\n if (i % 2 == 0) { \/\/At scale 2, test logic is only correct for even targets\n BOOST_CHECK(origFeeEst[i-1] < mult*baseRate.GetFeePerK() + deltaFee);\n BOOST_CHECK(origFeeEst[i-1] > mult*baseRate.GetFeePerK() - deltaFee);\n }\n }\n \/\/ Fill out rest of the original estimates\n for (int i = 10; i <= 48; i++) {\n origFeeEst.push_back(feeEst.estimateFee(i).GetFeePerK());\n }\n\n \/\/ Mine 50 more blocks with no transactions happening, estimates shouldn't change\n \/\/ We haven't decayed the moving average enough so we still have enough data points in every bucket\n while (blocknum < 250)\n mpool.removeForBlock(block, ++blocknum);\n\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n for (int i = 2; i < 10;i++) {\n BOOST_CHECK(feeEst.estimateFee(i).GetFeePerK() < origFeeEst[i-1] + deltaFee);\n BOOST_CHECK(feeEst.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);\n }\n\n\n \/\/ Mine 15 more blocks with lots of transactions happening and not getting mined\n \/\/ Estimates should go up\n while (blocknum < 265) {\n for (int j = 0; j < 10; j++) { \/\/ For each fee multiple\n for (int k = 0; k < 4; k++) { \/\/ add 4 fee txs\n tx.vin[0].prevout.n = 10000*blocknum+100*j+k;\n uint256 hash = tx.GetHash();\n mpool.addUnchecked(entry.Fee(feeV[j]).Time(GetTime()).Height(blocknum).FromTx(tx));\n txHashes[j].push_back(hash);\n }\n }\n mpool.removeForBlock(block, ++blocknum);\n }\n\n for (int i = 1; i < 10;i++) {\n BOOST_CHECK(feeEst.estimateFee(i) == CFeeRate(0) || feeEst.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);\n }\n\n \/\/ Mine all those transactions\n \/\/ Estimates should still not be below original\n for (int j = 0; j < 10; j++) {\n while(txHashes[j].size()) {\n CTransactionRef ptx = mpool.get(txHashes[j].back());\n if (ptx)\n block.push_back(ptx);\n txHashes[j].pop_back();\n }\n }\n mpool.removeForBlock(block, 266);\n block.clear();\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n for (int i = 2; i < 10;i++) {\n BOOST_CHECK(feeEst.estimateFee(i) == CFeeRate(0) || feeEst.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);\n }\n\n \/\/ Mine 400 more blocks where everything is mined every block\n \/\/ Estimates should be below original estimates\n while (blocknum < 665) {\n for (int j = 0; j < 10; j++) { \/\/ For each fee multiple\n for (int k = 0; k < 4; k++) { \/\/ add 4 fee txs\n tx.vin[0].prevout.n = 10000*blocknum+100*j+k;\n uint256 hash = tx.GetHash();\n mpool.addUnchecked(entry.Fee(feeV[j]).Time(GetTime()).Height(blocknum).FromTx(tx));\n CTransactionRef ptx = mpool.get(hash);\n if (ptx)\n block.push_back(ptx);\n\n }\n }\n mpool.removeForBlock(block, ++blocknum);\n block.clear();\n }\n BOOST_CHECK(feeEst.estimateFee(1) == CFeeRate(0));\n for (int i = 2; i < 9; i++) { \/\/ At 9, the original estimate was already at the bottom (b\/c scale = 2)\n BOOST_CHECK(feeEst.estimateFee(i).GetFeePerK() < origFeeEst[i-1] - deltaFee);\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-\n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software\n * Foundation. See file COPYING.\n *\n *\/\n\n#include \"auth\/Auth.h\"\n#include \"common\/ceph_argparse.h\"\n#include \"common\/common_init.h\"\n#include \"common\/ConfUtils.h\"\n#include \"common\/version.h\"\n#include \"common\/config.h\"\n#include \"include\/intarith.h\"\n#include \"include\/str_list.h\"\n#include \"msg\/msg_types.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*\n * Ceph argument parsing library\n *\n * We probably should eventually replace this with something standard like popt.\n * Until we do that, though, this file is the place for argv parsing\n * stuff to live.\n *\/\n\n#undef dout\n#undef pdout\n#undef derr\n#undef generic_dout\n#undef dendl\n\nstatic bool cmd_is_char(const char *cmd)\n{\n return ((cmd[0] == '-') &&\n cmd[1] && !cmd[2]);\n}\n\nbool ceph_argparse_cmd_equals(const char *cmd, const char *opt, char char_opt,\n\t\t\t unsigned int *val_pos)\n{\n unsigned int i;\n unsigned int len = strlen(opt);\n\n *val_pos = 0;\n\n if (!*cmd)\n return false;\n\n if (char_opt && cmd_is_char(cmd))\n return (char_opt == cmd[1]);\n\n if ((cmd[0] != '-') || (cmd[1] != '-'))\n return false;\n\n for (i=0; i& args)\n{\n char *p = getenv(\"CEPH_ARGS\");\n if (!p) return;\n\n static char buf[1000];\n int len = MIN(strlen(p), sizeof(buf)-1); \/\/ bleh.\n memcpy(buf, p, len);\n buf[len] = 0;\n\n p = buf;\n while (*p && p < buf + len) {\n char *e = p;\n while (*e && *e != ' ')\n e++;\n *e = 0;\n args.push_back(p);\n p = e+1;\n }\n}\n\nvoid argv_to_vec(int argc, const char **argv,\n std::vector& args)\n{\n for (int i=1; i& args)\n{\n for (int i=1; i& args,\n int& argc, const char **&argv)\n{\n const char *myname = \"asdf\";\n if (argc && argv)\n myname = argv[0];\n argv = (const char**)malloc(sizeof(char*) * argc);\n argc = 1;\n argv[0] = myname;\n\n for (unsigned i=0; i& vec)\n{\n const char *p = s;\n const char *end = p + strlen(p);\n while (p < end) {\n entity_addr_t a;\n \/\/cout << \" parse at '\" << p << \"'\" << std::endl;\n if (!a.parse(p, &p)) {\n \/\/dout(0) << \" failed to parse address '\" << p << \"'\" << dendl;\n return false;\n }\n \/\/cout << \" got \" << a << \", rest is '\" << p << \"'\" << std::endl;\n vec.push_back(a);\n while (*p == ',' || *p == ' ')\n p++;\n }\n return true;\n}\n\nvoid parse_config_option_string(std::string& s)\n{\n char b[s.length()+1];\n strcpy(b, s.c_str());\n std::vector nargs;\n char *p = b;\n while (*p) {\n nargs.push_back(p);\n while (*p && *p != ' ') p++;\n if (!*p)\n break;\n *p++ = 0;\n while (*p && *p == ' ') p++;\n }\n g_conf.parse_argv(nargs);\n}\n\n\/\/ The defaults for CephInitParameters\nCephInitParameters::CephInitParameters(uint32_t module_type, const char *conf_file_)\n : conf_file(conf_file_)\n{\n const char *c = getenv(\"CEPH_CONF\");\n if (c)\n conf_file = c;\n name.set(module_type, \"admin\");\n}\n\nstd::list CephInitParameters::\nget_conf_files() const\n{\n std::list ret;\n get_str_list(conf_file, ret);\n return ret;\n}\n\nstatic void dashes_to_underscores(const char *input, char *output)\n{\n char c = 0;\n char *o = output;\n const char *i = input;\n \/\/ first two characters are copied as-is\n *o = *i++;\n if (*o++ == '\\0')\n return;\n *o = *i++;\n if (*o++ == '\\0')\n return;\n for (; ((c = *i)); ++i) {\n if (c == '-')\n *o++ = '_';\n else\n *o++ = c;\n }\n *o++ = '\\0';\n}\n\nbool ceph_argparse_flag(std::vector &args,\n\tstd::vector::iterator &i, ...)\n{\n const char *first = *i;\n char tmp[strlen(first)+1];\n dashes_to_underscores(first, tmp);\n first = tmp;\n const char *a;\n va_list ap;\n\n va_start(ap, i);\n while (1) {\n a = va_arg(ap, char*);\n if (a == NULL)\n return false;\n if (strcmp(a, first) == 0) {\n i = args.erase(i);\n return true;\n }\n }\n}\n\nbool ceph_argparse_witharg(std::vector &args,\n\tstd::vector::iterator &i, std::string *ret, ...)\n{\n const char *first = *i;\n char tmp[strlen(first)+1];\n dashes_to_underscores(first, tmp);\n first = tmp;\n const char *a;\n va_list ap;\n int strlen_a;\n\n \/\/ does this argument match any of the possibilities?\n va_start(ap, ret);\n while (1) {\n a = va_arg(ap, char*);\n if (a == NULL)\n return false;\n strlen_a = strlen(a);\n if (strncmp(a, first, strlen(a)) == 0) {\n if (first[strlen_a] == '=') {\n\t*ret = first + strlen_a + 1;\n\ti = args.erase(i);\n\treturn true;\n }\n else if (first[strlen_a] == '\\0') {\n\t\/\/ find second part (or not)\n\tif (i+1 == args.end()) {\n\t std::cerr << \"Option \" << *i << \" requires an argument.\" << std::endl;\n\t _exit(1);\n\t}\n\ti = args.erase(i);\n\t*ret = *i;\n\ti = args.erase(i);\n\treturn true;\n }\n }\n }\n}\n\nCephInitParameters ceph_argparse_early_args\n\t (std::vector& args, uint32_t module_type, int flags)\n{\n const char *conf = (flags & CINIT_FLAG_NO_DEFAULT_CONFIG_FILE) ?\n \"\" : CEPH_CONF_FILE_DEFAULT;\n CephInitParameters iparams(module_type, conf);\n std::string val;\n for (std::vector::iterator i = args.begin(); i != args.end(); ) {\n if (strcmp(*i, \"--\") == 0)\n break;\n else if (ceph_argparse_flag(args, i, \"--version\", \"-v\", (char*)NULL)) {\n cout << pretty_version_to_str() << std::endl;\n _exit(0);\n }\n else if (ceph_argparse_witharg(args, i, &val, \"--conf\", \"-c\", (char*)NULL)) {\n iparams.conf_file = val;\n }\n else if ((module_type != CEPH_ENTITY_TYPE_CLIENT) &&\n\t (ceph_argparse_witharg(args, i, &val, \"-i\", (char*)NULL))) {\n iparams.name.set_id(val);\n }\n else if (ceph_argparse_witharg(args, i, &val, \"--id\", (char*)NULL)) {\n iparams.name.set_id(val);\n }\n else if (ceph_argparse_witharg(args, i, &val, \"--name\", \"-n\", (char*)NULL)) {\n if (!iparams.name.from_str(val)) {\n\tstd::cerr << \"You must pass a string of the form ID.TYPE to \"\n\t \"the --name option.\" << std::endl;\n\t_exit(1);\n }\n }\n else {\n \/\/ ignore\n ++i;\n }\n }\n return iparams;\n}\n\nstatic void generic_usage(bool is_server)\n{\n cout << \"\\\n--conf\/-c Read configuration from the given configuration file\\n\\\n-D Run in the foreground.\\n\\\n-f Run in foreground. Show all log messages on stderr.\\n\\\n--id set ID\\n\\\n--name set ID.TYPE\\n\\\n--version show version and quit\\n\\\n\" << std::endl;\n\n if (is_server) {\n cout << \" --debug_ms N\\n\";\n cout << \" set message debug level (e.g. 1)\\n\";\n }\n}\n\nvoid generic_server_usage()\n{\n generic_usage(true);\n exit(1);\n}\nvoid generic_client_usage()\n{\n generic_usage(false);\n exit(1);\n}\nceph_argparse: fix silly usage message\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-\n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software\n * Foundation. See file COPYING.\n *\n *\/\n\n#include \"auth\/Auth.h\"\n#include \"common\/ceph_argparse.h\"\n#include \"common\/common_init.h\"\n#include \"common\/ConfUtils.h\"\n#include \"common\/version.h\"\n#include \"common\/config.h\"\n#include \"include\/intarith.h\"\n#include \"include\/str_list.h\"\n#include \"msg\/msg_types.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*\n * Ceph argument parsing library\n *\n * We probably should eventually replace this with something standard like popt.\n * Until we do that, though, this file is the place for argv parsing\n * stuff to live.\n *\/\n\n#undef dout\n#undef pdout\n#undef derr\n#undef generic_dout\n#undef dendl\n\nstatic bool cmd_is_char(const char *cmd)\n{\n return ((cmd[0] == '-') &&\n cmd[1] && !cmd[2]);\n}\n\nbool ceph_argparse_cmd_equals(const char *cmd, const char *opt, char char_opt,\n\t\t\t unsigned int *val_pos)\n{\n unsigned int i;\n unsigned int len = strlen(opt);\n\n *val_pos = 0;\n\n if (!*cmd)\n return false;\n\n if (char_opt && cmd_is_char(cmd))\n return (char_opt == cmd[1]);\n\n if ((cmd[0] != '-') || (cmd[1] != '-'))\n return false;\n\n for (i=0; i& args)\n{\n char *p = getenv(\"CEPH_ARGS\");\n if (!p) return;\n\n static char buf[1000];\n int len = MIN(strlen(p), sizeof(buf)-1); \/\/ bleh.\n memcpy(buf, p, len);\n buf[len] = 0;\n\n p = buf;\n while (*p && p < buf + len) {\n char *e = p;\n while (*e && *e != ' ')\n e++;\n *e = 0;\n args.push_back(p);\n p = e+1;\n }\n}\n\nvoid argv_to_vec(int argc, const char **argv,\n std::vector& args)\n{\n for (int i=1; i& args)\n{\n for (int i=1; i& args,\n int& argc, const char **&argv)\n{\n const char *myname = \"asdf\";\n if (argc && argv)\n myname = argv[0];\n argv = (const char**)malloc(sizeof(char*) * argc);\n argc = 1;\n argv[0] = myname;\n\n for (unsigned i=0; i& vec)\n{\n const char *p = s;\n const char *end = p + strlen(p);\n while (p < end) {\n entity_addr_t a;\n \/\/cout << \" parse at '\" << p << \"'\" << std::endl;\n if (!a.parse(p, &p)) {\n \/\/dout(0) << \" failed to parse address '\" << p << \"'\" << dendl;\n return false;\n }\n \/\/cout << \" got \" << a << \", rest is '\" << p << \"'\" << std::endl;\n vec.push_back(a);\n while (*p == ',' || *p == ' ')\n p++;\n }\n return true;\n}\n\nvoid parse_config_option_string(std::string& s)\n{\n char b[s.length()+1];\n strcpy(b, s.c_str());\n std::vector nargs;\n char *p = b;\n while (*p) {\n nargs.push_back(p);\n while (*p && *p != ' ') p++;\n if (!*p)\n break;\n *p++ = 0;\n while (*p && *p == ' ') p++;\n }\n g_conf.parse_argv(nargs);\n}\n\n\/\/ The defaults for CephInitParameters\nCephInitParameters::CephInitParameters(uint32_t module_type, const char *conf_file_)\n : conf_file(conf_file_)\n{\n const char *c = getenv(\"CEPH_CONF\");\n if (c)\n conf_file = c;\n name.set(module_type, \"admin\");\n}\n\nstd::list CephInitParameters::\nget_conf_files() const\n{\n std::list ret;\n get_str_list(conf_file, ret);\n return ret;\n}\n\nstatic void dashes_to_underscores(const char *input, char *output)\n{\n char c = 0;\n char *o = output;\n const char *i = input;\n \/\/ first two characters are copied as-is\n *o = *i++;\n if (*o++ == '\\0')\n return;\n *o = *i++;\n if (*o++ == '\\0')\n return;\n for (; ((c = *i)); ++i) {\n if (c == '-')\n *o++ = '_';\n else\n *o++ = c;\n }\n *o++ = '\\0';\n}\n\nbool ceph_argparse_flag(std::vector &args,\n\tstd::vector::iterator &i, ...)\n{\n const char *first = *i;\n char tmp[strlen(first)+1];\n dashes_to_underscores(first, tmp);\n first = tmp;\n const char *a;\n va_list ap;\n\n va_start(ap, i);\n while (1) {\n a = va_arg(ap, char*);\n if (a == NULL)\n return false;\n if (strcmp(a, first) == 0) {\n i = args.erase(i);\n return true;\n }\n }\n}\n\nbool ceph_argparse_witharg(std::vector &args,\n\tstd::vector::iterator &i, std::string *ret, ...)\n{\n const char *first = *i;\n char tmp[strlen(first)+1];\n dashes_to_underscores(first, tmp);\n first = tmp;\n const char *a;\n va_list ap;\n int strlen_a;\n\n \/\/ does this argument match any of the possibilities?\n va_start(ap, ret);\n while (1) {\n a = va_arg(ap, char*);\n if (a == NULL)\n return false;\n strlen_a = strlen(a);\n if (strncmp(a, first, strlen(a)) == 0) {\n if (first[strlen_a] == '=') {\n\t*ret = first + strlen_a + 1;\n\ti = args.erase(i);\n\treturn true;\n }\n else if (first[strlen_a] == '\\0') {\n\t\/\/ find second part (or not)\n\tif (i+1 == args.end()) {\n\t std::cerr << \"Option \" << *i << \" requires an argument.\" << std::endl;\n\t _exit(1);\n\t}\n\ti = args.erase(i);\n\t*ret = *i;\n\ti = args.erase(i);\n\treturn true;\n }\n }\n }\n}\n\nCephInitParameters ceph_argparse_early_args\n\t (std::vector& args, uint32_t module_type, int flags)\n{\n const char *conf = (flags & CINIT_FLAG_NO_DEFAULT_CONFIG_FILE) ?\n \"\" : CEPH_CONF_FILE_DEFAULT;\n CephInitParameters iparams(module_type, conf);\n std::string val;\n for (std::vector::iterator i = args.begin(); i != args.end(); ) {\n if (strcmp(*i, \"--\") == 0)\n break;\n else if (ceph_argparse_flag(args, i, \"--version\", \"-v\", (char*)NULL)) {\n cout << pretty_version_to_str() << std::endl;\n _exit(0);\n }\n else if (ceph_argparse_witharg(args, i, &val, \"--conf\", \"-c\", (char*)NULL)) {\n iparams.conf_file = val;\n }\n else if ((module_type != CEPH_ENTITY_TYPE_CLIENT) &&\n\t (ceph_argparse_witharg(args, i, &val, \"-i\", (char*)NULL))) {\n iparams.name.set_id(val);\n }\n else if (ceph_argparse_witharg(args, i, &val, \"--id\", (char*)NULL)) {\n iparams.name.set_id(val);\n }\n else if (ceph_argparse_witharg(args, i, &val, \"--name\", \"-n\", (char*)NULL)) {\n if (!iparams.name.from_str(val)) {\n\tstd::cerr << \"You must pass a string of the form TYPE.ID to \"\n\t \"the --name option.\" << std::endl;\n\t_exit(1);\n }\n }\n else {\n \/\/ ignore\n ++i;\n }\n }\n return iparams;\n}\n\nstatic void generic_usage(bool is_server)\n{\n cout << \"\\\n--conf\/-c Read configuration from the given configuration file\\n\\\n-D Run in the foreground.\\n\\\n-f Run in foreground. Show all log messages on stderr.\\n\\\n--id set ID\\n\\\n--name set ID.TYPE\\n\\\n--version show version and quit\\n\\\n\" << std::endl;\n\n if (is_server) {\n cout << \" --debug_ms N\\n\";\n cout << \" set message debug level (e.g. 1)\\n\";\n }\n}\n\nvoid generic_server_usage()\n{\n generic_usage(true);\n exit(1);\n}\nvoid generic_client_usage()\n{\n generic_usage(false);\n exit(1);\n}\n<|endoftext|>"} {"text":"#include \"util.h\"\n\n#include \n#include \n\n#include \"chainparams.h\"\n#include \"key.h\"\n#include \"main.h\"\n#include \"pubkey.h\"\n#include \"txdb.h\"\n#include \"txmempool.h\"\n#include \"zerocoin_v3.h\"\n\n#include \"test\/fixtures.h\"\n#include \"test\/testutil.h\"\n\n#include \"wallet\/db.h\"\n#include \"wallet\/wallet.h\"\n\n#include \n#include \n#include \n\nBOOST_FIXTURE_TEST_SUITE(sigma_transition, ZerocoinTestingSetup200)\n\n\/*\n* 1. Create one denomination pair and check it can't be spend till 6 conf of mint\n* 2. Make one more mint of denom pair and check it can't be spend till 6 conf\n* 3. Create two spend transactions using same mint\n* 4. Double spend with previous spend in last block\n*\/\nBOOST_AUTO_TEST_CASE(sigma_transition_test)\n{\n sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState();\n string denomination;\n vector vtxid;\n\n denomination = \"1\";\n string stringError;\n \/\/ Make sure that transactions get to mempool\n pwalletMain->SetBroadcastTransactions(true);\n\n \/\/ Try to create a sigma mint. It must not be added to the mempool, because\n \/\/ Sigma is enabled at block \"nMintV3SigmaStartBlock=400 for regtest\".\n vector> denominationPairs;\n std::pair denominationPair(denomination, 1);\n denominationPairs.push_back(denominationPair);\n\n \/\/ Create 400-200+1 = 201 new empty blocks. \/\/ consensus.nMintV3SigmaStartBlock = 400\n CreateAndProcessEmptyBlocks(201, scriptPubKey);\n\n \/\/ Create a zerocoin mint, it must still pass.\n BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(\n stringError, denominationPairs, ZEROCOIN), stringError + \" - Create Mint failed\");\n BOOST_CHECK_MESSAGE(mempool.size() == 1, \"Mint was not added to mempool\");\n\n \/\/ Sigma mints must also pass.\n BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(\n stringError, denominationPairs, SIGMA), stringError + \" - Create Mint failed\");\n BOOST_CHECK_MESSAGE(mempool.size() == 2, \"Mint was not added to mempool\");\n\n \/\/ Both transactions must be able to be added to the next block.\n int previousHeight = chainActive.Height();\n CBlock b = CreateAndProcessBlock({}, scriptPubKey);\n BOOST_CHECK_MESSAGE(previousHeight + 1 == chainActive.Height(), \"Block not added to chain\");\n BOOST_CHECK_MESSAGE(mempool.size() == 0, \"Expected empty mempool.\");\n\n \/\/ Create some zerocoin mints.\n for (int i = 0; i < 5; ++i) {\n BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(\n stringError, denominationPairs, ZEROCOIN), stringError + \" - Create Mint failed\");\n }\n BOOST_CHECK_MESSAGE(mempool.size() == 5, \"Mint was not added to mempool\");\n\n vtxid.clear();\n mempool.queryHashes(vtxid);\n vtxid.resize(1);\n\n \/\/ Process one more block. After this one, old zerocoin mints must not be allowed to mempool\n \/\/ any more, because for regtest consensus.nMintV2MempoolGracefulPeriod = 2.\n previousHeight = chainActive.Height();\n\n b = CreateAndProcessBlock(vtxid, scriptPubKey);\n BOOST_CHECK_MESSAGE(previousHeight + 1 == chainActive.Height(), \"Block not added to chain\");\n\n \/\/ Now this new mint must not be added to the mempool any more,\n \/\/ because consensus.nMintV2MempoolGracefulPeriod = 2;\n BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(\n stringError, denominationPairs, ZEROCOIN), stringError + \" - Create Mint failed\");\n\n \/\/ Check that mempool size did not change, so this mint was not added.\n BOOST_CHECK_MESSAGE(mempool.size() == 4, \"Mint was added to mempool, but not expected to.\");\n\n \/\/ Create 1 more block. All the mints must pass.\n previousHeight = chainActive.Height();\n b = CreateAndProcessBlock({}, scriptPubKey);\n BOOST_CHECK_MESSAGE(previousHeight + 1 == chainActive.Height(), \"Block not added to chain\");\n\n \/\/ Check that mempool got empty.\n BOOST_CHECK_MESSAGE(mempool.size() == 0, \"Mempool did not get empty.\");\n\n \/\/ Create 5 more empty blocks, so mints can be spent.\n CreateAndProcessEmptyBlocks(5, scriptPubKey);\n\n \/\/ Add an old spend to mempool.\n BOOST_CHECK_MESSAGE(\n pwalletMain->CreateZerocoinSpendModel(stringError, \"\", denomination.c_str(), false, true),\n \"Spend not added to the mempool.\");\n\n \/\/ Create a block containing old spend and try to add it to the chain.\n CBlock block = CreateBlock({}, scriptPubKey);\n\n \/\/ Create 5 more empty blocks, such that nZerocoinV2SpendStopBlock = 410 passes.\n CreateAndProcessEmptyBlocks(5, scriptPubKey);\n\n \/\/ Create an old spend, it must not be added to the mempool,\n \/\/ since nZerocoinV2SpendStopBlock = 410 have passed.\n BOOST_CHECK_MESSAGE(\n pwalletMain->CreateZerocoinSpendModel(stringError, \"\", denomination.c_str(), false, true),\n \"Spend not added to the mempool.\");\n BOOST_CHECK_MESSAGE(mempool.size() == 0, \"Spend added to the mempool, but must not be added.\");\n\n \/\/ Create 10 more empty blocks, such that nZerocoinV2SpendStopBlockInBlocks = 420 passes.\n CreateAndProcessEmptyBlocks(10, scriptPubKey);\n\n previousHeight = chainActive.Height();\n ProcessBlock(block);\n BOOST_CHECK_MESSAGE(previousHeight == chainActive.Height(),\n \"Block added to chain, but must have been rejected.\");\n\n vtxid.clear();\n mempool.clear();\n sigmaState->Reset();\n}\n\nBOOST_AUTO_TEST_SUITE_END()Fix transition test#include \"util.h\"\n\n#include \n#include \n\n#include \"chainparams.h\"\n#include \"key.h\"\n#include \"main.h\"\n#include \"pubkey.h\"\n#include \"txdb.h\"\n#include \"txmempool.h\"\n#include \"zerocoin_v3.h\"\n\n#include \"test\/fixtures.h\"\n#include \"test\/testutil.h\"\n\n#include \"wallet\/db.h\"\n#include \"wallet\/wallet.h\"\n\n#include \n#include \n#include \n\nBOOST_FIXTURE_TEST_SUITE(sigma_transition, ZerocoinTestingSetup200)\n\n\/*\n* 1. Create one denomination pair and check it can't be spend till 6 conf of mint\n* 2. Make one more mint of denom pair and check it can't be spend till 6 conf\n* 3. Create two spend transactions using same mint\n* 4. Double spend with previous spend in last block\n*\/\nBOOST_AUTO_TEST_CASE(sigma_transition_test)\n{\n sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState();\n string denomination;\n vector vtxid;\n\n denomination = \"1\";\n string stringError;\n \/\/ Make sure that transactions get to mempool\n pwalletMain->SetBroadcastTransactions(true);\n\n \/\/ Try to create a sigma mint. It must not be added to the mempool, because\n \/\/ Sigma is enabled at block \"nMintV3SigmaStartBlock=400 for regtest\".\n vector> denominationPairs;\n std::pair denominationPair(denomination, 2);\n denominationPairs.push_back(denominationPair);\n\n \/\/ Create 400-200+1 = 201 new empty blocks. \/\/ consensus.nMintV3SigmaStartBlock = 400\n CreateAndProcessEmptyBlocks(201, scriptPubKey);\n\n \/\/ Create a zerocoin mint, it must not pass.\n BOOST_CHECK_MESSAGE(!pwalletMain->CreateZerocoinMintModel(\n stringError, denominationPairs, ZEROCOIN), \"Zerocoin mint creation is success\");\n BOOST_CHECK_MESSAGE(mempool.size() == 0, \"Mint was added to mempool\");\n\n \/\/ Sigma mints must pass.\n BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(\n stringError, denominationPairs, SIGMA), stringError + \" - Create Mint failed\");\n BOOST_CHECK_MESSAGE(mempool.size() == 1, \"Mint was not added to mempool\");\n\n \/\/ a sigma mint transaction must be able to be added to the next block.\n int previousHeight = chainActive.Height();\n CBlock b = CreateAndProcessBlock({}, scriptPubKey);\n BOOST_CHECK_MESSAGE(previousHeight + 1 == chainActive.Height(), \"Block not added to chain\");\n BOOST_CHECK_MESSAGE(mempool.size() == 0, \"Expected empty mempool.\");\n\n \/\/ Create 5 more empty blocks, so mints can be spent.\n CreateAndProcessEmptyBlocks(5, scriptPubKey);\n\n \/\/ Try to spend zerocoin should fail.\n BOOST_CHECK_MESSAGE(\n !pwalletMain->CreateZerocoinSpendModel(stringError, \"\", denomination.c_str(), false, true),\n \"Create zerocoin spend is success.\");\n BOOST_CHECK_MESSAGE(mempool.size() == 0, \"Zerocoin spend was added to mempool\");\n\n \/\/ Try to spend zerocoin should be success.\n CWalletTx wtx;\n std::string thirdPartyAddress = \"TXYb6pEWBDcxQvTxbFQ9sEV1c3rWUPGW3v\";\n vector denominationsForTx = {denomination};\n BOOST_CHECK_MESSAGE(\n pwalletMain->CreateZerocoinSpendModel(wtx, stringError, thirdPartyAddress, denominationsForTx),\n stringError + \" - Spend failed\");\n BOOST_CHECK_MESSAGE(mempool.size() == 1, \"Sigma spend was not added to mempool\");\n\n previousHeight = chainActive.Height();\n CreateAndProcessBlock({}, scriptPubKey);\n BOOST_CHECK_MESSAGE(previousHeight + 1 == chainActive.Height(), \"Block not added to chain\");\n BOOST_CHECK_MESSAGE(mempool.size() == 0, \"Expected empty mempool.\");\n\n vtxid.clear();\n mempool.clear();\n sigmaState->Reset();\n}\n\nBOOST_AUTO_TEST_SUITE_END()<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mvdDatabaseBrowserWidget.h\"\n#include \"ui_mvdDatabaseBrowserWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Gui\/mvdDatabaseTreeWidget.h\"\n#include \"Gui\/mvdTreeWidgetItem.h\"\n\n#define ENABLE_DISPLAY_ID 1\n\nnamespace mvd\n{\n\n\/*\n TRANSLATOR mvd::DatabaseBrowserWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::DatabaseBrowserWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::DatabaseBrowserWidget() ),\n m_StartDragPosition(),\n m_SearchText()\n{\n m_UI->setupUi( this );\n\n SetupUI();\n\n \/*\n \/\/ Devember 12th, 2013 - Trainee example. \n QPushButton* button=new QPushButton (\"Click me\", this);\n layout()->addWidget(button);\n *\/\n\n \/\/\n \/\/ Forward signals.\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( ItemMoved( QTreeWidgetItem*, QTreeWidgetItem* ) ),\n \/\/ to:\n this,\n SIGNAL( ItemMoved( QTreeWidgetItem*, QTreeWidgetItem* ) )\n );\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( AddItemRequested( QTreeWidgetItem* ) ),\n \/\/ to:\n this,\n SIGNAL( AddItemRequested( QTreeWidgetItem* ) )\n );\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( DeleteItemRequested( QTreeWidgetItem* ) ),\n \/\/ to:\n this,\n SIGNAL( DeleteItemRequested( QTreeWidgetItem* ) )\n );\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( ItemTextChanged( QTreeWidgetItem*, int ) ),\n \/\/ to:\n this,\n SIGNAL( ItemTextChanged( QTreeWidgetItem*, int ) )\n );\n}\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::~DatabaseBrowserWidget()\n{\n delete m_UI;\n m_UI = NULL;\n}\n\n\/*****************************************************************************\/\nconst QTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem() const\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*****************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem()\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*****************************************************************************\/\nDatabaseBrowserWidget::QTreeWidgetItemList\nDatabaseBrowserWidget\n::GetItems() const\n{\n return\n m_UI->databaseTreeWidget->findItems(\n \"*\",\n Qt::MatchWildcard | Qt::MatchRecursive,\n 0\n );\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidgetTest\n::Clear()\n{\n m_UI->databaseTreeWidget->clear();\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertLeafItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_LEAF,\n text,\n id,\n columns\n );\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertItem( QTreeWidgetItem* parent,\n TreeWidgetItem::ItemType type,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n TreeWidgetItem* item =\n new TreeWidgetItem(\n parent,\n text,\n id,\n columns,\n type\n );\n\n return item;\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertNodeItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_NODE,\n text,\n id,\n columns\n );\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetupUI()\n{\n \/\/\n \/\/ Header columns.\n m_UI->databaseTreeWidget->headerItem()->setText( 1, \"Id\" );\n m_UI->databaseTreeWidget->headerItem()->setText( 2, \"Info\" );\n\n\/\/ Conditionaly display some usefull columns.\n\/\/ #if (!defined( _DEBUG ) && FORCE_DISABLE) || FORCE_ENABLE\n#if (!defined( _DEBUG ) && 1) || 0\n m_UI->databaseTreeWidget->setColumnHidden( 1, true );\n m_UI->databaseTreeWidget->setColumnHidden( 2, true );\n#endif\n\n \/\/ set placeholder text\n#if (QT_VERSION >= 0x407000)\n m_UI->m_SearchLine->setPlaceholderText( tr( \"Search Dataset...\" ) );\n#endif\n}\n\n\/*******************************************************************************\/\n\/*\nDatabaseTreeWidget*\nDatabaseBrowserWidget\n::GetDatabaseTreeWidget()\n{\n return m_UI->databaseTreeWidget;\n}\n*\/\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetCurrentDataset( const QString& hash )\n{\n \/\/ qDebug() << this << \"::SetCurrentDataset(\" << hash << \")\";\n\n#if QT_VERSION < QT_VERSION_CHECK( 4, 8, 1 )\n \/\/ Workaround for MANTIS-934 (crash\/memory corruption after having\n \/\/ imported second image).\n#else\n assert( m_UI!=NULL );\n assert( m_UI->databaseTreeWidget!=NULL );\n\n QList< QTreeWidgetItem* > items(\n m_UI->databaseTreeWidget->findItems(\n hash,\n Qt::MatchExactly | Qt::MatchRecursive,\n TreeWidgetItem::COLUMN_INDEX_HASH\n )\n );\n\n assert( items.isEmpty() || items.size() == 1 );\n\n \/\/ qDebug()\n \/\/ << ( items.isEmpty() ? \"NONE\" : items.first()->text( 0 ) )\n \/\/ << m_UI->databaseTreeWidget->selectionModel()->selectedIndexes().size();\n\n m_UI->databaseTreeWidget->setCurrentItem(\n items.isEmpty()\n ? NULL\n : items.first(),\n TreeWidgetItem::COLUMN_INDEX_TEXT,\n QItemSelectionModel::Clear |\n QItemSelectionModel::Select |\n QItemSelectionModel::Current\n );\n#endif\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::InstallTreeEventFilter( QObject* eventFilter )\n{\n m_UI->databaseTreeWidget->installEventFilter( eventFilter );\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_databaseTreeWidget_currentItemChanged( QTreeWidgetItem* current,\n\t\t\t\t\t QTreeWidgetItem* previous )\n{\n \/\/\n \/\/ Current\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString currentHash;\n\n TreeWidgetItem* currentItem = dynamic_cast< TreeWidgetItem* >( current );\n\n if( currentItem!=NULL && currentItem->parent()!=NULL )\n \/\/ if current is root and not NULL get the Id of the corresponding\n \/\/ Dataset.\n currentHash = currentItem->GetHash();\n\n \/\/\n \/\/ Previous\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString previousHash;\n\n TreeWidgetItem* previousItem = dynamic_cast< TreeWidgetItem* >( previous );\n\n if( previousItem!=NULL )\n previousHash = previousItem->GetHash();\n\n \/\/\n \/\/ Emit event.\n emit CurrentDatasetChanged( currentHash, previousHash );\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_m_SearchLine_textChanged( const QString& search )\n{\n \/\/ qDebug() << this << \"on_m_SearchLine_textChanged(\" << search << \")\";\n\n \/\/\n \/\/ get the search text\n m_SearchText = search;\n\n QTreeWidgetItemList items( GetItems() );\n\n \/\/ qDebug() << items;\n\n for( QTreeWidgetItemList::iterator it( items.begin() );\n it!=items.end();\n ++it )\n {\n QTreeWidgetItem* qtwi = *it;\n assert( qtwi!=NULL );\n\n assert( qtwi==dynamic_cast< TreeWidgetItem* >( qtwi ) );\n TreeWidgetItem* item = dynamic_cast< TreeWidgetItem* >( qtwi );\n\n if( item==NULL )\n {\n \/\/ TODO: Implement general case when needed.\n }\n else\n {\n item->setHidden(\n item->GetType()==TreeWidgetItem::ITEM_TYPE_LEAF &&\n !item->GetText().contains( search, Qt::CaseInsensitive )\n );\n }\n\n \/\/ qDebug()\n \/\/ << item->text( 0 ) << \":\" << ( item->isHidden() ? \"HIDDEN\" : \"VISIBLE\" );\n }\n}\n\n} \/\/ end namespace 'mvd'\nCOMP: Fixed error.\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mvdDatabaseBrowserWidget.h\"\n#include \"ui_mvdDatabaseBrowserWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Gui\/mvdDatabaseTreeWidget.h\"\n#include \"Gui\/mvdTreeWidgetItem.h\"\n\n#define ENABLE_DISPLAY_ID 1\n\nnamespace mvd\n{\n\n\/*\n TRANSLATOR mvd::DatabaseBrowserWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::DatabaseBrowserWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::DatabaseBrowserWidget() ),\n m_StartDragPosition(),\n m_SearchText()\n{\n m_UI->setupUi( this );\n\n SetupUI();\n\n \/*\n \/\/ Devember 12th, 2013 - Trainee example. \n QPushButton* button=new QPushButton (\"Click me\", this);\n layout()->addWidget(button);\n *\/\n\n \/\/\n \/\/ Forward signals.\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( ItemMoved( QTreeWidgetItem*, QTreeWidgetItem* ) ),\n \/\/ to:\n this,\n SIGNAL( ItemMoved( QTreeWidgetItem*, QTreeWidgetItem* ) )\n );\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( AddItemRequested( QTreeWidgetItem* ) ),\n \/\/ to:\n this,\n SIGNAL( AddItemRequested( QTreeWidgetItem* ) )\n );\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( DeleteItemRequested( QTreeWidgetItem* ) ),\n \/\/ to:\n this,\n SIGNAL( DeleteItemRequested( QTreeWidgetItem* ) )\n );\n\n QObject::connect(\n m_UI->databaseTreeWidget,\n SIGNAL( ItemTextChanged( QTreeWidgetItem*, int ) ),\n \/\/ to:\n this,\n SIGNAL( ItemTextChanged( QTreeWidgetItem*, int ) )\n );\n}\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::~DatabaseBrowserWidget()\n{\n delete m_UI;\n m_UI = NULL;\n}\n\n\/*****************************************************************************\/\nconst QTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem() const\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*****************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem()\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*****************************************************************************\/\nDatabaseBrowserWidget::QTreeWidgetItemList\nDatabaseBrowserWidget\n::GetItems() const\n{\n return\n m_UI->databaseTreeWidget->findItems(\n \"*\",\n Qt::MatchWildcard | Qt::MatchRecursive,\n 0\n );\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::Clear()\n{\n m_UI->databaseTreeWidget->clear();\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertLeafItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_LEAF,\n text,\n id,\n columns\n );\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertItem( QTreeWidgetItem* parent,\n TreeWidgetItem::ItemType type,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n TreeWidgetItem* item =\n new TreeWidgetItem(\n parent,\n text,\n id,\n columns,\n type\n );\n\n return item;\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertNodeItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_NODE,\n text,\n id,\n columns\n );\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetupUI()\n{\n \/\/\n \/\/ Header columns.\n m_UI->databaseTreeWidget->headerItem()->setText( 1, \"Id\" );\n m_UI->databaseTreeWidget->headerItem()->setText( 2, \"Info\" );\n\n\/\/ Conditionaly display some usefull columns.\n\/\/ #if (!defined( _DEBUG ) && FORCE_DISABLE) || FORCE_ENABLE\n#if (!defined( _DEBUG ) && 1) || 0\n m_UI->databaseTreeWidget->setColumnHidden( 1, true );\n m_UI->databaseTreeWidget->setColumnHidden( 2, true );\n#endif\n\n \/\/ set placeholder text\n#if (QT_VERSION >= 0x407000)\n m_UI->m_SearchLine->setPlaceholderText( tr( \"Search Dataset...\" ) );\n#endif\n}\n\n\/*******************************************************************************\/\n\/*\nDatabaseTreeWidget*\nDatabaseBrowserWidget\n::GetDatabaseTreeWidget()\n{\n return m_UI->databaseTreeWidget;\n}\n*\/\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetCurrentDataset( const QString& hash )\n{\n \/\/ qDebug() << this << \"::SetCurrentDataset(\" << hash << \")\";\n\n#if QT_VERSION < QT_VERSION_CHECK( 4, 8, 1 )\n \/\/ Workaround for MANTIS-934 (crash\/memory corruption after having\n \/\/ imported second image).\n#else\n assert( m_UI!=NULL );\n assert( m_UI->databaseTreeWidget!=NULL );\n\n QList< QTreeWidgetItem* > items(\n m_UI->databaseTreeWidget->findItems(\n hash,\n Qt::MatchExactly | Qt::MatchRecursive,\n TreeWidgetItem::COLUMN_INDEX_HASH\n )\n );\n\n assert( items.isEmpty() || items.size() == 1 );\n\n \/\/ qDebug()\n \/\/ << ( items.isEmpty() ? \"NONE\" : items.first()->text( 0 ) )\n \/\/ << m_UI->databaseTreeWidget->selectionModel()->selectedIndexes().size();\n\n m_UI->databaseTreeWidget->setCurrentItem(\n items.isEmpty()\n ? NULL\n : items.first(),\n TreeWidgetItem::COLUMN_INDEX_TEXT,\n QItemSelectionModel::Clear |\n QItemSelectionModel::Select |\n QItemSelectionModel::Current\n );\n#endif\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::InstallTreeEventFilter( QObject* eventFilter )\n{\n m_UI->databaseTreeWidget->installEventFilter( eventFilter );\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_databaseTreeWidget_currentItemChanged( QTreeWidgetItem* current,\n\t\t\t\t\t QTreeWidgetItem* previous )\n{\n \/\/\n \/\/ Current\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString currentHash;\n\n TreeWidgetItem* currentItem = dynamic_cast< TreeWidgetItem* >( current );\n\n if( currentItem!=NULL && currentItem->parent()!=NULL )\n \/\/ if current is root and not NULL get the Id of the corresponding\n \/\/ Dataset.\n currentHash = currentItem->GetHash();\n\n \/\/\n \/\/ Previous\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString previousHash;\n\n TreeWidgetItem* previousItem = dynamic_cast< TreeWidgetItem* >( previous );\n\n if( previousItem!=NULL )\n previousHash = previousItem->GetHash();\n\n \/\/\n \/\/ Emit event.\n emit CurrentDatasetChanged( currentHash, previousHash );\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_m_SearchLine_textChanged( const QString& search )\n{\n \/\/ qDebug() << this << \"on_m_SearchLine_textChanged(\" << search << \")\";\n\n \/\/\n \/\/ get the search text\n m_SearchText = search;\n\n QTreeWidgetItemList items( GetItems() );\n\n \/\/ qDebug() << items;\n\n for( QTreeWidgetItemList::iterator it( items.begin() );\n it!=items.end();\n ++it )\n {\n QTreeWidgetItem* qtwi = *it;\n assert( qtwi!=NULL );\n\n assert( qtwi==dynamic_cast< TreeWidgetItem* >( qtwi ) );\n TreeWidgetItem* item = dynamic_cast< TreeWidgetItem* >( qtwi );\n\n if( item==NULL )\n {\n \/\/ TODO: Implement general case when needed.\n }\n else\n {\n item->setHidden(\n item->GetType()==TreeWidgetItem::ITEM_TYPE_LEAF &&\n !item->GetText().contains( search, Qt::CaseInsensitive )\n );\n }\n\n \/\/ qDebug()\n \/\/ << item->text( 0 ) << \":\" << ( item->isHidden() ? \"HIDDEN\" : \"VISIBLE\" );\n }\n}\n\n} \/\/ end namespace 'mvd'\n<|endoftext|>"} {"text":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"common\/protobuf_utils.hpp\"\n\n#include \"tests\/mesos.hpp\"\n\nusing std::set;\nusing std::string;\nusing std::vector;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n\/\/ This tests that helper function `getRoles` can correctly\n\/\/ get roles from multi-role FrameworkInfo and role from\n\/\/ single-role FrameworkInfo.\nTEST(ProtobufUtilTest, GetRoles)\n{\n \/\/ Get roles from a multi-role framework.\n {\n FrameworkInfo frameworkInfo;\n frameworkInfo.add_capabilities()->set_type(\n FrameworkInfo::Capability::MULTI_ROLE);\n frameworkInfo.add_roles(\"bar\");\n frameworkInfo.add_roles(\"qux\");\n\n set roles = protobuf::framework::getRoles(frameworkInfo);\n\n EXPECT_EQ(roles, set({\"qux\", \"bar\"}));\n }\n\n \/\/ Get role from a single-role framework.\n {\n FrameworkInfo frameworkInfo;\n frameworkInfo.set_role(\"foo\");\n\n set roles = protobuf::framework::getRoles(frameworkInfo);\n\n EXPECT_EQ(roles, set({\"foo\"}));\n }\n}\n\n\n\/\/ Tests that offer operations can be injected to include\n\/\/ the appropriate allocation info, if not already set.\nTEST(ProtobufUtilTest, InjectAllocationInfoInOfferOperation)\n{\n Resources resources = Resources::parse(\"cpus:1\").get();\n\n Resources allocatedResources = resources;\n allocatedResources.allocate(\"role\");\n\n Resource::AllocationInfo allocationInfo;\n allocationInfo.set_role(\"role\");\n\n \/\/ Test the LAUNCH case. This should be constructing a valid\n \/\/ task and executor, but for now this just sets the resources\n \/\/ in order to verify the allocation info injection.\n ExecutorInfo executorInfo;\n executorInfo.mutable_resources()->CopyFrom(resources);\n\n TaskInfo taskInfo;\n taskInfo.mutable_resources()->CopyFrom(resources);\n taskInfo.mutable_executor()->CopyFrom(executorInfo);\n\n Offer::Operation launch = LAUNCH({taskInfo});\n protobuf::injectAllocationInfo(&launch, allocationInfo);\n\n ASSERT_EQ(1, launch.launch().task_infos_size());\n\n EXPECT_EQ(allocatedResources,\n launch.launch().task_infos(0).resources());\n\n EXPECT_EQ(allocatedResources,\n launch.launch().task_infos(0).executor().resources());\n\n \/\/ Test the LAUNCH_GROUP case. This should be constructing a valid\n \/\/ task and executor, but for now this just sets the resources in\n \/\/ order to verify the allocation info injection.\n TaskGroupInfo taskGroupInfo;\n taskGroupInfo.add_tasks()->CopyFrom(taskInfo);\n\n Offer::Operation launchGroup = LAUNCH_GROUP(executorInfo, taskGroupInfo);\n protobuf::injectAllocationInfo(&launchGroup, allocationInfo);\n\n ASSERT_EQ(1, launchGroup.launch_group().task_group().tasks_size());\n\n EXPECT_EQ(allocatedResources,\n launchGroup.launch_group().task_group().tasks(0).resources());\n\n EXPECT_EQ(allocatedResources,\n launchGroup.launch_group().task_group().tasks(0).executor()\n .resources());\n\n \/\/ Test the RESERVE case. This should be constructing a valid\n \/\/ reservation, but for now this just sets the resources in\n \/\/ order to verify the allocation info injection.\n Offer::Operation reserve = RESERVE(resources);\n protobuf::injectAllocationInfo(&reserve, allocationInfo);\n\n EXPECT_EQ(allocatedResources, reserve.reserve().resources());\n\n \/\/ Test the UNRESERVE case. This should be constructing a valid\n \/\/ reservation, but for now this just sets the resources in\n \/\/ order to verify the allocation info injection.\n Offer::Operation unreserve = UNRESERVE(resources);\n protobuf::injectAllocationInfo(&unreserve, allocationInfo);\n\n EXPECT_EQ(allocatedResources, unreserve.unreserve().resources());\n\n \/\/ Test the CREATE case. This should be constructing a valid\n \/\/ volume, but for now this just sets the resources in order\n \/\/ to verify the allocation info injection.\n Offer::Operation create = CREATE(resources);\n protobuf::injectAllocationInfo(&create, allocationInfo);\n\n EXPECT_EQ(allocatedResources, create.create().volumes());\n\n \/\/ Test the DESTROY case. This should be constructing a valid\n \/\/ volume, but for now this just sets the resources in order\n \/\/ to verify the allocation info injection.\n Offer::Operation destroy = DESTROY(resources);\n protobuf::injectAllocationInfo(&destroy, allocationInfo);\n\n EXPECT_EQ(allocatedResources, destroy.destroy().volumes());\n}\n\n\n\/\/ This tests that Capabilities are correctly constructed\n\/\/ from given FrameworkInfo Capabilities.\nTEST(ProtobufUtilTest, FrameworkCapabilities)\n{\n auto toTypeSet = [](\n const protobuf::framework::Capabilities& capabilities) {\n set result;\n\n if (capabilities.revocableResources) {\n result.insert(FrameworkInfo::Capability::REVOCABLE_RESOURCES);\n }\n if (capabilities.taskKillingState) {\n result.insert(FrameworkInfo::Capability::TASK_KILLING_STATE);\n }\n if (capabilities.gpuResources) {\n result.insert(FrameworkInfo::Capability::GPU_RESOURCES);\n }\n if (capabilities.sharedResources) {\n result.insert(FrameworkInfo::Capability::SHARED_RESOURCES);\n }\n if (capabilities.partitionAware) {\n result.insert(FrameworkInfo::Capability::PARTITION_AWARE);\n }\n if (capabilities.multiRole) {\n result.insert(FrameworkInfo::Capability::MULTI_ROLE);\n }\n\n return result;\n };\n\n auto typeSetToCapabilityVector = [](\n const set& capabilitiesTypes) {\n vector result;\n\n foreach (FrameworkInfo::Capability::Type type, capabilitiesTypes) {\n FrameworkInfo::Capability capability;\n capability.set_type(type);\n\n result.push_back(capability);\n }\n\n return result;\n };\n\n \/\/ We test the `Capabilities` construction by converting back\n \/\/ to types and checking for equality with the original types.\n auto backAndForth = [=](const set& types) {\n protobuf::framework::Capabilities capabilities(\n typeSetToCapabilityVector(types));\n\n return toTypeSet(capabilities);\n };\n\n set expected;\n\n expected = { FrameworkInfo::Capability::REVOCABLE_RESOURCES };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::TASK_KILLING_STATE };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::GPU_RESOURCES };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::SHARED_RESOURCES };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::PARTITION_AWARE };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::MULTI_ROLE };\n EXPECT_EQ(expected, backAndForth(expected));\n}\n\n\n\/\/ This tests that Capabilities are correctly constructed\n\/\/ from given Agent Capabilities.\nTEST(ProtobufUtilTest, AgentCapabilities)\n{\n \/\/ TODO(jay_guo): consider applying the same test style in\n \/\/ FrameworkCapabilities when we have more capabilities in agent.\n RegisterSlaveMessage registerSlaveMessage;\n registerSlaveMessage.add_agent_capabilities()->set_type(\n SlaveInfo::Capability::MULTI_ROLE);\n\n protobuf::slave::Capabilities capabilities(\n registerSlaveMessage.agent_capabilities());\n\n ASSERT_TRUE(capabilities.multiRole);\n}\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\nAugmented a test to check protobuf::stripAllocationInfo.\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"common\/protobuf_utils.hpp\"\n\n#include \"tests\/mesos.hpp\"\n\nusing std::set;\nusing std::string;\nusing std::vector;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n\/\/ This tests that helper function `getRoles` can correctly\n\/\/ get roles from multi-role FrameworkInfo and role from\n\/\/ single-role FrameworkInfo.\nTEST(ProtobufUtilTest, GetRoles)\n{\n \/\/ Get roles from a multi-role framework.\n {\n FrameworkInfo frameworkInfo;\n frameworkInfo.add_capabilities()->set_type(\n FrameworkInfo::Capability::MULTI_ROLE);\n frameworkInfo.add_roles(\"bar\");\n frameworkInfo.add_roles(\"qux\");\n\n set roles = protobuf::framework::getRoles(frameworkInfo);\n\n EXPECT_EQ(roles, set({\"qux\", \"bar\"}));\n }\n\n \/\/ Get role from a single-role framework.\n {\n FrameworkInfo frameworkInfo;\n frameworkInfo.set_role(\"foo\");\n\n set roles = protobuf::framework::getRoles(frameworkInfo);\n\n EXPECT_EQ(roles, set({\"foo\"}));\n }\n}\n\n\n\/\/ Tests that allocation info can be injected to and stripped from\n\/\/ offer operations.\nTEST(ProtobufUtilTest, InjectAndStripAllocationInfoInOfferOperation)\n{\n Resources unallocatedResources = Resources::parse(\"cpus:1\").get();\n\n Resources allocatedResources = unallocatedResources;\n allocatedResources.allocate(\"role\");\n\n Resource::AllocationInfo allocationInfo;\n allocationInfo.set_role(\"role\");\n\n ExecutorInfo executorInfo;\n executorInfo.mutable_resources()->CopyFrom(unallocatedResources);\n\n TaskInfo taskInfo;\n taskInfo.mutable_resources()->CopyFrom(unallocatedResources);\n taskInfo.mutable_executor()->CopyFrom(executorInfo);\n\n {\n \/\/ Test the LAUNCH case. This should be constructing a valid\n \/\/ task and executor, but for now this just sets the resources\n \/\/ in order to verify the allocation info injection and stripping.\n Offer::Operation launch = LAUNCH({taskInfo});\n protobuf::injectAllocationInfo(&launch, allocationInfo);\n\n ASSERT_EQ(1, launch.launch().task_infos_size());\n\n EXPECT_EQ(allocatedResources,\n launch.launch().task_infos(0).resources());\n\n EXPECT_EQ(allocatedResources,\n launch.launch().task_infos(0).executor().resources());\n\n protobuf::stripAllocationInfo(&launch);\n\n EXPECT_EQ(unallocatedResources,\n launch.launch().task_infos(0).resources());\n\n EXPECT_EQ(unallocatedResources,\n launch.launch().task_infos(0).executor().resources());\n }\n\n {\n \/\/ Test the LAUNCH_GROUP case. This should be constructing a valid\n \/\/ task and executor, but for now this just sets the resources in\n \/\/ order to verify the allocation info injection.\n TaskGroupInfo taskGroupInfo;\n taskGroupInfo.add_tasks()->CopyFrom(taskInfo);\n\n Offer::Operation launchGroup = LAUNCH_GROUP(executorInfo, taskGroupInfo);\n protobuf::injectAllocationInfo(&launchGroup, allocationInfo);\n\n ASSERT_EQ(1, launchGroup.launch_group().task_group().tasks_size());\n\n EXPECT_EQ(allocatedResources,\n launchGroup.launch_group().task_group().tasks(0).resources());\n\n EXPECT_EQ(allocatedResources,\n launchGroup.launch_group().task_group().tasks(0).executor()\n .resources());\n\n protobuf::stripAllocationInfo(&launchGroup);\n\n EXPECT_EQ(unallocatedResources,\n launchGroup.launch_group().task_group().tasks(0).resources());\n\n EXPECT_EQ(unallocatedResources,\n launchGroup.launch_group().task_group().tasks(0).executor()\n .resources());\n }\n\n {\n \/\/ Test the RESERVE case. This should be constructing a valid\n \/\/ reservation, but for now this just sets the resources in\n \/\/ order to verify the allocation info injection.\n Offer::Operation reserve = RESERVE(unallocatedResources);\n protobuf::injectAllocationInfo(&reserve, allocationInfo);\n\n EXPECT_EQ(allocatedResources, reserve.reserve().resources());\n\n protobuf::stripAllocationInfo(&reserve);\n\n EXPECT_EQ(unallocatedResources, reserve.reserve().resources());\n }\n\n {\n \/\/ Test the UNRESERVE case. This should be constructing a valid\n \/\/ reservation, but for now this just sets the resources in\n \/\/ order to verify the allocation info injection.\n Offer::Operation unreserve = UNRESERVE(unallocatedResources);\n protobuf::injectAllocationInfo(&unreserve, allocationInfo);\n\n EXPECT_EQ(allocatedResources, unreserve.unreserve().resources());\n\n protobuf::stripAllocationInfo(&unreserve);\n\n EXPECT_EQ(unallocatedResources, unreserve.unreserve().resources());\n }\n\n {\n \/\/ Test the CREATE case. This should be constructing a valid\n \/\/ volume, but for now this just sets the resources in order\n \/\/ to verify the allocation info injection.\n Offer::Operation create = CREATE(unallocatedResources);\n protobuf::injectAllocationInfo(&create, allocationInfo);\n\n EXPECT_EQ(allocatedResources, create.create().volumes());\n\n protobuf::stripAllocationInfo(&create);\n\n EXPECT_EQ(unallocatedResources, create.create().volumes());\n }\n\n {\n \/\/ Test the DESTROY case. This should be constructing a valid\n \/\/ volume, but for now this just sets the resources in order\n \/\/ to verify the allocation info injection.\n Offer::Operation destroy = DESTROY(unallocatedResources);\n protobuf::injectAllocationInfo(&destroy, allocationInfo);\n\n EXPECT_EQ(allocatedResources, destroy.destroy().volumes());\n\n protobuf::stripAllocationInfo(&destroy);\n\n EXPECT_EQ(unallocatedResources, destroy.destroy().volumes());\n }\n}\n\n\n\/\/ This tests that Capabilities are correctly constructed\n\/\/ from given FrameworkInfo Capabilities.\nTEST(ProtobufUtilTest, FrameworkCapabilities)\n{\n auto toTypeSet = [](\n const protobuf::framework::Capabilities& capabilities) {\n set result;\n\n if (capabilities.revocableResources) {\n result.insert(FrameworkInfo::Capability::REVOCABLE_RESOURCES);\n }\n if (capabilities.taskKillingState) {\n result.insert(FrameworkInfo::Capability::TASK_KILLING_STATE);\n }\n if (capabilities.gpuResources) {\n result.insert(FrameworkInfo::Capability::GPU_RESOURCES);\n }\n if (capabilities.sharedResources) {\n result.insert(FrameworkInfo::Capability::SHARED_RESOURCES);\n }\n if (capabilities.partitionAware) {\n result.insert(FrameworkInfo::Capability::PARTITION_AWARE);\n }\n if (capabilities.multiRole) {\n result.insert(FrameworkInfo::Capability::MULTI_ROLE);\n }\n\n return result;\n };\n\n auto typeSetToCapabilityVector = [](\n const set& capabilitiesTypes) {\n vector result;\n\n foreach (FrameworkInfo::Capability::Type type, capabilitiesTypes) {\n FrameworkInfo::Capability capability;\n capability.set_type(type);\n\n result.push_back(capability);\n }\n\n return result;\n };\n\n \/\/ We test the `Capabilities` construction by converting back\n \/\/ to types and checking for equality with the original types.\n auto backAndForth = [=](const set& types) {\n protobuf::framework::Capabilities capabilities(\n typeSetToCapabilityVector(types));\n\n return toTypeSet(capabilities);\n };\n\n set expected;\n\n expected = { FrameworkInfo::Capability::REVOCABLE_RESOURCES };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::TASK_KILLING_STATE };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::GPU_RESOURCES };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::SHARED_RESOURCES };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::PARTITION_AWARE };\n EXPECT_EQ(expected, backAndForth(expected));\n\n expected = { FrameworkInfo::Capability::MULTI_ROLE };\n EXPECT_EQ(expected, backAndForth(expected));\n}\n\n\n\/\/ This tests that Capabilities are correctly constructed\n\/\/ from given Agent Capabilities.\nTEST(ProtobufUtilTest, AgentCapabilities)\n{\n \/\/ TODO(jay_guo): consider applying the same test style in\n \/\/ FrameworkCapabilities when we have more capabilities in agent.\n RegisterSlaveMessage registerSlaveMessage;\n registerSlaveMessage.add_agent_capabilities()->set_type(\n SlaveInfo::Capability::MULTI_ROLE);\n\n protobuf::slave::Capabilities capabilities(\n registerSlaveMessage.agent_capabilities());\n\n ASSERT_TRUE(capabilities.multiRole);\n}\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n<|endoftext|>"} {"text":"\/\/ interval_map.cpp\n\/\/\n#include \"dataserver\/numeric\/interval_map.h\"\n\n#if SDL_DEBUG\nnamespace sdl { namespace {\n\nclass unit_test {\n void test1();\npublic:\n unit_test() {\n if (0) {\n test1();\n }\n }\n};\nstatic unit_test s_test;\n\nvoid unit_test::test1()\n{\n SDL_TRACE_FUNCTION;\n\n\ttypedef int key_t;\n\ttypedef int val_t;\n\ttypedef interval_map map_type;\n\n\tmap_type test(-1);\n\tenum { N = 111 };\n\tenum { M = 1000 };\n\tenum { M2 = 1 };\n\tfor (int j = 0; j < M; ++j)\n\tfor (int j2 = 0; j2 < M2; ++j2)\n\t{\n\t\ttypedef std::vector vector_key_t;\n\t\ttypedef std::vector vector_val_t;\n\t\tvector_key_t dkeyBegin, dkeyEnd;\n\t\tvector_val_t dval;\n\t\tconst bool print = (0 == j) && (0 == j2);\n\t\tif (print) { \n\t\t\tstd::cout << \"assign:\\n\";\n\t\t}\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tconst key_t keyBegin = rand() % 100;\n\t\t\tconst key_t keyEnd = keyBegin + rand() % 100;\n\t\t\tconst val_t val = rand() % 100;\n\t\t\tdkeyBegin.push_back(keyBegin);\n\t\t\tdkeyEnd.push_back(keyEnd);\n\t\t\tdval.push_back(val);\n\t\t\tif (print) {\n\t\t\t\tstd::cout << i << \": (\" << keyBegin << \",\" << keyEnd << \",\" << val << \")\\n\";\n\t\t\t}\n\t\t\ttest.assign(keyBegin, keyEnd, val);\n\t\t}\n\t\tif (print) {\n\t\t\tstd::cout << \"trace map:\\n\";\n\t\t}\n\t\tauto it = test.map().begin();\n\t\tfor (; it != test.map().end(); ++it) {\n\t\t\tif (print) {\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"key = \" << it->first << \", \"\n\t\t\t\t\t<< \"val = \" << it->second << \"\\n\";\n\t\t\t}\n\t\t\tif (it != test.map().begin()) {\n\t\t\t\tauto it2 = it; --it2;\n\t\t\t\tif (it2->second == it->second) \/\/ error !\n\t\t\t\t{\n\t\t\t\t\tmap_type test2(-1);\n\t\t\t\t\tfor (size_t k = 0; k < dkeyBegin.size(); ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << k << \": (\" << dkeyBegin[k] << \",\" << dkeyEnd[k] << \",\" << dval[k] << \")\\n\";\n\t\t\t\t\t\ttest2.assign(dkeyBegin[k], dkeyEnd[k], dval[k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tassert(it2->second != it->second);\n\t\t\t\tassert(it2->first < it->first);\n\t\t\t}\n\t\t}\n\t}\n}\n\n}} \/\/ sdl\n#endif \/\/#if SDL_DEBUG\ninterval_map.cpp\/\/ interval_map.cpp\n\/\/\n#include \"dataserver\/numeric\/interval_map.h\"\n\n#if SDL_DEBUG\nnamespace sdl { namespace {\n\nclass unit_test {\n void test1();\npublic:\n unit_test() {\n if (0) {\n test1();\n }\n }\n};\nstatic unit_test s_test;\n\nvoid unit_test::test1()\n{\n\ttypedef int key_t;\n\ttypedef int val_t;\n\ttypedef interval_map map_type;\n\n\tmap_type test(-1);\n\tenum { N = 111 };\n\tenum { M = 1000 };\n\tenum { M2 = 1 };\n\tfor (int j = 0; j < M; ++j) {\n\tfor (int j2 = 0; j2 < M2; ++j2)\t{\n\t\ttypedef std::vector vector_key_t;\n\t\ttypedef std::vector vector_val_t;\n\t\tvector_key_t dkeyBegin, dkeyEnd;\n\t\tvector_val_t dval;\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tconst key_t keyBegin = rand() % 100;\n\t\t\tconst key_t keyEnd = keyBegin + rand() % 100;\n\t\t\tconst val_t val = rand() % 100;\n\t\t\tdkeyBegin.push_back(keyBegin);\n\t\t\tdkeyEnd.push_back(keyEnd);\n\t\t\tdval.push_back(val);\n\t\t\ttest.assign(keyBegin, keyEnd, val);\n\t\t}\n if (!test.map().empty()) {\n const auto end = test.map().end();\n\t\t auto it = test.map().begin();\n ++it;\n\t\t for (; it != end; ++it) {\n\t\t\t\tauto it2 = it; --it2;\n\t\t\t\tSDL_ASSERT(it2->second != it->second);\n\t\t\t\tSDL_ASSERT(it2->first < it->first);\n\t\t }\n }\n }}\n}\n\n}} \/\/ sdl\n#endif \/\/#if SDL_DEBUG\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n\nusing namespace Davix;\nusing namespace std;\n\n\nconst std::string scope_main = \"Davix::Tools::davix\";\n\n\nstatic void performanceCallback(const PerformanceData& perfData, void *udata)\n{\n (void) udata;\n std::cout << perfData.totalTransferred()\n << \" (\" << perfData.avgTransfer() << \" bytes\/sec)\"\n << std::endl;\n}\n\n\nstatic std::string help_msg(const std::string & cmd_path)(){\n std::string help_msg = fmt::format(\"Usage : {} \", cmd_path);\n help_msg += Tool::get_copy_description_options();\n help_msg += Tool::get_common_options();\n\n return help_msg;\n}\n\n\n\nint main(int argc, char** argv){\n int retcode=-1;\n Tool::OptParams opts;\n DavixError* tmp_err=NULL;\n opts.help_msg = help_msg(argv[0]);\n\n if( (retcode= Tool::parse_davix_options(argc, argv, opts, &tmp_err)) ==0){\n Context c;\n if( (retcode = Tool::configureAuth(opts)) == 0){\n configureContext(c, opts);\n DavixCopy copy(c, &opts.params);\n copy.setPerformanceCallback(performanceCallback, NULL);\n copy.copy(opts.vec_arg[0], opts.vec_arg[1],\n 1, &tmp_err);\n }\n }\n Tool::errorPrint(&tmp_err);\n return retcode;\n}\nFixed compilation of davix_tool_copy_main.cpp#include \n#include \n#include \n#include \n\n\nusing namespace Davix;\nusing namespace std;\n\n\nconst std::string scope_main = \"Davix::Tools::davix\";\n\n\nstatic void performanceCallback(const PerformanceData& perfData, void *udata)\n{\n (void) udata;\n std::cout << perfData.totalTransferred()\n << \" (\" << perfData.avgTransfer() << \" bytes\/sec)\"\n << std::endl;\n}\n\n\nstatic std::string help_msg(const std::string & cmd_path){\n std::string help_str = fmt::format(\"Usage : {} \", cmd_path);\n help_str += Tool::get_copy_description_options();\n help_str += Tool::get_common_options();\n\n return help_str;\n}\n\n\n\nint main(int argc, char** argv){\n int retcode=-1;\n Tool::OptParams opts;\n DavixError* tmp_err=NULL;\n opts.help_msg = help_msg(argv[0]);\n\n if( (retcode= Tool::parse_davix_options(argc, argv, opts, &tmp_err)) ==0){\n Context c;\n if( (retcode = Tool::configureAuth(opts)) == 0){\n configureContext(c, opts);\n DavixCopy copy(c, &opts.params);\n copy.setPerformanceCallback(performanceCallback, NULL);\n copy.copy(opts.vec_arg[0], opts.vec_arg[1],\n 1, &tmp_err);\n }\n }\n Tool::errorPrint(&tmp_err);\n return retcode;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"native_client\/src\/include\/nacl_string.h\"\n#include \"native_client\/src\/include\/portability.h\"\n#include \"native_client\/src\/trusted\/validator\/ncfileutil.h\"\n#include \"native_client\/src\/trusted\/cpu_features\/arch\/arm\/cpu_arm.h\"\n#include \"native_client\/src\/trusted\/validator_arm\/model.h\"\n#include \"native_client\/src\/trusted\/validator_arm\/problem_reporter.h\"\n#include \"native_client\/src\/trusted\/validator_arm\/validator.h\"\n\nusing nacl_arm_val::SfiValidator;\nusing nacl_arm_val::CodeSegment;\nusing nacl_arm_val::ProblemReporter;\nusing nacl_arm_dec::MAY_BE_SAFE;\n\nusing std::string;\nusing std::vector;\n\n\n\/*\n * Reports problems in an easily-parsed textual format, for consumption by a\n * validation-reporting script.\n *\n * The format is as follows:\n * ncval: \n *\n * For possible safety levels, see inst_classes.h.\n *\n * For possible problem ID strings, see validator.h.\n *\/\nclass NcvalProblemReporter : public ProblemReporter {\n protected:\n virtual void ReportProblemMessage(nacl_arm_dec::Violation violation,\n uint32_t vaddr,\n const char* message);\n};\n\nvoid NcvalProblemReporter::\nReportProblemMessage(nacl_arm_dec::Violation violation,\n uint32_t vaddr,\n const char* message) {\n UNREFERENCED_PARAMETER(vaddr);\n UNREFERENCED_PARAMETER(violation);\n printf(\"%8\"NACL_PRIx32\": %s\\n\", vaddr, message);\n}\n\nconst uint32_t kOneGig = 1U * 1024 * 1024 * 1024;\n\nint validate(const ncfile *ncf, const NaClCPUFeaturesArm *cpu_features) {\n SfiValidator validator(\n 16, \/\/ bytes per bundle\n \/\/ TODO(cbiffle): maybe check region sizes from ELF headers?\n \/\/ verify that instructions are in right region\n kOneGig, \/\/ code region size\n kOneGig, \/\/ data region size\n nacl_arm_dec::RegisterList(nacl_arm_dec::Register::Tp()),\n nacl_arm_dec::RegisterList(nacl_arm_dec::Register::Sp()),\n cpu_features);\n\n NcvalProblemReporter reporter;\n\n Elf_Shdr *shdr = ncf->sheaders;\n\n vector segments;\n for (int i = 0; i < ncf->shnum; i++) {\n if ((shdr[i].sh_flags & SHF_EXECINSTR) != SHF_EXECINSTR) {\n continue;\n }\n\n CodeSegment segment(ncf->data + (shdr[i].sh_addr - ncf->vbase),\n shdr[i].sh_addr, shdr[i].sh_size);\n segments.push_back(segment);\n }\n\n std::sort(segments.begin(), segments.end());\n\n bool success = validator.validate(segments, &reporter);\n if (!success) return 1;\n return 0;\n}\n\nint main(int argc, const char *argv[]) {\n static const char cond_mem_access_flag[] =\n \"--conditional_memory_access_allowed_for_sfi\";\n\n static const char number_runs_flag[] =\n \"--number_runs\";\n\n NaClCPUFeaturesArm cpu_features;\n NaClClearCPUFeaturesArm(&cpu_features);\n\n int exit_code = EXIT_FAILURE;\n bool print_usage = false;\n bool run_validation = false;\n int number_runs = 1;\n std::string filename;\n ncfile *ncf = NULL;\n\n for (int i = 1; i < argc; ++i) {\n std::string current_arg = argv[i];\n if (current_arg == \"--usage\" ||\n current_arg == \"--help\") {\n print_usage = true;\n run_validation = false;\n break;\n } else if (current_arg == number_runs_flag) {\n \/\/ next argument is the number of runs to try. Used when timing\n \/\/ performance, and want to run many times to get a good average\n \/\/ time result.\n ++i;\n if (i < argc) {\n number_runs = atoi(argv[i]);\n } else {\n \/\/ No value to got with argument, fail to run.\n print_usage = true;\n run_validation = false;\n }\n } else if (current_arg == cond_mem_access_flag) {\n \/\/ This flag is disallowed by default: not all ARM CPUs support it,\n \/\/ so be pessimistic unless the user asks for it.\n NaClSetCPUFeatureArm(&cpu_features, NaClCPUFeatureArm_CanUseTstMem, 1);\n } else if (!filename.empty()) {\n fprintf(stderr, \"Error: multiple files specified.\\n\");\n print_usage = true;\n run_validation = false;\n break;\n } else {\n filename = current_arg;\n run_validation = true;\n }\n }\n\n if (filename.empty()) {\n fprintf(stderr, \"Error: no file specified.\\n\");\n print_usage = true;\n run_validation = false;\n } else {\n ncf = nc_loadfile(filename.c_str());\n if (!ncf) {\n int err = errno;\n fprintf(stderr, \"Error: unable to load file %s: %s.\\n\",\n filename.c_str(), strerror(err));\n print_usage = true;\n run_validation = false;\n }\n }\n\n if (print_usage) {\n fprintf(stderr, \"Usage: %s [options] \\n\", argv[0]);\n fprintf(stderr, \" %s\\n\", cond_mem_access_flag);\n fprintf(stderr, \" Allow conditions on memory access.\\n\");\n fprintf(stderr, \" %s n\\n\", number_runs_flag);\n fprintf(stderr, \" Validate input n times.\\n\");\n fprintf(stderr, \" Used for performance timing.\\n\");\n }\n\n \/\/ TODO(cbiffle): check OS ABI, ABI version, align mask\n\n if (run_validation) {\n exit_code = 0;\n for (int i = 0; i < number_runs; ++i) {\n exit_code |= validate(ncf, &cpu_features);\n }\n if (exit_code == 0)\n printf(\"Valid.\\n\");\n else\n printf(\"Invalid.\\n\");\n }\n\n if (ncf)\n nc_freefile(ncf);\n\n return exit_code;\n}\nAllow passing raw code on command line of validator.\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"native_client\/src\/include\/nacl_string.h\"\n#include \"native_client\/src\/include\/portability.h\"\n#include \"native_client\/src\/trusted\/validator\/ncfileutil.h\"\n#include \"native_client\/src\/trusted\/cpu_features\/arch\/arm\/cpu_arm.h\"\n#include \"native_client\/src\/trusted\/validator_arm\/model.h\"\n#include \"native_client\/src\/trusted\/validator_arm\/problem_reporter.h\"\n#include \"native_client\/src\/trusted\/validator_arm\/validator.h\"\n\nusing nacl_arm_val::SfiValidator;\nusing nacl_arm_val::CodeSegment;\nusing nacl_arm_val::ProblemReporter;\nusing nacl_arm_dec::MAY_BE_SAFE;\n\nusing std::string;\nusing std::vector;\n\n\n\/*\n * Reports problems in an easily-parsed textual format, for consumption by a\n * validation-reporting script.\n *\n * The format is as follows:\n * ncval: \n *\n * For possible safety levels, see inst_classes.h.\n *\n * For possible problem ID strings, see validator.h.\n *\/\nclass NcvalProblemReporter : public ProblemReporter {\n protected:\n virtual void ReportProblemMessage(nacl_arm_dec::Violation violation,\n uint32_t vaddr,\n const char* message);\n};\n\nvoid NcvalProblemReporter::\nReportProblemMessage(nacl_arm_dec::Violation violation,\n uint32_t vaddr,\n const char* message) {\n UNREFERENCED_PARAMETER(vaddr);\n UNREFERENCED_PARAMETER(violation);\n printf(\"%8\"NACL_PRIx32\": %s\\n\", vaddr, message);\n}\n\nconst uint32_t kOneGig = 1U * 1024 * 1024 * 1024;\n\nint validate(const ncfile *ncf, const NaClCPUFeaturesArm *cpu_features) {\n SfiValidator validator(\n 16, \/\/ bytes per bundle\n \/\/ TODO(cbiffle): maybe check region sizes from ELF headers?\n \/\/ verify that instructions are in right region\n kOneGig, \/\/ code region size\n kOneGig, \/\/ data region size\n nacl_arm_dec::RegisterList(nacl_arm_dec::Register::Tp()),\n nacl_arm_dec::RegisterList(nacl_arm_dec::Register::Sp()),\n cpu_features);\n\n NcvalProblemReporter reporter;\n\n Elf_Shdr *shdr = ncf->sheaders;\n\n vector segments;\n for (int i = 0; i < ncf->shnum; i++) {\n if ((shdr[i].sh_flags & SHF_EXECINSTR) != SHF_EXECINSTR) {\n continue;\n }\n\n CodeSegment segment(ncf->data + (shdr[i].sh_addr - ncf->vbase),\n shdr[i].sh_addr, shdr[i].sh_size);\n segments.push_back(segment);\n }\n\n std::sort(segments.begin(), segments.end());\n\n bool success = validator.validate(segments, &reporter);\n if (!success) return 1;\n return 0;\n}\n\nstatic inline uint8_t as_hex(char c) {\n if (c >= '0' && c <= '9') return c - '0';\n if (c >= 'a' && c <= 'f') return c - 'a' + 0xa;\n if (c >= 'A' && c <= 'F') return c - 'A' + 0xa;\n CHECK(false);\n return 0;\n}\n\nint check_code(const std::string& code) {\n NaClCPUFeaturesArm cpu_features;\n SfiValidator validator(\n 16, \/\/ bytes per bundle\n kOneGig, \/\/ code region size\n kOneGig, \/\/ data region size\n nacl_arm_dec::RegisterList(nacl_arm_dec::Register::Tp()),\n nacl_arm_dec::RegisterList(nacl_arm_dec::Register::Sp()),\n &cpu_features);\n NcvalProblemReporter reporter;\n\n uint8_t* code_buf = new uint8_t[code.length()];\n uint32_t code_len = 0;\n for (uint32_t i = 0; i < code.length(); i += 3) {\n code_buf[code_len++] = (as_hex(code[i]) << 4) | as_hex(code[i+1]);\n }\n printf(\"Validating code: \");\n for (uint32_t i = 0; i < code_len; i++) {\n printf(\"%02x \", code_buf[i]);\n }\n printf(\"\\n\");\n\n vector segments;\n CodeSegment segment(code_buf, 0, code_len);\n segments.push_back(segment);\n bool success = validator.validate(segments, &reporter);\n if (success) {\n printf(\"valid!\\n\");\n return 0;\n } else {\n printf(\"invalid\\n\");\n return 1;\n }\n}\n\nint main(int argc, const char *argv[]) {\n static const char cond_mem_access_flag[] =\n \"--conditional_memory_access_allowed_for_sfi\";\n\n static const char number_runs_flag[] =\n \"--number_runs\";\n\n NaClCPUFeaturesArm cpu_features;\n NaClClearCPUFeaturesArm(&cpu_features);\n\n int exit_code = EXIT_FAILURE;\n bool print_usage = false;\n bool run_validation = false;\n int number_runs = 1;\n std::string filename;\n ncfile *ncf = NULL;\n std::string code;\n\n for (int i = 1; i < argc; ++i) {\n std::string current_arg = argv[i];\n if (current_arg == \"--usage\" ||\n current_arg == \"--help\") {\n print_usage = true;\n run_validation = false;\n break;\n } else if (current_arg == number_runs_flag) {\n \/\/ next argument is the number of runs to try. Used when timing\n \/\/ performance, and want to run many times to get a good average\n \/\/ time result.\n ++i;\n if (i < argc) {\n number_runs = atoi(argv[i]);\n } else {\n \/\/ No value to got with argument, fail to run.\n print_usage = true;\n run_validation = false;\n }\n } else if (current_arg == cond_mem_access_flag) {\n \/\/ This flag is disallowed by default: not all ARM CPUs support it,\n \/\/ so be pessimistic unless the user asks for it.\n NaClSetCPUFeatureArm(&cpu_features, NaClCPUFeatureArm_CanUseTstMem, 1);\n } else if (current_arg == \"--check\" && i + 1 < argc) {\n code = argv[i+1];\n i++;\n } else if (!filename.empty()) {\n fprintf(stderr, \"Error: multiple files specified.\\n\");\n print_usage = true;\n run_validation = false;\n break;\n } else {\n filename = current_arg;\n run_validation = true;\n }\n }\n\n if (!code.empty()) {\n return check_code(code);\n }\n\n if (filename.empty()) {\n fprintf(stderr, \"Error: no file specified.\\n\");\n print_usage = true;\n run_validation = false;\n } else {\n ncf = nc_loadfile(filename.c_str());\n if (!ncf) {\n int err = errno;\n fprintf(stderr, \"Error: unable to load file %s: %s.\\n\",\n filename.c_str(), strerror(err));\n print_usage = true;\n run_validation = false;\n }\n }\n\n if (print_usage) {\n fprintf(stderr, \"Usage: %s [options] \\n\", argv[0]);\n fprintf(stderr, \" %s\\n\", cond_mem_access_flag);\n fprintf(stderr, \" Allow conditions on memory access.\\n\");\n fprintf(stderr, \" %s n\\n\", number_runs_flag);\n fprintf(stderr, \" Validate input n times.\\n\");\n fprintf(stderr, \" Used for performance timing.\\n\");\n }\n\n \/\/ TODO(cbiffle): check OS ABI, ABI version, align mask\n\n if (run_validation) {\n exit_code = 0;\n for (int i = 0; i < number_runs; ++i) {\n exit_code |= validate(ncf, &cpu_features);\n }\n if (exit_code == 0)\n printf(\"Valid.\\n\");\n else\n printf(\"Invalid.\\n\");\n }\n\n if (ncf)\n nc_freefile(ncf);\n\n return exit_code;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2020 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"PairingCommand.h\"\n#include \"platform\/PlatformManager.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace ::chip;\nusing namespace ::chip::Controller;\n\nCHIP_ERROR PairingCommand::RunCommand()\n{\n CurrentCommissioner().RegisterPairingDelegate(this);\n return RunInternal(mNodeId);\n}\n\nCHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n switch (mPairingMode)\n {\n case PairingMode::None:\n err = Unpair(remoteId);\n break;\n case PairingMode::QRCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::ManualCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::QRCodePaseOnly:\n case PairingMode::ManualCodePaseOnly:\n err = PaseWithCode(remoteId);\n break;\n case PairingMode::Ble:\n err = Pair(remoteId, PeerAddress::BLE());\n break;\n case PairingMode::OnNetwork:\n err = PairWithMdns(remoteId);\n break;\n case PairingMode::SoftAP:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));\n break;\n case PairingMode::Ethernet:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));\n break;\n }\n\n return err;\n}\n\nCommissioningParameters PairingCommand::GetCommissioningParameters()\n{\n switch (mNetworkType)\n {\n case PairingNetworkType::WiFi:\n return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));\n case PairingNetworkType::Thread:\n return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);\n case PairingNetworkType::Ethernet:\n case PairingNetworkType::None:\n return CommissioningParameters();\n }\n return CommissioningParameters();\n}\n\nCHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)\n{\n return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);\n}\n\nCHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)\n{\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)\n{\n RendezvousParameters params =\n RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)\n{\n Dnssd::DiscoveryFilter filter(mFilterType);\n switch (mFilterType)\n {\n case chip::Dnssd::DiscoveryFilterType::kNone:\n break;\n case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:\n case chip::Dnssd::DiscoveryFilterType::kVendorId:\n case chip::Dnssd::DiscoveryFilterType::kDeviceType:\n filter.code = mDiscoveryFilterCode;\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioner:\n filter.code = 1;\n break;\n case chip::Dnssd::DiscoveryFilterType::kInstanceName:\n filter.code = 0;\n filter.instanceName = mDiscoveryFilterInstanceName;\n break;\n }\n\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);\n return CurrentCommissioner().DiscoverCommissionableNodes(filter);\n}\n\nCHIP_ERROR PairingCommand::Unpair(NodeId remoteId)\n{\n CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);\n SetCommandExitStatus(err);\n return err;\n}\n\nvoid PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)\n{\n switch (status)\n {\n case DevicePairingDelegate::Status::SecurePairingSuccess:\n ChipLogProgress(chipTool, \"Secure Pairing Success\");\n break;\n case DevicePairingDelegate::Status::SecurePairingFailed:\n ChipLogError(chipTool, \"Secure Pairing Failed\");\n break;\n }\n}\n\nvoid PairingCommand::OnPairingComplete(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Success\");\n if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)\n {\n SetCommandExitStatus(err);\n }\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Failure: %s\", ErrorStr(err));\n }\n\n if (err != CHIP_NO_ERROR)\n {\n SetCommandExitStatus(err);\n }\n}\n\nvoid PairingCommand::OnPairingDeleted(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Device commissioning completed with success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Device commissioning Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)\n{\n \/\/ Ignore nodes with closed comissioning window\n VerifyOrReturn(nodeData.commissioningMode != 0);\n\n const uint16_t port = nodeData.port;\n char buf[chip::Inet::IPAddress::kMaxStringLength];\n nodeData.ipAddress[0].ToString(buf);\n ChipLogProgress(chipTool, \"Discovered Device: %s:%u\", buf, port);\n\n \/\/ Stop Mdns discovery. Is it the right method ?\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);\n\n Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();\n PeerAddress peerAddress = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);\n CHIP_ERROR err = Pair(mNodeId, peerAddress);\n if (CHIP_NO_ERROR != err)\n {\n SetCommandExitStatus(err);\n }\n}\nchip-tool: use correct interface when specified (#16833)\/*\n * Copyright (c) 2020 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"PairingCommand.h\"\n#include \"platform\/PlatformManager.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace ::chip;\nusing namespace ::chip::Controller;\n\nCHIP_ERROR PairingCommand::RunCommand()\n{\n CurrentCommissioner().RegisterPairingDelegate(this);\n return RunInternal(mNodeId);\n}\n\nCHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n switch (mPairingMode)\n {\n case PairingMode::None:\n err = Unpair(remoteId);\n break;\n case PairingMode::QRCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::ManualCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::QRCodePaseOnly:\n case PairingMode::ManualCodePaseOnly:\n err = PaseWithCode(remoteId);\n break;\n case PairingMode::Ble:\n err = Pair(remoteId, PeerAddress::BLE());\n break;\n case PairingMode::OnNetwork:\n err = PairWithMdns(remoteId);\n break;\n case PairingMode::SoftAP:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort, mRemoteAddr.interfaceId));\n break;\n case PairingMode::Ethernet:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort, mRemoteAddr.interfaceId));\n break;\n }\n\n return err;\n}\n\nCommissioningParameters PairingCommand::GetCommissioningParameters()\n{\n switch (mNetworkType)\n {\n case PairingNetworkType::WiFi:\n return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));\n case PairingNetworkType::Thread:\n return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);\n case PairingNetworkType::Ethernet:\n case PairingNetworkType::None:\n return CommissioningParameters();\n }\n return CommissioningParameters();\n}\n\nCHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)\n{\n return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);\n}\n\nCHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)\n{\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)\n{\n RendezvousParameters params =\n RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)\n{\n Dnssd::DiscoveryFilter filter(mFilterType);\n switch (mFilterType)\n {\n case chip::Dnssd::DiscoveryFilterType::kNone:\n break;\n case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:\n case chip::Dnssd::DiscoveryFilterType::kVendorId:\n case chip::Dnssd::DiscoveryFilterType::kDeviceType:\n filter.code = mDiscoveryFilterCode;\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioner:\n filter.code = 1;\n break;\n case chip::Dnssd::DiscoveryFilterType::kInstanceName:\n filter.code = 0;\n filter.instanceName = mDiscoveryFilterInstanceName;\n break;\n }\n\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);\n return CurrentCommissioner().DiscoverCommissionableNodes(filter);\n}\n\nCHIP_ERROR PairingCommand::Unpair(NodeId remoteId)\n{\n CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);\n SetCommandExitStatus(err);\n return err;\n}\n\nvoid PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)\n{\n switch (status)\n {\n case DevicePairingDelegate::Status::SecurePairingSuccess:\n ChipLogProgress(chipTool, \"Secure Pairing Success\");\n break;\n case DevicePairingDelegate::Status::SecurePairingFailed:\n ChipLogError(chipTool, \"Secure Pairing Failed\");\n break;\n }\n}\n\nvoid PairingCommand::OnPairingComplete(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Success\");\n if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)\n {\n SetCommandExitStatus(err);\n }\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Failure: %s\", ErrorStr(err));\n }\n\n if (err != CHIP_NO_ERROR)\n {\n SetCommandExitStatus(err);\n }\n}\n\nvoid PairingCommand::OnPairingDeleted(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Device commissioning completed with success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Device commissioning Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)\n{\n \/\/ Ignore nodes with closed comissioning window\n VerifyOrReturn(nodeData.commissioningMode != 0);\n\n const uint16_t port = nodeData.port;\n char buf[chip::Inet::IPAddress::kMaxStringLength];\n nodeData.ipAddress[0].ToString(buf);\n ChipLogProgress(chipTool, \"Discovered Device: %s:%u\", buf, port);\n\n \/\/ Stop Mdns discovery. Is it the right method ?\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);\n\n Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();\n PeerAddress peerAddress = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);\n CHIP_ERROR err = Pair(mNodeId, peerAddress);\n if (CHIP_NO_ERROR != err)\n {\n SetCommandExitStatus(err);\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"coding\/varint.hpp\"\n\n#include \"base\/assert.hpp\"\n\n#include \"std\/string.hpp\"\n\n\nnamespace utils\n{\n template void WriteString(TSink & sink, string const & s)\n {\n CHECK(!s.empty(), ());\n\n size_t const sz = s.size();\n WriteVarUint(sink, static_cast(sz-1));\n sink.Write(s.c_str(), sz);\n }\n\n template void ReadString(TSource & src, string & s)\n {\n uint32_t const sz = ReadVarUint(src) + 1;\n s.resize(sz);\n src.Read(&s[0], sz);\n\n CHECK(!s.empty(), ());\n }\n}\n\nclass StringUtf8Multilang\n{\n string m_s;\n\n size_t GetNextIndex(size_t i) const;\n\npublic:\n static int8_t const UNSUPPORTED_LANGUAGE_CODE = -1;\n static int8_t const DEFAULT_CODE = 0;\n\n \/\/\/ @return UNSUPPORTED_LANGUAGE_CODE if language is not recognized\n static int8_t GetLangIndex(string const & lang);\n \/\/\/ @return empty string if langCode is invalid\n static char const * GetLangByCode(int8_t langCode);\n\n inline bool operator== (StringUtf8Multilang const & rhs) const\n {\n return (m_s == rhs.m_s);\n }\n\n inline void Clear() { m_s.clear(); }\n inline bool IsEmpty() const { return m_s.empty(); }\n\n void AddString(int8_t lang, string const & utf8s);\n void AddString(string const & lang, string const & utf8s)\n {\n int8_t const l = GetLangIndex(lang);\n if (l >= 0)\n AddString(l, utf8s);\n }\n\n template \n void ForEachRef(T & functor) const\n {\n size_t i = 0;\n size_t const sz = m_s.size();\n while (i < sz)\n {\n size_t const next = GetNextIndex(i);\n if (!functor((m_s[i] & 0x3F), m_s.substr(i + 1, next - i - 1)))\n return;\n i = next;\n }\n }\n\n bool GetString(int8_t lang, string & utf8s) const;\n bool GetString(string const & lang, string & utf8s) const\n {\n int8_t const l = GetLangIndex(lang);\n if (l >= 0)\n return GetString(l, utf8s);\n else\n return false;\n }\n\n int8_t FindString(string const & utf8s) const;\n\n template void Write(TSink & sink) const\n {\n utils::WriteString(sink, m_s);\n }\n\n template void Read(TSource & src)\n {\n utils::ReadString(src, m_s);\n }\n};\n\nstring DebugPrint(StringUtf8Multilang const & s);\nPass in-place lambdas.#pragma once\n\n#include \"coding\/varint.hpp\"\n\n#include \"base\/assert.hpp\"\n\n#include \"std\/string.hpp\"\n\n\nnamespace utils\n{\n template void WriteString(TSink & sink, string const & s)\n {\n CHECK(!s.empty(), ());\n\n size_t const sz = s.size();\n WriteVarUint(sink, static_cast(sz-1));\n sink.Write(s.c_str(), sz);\n }\n\n template void ReadString(TSource & src, string & s)\n {\n uint32_t const sz = ReadVarUint(src) + 1;\n s.resize(sz);\n src.Read(&s[0], sz);\n\n CHECK(!s.empty(), ());\n }\n}\n\nclass StringUtf8Multilang\n{\n string m_s;\n\n size_t GetNextIndex(size_t i) const;\n\npublic:\n static int8_t const UNSUPPORTED_LANGUAGE_CODE = -1;\n static int8_t const DEFAULT_CODE = 0;\n\n \/\/\/ @return UNSUPPORTED_LANGUAGE_CODE if language is not recognized\n static int8_t GetLangIndex(string const & lang);\n \/\/\/ @return empty string if langCode is invalid\n static char const * GetLangByCode(int8_t langCode);\n\n inline bool operator== (StringUtf8Multilang const & rhs) const\n {\n return (m_s == rhs.m_s);\n }\n\n inline void Clear() { m_s.clear(); }\n inline bool IsEmpty() const { return m_s.empty(); }\n\n void AddString(int8_t lang, string const & utf8s);\n void AddString(string const & lang, string const & utf8s)\n {\n int8_t const l = GetLangIndex(lang);\n if (l >= 0)\n AddString(l, utf8s);\n }\n\n template \n void ForEachRef(T && functor) const\n {\n size_t i = 0;\n size_t const sz = m_s.size();\n while (i < sz)\n {\n size_t const next = GetNextIndex(i);\n if (!functor((m_s[i] & 0x3F), m_s.substr(i + 1, next - i - 1)))\n return;\n i = next;\n }\n }\n\n bool GetString(int8_t lang, string & utf8s) const;\n bool GetString(string const & lang, string & utf8s) const\n {\n int8_t const l = GetLangIndex(lang);\n if (l >= 0)\n return GetString(l, utf8s);\n else\n return false;\n }\n\n int8_t FindString(string const & utf8s) const;\n\n template void Write(TSink & sink) const\n {\n utils::WriteString(sink, m_s);\n }\n\n template void Read(TSource & src)\n {\n utils::ReadString(src, m_s);\n }\n};\n\nstring DebugPrint(StringUtf8Multilang const & s);\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: dlgpage.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2004-02-03 20:13:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define ITEMID_COLOR_TABLE SID_COLOR_TABLE\n#define ITEMID_GRADIENT_LIST SID_GRADIENT_LIST\n#define ITEMID_HATCH_LIST SID_HATCH_LIST\n#define ITEMID_BITMAP_LIST SID_BITMAP_LIST\n#include \/\/add CHINA001\n#ifndef _SVX_PAGE_HXX\n#include \n#endif\n#ifndef _SVX_DIALOGS_HRC\n#include \n#endif\n#ifndef _SVX_TAB_AREA_HXX\n#include \n#endif\n#ifndef _SVX_DRAWITEM_HXX\n#include \n#endif\n\n#ifndef _SD_SDRESID_HXX\n#include \"sdresid.hxx\"\n#endif\n#include \"dlgpage.hxx\"\n\n#include \"DrawDocShell.hxx\"\n\n\n\/*************************************************************************\n|*\n|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu\n|*\n\\************************************************************************\/\n\nSdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) :\n SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ),\n rOutAttrs ( *pAttr ),\n pDocShell ( pDocSh )\n{\n SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*)\n ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) );\n SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*)\n ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) );\n SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*)\n ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) );\n SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*)\n ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) );\n\n pColorTab = aColorTableItem.GetColorTable();\n pGradientList = aGradientListItem.GetGradientList();\n pHatchingList = aHatchListItem.GetHatchList();\n pBitmapList = aBitmapListItem.GetBitmapList();\n\n FreeResource();\n\n AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0);\n AddTabPage( RID_SVXPAGE_AREA);\/\/CHINA001 AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );\n\n\n nDlgType = 1; \/\/ Vorlagen-Dialog\n nPageType = 0;\n nPos = 0;\n\n nColorTableState = CT_NONE;\n nBitmapListState = CT_NONE;\n nGradientListState = CT_NONE;\n nHatchingListState = CT_NONE;\n\n if(!bAreaPage) \/\/ I have to add the page before I remove it !\n RemoveTabPage( RID_SVXPAGE_AREA );\n}\n\n\n\/*************************************************************************\n|*\n|* Seite wird erzeugt\n|*\n\\************************************************************************\/\n\nvoid SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage)\n{\n switch(nId)\n {\n case RID_SVXPAGE_PAGE:\n ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION);\n ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E );\n break;\n case RID_SVXPAGE_AREA:\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).Construct();\n SfxAllItemSet aSet(*(GetRefreshedSet()->GetPool()));\n aSet.Put (SvxColorTableItem(pColorTab,SID_COLOR_TABLE));\n aSet.Put (SvxGradientListItem(pGradientList,SID_GRADIENT_LIST));\n aSet.Put (SvxHatchListItem(pHatchingList,SID_HATCH_LIST));\n aSet.Put (SvxBitmapListItem(pBitmapList,SID_BITMAP_LIST));\n aSet.Put (SfxUInt16Item(SID_PAGE_TYPE,nPageType));\n aSet.Put (SfxUInt16Item(SID_DLG_TYPE,nDlgType));\n aSet.Put (SfxUInt16Item(SID_TABPAGE_POS,nPos));\n rPage.PageCreated(aSet);\n break;\n }\n}\n\n\n\nINTEGRATION: CWS dialogdiet01 (1.4.22); FILE MERGED 2004\/03\/31 07:50:01 mwu 1.4.22.2: dialogdiet01 merge 2004-03-31 2004\/02\/27 06:01:40 mwu 1.4.22.1: dialogdiet01 2004_02_27\/*************************************************************************\n *\n * $RCSfile: dlgpage.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2004-05-10 15:43:46 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define ITEMID_COLOR_TABLE SID_COLOR_TABLE\n#define ITEMID_GRADIENT_LIST SID_GRADIENT_LIST\n#define ITEMID_HATCH_LIST SID_HATCH_LIST\n#define ITEMID_BITMAP_LIST SID_BITMAP_LIST\n#include \/\/add CHINA001\n\/\/CHINA001 #ifndef _SVX_PAGE_HXX\n\/\/CHINA001 #include \n\/\/CHINA001 #endif\n#ifndef _SVX_DIALOGS_HRC\n#include \n#endif\n#ifndef _SVX_TAB_AREA_HXX\n#include \n#endif\n#ifndef _SVX_DRAWITEM_HXX\n#include \n#endif\n\n#ifndef _SD_SDRESID_HXX\n#include \"sdresid.hxx\"\n#endif\n#include \"dlgpage.hxx\"\n\n#include \"DrawDocShell.hxx\"\n\n#ifndef _AEITEM_HXX \/\/CHINA001\n#include \/\/CHINA001\n#endif \/\/CHINA001\n#include \/\/CHINA001\n#include \/\/CHINA001\n\n\/*************************************************************************\n|*\n|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu\n|*\n\\************************************************************************\/\n\nSdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) :\n SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ),\n rOutAttrs ( *pAttr ),\n pDocShell ( pDocSh )\n{\n SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*)\n ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) );\n SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*)\n ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) );\n SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*)\n ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) );\n SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*)\n ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) );\n\n pColorTab = aColorTableItem.GetColorTable();\n pGradientList = aGradientListItem.GetGradientList();\n pHatchingList = aHatchListItem.GetHatchList();\n pBitmapList = aBitmapListItem.GetBitmapList();\n\n FreeResource();\n\n AddTabPage( RID_SVXPAGE_PAGE); \/\/CHINA001 AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0);\n AddTabPage( RID_SVXPAGE_AREA); \/\/CHINA001 AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );\n\n\n nDlgType = 1; \/\/ Vorlagen-Dialog\n nPageType = 0;\n nPos = 0;\n\n nColorTableState = CT_NONE;\n nBitmapListState = CT_NONE;\n nGradientListState = CT_NONE;\n nHatchingListState = CT_NONE;\n\n if(!bAreaPage) \/\/ I have to add the page before I remove it !\n RemoveTabPage( RID_SVXPAGE_AREA );\n}\n\n\n\/*************************************************************************\n|*\n|* Seite wird erzeugt\n|*\n\\************************************************************************\/\n\nvoid SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage)\n{\n SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));\n switch(nId)\n {\n case RID_SVXPAGE_PAGE:\n \/\/CHINA001 ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION);\n \/\/CHINA001 ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E );\n aSet.Put (SfxAllEnumItem((const USHORT)SID_ENUM_PAGE_MODE, SVX_PAGE_MODE_PRESENTATION)); \/\/CHINA001\n aSet.Put (SfxAllEnumItem((const USHORT)SID_PAPER_START, SVX_PAPER_A0)); \/\/CHINA001\n aSet.Put (SfxAllEnumItem((const USHORT)SID_PAPER_END, SVX_PAPER_E)); \/\/CHINA001\n rPage.PageCreated(aSet); \/\/CHINA001\n break;\n case RID_SVXPAGE_AREA:\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState );\n\/\/CHINA001 ( (SvxAreaTabPage&) rPage ).Construct();\n aSet.Put (SvxColorTableItem(pColorTab,SID_COLOR_TABLE));\n aSet.Put (SvxGradientListItem(pGradientList,SID_GRADIENT_LIST));\n aSet.Put (SvxHatchListItem(pHatchingList,SID_HATCH_LIST));\n aSet.Put (SvxBitmapListItem(pBitmapList,SID_BITMAP_LIST));\n aSet.Put (SfxUInt16Item(SID_PAGE_TYPE,nPageType));\n aSet.Put (SfxUInt16Item(SID_DLG_TYPE,nDlgType));\n aSet.Put (SfxUInt16Item(SID_TABPAGE_POS,nPos));\n rPage.PageCreated(aSet);\n break;\n }\n}\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: docprev.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: dr $ $Date: 2001-06-25 13:34:16 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_OBJSH_HXX \/\/ SfxObjectShell\n#include \n#endif\n\n#ifndef _SV_GDIMTF_HXX \/\/ GDIMetaFile\n#include \n#endif\n\n#ifndef _SV_VIRDEV_HXX \/\/ class VirtualDevice\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_\n#include \n#endif\n\n#ifndef _SD_FADEDEF_H \/\/ enum FadeSpeed\n#include \n#endif\n\n#ifndef _SV_CTRL_HXX \/\/ class Control\n#include \n#endif\n\n#ifndef _SD_FADER_HXX\n#include \"fader.hxx\"\n#endif\n\n#include \"docprev.hxx\"\n#include \"drawdoc.hxx\"\n#include \"docshell.hxx\"\n#include \"viewshel.hxx\"\n#include \"showview.hxx\"\n\nusing namespace ::com::sun::star;\n\nconst int SdDocPreviewWin::FRAME = 4;\n\nvoid SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, USHORT nShowPage )\n{\n\n SdDrawDocShell* pDocShell = PTR_CAST(SdDrawDocShell,pObj);\n SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;\n if(pDoc)\n {\n const USHORT nPageCount = pDoc->GetSdPageCount(PK_STANDARD);\n USHORT nPgNum = 0;\n while( nPgNum < nPageCount )\n {\n pDoc->SetSelected( pDoc->GetSdPage( nPgNum, PK_STANDARD ), nPgNum == nShowPage );\n nPgNum++;\n }\n }\n\n GDIMetaFile* pFile = pObj ? pObj->GetPreviewMetaFile( ) : 0;\n delete pMetaFile;\n pMetaFile = pFile;\n m_pObj = pObj;\n Invalidate();\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )\n: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)\n{\n SetBorderStyle( WINDOW_BORDER_MONO );\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent )\n: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)\n{\n SetBorderStyle( WINDOW_BORDER_MONO );\n Resize();\n Show();\n}\n\nvoid SdDocPreviewWin::Resize()\n{\n Invalidate();\n}\n\nvoid SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )\n{\n delete pMetaFile;\n pMetaFile = pFile;\n Invalidate();\n}\n\nvoid SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )\n{\n Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );\n long nWidth = rSize.Width() - 2*FRAME;\n long nHeight = rSize.Height() - 2*FRAME;\n if( nWidth < 0 ) nWidth = 0;\n if( nHeight < 0 ) nHeight = 0;\n\n double dRatio=((double)aTmpSize.Width())\/aTmpSize.Height();\n double dRatioPreV=((double) nWidth ) \/ nHeight;\n\n if (dRatio>dRatioPreV)\n {\n rSize=Size(nWidth, (USHORT)(nWidth\/dRatio));\n rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())\/2));\n }\n else\n {\n rSize=Size((USHORT)(nHeight*dRatio), nHeight);\n rPoint=Point((USHORT)((nWidth-rSize.Width())\/2),0);\n }\n}\n\nvoid SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )\n{\n Point aPoint;\n Size aSize = pVDev->GetOutputSize();\n Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );\n CalcSizeAndPos( pFile, aSize, aPoint );\n bPoint -= aPoint;\n aPoint += Point( FRAME, FRAME );\n\n pVDev->SetLineColor();\n pVDev->SetFillColor( Color( COL_LIGHTGRAY ) );\n pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));\n if( pFile )\n {\n pVDev->SetFillColor( Color( COL_WHITE ) );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n pFile->WindStart();\n pFile->Play( pVDev, aPoint, aSize );\n }\n}\n\nvoid SdDocPreviewWin::Paint( const Rectangle& rRect )\n{\n ImpPaint( pMetaFile, (VirtualDevice*)this );\n}\n\nvoid SdDocPreviewWin::ShowEffect( presentation::FadeEffect eEffect, FadeSpeed eSpeed )\n{\n if(bInEffect || !pMetaFile)\n return;\n\n bInEffect = TRUE;\n\n Point aPoint;\n Size aSize = GetOutputSize();\n Point bPoint( aSize.Width() - 2*FRAME, aSize.Height() - 2*FRAME );\n CalcSizeAndPos( pMetaFile, aSize, aPoint );\n bPoint -= aPoint;\n\n aPoint += Point( FRAME, FRAME );\n bPoint += Point( FRAME, FRAME );\n\n \/\/ Hintergrund Schwarz\n SetLineColor();\n SetFillColor( Color( COL_LIGHTGRAY ) );\n DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));\n\n \/\/ korrigierte Seitengroesse, sonst kommt die letzte Pixelreihe(spalte)\n \/\/ nicht mit\n Size aPixelSize = PixelToLogic(Size(1,1));\n aSize.Width() += aPixelSize.Width();\n aSize.Height() += aPixelSize.Height();\n\n \/\/ virtuelle Devices anlegen\n MapMode aMapMode = GetMapMode();\n aMapMode.SetOrigin(Point(0,0));\n\n VirtualDevice* pVDev = new VirtualDevice(*this);\n pVDev->SetMapMode(aMapMode);\n pVDev->SetOutputSize(aSize); \/\/ aCPageSize);\n\n if( pMetaFile )\n {\n pMetaFile->WindStart();\n pMetaFile->Play( pVDev, Point( 0,0 ), aSize );\n }\n\n \/\/ ein Fader zum Ueberblenden\n Fader* pFader = new Fader(this);\n pFader->SetEffect( eEffect );\n pFader->SetSpeed( eSpeed );\n pFader->SetSource(Rectangle(Point(), aSize));\n pFader->SetTarget(Rectangle(aPoint, aSize));\n\n \/\/ virtuelle Devices an Fader uebergeben\n pFader->SetNewVirtualDevice(pVDev);\n\n \/\/ ueberblenden\n pFader->Fade();\n\n delete pFader;\n delete pVDev;\n\n bInEffect = FALSE;\n}\n\nlong SdDocPreviewWin::Notify( NotifyEvent& rNEvt )\n{\n if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )\n {\n const MouseEvent* pMEvt = rNEvt.GetMouseEvent();\n if ( pMEvt->IsLeft() )\n {\n if( rNEvt.GetWindow() == this )\n {\n if(aClickHdl.IsSet())\n aClickHdl.Call(this);\n }\n }\n }\n\n return Control::Notify( rNEvt );\n}\n\n\n#101825# preview is now HC compiliant\/*************************************************************************\n *\n * $RCSfile: docprev.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: cl $ $Date: 2002-08-01 11:38:00 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_OBJSH_HXX \/\/ SfxObjectShell\n#include \n#endif\n\n#ifndef _SV_GDIMTF_HXX \/\/ GDIMetaFile\n#include \n#endif\n\n#ifndef _SV_VIRDEV_HXX \/\/ class VirtualDevice\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_\n#include \n#endif\n\n#ifndef _SD_FADEDEF_H \/\/ enum FadeSpeed\n#include \n#endif\n\n#ifndef _SV_CTRL_HXX \/\/ class Control\n#include \n#endif\n\n#ifndef _SD_FADER_HXX\n#include \"fader.hxx\"\n#endif\n\n#include \"docprev.hxx\"\n#include \"drawdoc.hxx\"\n#include \"docshell.hxx\"\n#include \"viewshel.hxx\"\n#include \"showview.hxx\"\n\nusing namespace ::com::sun::star;\n\nconst int SdDocPreviewWin::FRAME = 4;\n\nvoid SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, USHORT nShowPage )\n{\n\n SdDrawDocShell* pDocShell = PTR_CAST(SdDrawDocShell,pObj);\n SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;\n if(pDoc)\n {\n const USHORT nPageCount = pDoc->GetSdPageCount(PK_STANDARD);\n USHORT nPgNum = 0;\n while( nPgNum < nPageCount )\n {\n pDoc->SetSelected( pDoc->GetSdPage( nPgNum, PK_STANDARD ), nPgNum == nShowPage );\n nPgNum++;\n }\n }\n\n GDIMetaFile* pFile = pObj ? pObj->GetPreviewMetaFile( ) : 0;\n delete pMetaFile;\n pMetaFile = pFile;\n m_pObj = pObj;\n Invalidate();\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )\n: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)\n{\n SetBorderStyle( WINDOW_BORDER_MONO );\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent )\n: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)\n{\n SetBorderStyle( WINDOW_BORDER_MONO );\n Resize();\n Show();\n}\n\nvoid SdDocPreviewWin::Resize()\n{\n Invalidate();\n}\n\nvoid SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )\n{\n delete pMetaFile;\n pMetaFile = pFile;\n Invalidate();\n}\n\nvoid SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )\n{\n Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );\n long nWidth = rSize.Width() - 2*FRAME;\n long nHeight = rSize.Height() - 2*FRAME;\n if( nWidth < 0 ) nWidth = 0;\n if( nHeight < 0 ) nHeight = 0;\n\n double dRatio=((double)aTmpSize.Width())\/aTmpSize.Height();\n double dRatioPreV=((double) nWidth ) \/ nHeight;\n\n if (dRatio>dRatioPreV)\n {\n rSize=Size(nWidth, (USHORT)(nWidth\/dRatio));\n rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())\/2));\n }\n else\n {\n rSize=Size((USHORT)(nHeight*dRatio), nHeight);\n rPoint=Point((USHORT)((nWidth-rSize.Width())\/2),0);\n }\n}\n\nvoid SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )\n{\n Point aPoint;\n Size aSize = pVDev->GetOutputSize();\n Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );\n CalcSizeAndPos( pFile, aSize, aPoint );\n bPoint -= aPoint;\n aPoint += Point( FRAME, FRAME );\n\n pVDev->SetLineColor();\n pVDev->SetFillColor( Color( COL_LIGHTGRAY ) );\n pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));\n if( pFile )\n {\n pVDev->SetFillColor( Color( COL_WHITE ) );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n pFile->WindStart();\n pFile->Play( pVDev, aPoint, aSize );\n }\n}\n\nvoid SdDocPreviewWin::Paint( const Rectangle& rRect )\n{\n SvtAccessibilityOptions aAccOptions;\n bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();\n SetDrawMode( bUseContrast ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );\n\n ImpPaint( pMetaFile, (VirtualDevice*)this );\n}\n\nvoid SdDocPreviewWin::ShowEffect( presentation::FadeEffect eEffect, FadeSpeed eSpeed )\n{\n if(bInEffect || !pMetaFile)\n return;\n\n bInEffect = TRUE;\n\n Point aPoint;\n Size aSize = GetOutputSize();\n Point bPoint( aSize.Width() - 2*FRAME, aSize.Height() - 2*FRAME );\n CalcSizeAndPos( pMetaFile, aSize, aPoint );\n bPoint -= aPoint;\n\n aPoint += Point( FRAME, FRAME );\n bPoint += Point( FRAME, FRAME );\n\n \/\/ Hintergrund Schwarz\n SetLineColor();\n SetFillColor( Color( COL_LIGHTGRAY ) );\n DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));\n\n \/\/ korrigierte Seitengroesse, sonst kommt die letzte Pixelreihe(spalte)\n \/\/ nicht mit\n Size aPixelSize = PixelToLogic(Size(1,1));\n aSize.Width() += aPixelSize.Width();\n aSize.Height() += aPixelSize.Height();\n\n \/\/ virtuelle Devices anlegen\n MapMode aMapMode = GetMapMode();\n aMapMode.SetOrigin(Point(0,0));\n\n VirtualDevice* pVDev = new VirtualDevice(*this);\n pVDev->SetMapMode(aMapMode);\n pVDev->SetOutputSize(aSize); \/\/ aCPageSize);\n\n if( pMetaFile )\n {\n pMetaFile->WindStart();\n pMetaFile->Play( pVDev, Point( 0,0 ), aSize );\n }\n\n \/\/ ein Fader zum Ueberblenden\n Fader* pFader = new Fader(this);\n pFader->SetEffect( eEffect );\n pFader->SetSpeed( eSpeed );\n pFader->SetSource(Rectangle(Point(), aSize));\n pFader->SetTarget(Rectangle(aPoint, aSize));\n\n \/\/ virtuelle Devices an Fader uebergeben\n pFader->SetNewVirtualDevice(pVDev);\n\n \/\/ ueberblenden\n pFader->Fade();\n\n delete pFader;\n delete pVDev;\n\n bInEffect = FALSE;\n}\n\nlong SdDocPreviewWin::Notify( NotifyEvent& rNEvt )\n{\n if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )\n {\n const MouseEvent* pMEvt = rNEvt.GetMouseEvent();\n if ( pMEvt->IsLeft() )\n {\n if( rNEvt.GetWindow() == this )\n {\n if(aClickHdl.IsSet())\n aClickHdl.Call(this);\n }\n }\n }\n\n return Control::Notify( rNEvt );\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: fuvect.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:48:36 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SV_POLY_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVDOPATH_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_SVDOGRAF_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_SVDEDTV_HXX \/\/autogen\n#include \n#endif\n\n#pragma hdrstop\n\n#include \"sdview.hxx\"\n#include \"viewshel.hxx\"\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n#include \"vectdlg.hxx\"\n#include \"fuvect.hxx\"\n\nTYPEINIT1( FuVectorize, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuVectorize::FuVectorize( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,\n SdDrawDocument* pDoc, SfxRequest& rReq ) :\n FuPoor (pViewSh, pWin, pView, pDoc, rReq)\n{\n const SdrMarkList& rMarkList = pView->GetMarkList();\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) )\n {\n SdVectorizeDlg aDlg( (Window*) pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );\n\n if( aDlg.Execute() == RET_OK )\n {\n const GDIMetaFile& rMtf = aDlg.GetGDIMetaFile();\n SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );\n\n if( pPageView && rMtf.GetActionCount() )\n {\n SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();\n String aStr( pView->GetMarkDescription() );\n\n aStr.Append( sal_Unicode(' ') );\n aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );\n pView->BegUndo( aStr );\n pVectObj->SetGraphic( rMtf );\n pView->ReplaceObject( pObj, *pPageView, pVectObj );\n pView->EndUndo();\n }\n }\n }\n }\n}\n\nINTEGRATION: CWS vclcleanup02 (1.1.1.1.336); FILE MERGED 2003\/12\/11 09:17:29 mt 1.1.1.1.336.1: #i23061# VCL cleanup, removed headers, methods and types...\/*************************************************************************\n *\n * $RCSfile: fuvect.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2004-01-06 18:46:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _TL_POLY_HXX\n#include \n#endif\n#ifndef _SVDOPATH_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_SVDOGRAF_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_SVDEDTV_HXX \/\/autogen\n#include \n#endif\n\n#pragma hdrstop\n\n#include \"sdview.hxx\"\n#include \"viewshel.hxx\"\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n#include \"vectdlg.hxx\"\n#include \"fuvect.hxx\"\n\nTYPEINIT1( FuVectorize, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuVectorize::FuVectorize( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,\n SdDrawDocument* pDoc, SfxRequest& rReq ) :\n FuPoor (pViewSh, pWin, pView, pDoc, rReq)\n{\n const SdrMarkList& rMarkList = pView->GetMarkList();\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) )\n {\n SdVectorizeDlg aDlg( (Window*) pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );\n\n if( aDlg.Execute() == RET_OK )\n {\n const GDIMetaFile& rMtf = aDlg.GetGDIMetaFile();\n SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );\n\n if( pPageView && rMtf.GetActionCount() )\n {\n SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();\n String aStr( pView->GetMarkDescription() );\n\n aStr.Append( sal_Unicode(' ') );\n aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );\n pView->BegUndo( aStr );\n pVectObj->SetGraphic( rMtf );\n pView->ReplaceObject( pObj, *pPageView, pVectObj );\n pView->EndUndo();\n }\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\nstruct City{\n float x;\n float y;\n};\n\nfloat distance(const City& c1, const City& c2)\n{\n return std::hypot(c2.x - c1.x, c2.y - c1.y);\n}\n\nusing Trajectory = std::vector;\n\nstd::ostream& operator<<(std::ostream& o, const Trajectory& t)\n{\n for (auto& c : t)\n o << \"[\" << c.x << \", \" << c.y << \"], \";\n\n return o;\n}\n\nstruct Generator{\n Trajectory operator()(const Trajectory& t, const SimulatedAnnealing& sa) const\n {\n Trajectory t2 = t;\n\n std::shuffle(begin(t2), end(t2), std::default_random_engine{});\n\n return t2;\n }\n};\n\nstruct Energy{\n float operator()(const Trajectory& t) const\n {\n std::vector distances;\n\n for (int i = 1; i < t.size(); ++i)\n distances.push_back(distance(t[i-1], t[i]));\n\n return std::accumulate(begin(distances), end(distances), 0.0);\n }\n};\n\nint main()\n{\n Energy energy;\n Generator generator;\n\n City c0 { 200.0, 800.0};\n City c1 {3600.0, 2300.0};\n City c2 {3100.0, 3300.0};\n City c3 {4700.0, 5750.0};\n City c4 {5400.0, 5750.0};\n City c5 {5608.0, 7103.0};\n City c6 {4493.0, 7102.0};\n City c7 {3600.0, 6950.0};\n Trajectory trajectory{c0, c1, c2, c3, c4, c5, c6, c7};\n\n std::cout << \"Optimal trajectory: \" << trajectory << std::endl;\n std::cout << \"Optimal distance: \" << energy(trajectory) << std::endl;\n\n SimulatedAnnealing sim(1e3, \/\/ start temp\n 1e-1, \/\/ stop temp\n int(1e4), \/\/ max it\n energy(trajectory)); \/\/ energy min\n\n std::shuffle(begin(trajectory), end(trajectory), std::default_random_engine{});\n\n std::cout << \"Initial trajectory: \" << trajectory << std::endl;\n\n sim(energy, trajectory, generator);\n\n std::cout << \"Final trajectory: \" << trajectory << std::endl;\n\n return 0;\n}\n[traveling_salesman] fixed warning#include \n#include \n#include \n\n#include \n\nstruct City{\n float x;\n float y;\n};\n\nfloat distance(const City& c1, const City& c2)\n{\n return std::hypot(c2.x - c1.x, c2.y - c1.y);\n}\n\nusing Trajectory = std::vector;\n\nstd::ostream& operator<<(std::ostream& o, const Trajectory& t)\n{\n for (auto& c : t)\n o << \"[\" << c.x << \", \" << c.y << \"], \";\n\n return o;\n}\n\nstruct Generator{\n Trajectory operator()(const Trajectory& t, const SimulatedAnnealing& sa) const\n {\n Trajectory t2 = t;\n\n std::shuffle(begin(t2), end(t2), std::default_random_engine{});\n\n return t2;\n }\n};\n\nstruct Energy{\n float operator()(const Trajectory& t) const\n {\n std::vector distances;\n\n for (size_t i = 1; i < t.size(); ++i)\n distances.push_back(distance(t[i - 1], t[i]));\n\n return std::accumulate(begin(distances), end(distances), 0.0);\n }\n};\n\nint main()\n{\n Energy energy;\n Generator generator;\n\n City c0 { 200.0, 800.0};\n City c1 {3600.0, 2300.0};\n City c2 {3100.0, 3300.0};\n City c3 {4700.0, 5750.0};\n City c4 {5400.0, 5750.0};\n City c5 {5608.0, 7103.0};\n City c6 {4493.0, 7102.0};\n City c7 {3600.0, 6950.0};\n Trajectory trajectory{c0, c1, c2, c3, c4, c5, c6, c7};\n\n std::cout << \"Optimal trajectory: \" << trajectory << std::endl;\n std::cout << \"Optimal distance: \" << energy(trajectory) << std::endl;\n\n SimulatedAnnealing sim(1e3, \/\/ start temp\n 1e-1, \/\/ stop temp\n int(1e4), \/\/ max it\n energy(trajectory)); \/\/ energy min\n\n std::shuffle(begin(trajectory), end(trajectory), std::default_random_engine{});\n\n std::cout << \"Initial trajectory: \" << trajectory << std::endl;\n\n sim(energy, trajectory, generator);\n\n std::cout << \"Final trajectory: \" << trajectory << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n Dynamics\/Kinematics modeling and simulation library.\n Copyright (C) 1999 by Michael Alexander Ewert\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n*\/\n\n#include \"csphyzik\/math3d.h\"\n#include \"csphyzik\/refframe.h\"\n#include \"csphyzik\/rigidbod.h\"\n#include \"csphyzik\/debug.h\"\n#include \"csphyzik\/contact.h\"\n\nctRigidBody::ctRigidBody()\n{\n}\n\nctRigidBody::ctRigidBody( ctReferenceFrame &ref ) : ctDynamicEntity( ref )\n{\n\n}\n\nctRigidBody::~ctRigidBody()\n{\n\n}\n\n\nctRigidBody *ctRigidBody::new_ctRigidBody()\n{\nctReferenceFrame *rf = new ctReferenceFrame();\n\treturn new ctRigidBody( *rf );\n\n}\nctRigidBody *ctRigidBody::new_ctRigidBody( coord x, coord y, coord z )\n{\nctReferenceFrame *rf = new ctReferenceFrame();\n\/\/!me set coords\n\treturn new ctRigidBody( *rf );\n\n}\n\n\n\/\/ w is actually a secondary value that is calculated from L\n\/\/ so need to calc L to set w\nvoid ctRigidBody::set_angular_v( const ctVector3 &pw )\n{\n\tctMatrix3 I_inv_world = get_I_inv_world();\n\n\t\/\/ angular speed = \n\t\/\/ inverse of inertia tensor in world coords * angular momentum\n\tw = pw;\n\tL = I_inv_world.get_transpose() * w;\n}\n\n\/\/ v is a secondary value that is calculated from momentum\nvoid ctRigidBody::set_v( const ctVector3 &pv )\n{ \n v = pv; \n P = v*m;\n}\n\nint ctRigidBody::set_state( real *state_array )\n{\nint len;\n\n\tlen = ctPhysicalEntity::set_state( state_array );\t\n\tstate_array += len;\n\t\n\t*state_array++ = P[0];\n\t*state_array++ = P[1];\n\t*state_array++ = P[2];\n\n\t*state_array++ = L[0];\n\t*state_array++ = L[1];\n\t*state_array++ = L[2];\n\n\treturn ctRigidBody::get_state_size(); \n}\n\n\nint ctRigidBody::set_delta_state( real *state_array )\n{\nint len;\n\n\tlen = ctPhysicalEntity::set_delta_state( state_array );\t\n\tstate_array += len;\n\t\n\t\/\/ dP\/dt = F derivitive of momentum with time = applied force\n\t*state_array++ = F[0]; \n\t*state_array++ = F[1];\n\t*state_array++ = F[2];\n\n\t\/\/ dL\/dt = T derivitive of angular momentum with time = applied torque\n\t*state_array++ = T[0];\n\t*state_array++ = T[1];\n\t*state_array++ = T[2];\n\n\treturn ctRigidBody::get_state_size(); \n\n}\n\nint ctRigidBody::get_state( const real *state_array )\n{\nint len;\n\tlen = ctPhysicalEntity::get_state( state_array );\n\tstate_array += len;\n\n\t\/\/ momentum\n\tP[0] = *state_array++;\n\tP[1] = *state_array++;\n\tP[2] = *state_array++;\n\n\t\/\/ angular momentum\n\tL[0] = *state_array++;\n\tL[1] = *state_array++;\n\tL[2] = *state_array++;\n\n\t\/\/ calc velocity from eqn: p = mv momentum = mass * velocity\n\tif( m >= MIN_REAL ){\n\t\tv = P\/m;\n\t}\n\n\t\/\/ calculate inverse of inertia tensor in world coords \n\t\/\/ this result is used to calculate angular speed w\n\tctMatrix3 I_inv_world = get_I_inv_world();\n\n\t\/\/ angular speed = \n\t\/\/ inverse of inertia tensor in world coords * angular momentum\n\tw = I_inv_world * L;\n\n\treturn ctRigidBody::get_state_size(); \n}\n\n\/\/ calc I for a block of given dimensions\nvoid ctRigidBody::calc_simple_I_tensor( real x, real y, real z )\n{\nreal k;\n\t\n\tif( m > MIN_REAL ){\n\t\tk = m\/12.0;\n\t}else{\n\t\tk = MIN_REAL;\n\t}\n\tfor( int i = 0; i < 3; i++ )\n\t\tfor( int j = 0; j < 3; j++ )\n\t\t\tI[i][j] = 0.0;\n\n\tI[0][0] = (y*y + z*z)*k;\n\tI[1][1] = (x*x + z*z)*k;\n\tI[2][2] = (x*x + y*y)*k;\n\t\n\tI_inv[0][0] = ( y > MIN_REAL || z > MIN_REAL ) ? 1.0\/I[0][0] : MAX_REAL;\n\tI_inv[1][1] = ( x > MIN_REAL || z > MIN_REAL ) ? 1.0\/I[1][1] : MAX_REAL;\n\tI_inv[2][2] = ( x > MIN_REAL || y > MIN_REAL ) ? 1.0\/I[2][2] : MAX_REAL;\n}\n\nvoid ctRigidBody::set_m( real pm )\n{\n\tif( pm > MIN_REAL ){\n\t\tI *= ( pm\/m );\n\t\tI_inv *= ( m\/pm );\n\t\tm = pm;\n\t}\n}\n\n\n\/\/ collision response\nvoid ctRigidBody::resolve_collision( ctCollidingContact *cont )\n{\nctVector3 j;\nreal v_rel; \/\/ relative velocity of collision points\nctVector3 ra_v, rb_v;\nreal j_magnitude;\nreal bottom;\nreal ma_inv, mb_inv; \/\/ 1\/mass_body\nreal rota, rotb; \/\/ contribution from rotational inertia\nctVector3 & n = cont->n;\nctVector3 ra, rb; \/\/ center of body to collision point in inertail ref frame \n\/\/ keep track of previous object collided with.\n\/\/ in simultaneous collisions with the same object the restituion should\n\/\/ only be factored in once. So all subsequent collisions are handled as\n\/\/ seperate collisions, but with a restitution of 1.0\n\/\/ if they are different objects then treat them as multiple collisions with\n\/\/ normal restitution.\n\/\/!me this isn't actually a very good method.... maybe something better can be \n\/\/!me implemented once contact force solver is implemented\nctPhysicalEntity *prev;\n\n\/\/!debug\n\/\/int hit_cout = 0;\n\n \/\/ since NULL is used for an immovable object we need a \n \/\/ different \"nothing\" pointer\n prev = this; \n\n while( cont != NULL ){\n\n ctVector3 body_x = get_pos();\n ra = cont->contact_p - body_x;\n\n ra_v = get_angular_v()%ra + get_v();\n\n if( cont->body_b == NULL ){\n v_rel = n*ra_v;\n }else{\n \/\/rb = (cont->body_b->get_this_to_world())*cont->p_b;\n rb = cont->contact_p - cont->body_b->get_pos();\n rb_v = cont->body_b->get_angular_v()%rb + cont->body_b->get_v();\n v_rel = n*(ra_v - rb_v);\n }\n\n \/\/ if the objects are traveling towards each other do collision response\n if( v_rel < 0 ){\n\n \/\/ DEBUGLOGF2( \"contact %lf o %lf, \", cont->contact_p[0], body_x[0] );\n \/\/ DEBUGLOGF2( \"contact %lf o %lf, \", cont->contact_p[1], body_x[1] );\n \/\/ DEBUGLOGF2( \"contact %lf o %lf\\n \", cont->contact_p[2], body_x[2] );\n\n ma_inv = 1.0\/get_impulse_m();\n rota = n * ((get_impulse_I_inv()*( ra%n ) )%ra); \n\n if( cont->body_b == NULL ){\n \/\/ hit some kind of immovable object\n mb_inv = 0;\n rotb = 0;\n }else{\n mb_inv = 1.0\/cont->body_b->get_impulse_m();\n rotb = n * ((cont->body_b->get_impulse_I_inv()*( rb%n ) )%rb);\n }\n\n \/\/ bottom part of equation\n bottom = ma_inv + mb_inv + rota + rotb;\n \n if( prev != cont->body_b ){\n j_magnitude = -(1.0 + cont->restitution ) * v_rel \/ bottom;\n }else{\n \/\/ if we are dealing with a simulatneous collisin with with\n \/\/ same object.\n j_magnitude = -(1.0 + 1.0 ) * v_rel \/ bottom;\n }\n\n j = n*j_magnitude;\n apply_impulse( ra, j );\n\n if( cont->body_b != NULL ){\n cont->body_b->apply_impulse( rb, j*(-1.0) );\n }\n\n \/\/ treat next simultaneous collision as a seperate collision.\n prev = cont->body_b;\n\n \/\/ DEBUGLOGF( \"respond %d\\n\", ++hit_cout );\n }\n cont = cont->next; \n }\n}\n\nvoid ctRigidBody::apply_impulse( ctVector3 jx, ctVector3 jv )\n{\nreal mass = get_impulse_m();\n \n P += jv;\n v = P * (( mass > MIN_REAL ) ? 1.0\/mass : MAX_REAL);\n\n L += jx % jv;\n\n\tctMatrix3 I_inv_world = get_I_inv_world();\n w = I_inv_world * L;\n\n}Converted tabs to spaces. I'm also testing CVS.\/*\n Dynamics\/Kinematics modeling and simulation library.\n Copyright (C) 1999 by Michael Alexander Ewert\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n*\/\n\n#include \"csphyzik\/math3d.h\"\n#include \"csphyzik\/refframe.h\"\n#include \"csphyzik\/rigidbod.h\"\n#include \"csphyzik\/debug.h\"\n#include \"csphyzik\/contact.h\"\n\nctRigidBody::ctRigidBody()\n{\n}\n\nctRigidBody::ctRigidBody( ctReferenceFrame &ref ) : ctDynamicEntity( ref )\n{\n\n}\n\nctRigidBody::~ctRigidBody()\n{\n\n}\n\n\nctRigidBody *ctRigidBody::new_ctRigidBody()\n{\nctReferenceFrame *rf = new ctReferenceFrame();\n return new ctRigidBody( *rf );\n\n}\nctRigidBody *ctRigidBody::new_ctRigidBody( coord x, coord y, coord z )\n{\nctReferenceFrame *rf = new ctReferenceFrame();\n\/\/!me set coords\n return new ctRigidBody( *rf );\n\n}\n\n\n\/\/ w is actually a secondary value that is calculated from L\n\/\/ so need to calc L to set w\nvoid ctRigidBody::set_angular_v( const ctVector3 &pw )\n{\n ctMatrix3 I_inv_world = get_I_inv_world();\n\n \/\/ angular speed = \n \/\/ inverse of inertia tensor in world coords * angular momentum\n w = pw;\n L = I_inv_world.get_transpose() * w;\n}\n\n\/\/ v is a secondary value that is calculated from momentum\nvoid ctRigidBody::set_v( const ctVector3 &pv )\n{ \n v = pv; \n P = v*m;\n}\n\nint ctRigidBody::set_state( real *state_array )\n{\nint len;\n\n len = ctPhysicalEntity::set_state( state_array ); \n state_array += len;\n \n *state_array++ = P[0];\n *state_array++ = P[1];\n *state_array++ = P[2];\n\n *state_array++ = L[0];\n *state_array++ = L[1];\n *state_array++ = L[2];\n\n return ctRigidBody::get_state_size(); \n}\n\n\nint ctRigidBody::set_delta_state( real *state_array )\n{\nint len;\n\n len = ctPhysicalEntity::set_delta_state( state_array ); \n state_array += len;\n \n \/\/ dP\/dt = F derivitive of momentum with time = applied force\n *state_array++ = F[0]; \n *state_array++ = F[1];\n *state_array++ = F[2];\n\n \/\/ dL\/dt = T derivitive of angular momentum with time = applied torque\n *state_array++ = T[0];\n *state_array++ = T[1];\n *state_array++ = T[2];\n\n return ctRigidBody::get_state_size(); \n\n}\n\nint ctRigidBody::get_state( const real *state_array )\n{\nint len;\n len = ctPhysicalEntity::get_state( state_array );\n state_array += len;\n\n \/\/ momentum\n P[0] = *state_array++;\n P[1] = *state_array++;\n P[2] = *state_array++;\n\n \/\/ angular momentum\n L[0] = *state_array++;\n L[1] = *state_array++;\n L[2] = *state_array++;\n\n \/\/ calc velocity from eqn: p = mv momentum = mass * velocity\n if( m >= MIN_REAL ){\n v = P\/m;\n }\n\n \/\/ calculate inverse of inertia tensor in world coords \n \/\/ this result is used to calculate angular speed w\n ctMatrix3 I_inv_world = get_I_inv_world();\n\n \/\/ angular speed = \n \/\/ inverse of inertia tensor in world coords * angular momentum\n w = I_inv_world * L;\n\n return ctRigidBody::get_state_size(); \n}\n\n\/\/ calc I for a block of given dimensions\nvoid ctRigidBody::calc_simple_I_tensor( real x, real y, real z )\n{\nreal k;\n \n if( m > MIN_REAL ){\n k = m\/12.0;\n }else{\n k = MIN_REAL;\n }\n for( int i = 0; i < 3; i++ )\n for( int j = 0; j < 3; j++ )\n I[i][j] = 0.0;\n\n I[0][0] = (y*y + z*z)*k;\n I[1][1] = (x*x + z*z)*k;\n I[2][2] = (x*x + y*y)*k;\n \n I_inv[0][0] = ( y > MIN_REAL || z > MIN_REAL ) ? 1.0\/I[0][0] : MAX_REAL;\n I_inv[1][1] = ( x > MIN_REAL || z > MIN_REAL ) ? 1.0\/I[1][1] : MAX_REAL;\n I_inv[2][2] = ( x > MIN_REAL || y > MIN_REAL ) ? 1.0\/I[2][2] : MAX_REAL;\n}\n\nvoid ctRigidBody::set_m( real pm )\n{\n if( pm > MIN_REAL ){\n I *= ( pm\/m );\n I_inv *= ( m\/pm );\n m = pm;\n }\n}\n\n\n\/\/ collision response\nvoid ctRigidBody::resolve_collision( ctCollidingContact *cont )\n{\nctVector3 j;\nreal v_rel; \/\/ relative velocity of collision points\nctVector3 ra_v, rb_v;\nreal j_magnitude;\nreal bottom;\nreal ma_inv, mb_inv; \/\/ 1\/mass_body\nreal rota, rotb; \/\/ contribution from rotational inertia\nctVector3 & n = cont->n;\nctVector3 ra, rb; \/\/ center of body to collision point in inertail ref frame \n\/\/ keep track of previous object collided with.\n\/\/ in simultaneous collisions with the same object the restituion should\n\/\/ only be factored in once. So all subsequent collisions are handled as\n\/\/ seperate collisions, but with a restitution of 1.0\n\/\/ if they are different objects then treat them as multiple collisions with\n\/\/ normal restitution.\n\/\/!me this isn't actually a very good method.... maybe something better can be \n\/\/!me implemented once contact force solver is implemented\nctPhysicalEntity *prev;\n\n\/\/!debug\n\/\/int hit_cout = 0;\n\n \/\/ since NULL is used for an immovable object we need a \n \/\/ different \"nothing\" pointer\n prev = this; \n\n while( cont != NULL ){\n\n ctVector3 body_x = get_pos();\n ra = cont->contact_p - body_x;\n\n ra_v = get_angular_v()%ra + get_v();\n\n if( cont->body_b == NULL ){\n v_rel = n*ra_v;\n }else{\n \/\/rb = (cont->body_b->get_this_to_world())*cont->p_b;\n rb = cont->contact_p - cont->body_b->get_pos();\n rb_v = cont->body_b->get_angular_v()%rb + cont->body_b->get_v();\n v_rel = n*(ra_v - rb_v);\n }\n\n \/\/ if the objects are traveling towards each other do collision response\n if( v_rel < 0 ){\n\n \/\/ DEBUGLOGF2( \"contact %lf o %lf, \", cont->contact_p[0], body_x[0] );\n \/\/ DEBUGLOGF2( \"contact %lf o %lf, \", cont->contact_p[1], body_x[1] );\n \/\/ DEBUGLOGF2( \"contact %lf o %lf\\n \", cont->contact_p[2], body_x[2] );\n\n ma_inv = 1.0\/get_impulse_m();\n rota = n * ((get_impulse_I_inv()*( ra%n ) )%ra); \n\n if( cont->body_b == NULL ){\n \/\/ hit some kind of immovable object\n mb_inv = 0;\n rotb = 0;\n }else{\n mb_inv = 1.0\/cont->body_b->get_impulse_m();\n rotb = n * ((cont->body_b->get_impulse_I_inv()*( rb%n ) )%rb);\n }\n\n \/\/ bottom part of equation\n bottom = ma_inv + mb_inv + rota + rotb;\n \n if( prev != cont->body_b ){\n j_magnitude = -(1.0 + cont->restitution ) * v_rel \/ bottom;\n }else{\n \/\/ if we are dealing with a simulatneous collisin with with\n \/\/ same object.\n j_magnitude = -(1.0 + 1.0 ) * v_rel \/ bottom;\n }\n\n j = n*j_magnitude;\n apply_impulse( ra, j );\n\n if( cont->body_b != NULL ){\n cont->body_b->apply_impulse( rb, j*(-1.0) );\n }\n\n \/\/ treat next simultaneous collision as a seperate collision.\n prev = cont->body_b;\n\n \/\/ DEBUGLOGF( \"respond %d\\n\", ++hit_cout );\n }\n cont = cont->next; \n }\n}\n\nvoid ctRigidBody::apply_impulse( ctVector3 jx, ctVector3 jv )\n{\nreal mass = get_impulse_m();\n \n P += jv;\n v = P * (( mass > MIN_REAL ) ? 1.0\/mass : MAX_REAL);\n\n L += jx % jv;\n\n ctMatrix3 I_inv_world = get_I_inv_world();\n w = I_inv_world * L;\n\n}<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2018, University of Edinburgh\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \n#include \n\n#include \n\nREGISTER_PROBLEM_TYPE(\"BoundedEndPoseProblem\", exotica::BoundedEndPoseProblem)\n\nnamespace exotica\n{\nBoundedEndPoseProblem::BoundedEndPoseProblem()\n{\n flags_ = KIN_FK | KIN_J;\n}\n\nBoundedEndPoseProblem::~BoundedEndPoseProblem() = default;\n\nEigen::MatrixXd BoundedEndPoseProblem::GetBounds() const\n{\n return scene_->GetKinematicTree().GetJointLimits();\n}\n\nvoid BoundedEndPoseProblem::Instantiate(const BoundedEndPoseProblemInitializer& init)\n{\n num_tasks = tasks_.size();\n length_Phi = 0;\n length_jacobian = 0;\n for (int i = 0; i < num_tasks; ++i)\n {\n AppendVector(Phi.map, tasks_[i]->GetLieGroupIndices());\n length_Phi += tasks_[i]->length;\n length_jacobian += tasks_[i]->length_jacobian;\n }\n Phi.SetZero(length_Phi);\n W = Eigen::MatrixXd::Identity(N, N);\n if (init.W.rows() > 0)\n {\n if (init.W.rows() == N)\n {\n W.diagonal() = init.W;\n }\n else\n {\n ThrowNamed(\"W dimension mismatch! Expected \" << N << \", got \" << init.W.rows());\n }\n }\n if (flags_ & KIN_J) jacobian = Eigen::MatrixXd(length_jacobian, N);\n if (flags_ & KIN_J_DOT) hessian.setConstant(length_jacobian, Eigen::MatrixXd::Zero(N, N));\n\n if (init.LowerBound.rows() == N)\n {\n scene_->GetKinematicTree().SetJointLimitsLower(init.LowerBound);\n }\n else if (init.LowerBound.rows() != 0)\n {\n ThrowNamed(\"Lower bound size incorrect! Expected \" << N << \" got \" << init.LowerBound.rows());\n }\n if (init.UpperBound.rows() == N)\n {\n scene_->GetKinematicTree().SetJointLimitsUpper(init.UpperBound);\n }\n else if (init.UpperBound.rows() != 0)\n {\n ThrowNamed(\"Lower bound size incorrect! Expected \" << N << \" got \" << init.UpperBound.rows());\n }\n\n TaskSpaceVector dummy;\n cost.Initialize(init.Cost, shared_from_this(), dummy);\n ApplyStartState(false);\n PreUpdate();\n}\n\nvoid BoundedEndPoseProblem::PreUpdate()\n{\n PlanningProblem::PreUpdate();\n for (int i = 0; i < tasks_.size(); ++i) tasks_[i]->is_used = false;\n cost.UpdateS();\n}\n\ndouble BoundedEndPoseProblem::GetScalarCost() const\n{\n return cost.ydiff.transpose() * cost.S * cost.ydiff;\n}\n\nEigen::RowVectorXd BoundedEndPoseProblem::GetScalarJacobian() const\n{\n return cost.jacobian.transpose() * cost.S * cost.ydiff * 2.0;\n}\n\ndouble BoundedEndPoseProblem::GetScalarTaskCost(const std::string& task_name) const\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n return cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length).transpose() * cost.rho(cost.indexing[i].id) * cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length);\n }\n }\n ThrowPretty(\"Cannot get scalar task cost. Task map '\" << task_name << \"' does not exist.\");\n}\n\nvoid BoundedEndPoseProblem::Update(Eigen::VectorXdRefConst x)\n{\n scene_->Update(x, t_start);\n Phi.SetZero(length_Phi);\n if (flags_ & KIN_J) jacobian.setZero();\n if (flags_ & KIN_J_DOT)\n for (int i = 0; i < length_jacobian; ++i) hessian(i).setZero();\n for (int i = 0; i < tasks_.size(); ++i)\n {\n if (tasks_[i]->is_used)\n {\n if (flags_ & KIN_J_DOT)\n {\n tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian), hessian.segment(tasks_[i]->start, tasks_[i]->length));\n }\n else if (flags_ & KIN_J)\n {\n tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian));\n }\n else\n {\n tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length));\n }\n }\n }\n if (flags_ & KIN_J_DOT)\n {\n cost.Update(Phi, jacobian, hessian);\n }\n else if (flags_ & KIN_J)\n {\n cost.Update(Phi, jacobian);\n }\n else\n {\n cost.Update(Phi);\n }\n ++number_of_problem_updates_;\n}\n\nvoid BoundedEndPoseProblem::SetGoal(const std::string& task_name, Eigen::VectorXdRefConst goal)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n if (goal.rows() != cost.indexing[i].length) ThrowPretty(\"Expected length of \" << cost.indexing[i].length << \" and got \" << goal.rows());\n cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length) = goal;\n return;\n }\n }\n ThrowPretty(\"Cannot set Goal. Task map '\" << task_name << \"' does not exist.\");\n}\n\nvoid BoundedEndPoseProblem::SetRho(const std::string& task_name, const double& rho)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n cost.rho(cost.indexing[i].id) = rho;\n PreUpdate();\n return;\n }\n }\n ThrowPretty(\"Cannot set rho. Task map '\" << task_name << \"' does not exist.\");\n}\n\nEigen::VectorXd BoundedEndPoseProblem::GetGoal(const std::string& task_name)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n return cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length);\n }\n }\n ThrowPretty(\"Cannot get Goal. Task map '\" << task_name << \"' does not exist.\");\n}\n\ndouble BoundedEndPoseProblem::GetRho(const std::string& task_name)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n return cost.rho(cost.indexing[i].id);\n }\n }\n ThrowPretty(\"Cannot get rho. Task map '\" << task_name << \"' does not exist.\");\n}\n\nbool BoundedEndPoseProblem::IsValid()\n{\n Eigen::VectorXd x = scene_->GetKinematicTree().GetControlledState();\n Eigen::MatrixXd bounds = scene_->GetKinematicTree().GetJointLimits();\n for (unsigned int i = 0; i < N; ++i)\n {\n if (x(i) < bounds(i, 0) || x(i) > bounds(i, 1)) return false;\n }\n return true;\n}\n}\n[exotica_core] BoundedEndPoseProblem: Fix IsValid\/\/\n\/\/ Copyright (c) 2018, University of Edinburgh\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \n#include \n\n#include \n\nREGISTER_PROBLEM_TYPE(\"BoundedEndPoseProblem\", exotica::BoundedEndPoseProblem)\n\nnamespace exotica\n{\nBoundedEndPoseProblem::BoundedEndPoseProblem()\n{\n flags_ = KIN_FK | KIN_J;\n}\n\nBoundedEndPoseProblem::~BoundedEndPoseProblem() = default;\n\nEigen::MatrixXd BoundedEndPoseProblem::GetBounds() const\n{\n return scene_->GetKinematicTree().GetJointLimits();\n}\n\nvoid BoundedEndPoseProblem::Instantiate(const BoundedEndPoseProblemInitializer& init)\n{\n num_tasks = tasks_.size();\n length_Phi = 0;\n length_jacobian = 0;\n for (int i = 0; i < num_tasks; ++i)\n {\n AppendVector(Phi.map, tasks_[i]->GetLieGroupIndices());\n length_Phi += tasks_[i]->length;\n length_jacobian += tasks_[i]->length_jacobian;\n }\n Phi.SetZero(length_Phi);\n W = Eigen::MatrixXd::Identity(N, N);\n if (init.W.rows() > 0)\n {\n if (init.W.rows() == N)\n {\n W.diagonal() = init.W;\n }\n else\n {\n ThrowNamed(\"W dimension mismatch! Expected \" << N << \", got \" << init.W.rows());\n }\n }\n if (flags_ & KIN_J) jacobian = Eigen::MatrixXd(length_jacobian, N);\n if (flags_ & KIN_J_DOT) hessian.setConstant(length_jacobian, Eigen::MatrixXd::Zero(N, N));\n\n if (init.LowerBound.rows() == N)\n {\n scene_->GetKinematicTree().SetJointLimitsLower(init.LowerBound);\n }\n else if (init.LowerBound.rows() != 0)\n {\n ThrowNamed(\"Lower bound size incorrect! Expected \" << N << \" got \" << init.LowerBound.rows());\n }\n if (init.UpperBound.rows() == N)\n {\n scene_->GetKinematicTree().SetJointLimitsUpper(init.UpperBound);\n }\n else if (init.UpperBound.rows() != 0)\n {\n ThrowNamed(\"Lower bound size incorrect! Expected \" << N << \" got \" << init.UpperBound.rows());\n }\n\n TaskSpaceVector dummy;\n cost.Initialize(init.Cost, shared_from_this(), dummy);\n ApplyStartState(false);\n PreUpdate();\n}\n\nvoid BoundedEndPoseProblem::PreUpdate()\n{\n PlanningProblem::PreUpdate();\n for (int i = 0; i < tasks_.size(); ++i) tasks_[i]->is_used = false;\n cost.UpdateS();\n}\n\ndouble BoundedEndPoseProblem::GetScalarCost() const\n{\n return cost.ydiff.transpose() * cost.S * cost.ydiff;\n}\n\nEigen::RowVectorXd BoundedEndPoseProblem::GetScalarJacobian() const\n{\n return cost.jacobian.transpose() * cost.S * cost.ydiff * 2.0;\n}\n\ndouble BoundedEndPoseProblem::GetScalarTaskCost(const std::string& task_name) const\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n return cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length).transpose() * cost.rho(cost.indexing[i].id) * cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length);\n }\n }\n ThrowPretty(\"Cannot get scalar task cost. Task map '\" << task_name << \"' does not exist.\");\n}\n\nvoid BoundedEndPoseProblem::Update(Eigen::VectorXdRefConst x)\n{\n scene_->Update(x, t_start);\n Phi.SetZero(length_Phi);\n if (flags_ & KIN_J) jacobian.setZero();\n if (flags_ & KIN_J_DOT)\n for (int i = 0; i < length_jacobian; ++i) hessian(i).setZero();\n for (int i = 0; i < tasks_.size(); ++i)\n {\n if (tasks_[i]->is_used)\n {\n if (flags_ & KIN_J_DOT)\n {\n tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian), hessian.segment(tasks_[i]->start, tasks_[i]->length));\n }\n else if (flags_ & KIN_J)\n {\n tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian));\n }\n else\n {\n tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length));\n }\n }\n }\n if (flags_ & KIN_J_DOT)\n {\n cost.Update(Phi, jacobian, hessian);\n }\n else if (flags_ & KIN_J)\n {\n cost.Update(Phi, jacobian);\n }\n else\n {\n cost.Update(Phi);\n }\n ++number_of_problem_updates_;\n}\n\nvoid BoundedEndPoseProblem::SetGoal(const std::string& task_name, Eigen::VectorXdRefConst goal)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n if (goal.rows() != cost.indexing[i].length) ThrowPretty(\"Expected length of \" << cost.indexing[i].length << \" and got \" << goal.rows());\n cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length) = goal;\n return;\n }\n }\n ThrowPretty(\"Cannot set Goal. Task map '\" << task_name << \"' does not exist.\");\n}\n\nvoid BoundedEndPoseProblem::SetRho(const std::string& task_name, const double& rho)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n cost.rho(cost.indexing[i].id) = rho;\n PreUpdate();\n return;\n }\n }\n ThrowPretty(\"Cannot set rho. Task map '\" << task_name << \"' does not exist.\");\n}\n\nEigen::VectorXd BoundedEndPoseProblem::GetGoal(const std::string& task_name)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n return cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length);\n }\n }\n ThrowPretty(\"Cannot get Goal. Task map '\" << task_name << \"' does not exist.\");\n}\n\ndouble BoundedEndPoseProblem::GetRho(const std::string& task_name)\n{\n for (int i = 0; i < cost.indexing.size(); ++i)\n {\n if (cost.tasks[i]->GetObjectName() == task_name)\n {\n return cost.rho(cost.indexing[i].id);\n }\n }\n ThrowPretty(\"Cannot get rho. Task map '\" << task_name << \"' does not exist.\");\n}\n\nbool BoundedEndPoseProblem::IsValid()\n{\n Eigen::VectorXd x = scene_->GetKinematicTree().GetControlledState();\n Eigen::MatrixXd bounds = scene_->GetKinematicTree().GetJointLimits();\n\n std::cout.precision(4);\n constexpr double tolerance = 1.e-3;\n\n bool succeeded = true;\n for (unsigned int i = 0; i < N; ++i)\n {\n if (x(i) < bounds(i, 0) - tolerance || x(i) > bounds(i, 1) + tolerance)\n {\n if (debug_) HIGHLIGHT_NAMED(\"BoundedEndPoseProblem::IsValid\", \"Out of bounds (joint #\" << i << \"): \" << bounds(i, 0) << \" < \" << x(i) << \" < \" << bounds(i, 1));\n succeeded = false;\n }\n }\n return succeeded;\n}\n} \/\/ namespace exotica\n<|endoftext|>"} {"text":"\/* $Id$ *\/\n\/* Author: Toby Young, Polish Academy of Sciences, *\/\n\/* Wolfgang Bangerth, Texas A&M University *\/\n\/* $Id$ *\/\n\/* *\/\n\/* Copyright (C) 2009 by the deal.II authors *\/\n\/* *\/\n\/* This file is subject to QPL and may not be distributed *\/\n\/* without copyright and license information. Please refer *\/\n\/* to the file deal.II\/doc\/license.html for the text and *\/\n\/* further information on this license. *\/\n\n \/\/ @sect3{Include files}\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n\t\t\t\t \/\/ The final step, as in previous\n\t\t\t\t \/\/ programs, is to import all the\n\t\t\t\t \/\/ deal.II class and function names\n\t\t\t\t \/\/ into the global namespace:\nusing namespace dealii;\n\n \/\/ @sect3{The EigenvalueProblem<\/code> class template}\n\ntemplate \nclass EigenvalueProblem \n{\n public:\n EigenvalueProblem (const std::string &prm_file);\n void run ();\n \n private:\n void make_grid_and_dofs ();\n void assemble_system ();\n void solve ();\n void output_results () const;\n\n Triangulation triangulation;\n FE_Q fe;\n DoFHandler dof_handler;\n\n PETScWrappers::SparseMatrix stiffness_matrix, mass_matrix;\n std::vector eigenfunctions;\n\n ParameterHandler parameters;\n};\n\n\n\n \/\/ @sect3{Implementation of the EigenvalueProblem<\/code> class}\n\n \/\/ @sect4{EigenvalueProblem::EigenvalueProblem}\n\ntemplate \nEigenvalueProblem::EigenvalueProblem (const std::string &prm_file)\n\t\t:\n fe (1),\n\t\tdof_handler (triangulation)\n{\n parameters.declare_entry (\"Number of eigenvalues\/eigenfunctions\", \"10\",\n\t\t\t Patterns::Integer (0, 100),\n\t\t\t \"The number of eigenvalues\/eigenfunctions \"\n\t\t\t \"to be computed.\");\n parameters.declare_entry (\"Potential\", \"0\",\n\t\t\t Patterns::Anything(),\n\t\t\t \"A functional description of the potential.\");\n\n parameters.read_input (prm_file);\n}\n\n\n \/\/ @sect4{EigenvalueProblem::make_grid_and_dofs}\ntemplate \nvoid EigenvalueProblem::make_grid_and_dofs ()\n{\n GridGenerator::hyper_cube (triangulation, -1, 1);\n triangulation.refine_global (4);\n dof_handler.distribute_dofs (fe);\n\n CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(),\n\t\t\t\t dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern (dof_handler, csp);\n stiffness_matrix.reinit (csp);\n mass_matrix.reinit (csp);\n\n eigenfunctions\n .resize (parameters.get_integer (\"Number of eigenvalues\/eigenfunctions\"));\n for (unsigned int i=0; i\nvoid EigenvalueProblem::assemble_system () \n{ \n QGauss quadrature_formula(2);\n\n FEValues fe_values (fe, quadrature_formula, \n\t\t\t update_values | update_gradients |\n update_quadrature_points | update_JxW_values);\n\n const unsigned int dofs_per_cell = fe.dofs_per_cell;\n const unsigned int n_q_points = quadrature_formula.size();\n\n FullMatrix cell_stiffness_matrix (dofs_per_cell, dofs_per_cell);\n FullMatrix cell_mass_matrix (dofs_per_cell, dofs_per_cell);\n\n std::vector local_dof_indices (dofs_per_cell);\n\n FunctionParser potential;\n potential.initialize ((dim == 2 ?\n\t\t\t \"x,y\" :\n\t\t\t \"x,y,z\"),\n\t\t\tparameters.get (\"Potential\"),\n\t\t\ttypename FunctionParser::ConstMap());\n std::vector potential_values (n_q_points);\n\n ConstraintMatrix constraints;\n VectorTools::interpolate_boundary_values (dof_handler,\n\t\t\t\t\t 0,\n\t\t\t\t\t ZeroFunction(),\n\t\t\t\t\t constraints);\n constraints.close ();\n \n typename DoFHandler::active_cell_iterator\n cell = dof_handler.begin_active(),\n endc = dof_handler.end();\n for (; cell!=endc; ++cell)\n {\n fe_values.reinit (cell);\n cell_stiffness_matrix = 0;\n cell_mass_matrix = 0;\n\n potential.value_list (fe_values.get_quadrature_points(),\n\t\t\t potential_values);\n \n for (unsigned int q_point=0; q_pointget_dof_indices (local_dof_indices);\n\n constraints.distribute_local_to_global (cell_stiffness_matrix,\n\t\t\t\t\t local_dof_indices,\n\t\t\t\t\t stiffness_matrix);\n constraints.distribute_local_to_global (cell_mass_matrix,\n\t\t\t\t\t local_dof_indices,\n\t\t\t\t\t mass_matrix);\n }\n}\n\n\n \/\/ @sect4{EigenvalueProblem::solve}\ntemplate \nvoid EigenvalueProblem::solve () \n{\n\/\/ do whatever is necessary here. use stiffness_matrix, mass_matrix, and the\n\/\/ eigenfunctions[] array\n}\n\n\n \/\/ @sect4{EigenvalueProblem::output_results}\n\ntemplate \nvoid EigenvalueProblem::output_results () const\n{\n DataOut data_out;\n\n data_out.attach_dof_handler (dof_handler);\n\n for (unsigned int i=0; i\nvoid EigenvalueProblem::run () \n{\n std::cout << \"Solving problem in \" << dim << \" space dimensions.\" << std::endl;\n \n make_grid_and_dofs();\n assemble_system ();\n solve ();\n output_results ();\n}\n\n\n \/\/ @sect3{The main<\/code> function}\n\nint main (int argc, char **argv) \n{\n try\n {\n PetscInitialize(&argc,&argv,0,0);\n deallog.depth_console (0);\n \n EigenvalueProblem<2> problem (\"step-36.prm\");\n problem.run ();\n }\n catch (std::exception &exc)\n {\n std::cerr << std::endl << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n\t\t<< exc.what() << std::endl\n\t\t<< \"Aborting!\" << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n\n return 1;\n }\n catch (...) \n {\n std::cerr << std::endl << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n\t\t<< \"Aborting!\" << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n return 1;\n }\n \n return 0;\n}\nInterpolate potential and put it into the output. Refine once more.\/* $Id$ *\/\n\/* Author: Toby Young, Polish Academy of Sciences, *\/\n\/* Wolfgang Bangerth, Texas A&M University *\/\n\/* $Id$ *\/\n\/* *\/\n\/* Copyright (C) 2009 by the deal.II authors *\/\n\/* *\/\n\/* This file is subject to QPL and may not be distributed *\/\n\/* without copyright and license information. Please refer *\/\n\/* to the file deal.II\/doc\/license.html for the text and *\/\n\/* further information on this license. *\/\n\n \/\/ @sect3{Include files}\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n\t\t\t\t \/\/ The final step, as in previous\n\t\t\t\t \/\/ programs, is to import all the\n\t\t\t\t \/\/ deal.II class and function names\n\t\t\t\t \/\/ into the global namespace:\nusing namespace dealii;\n\n \/\/ @sect3{The EigenvalueProblem<\/code> class template}\n\ntemplate \nclass EigenvalueProblem \n{\n public:\n EigenvalueProblem (const std::string &prm_file);\n void run ();\n \n private:\n void make_grid_and_dofs ();\n void assemble_system ();\n void solve ();\n void output_results () const;\n\n Triangulation triangulation;\n FE_Q fe;\n DoFHandler dof_handler;\n\n PETScWrappers::SparseMatrix stiffness_matrix, mass_matrix;\n std::vector eigenfunctions;\n\n ParameterHandler parameters;\n};\n\n\n\n \/\/ @sect3{Implementation of the EigenvalueProblem<\/code> class}\n\n \/\/ @sect4{EigenvalueProblem::EigenvalueProblem}\n\ntemplate \nEigenvalueProblem::EigenvalueProblem (const std::string &prm_file)\n\t\t:\n fe (1),\n\t\tdof_handler (triangulation)\n{\n parameters.declare_entry (\"Number of eigenvalues\/eigenfunctions\", \"10\",\n\t\t\t Patterns::Integer (0, 100),\n\t\t\t \"The number of eigenvalues\/eigenfunctions \"\n\t\t\t \"to be computed.\");\n parameters.declare_entry (\"Potential\", \"0\",\n\t\t\t Patterns::Anything(),\n\t\t\t \"A functional description of the potential.\");\n\n parameters.read_input (prm_file);\n}\n\n\n \/\/ @sect4{EigenvalueProblem::make_grid_and_dofs}\ntemplate \nvoid EigenvalueProblem::make_grid_and_dofs ()\n{\n GridGenerator::hyper_cube (triangulation, -1, 1);\n triangulation.refine_global (5);\n dof_handler.distribute_dofs (fe);\n\n CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(),\n\t\t\t\t dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern (dof_handler, csp);\n stiffness_matrix.reinit (csp);\n mass_matrix.reinit (csp);\n\n eigenfunctions\n .resize (parameters.get_integer (\"Number of eigenvalues\/eigenfunctions\"));\n for (unsigned int i=0; i\nvoid EigenvalueProblem::assemble_system () \n{ \n QGauss quadrature_formula(2);\n\n FEValues fe_values (fe, quadrature_formula, \n\t\t\t update_values | update_gradients |\n update_quadrature_points | update_JxW_values);\n\n const unsigned int dofs_per_cell = fe.dofs_per_cell;\n const unsigned int n_q_points = quadrature_formula.size();\n\n FullMatrix cell_stiffness_matrix (dofs_per_cell, dofs_per_cell);\n FullMatrix cell_mass_matrix (dofs_per_cell, dofs_per_cell);\n\n std::vector local_dof_indices (dofs_per_cell);\n\n FunctionParser potential;\n potential.initialize ((dim == 2 ?\n\t\t\t \"x,y\" :\n\t\t\t \"x,y,z\"),\n\t\t\tparameters.get (\"Potential\"),\n\t\t\ttypename FunctionParser::ConstMap());\n std::vector potential_values (n_q_points);\n\n ConstraintMatrix constraints;\n VectorTools::interpolate_boundary_values (dof_handler,\n\t\t\t\t\t 0,\n\t\t\t\t\t ZeroFunction(),\n\t\t\t\t\t constraints);\n constraints.close ();\n \n typename DoFHandler::active_cell_iterator\n cell = dof_handler.begin_active(),\n endc = dof_handler.end();\n for (; cell!=endc; ++cell)\n {\n fe_values.reinit (cell);\n cell_stiffness_matrix = 0;\n cell_mass_matrix = 0;\n\n potential.value_list (fe_values.get_quadrature_points(),\n\t\t\t potential_values);\n \n for (unsigned int q_point=0; q_pointget_dof_indices (local_dof_indices);\n\n constraints.distribute_local_to_global (cell_stiffness_matrix,\n\t\t\t\t\t local_dof_indices,\n\t\t\t\t\t stiffness_matrix);\n constraints.distribute_local_to_global (cell_mass_matrix,\n\t\t\t\t\t local_dof_indices,\n\t\t\t\t\t mass_matrix);\n }\n}\n\n\n \/\/ @sect4{EigenvalueProblem::solve}\ntemplate \nvoid EigenvalueProblem::solve () \n{\n\/\/ do whatever is necessary here. use stiffness_matrix, mass_matrix, and the\n\/\/ eigenfunctions[] array\n}\n\n\n \/\/ @sect4{EigenvalueProblem::output_results}\n\ntemplate \nvoid EigenvalueProblem::output_results () const\n{\n DataOut data_out;\n\n data_out.attach_dof_handler (dof_handler);\n\n for (unsigned int i=0; i projected_potential (dof_handler.n_dofs());\n FunctionParser potential;\n potential.initialize ((dim == 2 ?\n\t\t\t \"x,y\" :\n\t\t\t \"x,y,z\"),\n\t\t\tparameters.get (\"Potential\"),\n\t\t\ttypename FunctionParser::ConstMap());\n VectorTools::interpolate (dof_handler, potential, projected_potential);\n data_out.add_data_vector (projected_potential, \"interpolated_potential\");\n \n data_out.build_patches ();\n\n std::ofstream output (\"eigenvectors.vtk\");\n data_out.write_vtk (output);\n}\n\n\n\n \/\/ @sect4{EigenvalueProblem::run}\n\n \/\/ This is the function which has the\n\t\t\t\t \/\/ top-level control over everything. It is\n\t\t\t\t \/\/ the same as for the previous example.\ntemplate \nvoid EigenvalueProblem::run () \n{\n std::cout << \"Solving problem in \" << dim << \" space dimensions.\" << std::endl;\n \n make_grid_and_dofs();\n assemble_system ();\n solve ();\n output_results ();\n}\n\n\n \/\/ @sect3{The main<\/code> function}\n\nint main (int argc, char **argv) \n{\n try\n {\n PetscInitialize(&argc,&argv,0,0);\n deallog.depth_console (0);\n \n EigenvalueProblem<2> problem (\"step-36.prm\");\n problem.run ();\n }\n catch (std::exception &exc)\n {\n std::cerr << std::endl << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n\t\t<< exc.what() << std::endl\n\t\t<< \"Aborting!\" << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n\n return 1;\n }\n catch (...) \n {\n std::cerr << std::endl << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n\t\t<< \"Aborting!\" << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl;\n return 1;\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ main.cpp\n\/\/ TonicStandaloneDemo\n\/\/\n\/\/ Created by Nick Donaldson on 5\/16\/13.\n\/\/\n\/\/\n\n\/\/ This is a super-simple demo showing a very basic command-line C++ program to play a Tonic synth\n\n#include \n#include \"Tonic.h\"\n#include \"RtAudio.h\"\n\nusing namespace Tonic;\n\nconst unsigned int nChannels = 2;\n\nSynth * synth = NULL;\n\nint renderCallback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,\n double streamTime, RtAudioStreamStatus status, void *userData )\n{\n if (synth != NULL){\n synth->fillBufferOfFloats((float*)outputBuffer, nBufferFrames, nChannels);\n }\n \n return 0;\n}\n\nint main(int argc, const char * argv[])\n{\n \/\/ Configure RtAudio\n RtAudio dac;\n RtAudio::StreamParameters rtParams;\n rtParams.deviceId = dac.getDefaultOutputDevice();\n rtParams.nChannels = nChannels;\n unsigned int sampleRate = 44100;\n unsigned int bufferFrames = 256; \/\/ 256 sample frames\n \n \/\/ You don't necessarily have to do this - it will default to 44100 if not set.\n Tonic::setSampleRate(sampleRate);\n \n \/\/ --------- MAKE A SYNTH HERE -----------\n \n synth = new Synth();\n \n synth->setLimitOutput(false);\n \n\/\/ ControlGenerator ctrlGen1 = ControlValue(2);\n\/\/ Generator gen1 = ctrlGen1 + FixedValue(3) * ctrlGen1;\n \n ControlGenerator val1 = ControlValue(2);\n ControlGenerator val2 = ControlValue(2);\n ControlGenerator final = val1 + val1 * val2;\n Tonic_::SynthesisContext_ context;\n final.tick(context);\n \n \/\/ synth->setOutputGen(FixedValue());\n \n \/\/ ---------------------------------------\n \n \n \/\/ open rtaudio stream\n try {\n dac.openStream( &rtParams, NULL, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, &renderCallback, NULL, NULL );\n \n dac.startStream();\n \n \/\/ hacky, yes, but let's just hang out for awhile until someone presses a key\n printf(\"\\n\\nPress any key to stop\\n\\n\");\n cin.get();\n \n dac.stopStream();\n }\n catch ( RtError& e ) {\n std::cout << '\\n' << e.getMessage() << '\\n' << std::endl;\n exit( 0 );\n }\n \n return 0;\n}\n\nReverting accidentally committed changes to main.cpp in standalone demo\/\/\n\/\/ main.cpp\n\/\/ TonicStandaloneDemo\n\/\/\n\/\/ Created by Nick Donaldson on 5\/16\/13.\n\/\/\n\/\/\n\n\/\/ This is a super-simple demo showing a very basic command-line C++ program to play a Tonic synth\n\n#include \n#include \"Tonic.h\"\n#include \"RtAudio.h\"\n\nusing namespace Tonic;\n\nconst unsigned int nChannels = 2;\n\nSynth * synth = NULL;\n\nint renderCallback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,\n double streamTime, RtAudioStreamStatus status, void *userData )\n{\n if (synth != NULL){\n synth->fillBufferOfFloats((float*)outputBuffer, nBufferFrames, nChannels);\n }\n \n return 0;\n}\n\nint main(int argc, const char * argv[])\n{\n \/\/ Configure RtAudio\n RtAudio dac;\n RtAudio::StreamParameters rtParams;\n rtParams.deviceId = dac.getDefaultOutputDevice();\n rtParams.nChannels = nChannels;\n unsigned int sampleRate = 44100;\n unsigned int bufferFrames = 256; \/\/ 256 sample frames\n \n \/\/ You don't necessarily have to do this - it will default to 44100 if not set.\n Tonic::setSampleRate(sampleRate);\n \n \/\/ --------- MAKE A SYNTH HERE -----------\n \n synth = new Synth();\n \n ControlMetro metro = ControlMetro().bpm(100);\n ControlGenerator freq = ControlRandom().trigger(metro).min(0).max(1);\n \n Generator tone = RectWave().freq(\n freq * 0.25 + 100\n + 400\n ) * SineWave().freq(50);\n \n ADSR env = ADSR()\n .attack(0.01)\n .decay( 0.4 )\n .sustain(0)\n .release(0)\n .doesSustain(false)\n .trigger(metro);\n \n StereoDelay delay = StereoDelay(3.0f,3.0f)\n .delayTimeLeft( 0.5 + SineWave().freq(0.2) * 0.01)\n .delayTimeRight(0.55 + SineWave().freq(0.23) * 0.01)\n .feedback(0.3)\n .dryLevel(0.8)\n .wetLevel(0.2);\n \n Generator filterFreq = (SineWave().freq(0.01) + 1) * 200 + 225;\n \n LPF24 filter = LPF24().Q(2).cutoff( filterFreq );\n \n Generator output = (( tone * env ) >> filter >> delay) * 0.3;\n \n synth->setOutputGen(output);\n \n \/\/ ---------------------------------------\n \n \n \/\/ open rtaudio stream\n try {\n dac.openStream( &rtParams, NULL, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, &renderCallback, NULL, NULL );\n \n dac.startStream();\n \n \/\/ hacky, yes, but let's just hang out for awhile until someone presses a key\n printf(\"\\n\\nPress any key to stop\\n\\n\");\n cin.get();\n \n dac.stopStream();\n }\n catch ( RtError& e ) {\n std::cout << '\\n' << e.getMessage() << '\\n' << std::endl;\n exit( 0 );\n }\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"vector_tile_projection.hpp\"\n#include \"vector_tile_geometry_decoder.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace mapnik { namespace vector_tile_impl {\n\n template \n class tile_featureset_pbf : public Featureset\n {\n public:\n tile_featureset_pbf(Filter const& filter,\n mapnik::box2d const& tile_extent,\n mapnik::box2d const& unbuffered_query,\n std::set const& attribute_names,\n std::vector const& features,\n double tile_x,\n double tile_y,\n double scale,\n std::vector const& layer_keys,\n layer_pbf_attr_type const& layer_values)\n : filter_(filter),\n tile_extent_(tile_extent),\n unbuffered_query_(unbuffered_query),\n features_(features),\n layer_keys_(layer_keys),\n layer_values_(layer_values),\n tile_x_(tile_x),\n tile_y_(tile_y),\n scale_(scale),\n itr_(0),\n tr_(\"utf-8\"),\n ctx_(std::make_shared())\n {\n std::set::const_iterator pos = attribute_names.begin();\n std::set::const_iterator end = attribute_names.end();\n for ( ;pos !=end; ++pos)\n {\n for (auto const& key : layer_keys_)\n {\n if (key == *pos)\n {\n ctx_->push(*pos);\n break;\n }\n }\n }\n }\n\n virtual ~tile_featureset_pbf() {}\n\n feature_ptr next()\n {\n while ( itr_ < features_.size() )\n {\n mapbox::util::pbf f = features_.at(itr_);\n \/\/ TODO: auto-increment feature id counter here\n mapnik::feature_ptr feature = mapnik::feature_factory::create(ctx_,itr_);\n pbf_attr_value_type val;\n\n ++itr_;\n int tagcount=0;\n uint32_t key_idx, val_idx;\n int32_t geometry_type = 0; \/\/ vector_tile::Tile_GeomType_UNKNOWN\n while (f.next())\n {\n switch(f.tag())\n {\n case 1:\n feature->set_id(f.get_uint64());\n break;\n case 2:\n {\n auto tag_iterator = f.packed_uint32();\n\n for (auto _i = tag_iterator.first; _i != tag_iterator.second; ++_i)\n {\n if (tagcount % 2 == 0)\n {\n key_idx = *_i;\n ++tagcount;\n }\n else\n {\n val_idx = *_i;\n val = layer_values_.at(val_idx);\n std::string name = layer_keys_.at(key_idx);\n if (feature->has_key(name))\n {\n if (val.is())\n {\n feature->put(name, tr_.transcode(val.get().data(), val.get().length()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n } else {\n throw std::runtime_error(\"unknown attribute type while reading feature\");\n }\n ++tagcount;\n }\n }\n }\n }\n break;\n case 3:\n geometry_type = f.get_enum();\n switch (geometry_type)\n {\n case 1: \/\/vector_tile::Tile_GeomType_POINT\n case 2: \/\/ vector_tile::Tile_GeomType_LINESTRING\n case 3: \/\/ vector_tile::Tile_GeomType_POLYGON\n break;\n default: \/\/ vector_tile::Tile_GeomType_UNKNOWN or any other value\n throw std::runtime_error(\"unknown geometry type \" + std::to_string(geometry_type) + \" in feature\");\n }\n break;\n case 5:\n {\n std::string const& image_buffer = f.get_bytes();\n std::unique_ptr reader(mapnik::get_image_reader(image_buffer.data(),image_buffer.size()));\n if (reader.get())\n {\n int image_width = reader->width();\n int image_height = reader->height();\n if (image_width > 0 && image_height > 0)\n {\n mapnik::view_transform t(image_width, image_height, tile_extent_, 0, 0);\n box2d intersect = tile_extent_.intersect(unbuffered_query_);\n box2d ext = t.forward(intersect);\n if (ext.width() > 0.5 && ext.height() > 0.5 )\n {\n \/\/ select minimum raster containing whole ext\n int x_off = static_cast(std::floor(ext.minx() +.5));\n int y_off = static_cast(std::floor(ext.miny() +.5));\n int end_x = static_cast(std::floor(ext.maxx() +.5));\n int end_y = static_cast(std::floor(ext.maxy() +.5));\n\n \/\/ clip to available data\n if (x_off < 0)\n x_off = 0;\n if (y_off < 0)\n y_off = 0;\n if (end_x > image_width)\n end_x = image_width;\n if (end_y > image_height)\n end_y = image_height;\n int width = end_x - x_off;\n int height = end_y - y_off;\n box2d feature_raster_extent(x_off,\n y_off,\n x_off + width,\n y_off + height);\n intersect = t.backward(feature_raster_extent);\n double filter_factor = 1.0;\n mapnik::image_any data = reader->read(x_off, y_off, width, height);\n mapnik::raster_ptr raster = std::make_shared(intersect,\n data,\n filter_factor\n );\n feature->set_raster(raster);\n return feature;\n }\n }\n }\n }\n break;\n case 4:\n {\n auto geom_itr = f.packed_uint32();\n mapnik::vector_tile_impl::GeometryPBF geoms(geom_itr, tile_x_,tile_y_,scale_,-1*scale_);\n mapnik::geometry::geometry geom = decode_geometry(geoms, geometry_type);\n if (geom.is())\n {\n continue;\n }\n mapnik::box2d envelope = mapnik::geometry::envelope(geom);\n if (!filter_.pass(envelope))\n {\n continue;\n }\n feature->set_geometry(std::move(geom));\n return feature;\n }\n break;\n default:\n \/\/ NOTE: The vector_tile.proto file technically allows for extension fields\n \/\/ of values 16 to max here. Technically, we should just skip() those\n \/\/ fields.\n \/\/ However, if we're fed a corrupt file (or random data), we don't\n \/\/ want to just blindly follow the bytes, so we have made the decision\n \/\/ to abort cleanly, rather than doing GIGO.\n throw std::runtime_error(\"unknown field type \" + std::to_string(f.tag()) +\" in feature\");\n\n }\n }\n }\n return feature_ptr();\n }\n\n private:\n Filter filter_;\n mapnik::box2d tile_extent_;\n mapnik::box2d unbuffered_query_;\n std::vector const& features_;\n std::vector const& layer_keys_;\n layer_pbf_attr_type const& layer_values_;\n\n double tile_x_;\n double tile_y_;\n double scale_;\n unsigned itr_;\n mapnik::transcoder tr_;\n mapnik::context_ptr ctx_;\n\n };\n\n \/\/ tile_datasource impl\n tile_datasource_pbf::tile_datasource_pbf(mapbox::util::pbf const& layer,\n unsigned x,\n unsigned y,\n unsigned z,\n unsigned tile_size)\n : datasource(parameters()),\n desc_(\"in-memory PBF encoded datasource\",\"utf-8\"),\n attributes_added_(false),\n layer_(layer),\n x_(x),\n y_(y),\n z_(z),\n tile_size_(tile_size),\n extent_initialized_(false),\n tile_x_(0.0),\n tile_y_(0.0),\n scale_(0.0),\n layer_extent_(0)\n {\n double resolution = mapnik::EARTH_CIRCUMFERENCE\/(1 << z_);\n tile_x_ = -0.5 * mapnik::EARTH_CIRCUMFERENCE + x_ * resolution;\n tile_y_ = 0.5 * mapnik::EARTH_CIRCUMFERENCE - y_ * resolution;\n\n mapbox::util::pbf val_msg;\n\n while (layer_.next())\n {\n switch(layer_.tag())\n {\n case 1:\n name_ = layer_.get_string();\n break;\n case 2:\n features_.push_back(layer_.get_message());\n break;\n case 3:\n layer_keys_.push_back(layer_.get_string());\n break;\n case 4:\n val_msg = layer_.get_message();\n while (val_msg.next())\n {\n switch(val_msg.tag()) {\n case 1:\n layer_values_.push_back(val_msg.get_string());\n break;\n case 2:\n layer_values_.push_back(val_msg.get_float());\n break;\n case 3:\n layer_values_.push_back(val_msg.get_double());\n break;\n case 4:\n layer_values_.push_back(val_msg.get_int64());\n break;\n case 5:\n layer_values_.push_back(val_msg.get_uint64());\n break;\n case 6:\n layer_values_.push_back(val_msg.get_sint64());\n break;\n case 7:\n layer_values_.push_back(val_msg.get_bool());\n break;\n default:\n throw std::runtime_error(\"unknown Value type \" + std::to_string(layer_.tag()) + \" in layer.values\");\n }\n }\n break;\n case 5:\n layer_extent_ = layer_.get_uint32();\n break;\n case 15:\n layer_.skip();\n break;\n default:\n throw std::runtime_error(\"unknown field type \" + std::to_string(layer_.tag()) + \" in layer\");\n }\n }\n scale_ = (static_cast(layer_extent_) \/ tile_size_) * tile_size_\/resolution;\n }\n\n tile_datasource_pbf::~tile_datasource_pbf() {}\n\n datasource::datasource_t tile_datasource_pbf::type() const\n {\n return datasource::Vector;\n }\n\n featureset_ptr tile_datasource_pbf::features(query const& q) const\n {\n mapnik::filter_in_box filter(q.get_bbox());\n return std::make_shared >\n (filter, get_tile_extent(), q.get_unbuffered_bbox(), q.property_names(), features_, tile_x_, tile_y_, scale_, layer_keys_, layer_values_);\n }\n\n featureset_ptr tile_datasource_pbf::features_at_point(coord2d const& pt, double tol) const\n {\n mapnik::filter_at_point filter(pt,tol);\n std::set names;\n for (auto const& key : layer_keys_)\n {\n names.insert(key);\n }\n return std::make_shared >\n (filter, get_tile_extent(), get_tile_extent(), names, features_, tile_x_, tile_y_, scale_, layer_keys_, layer_values_);\n }\n\n void tile_datasource_pbf::set_envelope(box2d const& bbox)\n {\n extent_initialized_ = true;\n extent_ = bbox;\n }\n\n box2d tile_datasource_pbf::get_tile_extent() const\n {\n spherical_mercator merc(tile_size_);\n double minx,miny,maxx,maxy;\n merc.xyz(x_,y_,z_,minx,miny,maxx,maxy);\n return box2d(minx,miny,maxx,maxy);\n }\n\n box2d tile_datasource_pbf::envelope() const\n {\n if (!extent_initialized_)\n {\n extent_ = get_tile_extent();\n extent_initialized_ = true;\n }\n return extent_;\n }\n\n boost::optional tile_datasource_pbf::get_geometry_type() const\n {\n return mapnik::datasource_geometry_t::Collection;\n }\n\n layer_descriptor tile_datasource_pbf::get_descriptor() const\n {\n if (!attributes_added_)\n {\n for (auto const& key : layer_keys_)\n {\n \/\/ Object type here because we don't know the precise value until features are unpacked\n desc_.add_descriptor(attribute_descriptor(key, Object));\n }\n attributes_added_ = true;\n }\n return desc_;\n }\n\n }} \/\/ end ns\nfix #132#include \"vector_tile_projection.hpp\"\n#include \"vector_tile_geometry_decoder.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace mapnik { namespace vector_tile_impl {\n\n template \n class tile_featureset_pbf : public Featureset\n {\n public:\n tile_featureset_pbf(Filter const& filter,\n mapnik::box2d const& tile_extent,\n mapnik::box2d const& unbuffered_query,\n std::set const& attribute_names,\n std::vector const& features,\n double tile_x,\n double tile_y,\n double scale,\n std::vector const& layer_keys,\n layer_pbf_attr_type const& layer_values)\n : filter_(filter),\n tile_extent_(tile_extent),\n unbuffered_query_(unbuffered_query),\n features_(features),\n layer_keys_(layer_keys),\n layer_values_(layer_values),\n tile_x_(tile_x),\n tile_y_(tile_y),\n scale_(scale),\n itr_(0),\n tr_(\"utf-8\"),\n ctx_(std::make_shared())\n {\n std::set::const_iterator pos = attribute_names.begin();\n std::set::const_iterator end = attribute_names.end();\n for ( ;pos !=end; ++pos)\n {\n for (auto const& key : layer_keys_)\n {\n if (key == *pos)\n {\n ctx_->push(*pos);\n break;\n }\n }\n }\n }\n\n virtual ~tile_featureset_pbf() {}\n\n feature_ptr next()\n {\n while ( itr_ < features_.size() )\n {\n mapbox::util::pbf f = features_.at(itr_);\n \/\/ TODO: auto-increment feature id counter here\n mapnik::feature_ptr feature = mapnik::feature_factory::create(ctx_,itr_);\n pbf_attr_value_type val;\n\n ++itr_;\n int tagcount=0;\n uint32_t key_idx, val_idx;\n int32_t geometry_type = 0; \/\/ vector_tile::Tile_GeomType_UNKNOWN\n while (f.next())\n {\n switch(f.tag())\n {\n case 1:\n feature->set_id(f.get_uint64());\n break;\n case 2:\n {\n auto tag_iterator = f.packed_uint32();\n\n for (auto _i = tag_iterator.first; _i != tag_iterator.second; ++_i)\n {\n if (tagcount % 2 == 0)\n {\n key_idx = *_i;\n ++tagcount;\n }\n else\n {\n val_idx = *_i;\n std::string name = layer_keys_.at(key_idx);\n if (feature->has_key(name))\n {\n val = layer_values_.at(val_idx);\n if (val.is())\n {\n feature->put(name, tr_.transcode(val.get().data(), val.get().length()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n }\n else if (val.is())\n {\n feature->put(name, static_cast(val.get()));\n } else {\n throw std::runtime_error(\"unknown attribute type while reading feature\");\n }\n ++tagcount;\n }\n }\n }\n }\n break;\n case 3:\n geometry_type = f.get_enum();\n switch (geometry_type)\n {\n case 1: \/\/vector_tile::Tile_GeomType_POINT\n case 2: \/\/ vector_tile::Tile_GeomType_LINESTRING\n case 3: \/\/ vector_tile::Tile_GeomType_POLYGON\n break;\n default: \/\/ vector_tile::Tile_GeomType_UNKNOWN or any other value\n throw std::runtime_error(\"unknown geometry type \" + std::to_string(geometry_type) + \" in feature\");\n }\n break;\n case 5:\n {\n std::string const& image_buffer = f.get_bytes();\n std::unique_ptr reader(mapnik::get_image_reader(image_buffer.data(),image_buffer.size()));\n if (reader.get())\n {\n int image_width = reader->width();\n int image_height = reader->height();\n if (image_width > 0 && image_height > 0)\n {\n mapnik::view_transform t(image_width, image_height, tile_extent_, 0, 0);\n box2d intersect = tile_extent_.intersect(unbuffered_query_);\n box2d ext = t.forward(intersect);\n if (ext.width() > 0.5 && ext.height() > 0.5 )\n {\n \/\/ select minimum raster containing whole ext\n int x_off = static_cast(std::floor(ext.minx() +.5));\n int y_off = static_cast(std::floor(ext.miny() +.5));\n int end_x = static_cast(std::floor(ext.maxx() +.5));\n int end_y = static_cast(std::floor(ext.maxy() +.5));\n\n \/\/ clip to available data\n if (x_off < 0)\n x_off = 0;\n if (y_off < 0)\n y_off = 0;\n if (end_x > image_width)\n end_x = image_width;\n if (end_y > image_height)\n end_y = image_height;\n int width = end_x - x_off;\n int height = end_y - y_off;\n box2d feature_raster_extent(x_off,\n y_off,\n x_off + width,\n y_off + height);\n intersect = t.backward(feature_raster_extent);\n double filter_factor = 1.0;\n mapnik::image_any data = reader->read(x_off, y_off, width, height);\n mapnik::raster_ptr raster = std::make_shared(intersect,\n data,\n filter_factor\n );\n feature->set_raster(raster);\n return feature;\n }\n }\n }\n }\n break;\n case 4:\n {\n auto geom_itr = f.packed_uint32();\n mapnik::vector_tile_impl::GeometryPBF geoms(geom_itr, tile_x_,tile_y_,scale_,-1*scale_);\n mapnik::geometry::geometry geom = decode_geometry(geoms, geometry_type);\n if (geom.is())\n {\n continue;\n }\n mapnik::box2d envelope = mapnik::geometry::envelope(geom);\n if (!filter_.pass(envelope))\n {\n continue;\n }\n feature->set_geometry(std::move(geom));\n return feature;\n }\n break;\n default:\n \/\/ NOTE: The vector_tile.proto file technically allows for extension fields\n \/\/ of values 16 to max here. Technically, we should just skip() those\n \/\/ fields.\n \/\/ However, if we're fed a corrupt file (or random data), we don't\n \/\/ want to just blindly follow the bytes, so we have made the decision\n \/\/ to abort cleanly, rather than doing GIGO.\n throw std::runtime_error(\"unknown field type \" + std::to_string(f.tag()) +\" in feature\");\n\n }\n }\n }\n return feature_ptr();\n }\n\n private:\n Filter filter_;\n mapnik::box2d tile_extent_;\n mapnik::box2d unbuffered_query_;\n std::vector const& features_;\n std::vector const& layer_keys_;\n layer_pbf_attr_type const& layer_values_;\n\n double tile_x_;\n double tile_y_;\n double scale_;\n unsigned itr_;\n mapnik::transcoder tr_;\n mapnik::context_ptr ctx_;\n\n };\n\n \/\/ tile_datasource impl\n tile_datasource_pbf::tile_datasource_pbf(mapbox::util::pbf const& layer,\n unsigned x,\n unsigned y,\n unsigned z,\n unsigned tile_size)\n : datasource(parameters()),\n desc_(\"in-memory PBF encoded datasource\",\"utf-8\"),\n attributes_added_(false),\n layer_(layer),\n x_(x),\n y_(y),\n z_(z),\n tile_size_(tile_size),\n extent_initialized_(false),\n tile_x_(0.0),\n tile_y_(0.0),\n scale_(0.0),\n layer_extent_(0)\n {\n double resolution = mapnik::EARTH_CIRCUMFERENCE\/(1 << z_);\n tile_x_ = -0.5 * mapnik::EARTH_CIRCUMFERENCE + x_ * resolution;\n tile_y_ = 0.5 * mapnik::EARTH_CIRCUMFERENCE - y_ * resolution;\n\n mapbox::util::pbf val_msg;\n\n while (layer_.next())\n {\n switch(layer_.tag())\n {\n case 1:\n name_ = layer_.get_string();\n break;\n case 2:\n features_.push_back(layer_.get_message());\n break;\n case 3:\n layer_keys_.push_back(layer_.get_string());\n break;\n case 4:\n val_msg = layer_.get_message();\n while (val_msg.next())\n {\n switch(val_msg.tag()) {\n case 1:\n layer_values_.push_back(val_msg.get_string());\n break;\n case 2:\n layer_values_.push_back(val_msg.get_float());\n break;\n case 3:\n layer_values_.push_back(val_msg.get_double());\n break;\n case 4:\n layer_values_.push_back(val_msg.get_int64());\n break;\n case 5:\n layer_values_.push_back(val_msg.get_uint64());\n break;\n case 6:\n layer_values_.push_back(val_msg.get_sint64());\n break;\n case 7:\n layer_values_.push_back(val_msg.get_bool());\n break;\n default:\n throw std::runtime_error(\"unknown Value type \" + std::to_string(layer_.tag()) + \" in layer.values\");\n }\n }\n break;\n case 5:\n layer_extent_ = layer_.get_uint32();\n break;\n case 15:\n layer_.skip();\n break;\n default:\n throw std::runtime_error(\"unknown field type \" + std::to_string(layer_.tag()) + \" in layer\");\n }\n }\n scale_ = (static_cast(layer_extent_) \/ tile_size_) * tile_size_\/resolution;\n }\n\n tile_datasource_pbf::~tile_datasource_pbf() {}\n\n datasource::datasource_t tile_datasource_pbf::type() const\n {\n return datasource::Vector;\n }\n\n featureset_ptr tile_datasource_pbf::features(query const& q) const\n {\n mapnik::filter_in_box filter(q.get_bbox());\n return std::make_shared >\n (filter, get_tile_extent(), q.get_unbuffered_bbox(), q.property_names(), features_, tile_x_, tile_y_, scale_, layer_keys_, layer_values_);\n }\n\n featureset_ptr tile_datasource_pbf::features_at_point(coord2d const& pt, double tol) const\n {\n mapnik::filter_at_point filter(pt,tol);\n std::set names;\n for (auto const& key : layer_keys_)\n {\n names.insert(key);\n }\n return std::make_shared >\n (filter, get_tile_extent(), get_tile_extent(), names, features_, tile_x_, tile_y_, scale_, layer_keys_, layer_values_);\n }\n\n void tile_datasource_pbf::set_envelope(box2d const& bbox)\n {\n extent_initialized_ = true;\n extent_ = bbox;\n }\n\n box2d tile_datasource_pbf::get_tile_extent() const\n {\n spherical_mercator merc(tile_size_);\n double minx,miny,maxx,maxy;\n merc.xyz(x_,y_,z_,minx,miny,maxx,maxy);\n return box2d(minx,miny,maxx,maxy);\n }\n\n box2d tile_datasource_pbf::envelope() const\n {\n if (!extent_initialized_)\n {\n extent_ = get_tile_extent();\n extent_initialized_ = true;\n }\n return extent_;\n }\n\n boost::optional tile_datasource_pbf::get_geometry_type() const\n {\n return mapnik::datasource_geometry_t::Collection;\n }\n\n layer_descriptor tile_datasource_pbf::get_descriptor() const\n {\n if (!attributes_added_)\n {\n for (auto const& key : layer_keys_)\n {\n \/\/ Object type here because we don't know the precise value until features are unpacked\n desc_.add_descriptor(attribute_descriptor(key, Object));\n }\n attributes_added_ = true;\n }\n return desc_;\n }\n\n }} \/\/ end ns\n<|endoftext|>"} {"text":"\/\/ vrkit is (C) Copyright 2005-2007\n\/\/ by Allen Bierbaum, Aron Bierbuam, Patrick Hartling, and Daniel Shipton\n\/\/\n\/\/ This file is part of vrkit.\n\/\/\n\/\/ vrkit is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License as published by the Free\n\/\/ Software Foundation; either version 2 of the License, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ vrkit is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n\/\/ more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program. If not, see .\n\n#include \n\n#include \n#include \n#include \n\n\nnamespace vrkit\n{\n\nnamespace plugin\n{\n\nRegistryEntry::RegistryEntry(vpr::LibraryPtr module)\n : mModule(module)\n , mModuleInfo(getModuleInfo(module))\n{\n \/* Do nothing. *\/ ;\n std::cout << \"Registry entry for \" << mModule->getName() << \" created\"\n << std::endl;\n}\n\nRegistryEntry::~RegistryEntry()\n{\n}\n\nCreatorBase*\nRegistryEntry::getCreatorFunc(vpr::LibraryPtr module,\n const std::string& getCreatorFuncName)\n const\n{\n Module pm(module);\n return pm.getFunction(getCreatorFuncName)();\n}\n\nInfo RegistryEntry::getModuleInfo(vpr::LibraryPtr module)\n{\n Module pm(module);\n typedef const Info* sig_type();\n return *pm.getFunction(AbstractPlugin::getInfoFuncName())();\n}\n\n}\n\n}\nRemoved debug output that I did not mean to commit with the last revision.\/\/ vrkit is (C) Copyright 2005-2007\n\/\/ by Allen Bierbaum, Aron Bierbuam, Patrick Hartling, and Daniel Shipton\n\/\/\n\/\/ This file is part of vrkit.\n\/\/\n\/\/ vrkit is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License as published by the Free\n\/\/ Software Foundation; either version 2 of the License, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ vrkit is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n\/\/ more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program. If not, see .\n\n#include \n\n#include \n#include \n#include \n\n\nnamespace vrkit\n{\n\nnamespace plugin\n{\n\nRegistryEntry::RegistryEntry(vpr::LibraryPtr module)\n : mModule(module)\n , mModuleInfo(getModuleInfo(module))\n{\n \/* Do nothing. *\/ ;\n}\n\nRegistryEntry::~RegistryEntry()\n{\n}\n\nCreatorBase*\nRegistryEntry::getCreatorFunc(vpr::LibraryPtr module,\n const std::string& getCreatorFuncName)\n const\n{\n Module pm(module);\n return pm.getFunction(getCreatorFuncName)();\n}\n\nInfo RegistryEntry::getModuleInfo(vpr::LibraryPtr module)\n{\n Module pm(module);\n typedef const Info* sig_type();\n return *pm.getFunction(AbstractPlugin::getInfoFuncName())();\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * xmpp_features.cpp - XMPP entity features\n * Copyright (C) 2003 Justin Karneges\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"xmpp_features.h\"\n\nusing namespace XMPP;\n\nFeatures::Features()\n{\n}\n\nFeatures::Features(const QStringList &l)\n{\n\tsetList(l);\n}\n\nFeatures::Features(const QString &str)\n{\n\tQStringList l;\n\tl << str;\n\n\tsetList(l);\n}\n\nFeatures::~Features()\n{\n}\n\nQStringList Features::list() const\n{\n\treturn _list;\n}\n\nvoid Features::setList(const QStringList &l)\n{\n\t_list = l;\n}\n\nvoid Features::addFeature(const QString& s)\n{\n\t_list += s;\n}\n\nbool Features::test(const QStringList &ns) const\n{\n\tQStringList::ConstIterator it = ns.begin();\n\tfor ( ; it != ns.end(); ++it) {\n\t\tif ( _list.contains( *it )) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n#define FID_MULTICAST \"http:\/\/jabber.org\/protocol\/address\"\nbool Features::canMulticast() const\n{\n\tQStringList ns;\n\tns << FID_MULTICAST;\n\n\treturn test(ns);\n}\n\n#define FID_AHCOMMAND \"http:\/\/jabber.org\/protocol\/commands\"\nbool Features::canCommand() const\n{\n\tQStringList ns;\n\tns << FID_AHCOMMAND;\n\n\treturn test(ns);\n}\n\n#define FID_REGISTER \"jabber:iq:register\"\nbool Features::canRegister() const\n{\n\tQStringList ns;\n\tns << FID_REGISTER;\n\n\treturn test(ns);\n}\n\n#define FID_SEARCH \"jabber:iq:search\"\nbool Features::canSearch() const\n{\n\tQStringList ns;\n\tns << FID_SEARCH;\n\n\treturn test(ns);\n}\n\n#define FID_GROUPCHAT \"jabber:iq:conference\"\nbool Features::canGroupchat() const\n{\n\tQStringList ns;\n\tns << \"http:\/\/jabber.org\/protocol\/muc\";\n\tns << FID_GROUPCHAT;\n\n\treturn test(ns);\n}\n\n#define FID_VOICE \"http:\/\/www.google.com\/xmpp\/protocol\/voice\/v1\"\nbool Features::canVoice() const\n{\n\tQStringList ns;\n\tns << FID_VOICE;\n\n\treturn test(ns);\n}\n\n#define FID_GATEWAY \"jabber:iq:gateway\"\nbool Features::isGateway() const\n{\n\tQStringList ns;\n\tns << FID_GATEWAY;\n\n\treturn test(ns);\n}\n\n#define FID_DISCO \"http:\/\/jabber.org\/protocol\/disco\"\nbool Features::canDisco() const\n{\n\tQStringList ns;\n\tns << FID_DISCO;\n\tns << \"http:\/\/jabber.org\/protocol\/disco#info\";\n\tns << \"http:\/\/jabber.org\/protocol\/disco#items\";\n\n\treturn test(ns);\n}\n\n#define FID_CHATSTATE \"http:\/\/jabber.org\/protocol\/chatstates\"\nbool Features::canChatState() const\n{\n\tQStringList ns;\n\tns << FID_CHATSTATE;\n\n\treturn test(ns);\n}\n\n#define FID_VCARD \"vcard-temp\"\nbool Features::haveVCard() const\n{\n\tQStringList ns;\n\tns << FID_VCARD;\n\n\treturn test(ns);\n}\n\n\/\/ custom Psi acitons\n#define FID_ADD \"psi:add\"\n\nclass Features::FeatureName : public QObject\n{\n\tQ_OBJECT\n\npublic:\n\tFeatureName()\n\t: QObject(qApp)\n\t{\n\t\tid2s[FID_Invalid]\t= tr(\"ERROR: Incorrect usage of Features class\");\n\t\tid2s[FID_None]\t\t= tr(\"None\");\n\t\tid2s[FID_Register]\t= tr(\"Register\");\n\t\tid2s[FID_Search]\t= tr(\"Search\");\n\t\tid2s[FID_Groupchat]\t= tr(\"Groupchat\");\n\t\tid2s[FID_Gateway]\t= tr(\"Gateway\");\n\t\tid2s[FID_Disco]\t\t= tr(\"Service Discovery\");\n\t\tid2s[FID_VCard]\t\t= tr(\"VCard\");\n\t\tid2s[FID_AHCommand]\t= tr(\"Execute command\");\n\n\t\t\/\/ custom Psi actions\n\t\tid2s[FID_Add]\t\t= tr(\"Add to roster\");\n\n\t\t\/\/ compute reverse map\n\t\t\/\/QMap::Iterator it = id2s.begin();\n\t\t\/\/for ( ; it != id2s.end(); ++it)\n\t\t\/\/\ts2id[it.data()] = it.key();\n\n\t\tid2f[FID_Register]\t= FID_REGISTER;\n\t\tid2f[FID_Search]\t= FID_SEARCH;\n\t\tid2f[FID_Groupchat]\t= FID_GROUPCHAT;\n\t\tid2f[FID_Gateway]\t= FID_GATEWAY;\n\t\tid2f[FID_Disco]\t\t= FID_DISCO;\n\t\tid2f[FID_VCard]\t\t= FID_VCARD;\n\t\tid2f[FID_AHCommand]\t= FID_AHCOMMAND;\n\n\t\t\/\/ custom Psi actions\n\t\tid2f[FID_Add]\t\t= FID_ADD;\n\t}\n\n\t\/\/QMap s2id;\n\tQMap id2s;\n\tQMap id2f;\n};\n\nstatic Features::FeatureName *featureName = 0;\n\nlong Features::id() const\n{\n\tif ( _list.count() > 1 )\n\t\treturn FID_Invalid;\n\telse if ( canRegister() )\n\t\treturn FID_Register;\n\telse if ( canSearch() )\n\t\treturn FID_Search;\n\telse if ( canGroupchat() )\n\t\treturn FID_Groupchat;\n\telse if ( isGateway() )\n\t\treturn FID_Gateway;\n\telse if ( canDisco() )\n\t\treturn FID_Disco;\n\telse if ( haveVCard() )\n\t\treturn FID_VCard;\n\telse if ( canCommand() )\n\t\treturn FID_AHCommand;\n\telse if ( test(QStringList(FID_ADD)) )\n\t\treturn FID_Add;\n\n\treturn FID_None;\n}\n\nlong Features::id(const QString &feature)\n{\n\tFeatures f(feature);\n\treturn f.id();\n}\n\nQString Features::feature(long id)\n{\n\tif ( !featureName )\n\t\tfeatureName = new FeatureName();\n\n\treturn featureName->id2f[id];\n}\n\nQString Features::name(long id)\n{\n\tif ( !featureName )\n\t\tfeatureName = new FeatureName();\n\n\treturn featureName->id2s[id];\n}\n\nQString Features::name() const\n{\n\treturn name(id());\n}\n\nQString Features::name(const QString &feature)\n{\n\tFeatures f(feature);\n\treturn f.name(f.id());\n}\n\n#include \"xmpp_features.moc\"\nfix compile on qt 4.3\/*\n * xmpp_features.cpp - XMPP entity features\n * Copyright (C) 2003 Justin Karneges\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"xmpp_features.h\"\n\nusing namespace XMPP;\n\nFeatures::Features()\n{\n}\n\nFeatures::Features(const QStringList &l)\n{\n\tsetList(l);\n}\n\nFeatures::Features(const QString &str)\n{\n\tQStringList l;\n\tl << str;\n\n\tsetList(l);\n}\n\nFeatures::~Features()\n{\n}\n\nQStringList Features::list() const\n{\n\treturn _list;\n}\n\nvoid Features::setList(const QStringList &l)\n{\n\t_list = l;\n}\n\nvoid Features::addFeature(const QString& s)\n{\n\t_list += s;\n}\n\nbool Features::test(const QStringList &ns) const\n{\n\tQStringList::ConstIterator it = ns.begin();\n\tfor ( ; it != ns.end(); ++it) {\n\t\tif ( _list.contains( *it )) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n#define FID_MULTICAST \"http:\/\/jabber.org\/protocol\/address\"\nbool Features::canMulticast() const\n{\n\tQStringList ns;\n\tns << FID_MULTICAST;\n\n\treturn test(ns);\n}\n\n#define FID_AHCOMMAND \"http:\/\/jabber.org\/protocol\/commands\"\nbool Features::canCommand() const\n{\n\tQStringList ns;\n\tns << FID_AHCOMMAND;\n\n\treturn test(ns);\n}\n\n#define FID_REGISTER \"jabber:iq:register\"\nbool Features::canRegister() const\n{\n\tQStringList ns;\n\tns << FID_REGISTER;\n\n\treturn test(ns);\n}\n\n#define FID_SEARCH \"jabber:iq:search\"\nbool Features::canSearch() const\n{\n\tQStringList ns;\n\tns << FID_SEARCH;\n\n\treturn test(ns);\n}\n\n#define FID_GROUPCHAT \"jabber:iq:conference\"\nbool Features::canGroupchat() const\n{\n\tQStringList ns;\n\tns << \"http:\/\/jabber.org\/protocol\/muc\";\n\tns << FID_GROUPCHAT;\n\n\treturn test(ns);\n}\n\n#define FID_VOICE \"http:\/\/www.google.com\/xmpp\/protocol\/voice\/v1\"\nbool Features::canVoice() const\n{\n\tQStringList ns;\n\tns << FID_VOICE;\n\n\treturn test(ns);\n}\n\n#define FID_GATEWAY \"jabber:iq:gateway\"\nbool Features::isGateway() const\n{\n\tQStringList ns;\n\tns << FID_GATEWAY;\n\n\treturn test(ns);\n}\n\n#define FID_DISCO \"http:\/\/jabber.org\/protocol\/disco\"\nbool Features::canDisco() const\n{\n\tQStringList ns;\n\tns << FID_DISCO;\n\tns << \"http:\/\/jabber.org\/protocol\/disco#info\";\n\tns << \"http:\/\/jabber.org\/protocol\/disco#items\";\n\n\treturn test(ns);\n}\n\n#define FID_CHATSTATE \"http:\/\/jabber.org\/protocol\/chatstates\"\nbool Features::canChatState() const\n{\n\tQStringList ns;\n\tns << FID_CHATSTATE;\n\n\treturn test(ns);\n}\n\n#define FID_VCARD \"vcard-temp\"\nbool Features::haveVCard() const\n{\n\tQStringList ns;\n\tns << FID_VCARD;\n\n\treturn test(ns);\n}\n\n\/\/ custom Psi acitons\n#define FID_ADD \"psi:add\"\n\nclass Features::FeatureName : public QObject\n{\n\tQ_OBJECT\n\npublic:\n\tFeatureName()\n\t: QObject(QCoreApplication::instance())\n\t{\n\t\tid2s[FID_Invalid]\t= tr(\"ERROR: Incorrect usage of Features class\");\n\t\tid2s[FID_None]\t\t= tr(\"None\");\n\t\tid2s[FID_Register]\t= tr(\"Register\");\n\t\tid2s[FID_Search]\t= tr(\"Search\");\n\t\tid2s[FID_Groupchat]\t= tr(\"Groupchat\");\n\t\tid2s[FID_Gateway]\t= tr(\"Gateway\");\n\t\tid2s[FID_Disco]\t\t= tr(\"Service Discovery\");\n\t\tid2s[FID_VCard]\t\t= tr(\"VCard\");\n\t\tid2s[FID_AHCommand]\t= tr(\"Execute command\");\n\n\t\t\/\/ custom Psi actions\n\t\tid2s[FID_Add]\t\t= tr(\"Add to roster\");\n\n\t\t\/\/ compute reverse map\n\t\t\/\/QMap::Iterator it = id2s.begin();\n\t\t\/\/for ( ; it != id2s.end(); ++it)\n\t\t\/\/\ts2id[it.data()] = it.key();\n\n\t\tid2f[FID_Register]\t= FID_REGISTER;\n\t\tid2f[FID_Search]\t= FID_SEARCH;\n\t\tid2f[FID_Groupchat]\t= FID_GROUPCHAT;\n\t\tid2f[FID_Gateway]\t= FID_GATEWAY;\n\t\tid2f[FID_Disco]\t\t= FID_DISCO;\n\t\tid2f[FID_VCard]\t\t= FID_VCARD;\n\t\tid2f[FID_AHCommand]\t= FID_AHCOMMAND;\n\n\t\t\/\/ custom Psi actions\n\t\tid2f[FID_Add]\t\t= FID_ADD;\n\t}\n\n\t\/\/QMap s2id;\n\tQMap id2s;\n\tQMap id2f;\n};\n\nstatic Features::FeatureName *featureName = 0;\n\nlong Features::id() const\n{\n\tif ( _list.count() > 1 )\n\t\treturn FID_Invalid;\n\telse if ( canRegister() )\n\t\treturn FID_Register;\n\telse if ( canSearch() )\n\t\treturn FID_Search;\n\telse if ( canGroupchat() )\n\t\treturn FID_Groupchat;\n\telse if ( isGateway() )\n\t\treturn FID_Gateway;\n\telse if ( canDisco() )\n\t\treturn FID_Disco;\n\telse if ( haveVCard() )\n\t\treturn FID_VCard;\n\telse if ( canCommand() )\n\t\treturn FID_AHCommand;\n\telse if ( test(QStringList(FID_ADD)) )\n\t\treturn FID_Add;\n\n\treturn FID_None;\n}\n\nlong Features::id(const QString &feature)\n{\n\tFeatures f(feature);\n\treturn f.id();\n}\n\nQString Features::feature(long id)\n{\n\tif ( !featureName )\n\t\tfeatureName = new FeatureName();\n\n\treturn featureName->id2f[id];\n}\n\nQString Features::name(long id)\n{\n\tif ( !featureName )\n\t\tfeatureName = new FeatureName();\n\n\treturn featureName->id2s[id];\n}\n\nQString Features::name() const\n{\n\treturn name(id());\n}\n\nQString Features::name(const QString &feature)\n{\n\tFeatures f(feature);\n\treturn f.name(f.id());\n}\n\n#include \"xmpp_features.moc\"\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin_explorer.\n *\n * libbitcoin_explorer is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n#ifndef BX_FETCH_CONFIRMATIONS_HPP\n#define BX_FETCH_CONFIRMATIONS_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/********* GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY **********\/\n\nnamespace libbitcoin {\nnamespace explorer {\nnamespace commands {\n\n\/**\n * Various localizable strings.\n *\/\n#define BX_FETCH_CONFIRMATIONS_OUTPUT \\\n \"[%1%] Confirmations: %2%\"\n\n\/**\n * Class to implement the fetch-confirmations command.\n *\/\nclass fetch_confirmations \n : public command\n{\npublic:\n\n \/**\n * The symbolic (not localizable) command name, lower case.\n *\/\n static const char* symbol() { return \"fetch-confirmations\"; }\n\n \/**\n * The member symbolic (not localizable) command name, lower case.\n *\/\n virtual const char* name()\n {\n return fetch_confirmations::symbol();\n }\n\n \/**\n * The localizable command category name, upper case.\n *\/\n virtual const char* category()\n {\n return \"ONLINE\";\n }\n\n \/**\n * Load program argument definitions.\n * A value of -1 indicates that the number of instances is unlimited.\n * @return The loaded program argument definitions.\n *\/\n virtual arguments_metadata& load_arguments()\n {\n return get_argument_metadata()\n .add(\"TRANSACTION\", -1);\n }\n\t\n\t\/**\n * Load parameter fallbacks from file or input as appropriate.\n * @param[in] input The input stream for loading the parameters.\n * @param[in] The loaded variables.\n *\/\n virtual void load_fallbacks(std::istream& input, \n po::variables_map& variables)\n {\n \/\/load_path(get_transactions_argument(), \"TRANSACTION\", variables);\n \/\/load_input(get_transactions_argument(), \"TRANSACTION\", variables, input);\n }\n \n \/**\n * Load program option definitions.\n * The implicit_value call allows flags to be strongly-typed on read while\n * allowing but not requiring a value on the command line for the option.\n * BUGBUG: see boost bug\/fix: svn.boost.org\/trac\/boost\/ticket\/8009\n * @return The loaded program option definitions.\n *\/\n virtual options_metadata& load_options()\n {\n using namespace po;\n options_description& options = get_option_metadata();\n options.add_options()\n (\n BX_CONFIG_VARIABLE \",c\",\n value(),\n \"The path and file name for the configuration settings file to be used in the execution of the command.\"\n )\n (\n \"help,h\",\n value(&option_.help)->implicit_value(true),\n \"Get confirmations for a set of transactions. Requires an Obelisk server connection.\"\n )\n (\n \"format,f\",\n value(&option_.format),\n \"The output format. Options are 'json', 'xml', 'info' or 'native', defaults to native.\"\n )\n (\n \"TRANSACTION\",\n value(),\n \"The file path of the set of Base16 transactions. If not specified the transactions are read from STDIN.\"\n );\n\n return options;\n }\n\n \/**\n * Invoke the command.\n * @param[out] output The input stream for the command execution.\n * @param[out] error The input stream for the command execution.\n * @return The appropriate console return code { -1, 0, 1 }.\n *\/\n virtual console_result invoke(std::ostream& output, std::ostream& cerr);\n \n \/* Properties *\/\n\n \/**\n * Get the value of the TRANSACTION arguments.\n *\/\n virtual std::vector& get_transactions_argument()\n {\n return argument_.transactions;\n }\n \n \/**\n * Set the value of the TRANSACTION arguments.\n *\/\n virtual void set_transactions_argument(\n const std::vector& value)\n {\n argument_.transactions = value;\n }\n\n \/**\n * Get the value of the help option.\n *\/\n virtual bool& get_help_option()\n {\n return option_.help;\n }\n \n \/**\n * Set the value of the help option.\n *\/\n virtual void set_help_option(\n const bool& value)\n {\n option_.help = value;\n }\n\n \/**\n * Get the value of the format option.\n *\/\n virtual primitives::encoding& get_format_option()\n {\n return option_.format;\n }\n \n \/**\n * Set the value of the format option.\n *\/\n virtual void set_format_option(\n const primitives::encoding& value)\n {\n option_.format = value;\n }\n\nprivate:\n\n \/**\n * Command line argument bound variables.\n * Uses cross-compiler safe constructor-based zeroize.\n * Zeroize for unit test consistency with program_options initialization.\n *\/\n struct argument\n {\n argument()\n : transactions()\n {\n }\n \n std::vector transactions;\n } argument_;\n \n \/**\n * Command line option bound variables.\n * Uses cross-compiler safe constructor-based zeroize.\n * Zeroize for unit test consistency with program_options initialization.\n *\/\n struct option\n {\n option()\n : help(),\n format()\n {\n }\n \n bool help;\n primitives::encoding format;\n } option_;\n};\n\n} \/\/ namespace commands\n} \/\/ namespace explorer\n} \/\/ namespace libbitcoin\n\n#endif\nDisable fetch-configmrations format option.\/**\n * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin_explorer.\n *\n * libbitcoin_explorer is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n#ifndef BX_FETCH_CONFIRMATIONS_HPP\n#define BX_FETCH_CONFIRMATIONS_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/********* GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY **********\/\n\nnamespace libbitcoin {\nnamespace explorer {\nnamespace commands {\n\n\/**\n * Various localizable strings.\n *\/\n#define BX_FETCH_CONFIRMATIONS_OUTPUT \\\n \"[%1%] Confirmations: %2%\"\n\n\/**\n * Class to implement the fetch-confirmations command.\n *\/\nclass fetch_confirmations \n : public command\n{\npublic:\n\n \/**\n * The symbolic (not localizable) command name, lower case.\n *\/\n static const char* symbol() { return \"fetch-confirmations\"; }\n\n \/**\n * The member symbolic (not localizable) command name, lower case.\n *\/\n virtual const char* name()\n {\n return fetch_confirmations::symbol();\n }\n\n \/**\n * The localizable command category name, upper case.\n *\/\n virtual const char* category()\n {\n return \"ONLINE\";\n }\n\n \/**\n * Load program argument definitions.\n * A value of -1 indicates that the number of instances is unlimited.\n * @return The loaded program argument definitions.\n *\/\n virtual arguments_metadata& load_arguments()\n {\n return get_argument_metadata()\n .add(\"TRANSACTION\", -1);\n }\n\t\n\t\/**\n * Load parameter fallbacks from file or input as appropriate.\n * @param[in] input The input stream for loading the parameters.\n * @param[in] The loaded variables.\n *\/\n virtual void load_fallbacks(std::istream& input, \n po::variables_map& variables)\n {\n \/\/load_path(get_transactions_argument(), \"TRANSACTION\", variables);\n \/\/load_input(get_transactions_argument(), \"TRANSACTION\", variables, input);\n }\n \n \/**\n * Load program option definitions.\n * The implicit_value call allows flags to be strongly-typed on read while\n * allowing but not requiring a value on the command line for the option.\n * BUGBUG: see boost bug\/fix: svn.boost.org\/trac\/boost\/ticket\/8009\n * @return The loaded program option definitions.\n *\/\n virtual options_metadata& load_options()\n {\n using namespace po;\n options_description& options = get_option_metadata();\n options.add_options()\n (\n BX_CONFIG_VARIABLE \",c\",\n value(),\n \"The path and file name for the configuration settings file to be used in the execution of the command.\"\n )\n (\n \"help,h\",\n value(&option_.help)->implicit_value(true),\n \"Get confirmations for a set of transactions. Requires an Obelisk server connection.\"\n )\n (\n \"TRANSACTION\",\n value(),\n \"The file path of the set of Base16 transactions. If not specified the transactions are read from STDIN.\"\n );\n\n return options;\n }\n\n \/**\n * Invoke the command.\n * @param[out] output The input stream for the command execution.\n * @param[out] error The input stream for the command execution.\n * @return The appropriate console return code { -1, 0, 1 }.\n *\/\n virtual console_result invoke(std::ostream& output, std::ostream& cerr);\n \n \/* Properties *\/\n\n \/**\n * Get the value of the TRANSACTION arguments.\n *\/\n virtual std::vector& get_transactions_argument()\n {\n return argument_.transactions;\n }\n \n \/**\n * Set the value of the TRANSACTION arguments.\n *\/\n virtual void set_transactions_argument(\n const std::vector& value)\n {\n argument_.transactions = value;\n }\n\n \/**\n * Get the value of the help option.\n *\/\n virtual bool& get_help_option()\n {\n return option_.help;\n }\n \n \/**\n * Set the value of the help option.\n *\/\n virtual void set_help_option(\n const bool& value)\n {\n option_.help = value;\n }\n\nprivate:\n\n \/**\n * Command line argument bound variables.\n * Uses cross-compiler safe constructor-based zeroize.\n * Zeroize for unit test consistency with program_options initialization.\n *\/\n struct argument\n {\n argument()\n : transactions()\n {\n }\n \n std::vector transactions;\n } argument_;\n \n \/**\n * Command line option bound variables.\n * Uses cross-compiler safe constructor-based zeroize.\n * Zeroize for unit test consistency with program_options initialization.\n *\/\n struct option\n {\n option()\n : help()\n {\n }\n \n bool help;\n } option_;\n};\n\n} \/\/ namespace commands\n} \/\/ namespace explorer\n} \/\/ namespace libbitcoin\n\n#endif\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"timing_analyzers.hpp\"\n#include \"TimingGraph.hpp\"\n#include \"TimingConstraints.hpp\"\n#include \"TimingTags.hpp\"\n#include \"FixedDelayCalculator.hpp\"\n\nnamespace tatum {\n\nfloat time_sec(struct timespec start, struct timespec end);\n\nvoid print_histogram(const std::vector& values, int nbuckets);\n\nvoid print_level_histogram(const TimingGraph& tg, int nbuckets);\nvoid print_node_fanin_histogram(const TimingGraph& tg, int nbuckets);\nvoid print_node_fanout_histogram(const TimingGraph& tg, int nbuckets);\n\nvoid print_timing_graph(std::shared_ptr tg);\nvoid print_levelization(std::shared_ptr tg);\n\nvoid dump_level_times(std::string fname, const TimingGraph& timing_graph, std::map serial_prof_data, std::map parallel_prof_data);\n\nstd::vector find_related_nodes(const TimingGraph& tg, const std::vector through_nodes, size_t max_depth=std::numeric_limits::max());\nvoid find_transitive_fanout_nodes(const TimingGraph& tg, std::vector& nodes, const NodeId node, size_t max_depth=std::numeric_limits::max(), size_t depth=0);\nvoid find_transitive_fanin_nodes(const TimingGraph& tg, std::vector& nodes, const NodeId node, size_t max_depth=std::numeric_limits::max(), size_t depth=0);\n\nstd::string print_tag_domain_from_to(const TimingTag& tag);\n\n\/*\n * Templated function implementations\n *\/\n\ntemplate\nvoid write_dot_file_setup(std::string filename,\n const TimingGraph& tg,\n const DelayCalc& delay_calc = DelayCalc(),\n const SetupTimingAnalyzer& analyzer = SetupTimingAnalyzer(),\n std::vector nodes = std::vector()) {\n\n if(tg.nodes().size() > 1000 && nodes.empty()) {\n std::cout << \"Skipping setup dot file due to large timing graph size\\n\";\n return;\n }\n\n std::ofstream os(filename);\n\n \/\/Write out a dot file of the timing graph\n os << \"digraph G {\" < node\" << size_t(sink_node_id);\n os << \" [ label=\\\"\" << edge_id;\n if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) {\n os << \"\\\\n\"<< -delay_calc.setup_time(tg, edge_id) << \" (-tsu)\";\n } else if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SOURCE) {\n os << \"\\\\n\" << delay_calc.max_edge_delay(tg, edge_id) << \" (tcq)\";\n } else {\n os << \"\\\\n\" << delay_calc.max_edge_delay(tg, edge_id);\n }\n auto slacks = analyzer.setup_slacks(edge_id);\n for(const auto& tag : slacks) {\n os << \"\\\\n\" << \" (slack \" << print_tag_domain_from_to(tag) << \": \" << tag.time().value() << \")\";\n }\n if(tg.edge_disabled(edge_id)) {\n os << \"\\\\n\" << \"(disabled)\";\n }\n os << \"\\\"\"; \/\/end label\n if(tg.edge_disabled(edge_id)) {\n os << \" style=\\\"dashed\\\"\";\n os << \" color=\\\"#aaaaaa\\\"\"; \/\/grey\n os << \" fontcolor=\\\"#aaaaaa\\\"\"; \/\/grey\n }\n os << \"]\";\n os << \";\" <\nvoid write_dot_file_hold(std::string filename,\n const TimingGraph& tg,\n const DelayCalc& delay_calc = DelayCalc(),\n const HoldTimingAnalyzer& analyzer = TimingAnalyzer(),\n std::vector nodes = std::vector()) {\n\n if(tg.nodes().size() > 1000 && nodes.empty()) {\n std::cout << \"Skipping hold dot file due to large timing graph size\\n\";\n return;\n }\n\n std::ofstream os(filename);\n\n \/\/Write out a dot file of the timing graph\n os << \"digraph G {\" < node\" << size_t(sink_node_id);\n os << \" [ label=\\\"\" << edge_id;\n if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) {\n os << \" [ label=\\\"\" << edge_id << \"\\n\" << delay_calc.hold_time(tg, edge_id) << \" (thld)\\\" ]\";\n } else if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SOURCE) {\n os << \" [ label=\\\"\" << edge_id << \"\\n\" << delay_calc.min_edge_delay(tg, edge_id) << \" (tcq)\\\" ]\";\n } else {\n os << \" [ label=\\\"\" << edge_id << \"\\n\" << delay_calc.min_edge_delay(tg, edge_id) << \"\\\" ]\";\n }\n auto slacks = analyzer.hold_slacks(edge_id);\n for(const auto& tag : slacks) {\n os << \"\\\\n\" << \" (slack \" << print_tag_domain_from_to(tag) << \": \" << tag.time().value() << \")\";\n }\n if(tg.edge_disabled(edge_id)) {\n os << \"\\\\n\" << \"(disabled)\";\n }\n os << \"\\\"\"; \/\/end label\n if(tg.edge_disabled(edge_id)) {\n os << \" style=\\\"dashed\\\"\";\n os << \" color=\\\"#aaaaaa\\\"\"; \/\/grey\n os << \" fontcolor=\\\"#aaaaaa\\\"\"; \/\/grey\n }\n os << \"]\";\n os << \";\" <Fix hold dot file output#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"timing_analyzers.hpp\"\n#include \"TimingGraph.hpp\"\n#include \"TimingConstraints.hpp\"\n#include \"TimingTags.hpp\"\n#include \"FixedDelayCalculator.hpp\"\n\nnamespace tatum {\n\nfloat time_sec(struct timespec start, struct timespec end);\n\nvoid print_histogram(const std::vector& values, int nbuckets);\n\nvoid print_level_histogram(const TimingGraph& tg, int nbuckets);\nvoid print_node_fanin_histogram(const TimingGraph& tg, int nbuckets);\nvoid print_node_fanout_histogram(const TimingGraph& tg, int nbuckets);\n\nvoid print_timing_graph(std::shared_ptr tg);\nvoid print_levelization(std::shared_ptr tg);\n\nvoid dump_level_times(std::string fname, const TimingGraph& timing_graph, std::map serial_prof_data, std::map parallel_prof_data);\n\nstd::vector find_related_nodes(const TimingGraph& tg, const std::vector through_nodes, size_t max_depth=std::numeric_limits::max());\nvoid find_transitive_fanout_nodes(const TimingGraph& tg, std::vector& nodes, const NodeId node, size_t max_depth=std::numeric_limits::max(), size_t depth=0);\nvoid find_transitive_fanin_nodes(const TimingGraph& tg, std::vector& nodes, const NodeId node, size_t max_depth=std::numeric_limits::max(), size_t depth=0);\n\nstd::string print_tag_domain_from_to(const TimingTag& tag);\n\n\/*\n * Templated function implementations\n *\/\n\ntemplate\nvoid write_dot_file_setup(std::string filename,\n const TimingGraph& tg,\n const DelayCalc& delay_calc = DelayCalc(),\n const SetupTimingAnalyzer& analyzer = SetupTimingAnalyzer(),\n std::vector nodes = std::vector()) {\n\n if(tg.nodes().size() > 1000 && nodes.empty()) {\n std::cout << \"Skipping setup dot file due to large timing graph size\\n\";\n return;\n }\n\n std::ofstream os(filename);\n\n \/\/Write out a dot file of the timing graph\n os << \"digraph G {\" < node\" << size_t(sink_node_id);\n os << \" [ label=\\\"\" << edge_id;\n if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) {\n os << \"\\\\n\"<< -delay_calc.setup_time(tg, edge_id) << \" (-tsu)\";\n } else if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SOURCE) {\n os << \"\\\\n\" << delay_calc.max_edge_delay(tg, edge_id) << \" (tcq)\";\n } else {\n os << \"\\\\n\" << delay_calc.max_edge_delay(tg, edge_id);\n }\n auto slacks = analyzer.setup_slacks(edge_id);\n for(const auto& tag : slacks) {\n os << \"\\\\n\" << \" (slack \" << print_tag_domain_from_to(tag) << \": \" << tag.time().value() << \")\";\n }\n if(tg.edge_disabled(edge_id)) {\n os << \"\\\\n\" << \"(disabled)\";\n }\n os << \"\\\"\"; \/\/end label\n if(tg.edge_disabled(edge_id)) {\n os << \" style=\\\"dashed\\\"\";\n os << \" color=\\\"#aaaaaa\\\"\"; \/\/grey\n os << \" fontcolor=\\\"#aaaaaa\\\"\"; \/\/grey\n }\n os << \"]\";\n os << \";\" <\nvoid write_dot_file_hold(std::string filename,\n const TimingGraph& tg,\n const DelayCalc& delay_calc = DelayCalc(),\n const HoldTimingAnalyzer& analyzer = TimingAnalyzer(),\n std::vector nodes = std::vector()) {\n\n if(tg.nodes().size() > 1000 && nodes.empty()) {\n std::cout << \"Skipping hold dot file due to large timing graph size\\n\";\n return;\n }\n\n std::ofstream os(filename);\n\n \/\/Write out a dot file of the timing graph\n os << \"digraph G {\" < node\" << size_t(sink_node_id);\n os << \" [ label=\\\"\" << edge_id;\n if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SINK) {\n os << \"\\\\n\" << delay_calc.hold_time(tg, edge_id) << \" (thld)\";\n } else if(tg.node_type(node_id) == NodeType::CPIN && tg.node_type(sink_node_id) == NodeType::SOURCE) {\n os << \"\\\\n\" << delay_calc.min_edge_delay(tg, edge_id) << \" (tcq)\";\n } else {\n os << \"\\\\n\" << delay_calc.min_edge_delay(tg, edge_id);\n }\n auto slacks = analyzer.hold_slacks(edge_id);\n for(const auto& tag : slacks) {\n os << \"\\\\n\" << \" (slack \" << print_tag_domain_from_to(tag) << \": \" << tag.time().value() << \")\";\n }\n if(tg.edge_disabled(edge_id)) {\n os << \"\\\\n\" << \"(disabled)\";\n }\n os << \"\\\"\"; \/\/end label\n if(tg.edge_disabled(edge_id)) {\n os << \" style=\\\"dashed\\\"\";\n os << \" color=\\\"#aaaaaa\\\"\"; \/\/grey\n os << \" fontcolor=\\\"#aaaaaa\\\"\"; \/\/grey\n }\n os << \"]\";\n os << \";\" <"} {"text":"#include \"Unit.h\"\n#include \"CCBot.h\"\n\nUnit::Unit()\n : m_bot(nullptr)\n , m_unit(nullptr)\n , m_unitID(0)\n{\n\n}\n\n#ifdef SC2API\nUnit::Unit(const sc2::Unit * unit, CCBot & bot)\n : m_bot(&bot)\n , m_unit(unit)\n , m_unitID(unit->tag)\n , m_unitType(unit->unit_type, bot)\n{\n \n}\n\nconst sc2::Unit * Unit::getUnitPtr() const\n{\n return m_unit;\n}\n\nconst sc2::UnitTypeID & Unit::getAPIUnitType() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n return m_unit->unit_type;\n}\n\n#else\nUnit::Unit(const BWAPI::Unit unit, CCBot & bot)\n : m_bot(&bot)\n , m_unit(unit)\n , m_unitID(unit->getID())\n , m_unitType(unit->getType(), bot)\n{\n \n}\n\nconst BWAPI::Unit Unit::getUnitPtr() const\n{\n return m_unit;\n}\n\nconst BWAPI::UnitType & Unit::getAPIUnitType() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n return m_unit->getType();\n}\n\n#endif\nbool Unit::operator < (const Unit & rhs) const\n{\n return m_unit < rhs.m_unit;\n}\n\nbool Unit::operator == (const Unit & rhs) const\n{\n return m_unit == rhs.m_unit;\n}\n\nconst UnitType & Unit::getType() const\n{\n return m_unitType;\n}\n\n\nCCPosition Unit::getPosition() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->pos;\n#else\n return m_unit->getPosition();\n#endif\n}\n\nCCTilePosition Unit::getTilePosition() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return Util::GetTilePosition(m_unit->pos);\n#else\n return m_unit->getTilePosition();\n#endif\n}\n\nCCHealth Unit::getHitPoints() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->health;\n#else\n return m_unit->getHitPoints();\n#endif\n}\n\nCCHealth Unit::getShields() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->shield;\n#else\n return m_unit->getShields();\n#endif\n}\n\nCCHealth Unit::getEnergy() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->energy;\n#else\n return m_unit->getEnergy();\n#endif\n}\n\nfloat Unit::getBuildPercentage() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->build_progress;\n#else\n if (getType().isBuilding()) { return m_unit->getRemainingBuildTime() \/ (float)getType().getAPIUnitType().buildTime(); }\n else { return m_unit->getRemainingTrainTime() \/ (float)getType().getAPIUnitType().buildTime(); }\n#endif\n}\n\nCCPlayer Unit::getPlayer() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n if (m_unit->alliance == sc2::Unit::Alliance::Self) { return 0; }\n else if (m_unit->alliance == sc2::Unit::Alliance::Enemy) { return 1; }\n else { return 2; }\n#else\n if (m_unit->getPlayer() == BWAPI::Broodwar->self()) { return 0; }\n else if (m_unit->getPlayer() == BWAPI::Broodwar->enemy()) { return 1; }\n else { return 2; }\n#endif\n}\n\nCCUnitID Unit::getID() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n CCUnitID id = m_unit->tag;\n#else\n CCUnitID id = m_unit->getID();\n#endif\n\n BOT_ASSERT(id == m_unitID, \"Unit ID changed somehow\");\n return id;\n}\n\nbool Unit::isCompleted() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->build_progress >= 1.0f;\n#else\n return m_unit->isCompleted();\n#endif\n}\n\nbool Unit::isTraining() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->orders.size() > 0;\n#else\n return m_unit->isTraining();\n#endif\n}\n\nbool Unit::isBeingConstructed() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return !isCompleted() && m_unit->build_progress > 0.0f;\n#else\n return m_unit->isBeingConstructed();\n#endif\n}\n\nint Unit::getWeaponCooldown() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return (int)m_unit->weapon_cooldown;\n#else\n return std::max(m_unit->getGroundWeaponCooldown(), m_unit->getAirWeaponCooldown());\n#endif\n}\n\nbool Unit::isCloaked() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->cloak;\n#else\n return m_unit->isCloaked();\n#endif\n}\n\nbool Unit::isFlying() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_flying;\n#else\n return m_unit->isFlying();\n#endif\n}\n\nbool Unit::isAlive() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_alive;\n#else\n return m_unit->getHitPoints() > 0;\n#endif\n}\n\nbool Unit::isPowered() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_powered;\n#else\n return m_unit->isPowered();\n#endif\n}\n\nbool Unit::isIdle() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->orders.empty();\n#else\n return m_unit->isIdle();\n#endif\n}\n\nbool Unit::isBurrowed() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_burrowed;\n#else\n return m_unit->isBurrowed();\n#endif\n}\n\nbool Unit::isValid() const\n{\n return m_unit != nullptr;\n}\n\nvoid Unit::stop() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::STOP);\n#else\n m_unit->stop();\n#endif\n}\n\nvoid Unit::attackUnit(const Unit & target) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n BOT_ASSERT(target.isValid(), \"Target is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::ATTACK_ATTACK, target.getUnitPtr());\n#else\n m_unit->attack(target.getUnitPtr());\n#endif\n}\n\nvoid Unit::attackMove(const CCPosition & targetPosition) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::ATTACK_ATTACK, targetPosition);\n#else\n m_unit->attack(targetPosition);\n#endif\n}\n\nvoid Unit::move(const CCPosition & targetPosition) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::MOVE, targetPosition);\n#else\n m_unit->move(targetPosition);\n#endif\n}\n\nvoid Unit::move(const CCTilePosition & targetPosition) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::MOVE, CCPosition((float)targetPosition.x, (float)targetPosition.y));\n#else\n m_unit->move(CCPosition(targetPosition));\n#endif\n}\n\nvoid Unit::rightClick(const Unit & target) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::SMART, target.getUnitPtr());\n#else\n m_unit->rightClick(target.getUnitPtr());\n#endif\n}\n\nvoid Unit::repair(const Unit & target) const\n{\n rightClick(target);\n}\n\nvoid Unit::build(const UnitType & buildingType, CCTilePosition pos) const\n{\n BOT_ASSERT(m_bot->Map().isConnected(getTilePosition(), pos), \"Error: Build Position is not connected to worker\");\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, m_bot->Data(buildingType).buildAbility, Util::GetPosition(pos));\n#else\n m_unit->build(buildingType.getAPIUnitType(), pos);\n#endif\n}\n\nvoid Unit::buildTarget(const UnitType & buildingType, const Unit & target) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, m_bot->Data(buildingType).buildAbility, target.getUnitPtr());\n#else\n BOT_ASSERT(false, \"buildTarget shouldn't be called for BWAPI bots\");\n#endif\n}\n\nvoid Unit::train(const UnitType & type) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, m_bot->Data(type).buildAbility);\n#else\n m_unit->train(type.getAPIUnitType());\n#endif\n}\n\nbool Unit::isConstructing(const UnitType & type) const\n{\n#ifdef SC2API\n sc2::AbilityID buildAbility = m_bot->Data(type).buildAbility;\n return (getUnitPtr()->orders.size() > 0) && (getUnitPtr()->orders[0].ability_id == buildAbility);\n#else\n return m_unit->isConstructing();\n#endif\n}unit fix#include \"Unit.h\"\n#include \"CCBot.h\"\n\nUnit::Unit()\n : m_bot(nullptr)\n , m_unit(nullptr)\n , m_unitID(0)\n{\n\n}\n\n#ifdef SC2API\nUnit::Unit(const sc2::Unit * unit, CCBot & bot)\n : m_bot(&bot)\n , m_unit(unit)\n , m_unitID(unit->tag)\n , m_unitType(unit->unit_type, bot)\n{\n \n}\n\nconst sc2::Unit * Unit::getUnitPtr() const\n{\n return m_unit;\n}\n\nconst sc2::UnitTypeID & Unit::getAPIUnitType() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n return m_unit->unit_type;\n}\n\n#else\nUnit::Unit(const BWAPI::Unit unit, CCBot & bot)\n : m_bot(&bot)\n , m_unit(unit)\n , m_unitID(unit->getID())\n , m_unitType(unit->getType(), bot)\n{\n \n}\n\nconst BWAPI::Unit Unit::getUnitPtr() const\n{\n return m_unit;\n}\n\nconst BWAPI::UnitType & Unit::getAPIUnitType() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n return m_unit->getType();\n}\n\n#endif\nbool Unit::operator < (const Unit & rhs) const\n{\n return m_unit < rhs.m_unit;\n}\n\nbool Unit::operator == (const Unit & rhs) const\n{\n return m_unit == rhs.m_unit;\n}\n\nconst UnitType & Unit::getType() const\n{\n return m_unitType;\n}\n\n\nCCPosition Unit::getPosition() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->pos;\n#else\n return m_unit->getPosition();\n#endif\n}\n\nCCTilePosition Unit::getTilePosition() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return Util::GetTilePosition(m_unit->pos);\n#else\n return m_unit->getTilePosition();\n#endif\n}\n\nCCHealth Unit::getHitPoints() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->health;\n#else\n return m_unit->getHitPoints();\n#endif\n}\n\nCCHealth Unit::getShields() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->shield;\n#else\n return m_unit->getShields();\n#endif\n}\n\nCCHealth Unit::getEnergy() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->energy;\n#else\n return m_unit->getEnergy();\n#endif\n}\n\nfloat Unit::getBuildPercentage() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->build_progress;\n#else\n if (getType().isBuilding()) { return m_unit->getRemainingBuildTime() \/ (float)getType().getAPIUnitType().buildTime(); }\n else { return m_unit->getRemainingTrainTime() \/ (float)getType().getAPIUnitType().buildTime(); }\n#endif\n}\n\nCCPlayer Unit::getPlayer() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n if (m_unit->alliance == sc2::Unit::Alliance::Self) { return 0; }\n else if (m_unit->alliance == sc2::Unit::Alliance::Enemy) { return 1; }\n else { return 2; }\n#else\n if (m_unit->getPlayer() == BWAPI::Broodwar->self()) { return 0; }\n else if (m_unit->getPlayer() == BWAPI::Broodwar->enemy()) { return 1; }\n else { return 2; }\n#endif\n}\n\nCCUnitID Unit::getID() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n CCUnitID id = m_unit->tag;\n#else\n CCUnitID id = m_unit->getID();\n#endif\n\n BOT_ASSERT(id == m_unitID, \"Unit ID changed somehow\");\n return id;\n}\n\nbool Unit::isCompleted() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->build_progress >= 1.0f;\n#else\n return m_unit->isCompleted();\n#endif\n}\n\nbool Unit::isTraining() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->orders.size() > 0;\n#else\n return m_unit->isTraining();\n#endif\n}\n\nbool Unit::isBeingConstructed() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return !isCompleted() && m_unit->build_progress > 0.0f;\n#else\n return m_unit->isBeingConstructed();\n#endif\n}\n\nint Unit::getWeaponCooldown() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return (int)m_unit->weapon_cooldown;\n#else\n return std::max(m_unit->getGroundWeaponCooldown(), m_unit->getAirWeaponCooldown());\n#endif\n}\n\nbool Unit::isCloaked() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->cloak;\n#else\n return m_unit->isCloaked();\n#endif\n}\n\nbool Unit::isFlying() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_flying;\n#else\n return m_unit->isFlying();\n#endif\n}\n\nbool Unit::isAlive() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_alive;\n#else\n return m_unit->getHitPoints() > 0;\n#endif\n}\n\nbool Unit::isPowered() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_powered;\n#else\n return m_unit->isPowered();\n#endif\n}\n\nbool Unit::isIdle() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->orders.empty();\n#else\n return m_unit->isIdle() && !m_unit->isMoving() && !m_unit->isGatheringGas() && !m_unit->isGatheringMinerals();\n#endif\n}\n\nbool Unit::isBurrowed() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n return m_unit->is_burrowed;\n#else\n return m_unit->isBurrowed();\n#endif\n}\n\nbool Unit::isValid() const\n{\n return m_unit != nullptr;\n}\n\nvoid Unit::stop() const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::STOP);\n#else\n m_unit->stop();\n#endif\n}\n\nvoid Unit::attackUnit(const Unit & target) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n BOT_ASSERT(target.isValid(), \"Target is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::ATTACK_ATTACK, target.getUnitPtr());\n#else\n m_unit->attack(target.getUnitPtr());\n#endif\n}\n\nvoid Unit::attackMove(const CCPosition & targetPosition) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::ATTACK_ATTACK, targetPosition);\n#else\n m_unit->attack(targetPosition);\n#endif\n}\n\nvoid Unit::move(const CCPosition & targetPosition) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::MOVE, targetPosition);\n#else\n m_unit->move(targetPosition);\n#endif\n}\n\nvoid Unit::move(const CCTilePosition & targetPosition) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::MOVE, CCPosition((float)targetPosition.x, (float)targetPosition.y));\n#else\n m_unit->move(CCPosition(targetPosition));\n#endif\n}\n\nvoid Unit::rightClick(const Unit & target) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, sc2::ABILITY_ID::SMART, target.getUnitPtr());\n#else\n m_unit->rightClick(target.getUnitPtr());\n#endif\n}\n\nvoid Unit::repair(const Unit & target) const\n{\n rightClick(target);\n}\n\nvoid Unit::build(const UnitType & buildingType, CCTilePosition pos) const\n{\n BOT_ASSERT(m_bot->Map().isConnected(getTilePosition(), pos), \"Error: Build Position is not connected to worker\");\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, m_bot->Data(buildingType).buildAbility, Util::GetPosition(pos));\n#else\n m_unit->build(buildingType.getAPIUnitType(), pos);\n#endif\n}\n\nvoid Unit::buildTarget(const UnitType & buildingType, const Unit & target) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, m_bot->Data(buildingType).buildAbility, target.getUnitPtr());\n#else\n BOT_ASSERT(false, \"buildTarget shouldn't be called for BWAPI bots\");\n#endif\n}\n\nvoid Unit::train(const UnitType & type) const\n{\n BOT_ASSERT(isValid(), \"Unit is not valid\");\n#ifdef SC2API\n m_bot->Actions()->UnitCommand(m_unit, m_bot->Data(type).buildAbility);\n#else\n m_unit->train(type.getAPIUnitType());\n#endif\n}\n\nbool Unit::isConstructing(const UnitType & type) const\n{\n#ifdef SC2API\n sc2::AbilityID buildAbility = m_bot->Data(type).buildAbility;\n return (getUnitPtr()->orders.size() > 0) && (getUnitPtr()->orders[0].ability_id == buildAbility);\n#else\n return m_unit->isConstructing();\n#endif\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkBlankStructuredGridWithImage.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkBlankStructuredGridWithImage.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkFieldData.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStructuredGrid.h\"\n#include \"vtkUnsignedCharArray.h\"\n\nvtkCxxRevisionMacro(vtkBlankStructuredGridWithImage, \"1.10\");\nvtkStandardNewMacro(vtkBlankStructuredGridWithImage);\n\n\/\/----------------------------------------------------------------------------\nvtkBlankStructuredGridWithImage::vtkBlankStructuredGridWithImage()\n{\n this->NumberOfRequiredInputs = 2;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkBlankStructuredGridWithImage::~vtkBlankStructuredGridWithImage()\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Specify the input data or filter.\nvoid vtkBlankStructuredGridWithImage::SetBlankingInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(1, input);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Specify the input data or filter.\nvtkImageData *vtkBlankStructuredGridWithImage::GetBlankingInput()\n{\n if (this->NumberOfInputs < 2)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[1]);\n}\n\nvoid vtkBlankStructuredGridWithImage::Execute()\n{\n vtkStructuredGrid *grid = this->GetInput();\n vtkStructuredGrid *output = this->GetOutput();\n vtkImageData *image = this->GetBlankingInput();\n int gridDims[3], imageDims[3];\n\n vtkDebugMacro(<< \"Adding image blanking\");\n \n \/\/ Perform error checking\n grid->GetDimensions(gridDims);\n image->GetDimensions(imageDims);\n if ( gridDims[0] != imageDims[0] || gridDims[1] != imageDims[1] ||\n gridDims[2] != imageDims[2] )\n {\n vtkErrorMacro(<< \"Blanking dimensions must be identical with grid dimensions\");\n return;\n }\n \n if ( image->GetScalarType() != VTK_UNSIGNED_CHAR ||\n image->GetNumberOfScalarComponents() != 1 )\n {\n vtkErrorMacro(<<\"This filter requires unsigned char images with one component\");\n return;\n }\n \n \/\/ Get the image, set it as the blanking array.\n unsigned char *data = (unsigned char *)image->GetScalarPointer();\n vtkUnsignedCharArray *dataArray = vtkUnsignedCharArray::New();\n dataArray->SetArray(data, gridDims[0]*gridDims[1]*gridDims[2], 1);\n\n output->CopyStructure(grid);\n output->GetPointData()->PassData(grid->GetPointData());\n output->GetCellData()->PassData(grid->GetCellData());\n output->SetPointVisibilityArray(dataArray);\n \n dataArray->Delete();\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkBlankStructuredGridWithImage::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\nENH: Added more verbose error message for bad inputs.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkBlankStructuredGridWithImage.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkBlankStructuredGridWithImage.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkFieldData.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStructuredGrid.h\"\n#include \"vtkUnsignedCharArray.h\"\n\nvtkCxxRevisionMacro(vtkBlankStructuredGridWithImage, \"1.11\");\nvtkStandardNewMacro(vtkBlankStructuredGridWithImage);\n\n\/\/----------------------------------------------------------------------------\nvtkBlankStructuredGridWithImage::vtkBlankStructuredGridWithImage()\n{\n this->NumberOfRequiredInputs = 2;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkBlankStructuredGridWithImage::~vtkBlankStructuredGridWithImage()\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Specify the input data or filter.\nvoid vtkBlankStructuredGridWithImage::SetBlankingInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(1, input);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Specify the input data or filter.\nvtkImageData *vtkBlankStructuredGridWithImage::GetBlankingInput()\n{\n if (this->NumberOfInputs < 2)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[1]);\n}\n\nvoid vtkBlankStructuredGridWithImage::Execute()\n{\n vtkStructuredGrid *grid = this->GetInput();\n vtkStructuredGrid *output = this->GetOutput();\n vtkImageData *image = this->GetBlankingInput();\n int gridDims[3], imageDims[3];\n\n vtkDebugMacro(<< \"Adding image blanking\");\n \n \/\/ Perform error checking\n grid->GetDimensions(gridDims);\n image->GetDimensions(imageDims);\n if ( gridDims[0] != imageDims[0] || gridDims[1] != imageDims[1] ||\n gridDims[2] != imageDims[2] )\n {\n vtkErrorMacro(\"Blanking dimensions must be identical with grid dimensions. \"\n \"Blanking dimensions are \" << imageDims[0] << \" \"\n << imageDims[1] << \" \" << imageDims[2]\n << \". Grid dimensions are \" << gridDims[0] << \" \"\n << gridDims[1] << \" \" << gridDims[2] << \".\");\n return;\n }\n \n if ( image->GetScalarType() != VTK_UNSIGNED_CHAR ||\n image->GetNumberOfScalarComponents() != 1 )\n {\n vtkErrorMacro(<<\"This filter requires unsigned char images with one component\");\n return;\n }\n \n \/\/ Get the image, set it as the blanking array.\n unsigned char *data = (unsigned char *)image->GetScalarPointer();\n vtkUnsignedCharArray *dataArray = vtkUnsignedCharArray::New();\n dataArray->SetArray(data, gridDims[0]*gridDims[1]*gridDims[2], 1);\n\n output->CopyStructure(grid);\n output->GetPointData()->PassData(grid->GetPointData());\n output->GetCellData()->PassData(grid->GetCellData());\n output->SetPointVisibilityArray(dataArray);\n \n dataArray->Delete();\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkBlankStructuredGridWithImage::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright David Doria 2011 daviddoria@gmail.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"PatchBasedInpaintingGUI.h\"\n\n\/\/ Custom\n#include \"InteractorStyleImageWithDrag.h\"\n#include \"FileSelector.h\"\n#include \"HelpersOutput.h\"\n\n\/\/ VTK\n#include \n#include \n#include \n\n\/\/ QT\n#include \n#include \n\nvoid PatchBasedInpaintingGUI::on_chkDisplayUserPatch_clicked()\n{\n this->UserPatchLayer.ImageSlice->SetVisibility(this->chkDisplayUserPatch->isChecked());\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radDisplayColorImage_clicked()\n{\n this->spinChannelToDisplay->setEnabled(false);\n this->ImageDisplayStyle.Style = DisplayStyle::COLOR;\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radDisplayMagnitudeImage_clicked()\n{\n this->spinChannelToDisplay->setEnabled(false);\n this->ImageDisplayStyle.Style = DisplayStyle::MAGNITUDE;\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radDisplayChannel_clicked()\n{\n this->spinChannelToDisplay->setEnabled(true);\n this->ImageDisplayStyle.Style = DisplayStyle::CHANNEL;\n this->ImageDisplayStyle.Channel = this->spinChannelToDisplay->value();\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_spinChannelToDisplay_valueChanged(int unused)\n{\n this->ImageDisplayStyle.Channel = this->spinChannelToDisplay->value();\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radCompareOriginal_clicked()\n{\n this->Inpainting.SetCompareToOriginal();\n}\n\nvoid PatchBasedInpaintingGUI::on_radCompareBlurred_clicked()\n{\n this->Inpainting.SetCompareToBlurred();\n}\n\nvoid PatchBasedInpaintingGUI::on_radCompareCIELAB_clicked()\n{\n this->Inpainting.SetCompareToCIELAB();\n}\n \nvoid PatchBasedInpaintingGUI::on_chkLive_clicked()\n{\n \/\/ When \"Live\" is checked, we do not want to be able to click 'next' and 'previous'\n this->btnDisplayNextStep->setEnabled(!this->chkLive->isChecked());\n this->btnDisplayPreviousStep->setEnabled(!this->chkLive->isChecked());\n \n this->btnGoToIteration->setEnabled(!this->chkLive->isChecked());\n this->txtGoToIteration->setEnabled(!this->chkLive->isChecked());\n}\n\nvoid PatchBasedInpaintingGUI::on_btnGoToIteration_clicked()\n{\n if(this->GoToIteration < this->AllPotentialCandidatePairs.size() && this->GoToIteration >= 0)\n {\n this->IterationToDisplay = this->GoToIteration;\n ChangeDisplayedIteration();\n }\n}\n\nvoid PatchBasedInpaintingGUI::on_btnResort_clicked()\n{\n for(unsigned int iteration = 0; iteration < this->AllPotentialCandidatePairs.size(); iteration++)\n {\n for(unsigned int forwardLookId = 0; forwardLookId < this->AllPotentialCandidatePairs[iteration].size(); forwardLookId++)\n {\n CandidatePairs& candidatePairs = this->AllPotentialCandidatePairs[iteration][forwardLookId];\n\n if(this->radSortByAverageAbsoluteDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByAverageAbsoluteDifference);\n }\n else if(this->radSortByAverageSquaredDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByAverageSquaredDifference);\n }\n else if(this->radSortByBoundaryPixelDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByBoundaryPixelDifference);\n }\n else if(this->radSortByBoundaryIsophoteAngleDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByBoundaryIsophoteAngleDifference);\n }\n else if(this->radSortByBoundaryIsophoteStrengthDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByBoundaryIsophoteStrengthDifference);\n }\n else if(this->radSortByTotalScore->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByTotalScore);\n }\n else\n {\n std::cerr << \"No valid sorting criterion selected.\" << std::endl;\n }\n }\n }\n\n SetupTopPatchesTable();\n \/\/on_topPatchesTableWidget_currentCellChanged(0, 0);\n \n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkHighlightUsedPatches_clicked()\n{\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkImage_clicked()\n{\n this->ImageLayer.ImageSlice->SetVisibility(this->chkImage->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkMask_clicked()\n{\n this->MaskLayer.ImageSlice->SetVisibility(this->chkMask->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkPriority_clicked()\n{\n this->PriorityLayer.ImageSlice->SetVisibility(this->chkPriority->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkDisplayForwardLookPatchLocations_clicked()\n{\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkDisplaySourcePatchLocations_clicked()\n{\n RefreshVTK();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_chkBoundary_clicked()\n{\n this->BoundaryLayer.ImageSlice->SetVisibility(this->chkBoundary->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::SetCameraPosition()\n{\n double leftToRight[3] = {this->CameraLeftToRightVector[0], this->CameraLeftToRightVector[1], this->CameraLeftToRightVector[2]};\n double bottomToTop[3] = {this->CameraBottomToTopVector[0], this->CameraBottomToTopVector[1], this->CameraBottomToTopVector[2]};\n this->InteractorStyle->SetImageOrientation(leftToRight, bottomToTop);\n\n this->Renderer->ResetCamera();\n this->Renderer->ResetCameraClippingRange();\n this->qvtkWidget->GetRenderWindow()->Render();\n}\n\nvoid PatchBasedInpaintingGUI::on_actionFlipImageVertically_activated()\n{\n this->CameraBottomToTopVector[1] *= -1;\n SetCameraPosition();\n}\n\nvoid PatchBasedInpaintingGUI::on_actionFlipImageHorizontally_activated()\n{\n this->CameraLeftToRightVector[0] *= -1;\n SetCameraPosition();\n}\n\nvoid PatchBasedInpaintingGUI::SetCheckboxVisibility(const bool visible)\n{\n chkImage->setEnabled(visible);\n chkPriority->setEnabled(visible);\n chkBoundary->setEnabled(visible);\n chkMask->setEnabled(visible);\n}\n\nvoid PatchBasedInpaintingGUI::on_btnDisplayPreviousStep_clicked()\n{\n if(this->IterationToDisplay > 0)\n {\n this->IterationToDisplay--;\n DebugMessage(\"Displaying iteration: \", this->IterationToDisplay);\n ChangeDisplayedIteration();\n }\n else\n {\n DebugMessage(\"Iteration not changed.\");\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnDisplayNextStep_clicked()\n{\n \/\/std::cout << \"IterationToDisplay: \" << this->IterationToDisplay\n \/\/ << \" Inpainting iteration: \" << static_cast(this->Inpainting.GetIteration()) << std::endl;\n \n \/\/if(this->IterationToDisplay < this->Inpainting.GetNumberOfCompletedIterations() - 1)\n if(this->IterationToDisplay < this->IntermediateImages.size() - 1)\n {\n this->IterationToDisplay++;\n DebugMessage(\"Displaying iteration: \", this->IterationToDisplay);\n ChangeDisplayedIteration();\n }\n else\n {\n DebugMessage(\"Iteration not changed.\");\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_actionOpen_activated()\n{\n FileSelector* fileSelector(new FileSelector);\n fileSelector->exec();\n\n int result = fileSelector->result();\n if(result) \/\/ The user clicked 'ok'\n {\n std::cout << \"User clicked ok.\" << std::endl;\n OpenImage(fileSelector->GetImageFileName());\n OpenMask(fileSelector->GetMaskFileName(), fileSelector->IsMaskInverted());\n Initialize();\n }\n else\n {\n std::cout << \"User clicked cancel.\" << std::endl;\n \/\/ The user clicked 'cancel' or closed the dialog, do nothing.\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_actionSaveResult_activated()\n{\n \/\/ Get a filename to save\n QString fileName = QFileDialog::getSaveFileName(this, \"Save File\", \".\", \"Image Files (*.jpg *.jpeg *.bmp *.png *.mha)\");\n\n DebugMessage(\"Got filename: \", fileName.toStdString());\n if(fileName.toStdString().empty())\n {\n std::cout << \"Filename was empty.\" << std::endl;\n return;\n }\n\n HelpersOutput::WriteImage(this->Inpainting.GetCurrentOutputImage(), fileName.toStdString());\n\n this->statusBar()->showMessage(\"Saved result.\");\n}\n\n\nvoid PatchBasedInpaintingGUI::on_chkDebugImages_clicked()\n{\n QDir directoryMaker;\n directoryMaker.mkdir(\"Debug\");\n\n this->Inpainting.SetDebugImages(this->chkDebugImages->isChecked());\n this->DebugImages = this->chkDebugImages->isChecked();\n\n DebugMessage(\"DebugImages: \", this->DebugImages);\n}\n\nvoid PatchBasedInpaintingGUI::on_chkDebugMessages_clicked()\n{\n this->Inpainting.SetDebugMessages(this->chkDebugMessages->isChecked());\n this->DebugMessages = this->chkDebugMessages->isChecked();\n}\n\nvoid PatchBasedInpaintingGUI::on_actionQuit_activated()\n{\n exit(0);\n}\n\n\nvoid PatchBasedInpaintingGUI::slot_ForwardLookTableView_changed(const QModelIndex& currentIndex, const QModelIndex& previousIndex)\n{\n std::cout << \"on_ForwardLookTableView_currentCellChanged\" << std::endl;\n \n if(currentIndex.row() < 0)\n {\n std::cout << \"on_ForwardLookTableView_currentCellChanged: row < 0!\" << std::endl;\n return;\n }\n \n if(currentIndex.row() > static_cast(this->AllPotentialCandidatePairs[this->IterationToDisplay - 1].size() - 1))\n {\n std::cerr << \"Requested display of forward look patch \" << currentIndex.row() << \" but there are only \" << this->AllPotentialCandidatePairs[this->IterationToDisplay - 1].size() - 1 << std::endl;\n }\n\n std::cerr << \"Requested display of forward look patch \" << currentIndex.row() << std::endl;\n \n this->ForwardLookToDisplay = currentIndex.row();\n this->SourcePatchToDisplay = 0;\n \n ChangeDisplayedForwardLookPatch();\n \n SetupTopPatchesTable();\n ChangeDisplayedTopPatch();\n \n}\n\n\nvoid PatchBasedInpaintingGUI::slot_TopPatchesTableView_changed(const QModelIndex& currentIndex, const QModelIndex& previousIndex)\n{\n try\n {\n if(currentIndex.row() < 0)\n {\n std::cout << \"Selected row is < 0!\" << std::endl;\n return;\n }\n \n if(currentIndex.row() == previousIndex.row())\n {\n std::cout << \"Nothing changed!\" << std::endl;\n return;\n }\n \n this->SourcePatchToDisplay = currentIndex.row();\n ChangeDisplayedTopPatch();\n \n }\/\/ end try\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ExceptionObject caught in on_topPatchesTableWidget_currentCellChanged!\" << std::endl;\n std::cerr << err << std::endl;\n exit(-1);\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnInpaint_clicked()\n{\n EnterFunction(\"on_btnInpaint_clicked()\");\n \n \/\/Initialize();\n \n \/\/Refresh();\n \n this->Inpainting.SetMaxForwardLookPatches(this->NumberOfForwardLook);\n this->Inpainting.SetNumberOfTopPatchesToSave(this->NumberOfTopPatchesToSave);\n \n ComputationThread.start();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnStep_clicked()\n{\n this->Inpainting.SetDebugImages(this->chkDebugImages->isChecked());\n this->Inpainting.SetDebugMessages(this->chkDebugMessages->isChecked());\n this->Inpainting.SetMaxForwardLookPatches(this->NumberOfForwardLook);\n this->Inpainting.SetNumberOfTopPatchesToSave(this->NumberOfTopPatchesToSave);\n PatchPair usedPair = this->Inpainting.Iterate();\n \n this->UsedPatchPairs.push_back(usedPair);\n \n IterationComplete();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnStop_clicked()\n{\n this->ComputationThread.StopInpainting();\n}\n\nvoid PatchBasedInpaintingGUI::on_btnReset_clicked()\n{\n slot_Refresh();\n}\n \n\nvoid PatchBasedInpaintingGUI::on_btnInitialize_clicked()\n{\n Initialize();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_actionHelp_activated()\n{\n QTextEdit* help=new QTextEdit();\n\n help->setReadOnly(true);\n help->append(\"

Patch Based Inpainting<\/h1>\\\n Load an image and a mask. \\\n Set the settings such as patch size. \\\n To do the complete inpainting, click 'Inpaint'.\\\n To do one step of the inpainting, click 'Step'. This will allow you to inspect forward look candidates and each of their top matches.\\\n \");\n help->show();\n}\n\n\nvoid PatchBasedInpaintingGUI::slot_StartProgress()\n{\n \/\/std::cout << \"Form::StartProgressSlot()\" << std::endl;\n \/\/ Connected to the StartProgressSignal of the ProgressThread member\n this->progressBar->show();\n}\n\nvoid PatchBasedInpaintingGUI::slot_StopProgress()\n{\n \/\/std::cout << \"Form::StopProgressSlot()\" << std::endl;\n \/\/ When the ProgressThread emits the StopProgressSignal, we need to display the result of the segmentation\n\n this->progressBar->hide();\n}\n\nvoid PatchBasedInpaintingGUI::slot_Refresh()\n{\n DebugMessage(\"RefreshSlot()\");\n\n Refresh();\n}\n\n\nvoid PatchBasedInpaintingGUI::slot_IterationComplete()\n{\n DebugMessage(\"IterationCompleteSlot()\");\n IterationComplete();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtPatchRadius_textEdited ( const QString & text )\n{\n this->PatchRadius = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtNumberOfTopPatchesToSave_textEdited ( const QString & text )\n{\n this->NumberOfTopPatchesToSave = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtNumberOfForwardLook_textEdited ( const QString & text )\n{\n this->NumberOfForwardLook = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtGoToIteration_textEdited ( const QString & text )\n{\n this->GoToIteration = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtNumberOfTopPatchesToDisplay_textEdited ( const QString & text )\n{\n this->NumberOfTopPatchesToDisplay = text.toUInt();\n}\nDisable some text boxes while inpainting is running.\/*=========================================================================\n *\n * Copyright David Doria 2011 daviddoria@gmail.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"PatchBasedInpaintingGUI.h\"\n\n\/\/ Custom\n#include \"InteractorStyleImageWithDrag.h\"\n#include \"FileSelector.h\"\n#include \"HelpersOutput.h\"\n\n\/\/ VTK\n#include \n#include \n#include \n\n\/\/ QT\n#include \n#include \n\nvoid PatchBasedInpaintingGUI::on_chkDisplayUserPatch_clicked()\n{\n this->UserPatchLayer.ImageSlice->SetVisibility(this->chkDisplayUserPatch->isChecked());\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radDisplayColorImage_clicked()\n{\n this->spinChannelToDisplay->setEnabled(false);\n this->ImageDisplayStyle.Style = DisplayStyle::COLOR;\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radDisplayMagnitudeImage_clicked()\n{\n this->spinChannelToDisplay->setEnabled(false);\n this->ImageDisplayStyle.Style = DisplayStyle::MAGNITUDE;\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radDisplayChannel_clicked()\n{\n this->spinChannelToDisplay->setEnabled(true);\n this->ImageDisplayStyle.Style = DisplayStyle::CHANNEL;\n this->ImageDisplayStyle.Channel = this->spinChannelToDisplay->value();\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_spinChannelToDisplay_valueChanged(int unused)\n{\n this->ImageDisplayStyle.Channel = this->spinChannelToDisplay->value();\n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_radCompareOriginal_clicked()\n{\n this->Inpainting.SetCompareToOriginal();\n}\n\nvoid PatchBasedInpaintingGUI::on_radCompareBlurred_clicked()\n{\n this->Inpainting.SetCompareToBlurred();\n}\n\nvoid PatchBasedInpaintingGUI::on_radCompareCIELAB_clicked()\n{\n this->Inpainting.SetCompareToCIELAB();\n}\n \nvoid PatchBasedInpaintingGUI::on_chkLive_clicked()\n{\n \/\/ When \"Live\" is checked, we do not want to be able to click 'next' and 'previous'\n this->btnDisplayNextStep->setEnabled(!this->chkLive->isChecked());\n this->btnDisplayPreviousStep->setEnabled(!this->chkLive->isChecked());\n \n this->btnGoToIteration->setEnabled(!this->chkLive->isChecked());\n this->txtGoToIteration->setEnabled(!this->chkLive->isChecked());\n}\n\nvoid PatchBasedInpaintingGUI::on_btnGoToIteration_clicked()\n{\n if(this->GoToIteration < this->AllPotentialCandidatePairs.size() && this->GoToIteration >= 0)\n {\n this->IterationToDisplay = this->GoToIteration;\n ChangeDisplayedIteration();\n }\n}\n\nvoid PatchBasedInpaintingGUI::on_btnResort_clicked()\n{\n for(unsigned int iteration = 0; iteration < this->AllPotentialCandidatePairs.size(); iteration++)\n {\n for(unsigned int forwardLookId = 0; forwardLookId < this->AllPotentialCandidatePairs[iteration].size(); forwardLookId++)\n {\n CandidatePairs& candidatePairs = this->AllPotentialCandidatePairs[iteration][forwardLookId];\n\n if(this->radSortByAverageAbsoluteDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByAverageAbsoluteDifference);\n }\n else if(this->radSortByAverageSquaredDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByAverageSquaredDifference);\n }\n else if(this->radSortByBoundaryPixelDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByBoundaryPixelDifference);\n }\n else if(this->radSortByBoundaryIsophoteAngleDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByBoundaryIsophoteAngleDifference);\n }\n else if(this->radSortByBoundaryIsophoteStrengthDifference->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByBoundaryIsophoteStrengthDifference);\n }\n else if(this->radSortByTotalScore->isChecked())\n {\n std::sort(candidatePairs.begin(), candidatePairs.end(), SortByTotalScore);\n }\n else\n {\n std::cerr << \"No valid sorting criterion selected.\" << std::endl;\n }\n }\n }\n\n SetupTopPatchesTable();\n \/\/on_topPatchesTableWidget_currentCellChanged(0, 0);\n \n Refresh();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkHighlightUsedPatches_clicked()\n{\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkImage_clicked()\n{\n this->ImageLayer.ImageSlice->SetVisibility(this->chkImage->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkMask_clicked()\n{\n this->MaskLayer.ImageSlice->SetVisibility(this->chkMask->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkPriority_clicked()\n{\n this->PriorityLayer.ImageSlice->SetVisibility(this->chkPriority->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkDisplayForwardLookPatchLocations_clicked()\n{\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::on_chkDisplaySourcePatchLocations_clicked()\n{\n RefreshVTK();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_chkBoundary_clicked()\n{\n this->BoundaryLayer.ImageSlice->SetVisibility(this->chkBoundary->isChecked());\n RefreshVTK();\n}\n\nvoid PatchBasedInpaintingGUI::SetCameraPosition()\n{\n double leftToRight[3] = {this->CameraLeftToRightVector[0], this->CameraLeftToRightVector[1], this->CameraLeftToRightVector[2]};\n double bottomToTop[3] = {this->CameraBottomToTopVector[0], this->CameraBottomToTopVector[1], this->CameraBottomToTopVector[2]};\n this->InteractorStyle->SetImageOrientation(leftToRight, bottomToTop);\n\n this->Renderer->ResetCamera();\n this->Renderer->ResetCameraClippingRange();\n this->qvtkWidget->GetRenderWindow()->Render();\n}\n\nvoid PatchBasedInpaintingGUI::on_actionFlipImageVertically_activated()\n{\n this->CameraBottomToTopVector[1] *= -1;\n SetCameraPosition();\n}\n\nvoid PatchBasedInpaintingGUI::on_actionFlipImageHorizontally_activated()\n{\n this->CameraLeftToRightVector[0] *= -1;\n SetCameraPosition();\n}\n\nvoid PatchBasedInpaintingGUI::SetCheckboxVisibility(const bool visible)\n{\n chkImage->setEnabled(visible);\n chkPriority->setEnabled(visible);\n chkBoundary->setEnabled(visible);\n chkMask->setEnabled(visible);\n}\n\nvoid PatchBasedInpaintingGUI::on_btnDisplayPreviousStep_clicked()\n{\n if(this->IterationToDisplay > 0)\n {\n this->IterationToDisplay--;\n DebugMessage(\"Displaying iteration: \", this->IterationToDisplay);\n ChangeDisplayedIteration();\n }\n else\n {\n DebugMessage(\"Iteration not changed.\");\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnDisplayNextStep_clicked()\n{\n \/\/std::cout << \"IterationToDisplay: \" << this->IterationToDisplay\n \/\/ << \" Inpainting iteration: \" << static_cast(this->Inpainting.GetIteration()) << std::endl;\n \n \/\/if(this->IterationToDisplay < this->Inpainting.GetNumberOfCompletedIterations() - 1)\n if(this->IterationToDisplay < this->IntermediateImages.size() - 1)\n {\n this->IterationToDisplay++;\n DebugMessage(\"Displaying iteration: \", this->IterationToDisplay);\n ChangeDisplayedIteration();\n }\n else\n {\n DebugMessage(\"Iteration not changed.\");\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_actionOpen_activated()\n{\n FileSelector* fileSelector(new FileSelector);\n fileSelector->exec();\n\n int result = fileSelector->result();\n if(result) \/\/ The user clicked 'ok'\n {\n std::cout << \"User clicked ok.\" << std::endl;\n OpenImage(fileSelector->GetImageFileName());\n OpenMask(fileSelector->GetMaskFileName(), fileSelector->IsMaskInverted());\n Initialize();\n }\n else\n {\n std::cout << \"User clicked cancel.\" << std::endl;\n \/\/ The user clicked 'cancel' or closed the dialog, do nothing.\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_actionSaveResult_activated()\n{\n \/\/ Get a filename to save\n QString fileName = QFileDialog::getSaveFileName(this, \"Save File\", \".\", \"Image Files (*.jpg *.jpeg *.bmp *.png *.mha)\");\n\n DebugMessage(\"Got filename: \", fileName.toStdString());\n if(fileName.toStdString().empty())\n {\n std::cout << \"Filename was empty.\" << std::endl;\n return;\n }\n\n HelpersOutput::WriteImage(this->Inpainting.GetCurrentOutputImage(), fileName.toStdString());\n\n this->statusBar()->showMessage(\"Saved result.\");\n}\n\n\nvoid PatchBasedInpaintingGUI::on_chkDebugImages_clicked()\n{\n QDir directoryMaker;\n directoryMaker.mkdir(\"Debug\");\n\n this->Inpainting.SetDebugImages(this->chkDebugImages->isChecked());\n this->DebugImages = this->chkDebugImages->isChecked();\n\n DebugMessage(\"DebugImages: \", this->DebugImages);\n}\n\nvoid PatchBasedInpaintingGUI::on_chkDebugMessages_clicked()\n{\n this->Inpainting.SetDebugMessages(this->chkDebugMessages->isChecked());\n this->DebugMessages = this->chkDebugMessages->isChecked();\n}\n\nvoid PatchBasedInpaintingGUI::on_actionQuit_activated()\n{\n exit(0);\n}\n\n\nvoid PatchBasedInpaintingGUI::slot_ForwardLookTableView_changed(const QModelIndex& currentIndex, const QModelIndex& previousIndex)\n{\n std::cout << \"on_ForwardLookTableView_currentCellChanged\" << std::endl;\n \n if(currentIndex.row() < 0)\n {\n std::cout << \"on_ForwardLookTableView_currentCellChanged: row < 0!\" << std::endl;\n return;\n }\n \n if(currentIndex.row() > static_cast(this->AllPotentialCandidatePairs[this->IterationToDisplay - 1].size() - 1))\n {\n std::cerr << \"Requested display of forward look patch \" << currentIndex.row() << \" but there are only \" << this->AllPotentialCandidatePairs[this->IterationToDisplay - 1].size() - 1 << std::endl;\n }\n\n std::cerr << \"Requested display of forward look patch \" << currentIndex.row() << std::endl;\n \n this->ForwardLookToDisplay = currentIndex.row();\n this->SourcePatchToDisplay = 0;\n \n ChangeDisplayedForwardLookPatch();\n \n SetupTopPatchesTable();\n ChangeDisplayedTopPatch();\n \n}\n\n\nvoid PatchBasedInpaintingGUI::slot_TopPatchesTableView_changed(const QModelIndex& currentIndex, const QModelIndex& previousIndex)\n{\n try\n {\n if(currentIndex.row() < 0)\n {\n std::cout << \"Selected row is < 0!\" << std::endl;\n return;\n }\n \n if(currentIndex.row() == previousIndex.row())\n {\n std::cout << \"Nothing changed!\" << std::endl;\n return;\n }\n \n this->SourcePatchToDisplay = currentIndex.row();\n ChangeDisplayedTopPatch();\n \n }\/\/ end try\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ExceptionObject caught in on_topPatchesTableWidget_currentCellChanged!\" << std::endl;\n std::cerr << err << std::endl;\n exit(-1);\n }\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnInpaint_clicked()\n{\n EnterFunction(\"on_btnInpaint_clicked()\");\n \n \/\/Initialize();\n \n \/\/Refresh();\n\n \/\/ Gray out some items that should not be changed while the inpainting is running.\n this->txtNumberOfForwardLook->setEnabled(false);\n this->txtNumberOfTopPatchesToSave->setEnabled(false);\n \n this->Inpainting.SetMaxForwardLookPatches(this->NumberOfForwardLook);\n this->Inpainting.SetNumberOfTopPatchesToSave(this->NumberOfTopPatchesToSave);\n \n ComputationThread.start();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnStep_clicked()\n{\n this->Inpainting.SetDebugImages(this->chkDebugImages->isChecked());\n this->Inpainting.SetDebugMessages(this->chkDebugMessages->isChecked());\n this->Inpainting.SetMaxForwardLookPatches(this->NumberOfForwardLook);\n this->Inpainting.SetNumberOfTopPatchesToSave(this->NumberOfTopPatchesToSave);\n PatchPair usedPair = this->Inpainting.Iterate();\n \n this->UsedPatchPairs.push_back(usedPair);\n \n IterationComplete();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_btnStop_clicked()\n{\n this->ComputationThread.StopInpainting();\n}\n\nvoid PatchBasedInpaintingGUI::on_btnReset_clicked()\n{\n slot_Refresh();\n}\n \n\nvoid PatchBasedInpaintingGUI::on_btnInitialize_clicked()\n{\n Initialize();\n}\n\n\nvoid PatchBasedInpaintingGUI::on_actionHelp_activated()\n{\n QTextEdit* help=new QTextEdit();\n\n help->setReadOnly(true);\n help->append(\"

Patch Based Inpainting<\/h1>\\\n Load an image and a mask. \\\n Set the settings such as patch size. \\\n To do the complete inpainting, click 'Inpaint'.\\\n To do one step of the inpainting, click 'Step'. This will allow you to inspect forward look candidates and each of their top matches.\\\n \");\n help->show();\n}\n\n\nvoid PatchBasedInpaintingGUI::slot_StartProgress()\n{\n \/\/std::cout << \"Form::StartProgressSlot()\" << std::endl;\n \/\/ Connected to the StartProgressSignal of the ProgressThread member\n this->progressBar->show();\n}\n\nvoid PatchBasedInpaintingGUI::slot_StopProgress()\n{\n \/\/std::cout << \"Form::StopProgressSlot()\" << std::endl;\n\n \/\/ Re-enable some items that should not be changed while the inpainting is running.\n this->txtNumberOfForwardLook->setEnabled(false);\n this->txtNumberOfTopPatchesToSave->setEnabled(false);\n \n this->progressBar->hide();\n}\n\nvoid PatchBasedInpaintingGUI::slot_Refresh()\n{\n DebugMessage(\"RefreshSlot()\");\n\n Refresh();\n}\n\n\nvoid PatchBasedInpaintingGUI::slot_IterationComplete()\n{\n DebugMessage(\"IterationCompleteSlot()\");\n IterationComplete();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtPatchRadius_textEdited ( const QString & text )\n{\n this->PatchRadius = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtNumberOfTopPatchesToSave_textEdited ( const QString & text )\n{\n this->NumberOfTopPatchesToSave = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtNumberOfForwardLook_textEdited ( const QString & text )\n{\n this->NumberOfForwardLook = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtGoToIteration_textEdited ( const QString & text )\n{\n this->GoToIteration = text.toUInt();\n}\n\nvoid PatchBasedInpaintingGUI::on_txtNumberOfTopPatchesToDisplay_textEdited ( const QString & text )\n{\n this->NumberOfTopPatchesToDisplay = text.toUInt();\n}\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n \n#include \"subdivpatch1cached_intersector1.h\"\n#include \"..\/bvh4\/bvh4.h\"\n#include \"..\/bvh4\/bvh4_intersector1.h\"\n\n#define TIMER(x) \n#define DBG(x) \n\nnamespace embree\n{\n namespace isa\n { \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void verifySubTreeBVH(const BVH4::NodeRef ref)\n {\n assert(ref != BVH4::invalidNode );\n\n \/* this is a leaf node *\/\n if (unlikely(ref.isLeaf()))\n return;\n \n const BVH4::Node* node = ref.node();\n \n for (size_t i=0;i<4;i++)\n\t{\n\t assert(node->child(i) != BVH4::emptyNode);\n\t \n\t BBox3fa bounds = node->bounds(i);\n\n\t assert( std::isfinite(bounds.lower.x) );\n\t assert( std::isfinite(bounds.lower.y) );\n\t assert( std::isfinite(bounds.lower.z) );\n\n\t assert( std::isfinite(bounds.upper.x) );\n\t assert( std::isfinite(bounds.upper.y) );\n\t assert( std::isfinite(bounds.upper.z) );\n\n\t verifySubTreeBVH(node->child(i));\n\t}\n }\n\n size_t countBlocks(const BVH4::NodeRef ref, const size_t range0, const size_t range1)\n {\n \n size_t t = (size_t)ref;\n\n assert(range0 <= t);\n assert(t <= range1);\n\n \/* this is a leaf node *\/\n if (unlikely(ref.isLeaf()))\n return 3;\n \n const BVH4::Node* node = ref.node();\n \n size_t size = 0;\n for (size_t i=0;i<4;i++)\n if (node->child(i) != BVH4::emptyNode)\n size += countBlocks(node->child(i),range0,range1);\n\n return 2 + size;\n }\n\n void updateBVH4Refs(const BVH4::NodeRef &ref, const size_t old_ptr, const size_t new_ptr)\n {\n if (unlikely(ref == BVH4::emptyNode))\n return;\n\n assert(ref != BVH4::invalidNode);\n\n \/* this is a leaf node *\/\n if (unlikely(ref.isLeaf()))\n return;\n\n const BVH4::Node* node = ref.node();\n \n for (size_t i=0;i<4;i++)\n {\n const BVH4::NodeRef &child = node->child(i);\n if (node->child(i) != BVH4::emptyNode)\n {\n if (child.isNode())\n updateBVH4Refs(child,old_ptr,new_ptr);\n\n const size_t dest_offset = (size_t)&child - old_ptr; \n const size_t new_ref = (size_t)child - old_ptr + new_ptr;\n size_t *ptr = (size_t*)((char*)new_ptr + dest_offset);\n *ptr = new_ref; \n }\n }\n }\n\n \/* build lazy subtree over patch *\/\n size_t SubdivPatch1CachedIntersector1::lazyBuildPatch(Precalculations &pre,\n\t\t\t\t\t\t\t SubdivPatch1Cached* const subdiv_patch, \n\t\t\t\t\t\t\t const Scene* scene)\n {\n \/* unlock previous patch *\/\n if (pre.current_patch)\n {\n assert(SharedLazyTessellationCache::sharedLazyTessellationCache.isLocked(pre.t_state));\n SharedLazyTessellationCache::sharedLazyTessellationCache.unlockThread(pre.t_state);\n }\n\n while(1)\n {\n\n SharedLazyTessellationCache::sharedLazyTessellationCache.lockThreadLoop(pre.t_state);\n \n const size_t globalTime = scene->commitCounter;\n if (void* ptr = SharedLazyTessellationCache::lookup(&subdiv_patch->root_ref,globalTime))\n return (size_t) ptr;\n \n SharedLazyTessellationCache::sharedLazyTessellationCache.unlockThread(pre.t_state);\t\t \n\n if (subdiv_patch->try_write_lock())\n {\n if (!SharedLazyTessellationCache::validTag(subdiv_patch->root_ref,globalTime)) \n {\n \/* generate vertex grid, lock and allocate memory in the cache *\/\n size_t new_root_ref = (size_t)buildSubdivPatchTreeCompact(*subdiv_patch,pre.t_state,scene->getSubdivMesh(subdiv_patch->geom)); \n \n \/* get current commit index *\/\n \/\/const size_t commitIndex = SharedLazyTessellationCache::sharedLazyTessellationCache.getCurrentIndex();\n const size_t combinedTime = SharedLazyTessellationCache::sharedLazyTessellationCache.getTime(globalTime);\n\n __memory_barrier();\n \/* write new root ref *\/\n subdiv_patch->root_ref = SharedLazyTessellationCache::Tag((void*)new_root_ref,combinedTime);\n \n#if _DEBUG\n const size_t patchIndex = subdiv_patch - pre.array;\n assert(patchIndex < pre.numPrimitives);\n CACHE_STATS(SharedTessellationCacheStats::incPatchBuild(patchIndex,pre.numPrimitives));\n#endif\n assert(SharedLazyTessellationCache::sharedLazyTessellationCache.isLocked(pre.t_state));\n\n \/* unlock current patch *\/\n subdiv_patch->write_unlock();\n\n \/* memory region still locked, forward progress guaranteed *\/\n return new_root_ref;\n }\n \/* unlock current patch *\/\n subdiv_patch->write_unlock();\n }\n }\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n BVH4::NodeRef SubdivPatch1CachedIntersector1::buildSubdivPatchTreeCompact(const SubdivPatch1Cached &patch,\n ThreadWorkState *t_state,\n\t\t\t\t\t\t\t\t\t const SubdivMesh* const geom, BBox3fa* bounds_o)\n { \n assert( patch.grid_size_simd_blocks >= 1 );\n\n const size_t array_elements = patch.grid_size_simd_blocks * vfloat::size;\n dynamic_large_stack_array(float,local_grid_u,array_elements,64*64);\n dynamic_large_stack_array(float,local_grid_v,array_elements,64*64);\n dynamic_large_stack_array(float,local_grid_x,array_elements,64*64);\n dynamic_large_stack_array(float,local_grid_y,array_elements,64*64);\n dynamic_large_stack_array(float,local_grid_z,array_elements,64*64);\n\n \/* compute vertex grid (+displacement) *\/\n evalGrid(patch,0,patch.grid_u_res-1,0,patch.grid_v_res-1,patch.grid_u_res,patch.grid_v_res,local_grid_x,local_grid_y,local_grid_z,local_grid_u,local_grid_v,geom);\n\n \/* lock the cache *\/\n SharedLazyTessellationCache::sharedLazyTessellationCache.lockThreadLoop(t_state);\n\n \/* allocate memory in cache and get current commit index *\/\n void *const lazymem = SharedLazyTessellationCache::sharedLazyTessellationCache.allocLoop(t_state,64*patch.grid_subtree_size_64b_blocks);\n\n \/* copy temporary data to tessellation cache *\/\n const size_t grid_offset = patch.grid_bvh_size_64b_blocks * 16;\n\n float *const grid_x = (float*)lazymem + grid_offset + 0 * array_elements;\n float *const grid_y = (float*)lazymem + grid_offset + 1 * array_elements;\n float *const grid_z = (float*)lazymem + grid_offset + 2 * array_elements;\n int *const grid_uv = (int*) lazymem + grid_offset + 3 * array_elements;\n assert( patch.grid_subtree_size_64b_blocks * 16 >= grid_offset + 4 * array_elements);\n\n memcpy(grid_x ,local_grid_x ,array_elements*sizeof(float));\n memcpy(grid_y ,local_grid_y ,array_elements*sizeof(float));\n memcpy(grid_z ,local_grid_z ,array_elements*sizeof(float));\n\n for (size_t i=0;i= delta_u) \n\t\tu_start -= delta_u; \n\t else\n\t\tu_start = 0;\n\t }\n if (unlikely(v_end-v_start+1 < 3)) \n\t { \n\t const unsigned int delta_v = 3 - (v_end-v_start+1);\n\t if (v_start >= delta_v) \n\t\tv_start -= delta_v; \n\t else\n\t\tv_start = 0;\n\t }\n\n\t const unsigned int u_size = u_end-u_start+1;\n\t const unsigned int v_size = v_end-v_start+1;\n \n\t assert(u_size >= 1);\n\t assert(v_size >= 1);\n \n\t const size_t grid_offset3x3 = v_start * patch.grid_u_res + u_start;\n\n\n\t size_t offset_bytes = (size_t)&grid_x_array[ grid_offset3x3 ] - (size_t)SharedLazyTessellationCache::sharedLazyTessellationCache.getDataPtr();\n\t assert(offset_bytes < 0xffffffff);\n\t assert((offset_bytes & 3) == 0);\n size_t value = (offset_bytes << 2) + (size_t)SharedLazyTessellationCache::sharedLazyTessellationCache.getDataPtr();\n assert( (value & 2) == 0 );\n\t curNode = BVH4::encodeTypedLeaf((void*)value,2);\n\n\t assert( std::isfinite(bounds.lower.x) );\n\t assert( std::isfinite(bounds.lower.y) );\n\t assert( std::isfinite(bounds.lower.z) );\n\t \n\t assert( std::isfinite(bounds.upper.x) );\n\t assert( std::isfinite(bounds.upper.y) );\n\t assert( std::isfinite(bounds.upper.z) );\n\n\t return bounds;\n\t}\n \n \n \/* allocate new bvh4 node *\/\n const size_t currentIndex = localCounter;\n \n \/* 128 bytes == 2 x 64 bytes cachelines *\/\n localCounter += 2; \n \n BVH4::Node *node = (BVH4::Node *)&lazymem[currentIndex*16];\n \n curNode = BVH4::encodeNode( node );\n \n node->clear();\n \n GridRange r[4];\n \n const unsigned int children = range.splitIntoSubRanges(r);\n \n \/* create four subtrees *\/\n BBox3fa bounds( empty );\n \n for (unsigned int i=0;ichild(i), \n\t\t\t\t\t\t\t lazymem, \n\t\t\t\t\t\t\t patch, \n\t\t\t\t\t\t\t grid_array,\n\t\t\t\t\t\t\t grid_array_elements,\n\t\t\t\t\t\t\t r[i],\t\t\t\t\t\t \n\t\t\t\t\t\t\t localCounter);\n\t node->set(i, bounds_subtree);\n\t bounds.extend( bounds_subtree );\n\t}\n \n return bounds;\n }\n }\n}\nbugfix in subdivpatch1_intersector1.cpp, by introducing dynamic_large_stack_array some array padding got lost\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n \n#include \"subdivpatch1cached_intersector1.h\"\n#include \"..\/bvh4\/bvh4.h\"\n#include \"..\/bvh4\/bvh4_intersector1.h\"\n\n#define TIMER(x) \n#define DBG(x) \n\nnamespace embree\n{\n namespace isa\n { \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void verifySubTreeBVH(const BVH4::NodeRef ref)\n {\n assert(ref != BVH4::invalidNode );\n\n \/* this is a leaf node *\/\n if (unlikely(ref.isLeaf()))\n return;\n \n const BVH4::Node* node = ref.node();\n \n for (size_t i=0;i<4;i++)\n\t{\n\t assert(node->child(i) != BVH4::emptyNode);\n\t \n\t BBox3fa bounds = node->bounds(i);\n\n\t assert( std::isfinite(bounds.lower.x) );\n\t assert( std::isfinite(bounds.lower.y) );\n\t assert( std::isfinite(bounds.lower.z) );\n\n\t assert( std::isfinite(bounds.upper.x) );\n\t assert( std::isfinite(bounds.upper.y) );\n\t assert( std::isfinite(bounds.upper.z) );\n\n\t verifySubTreeBVH(node->child(i));\n\t}\n }\n\n size_t countBlocks(const BVH4::NodeRef ref, const size_t range0, const size_t range1)\n {\n \n size_t t = (size_t)ref;\n\n assert(range0 <= t);\n assert(t <= range1);\n\n \/* this is a leaf node *\/\n if (unlikely(ref.isLeaf()))\n return 3;\n \n const BVH4::Node* node = ref.node();\n \n size_t size = 0;\n for (size_t i=0;i<4;i++)\n if (node->child(i) != BVH4::emptyNode)\n size += countBlocks(node->child(i),range0,range1);\n\n return 2 + size;\n }\n\n void updateBVH4Refs(const BVH4::NodeRef &ref, const size_t old_ptr, const size_t new_ptr)\n {\n if (unlikely(ref == BVH4::emptyNode))\n return;\n\n assert(ref != BVH4::invalidNode);\n\n \/* this is a leaf node *\/\n if (unlikely(ref.isLeaf()))\n return;\n\n const BVH4::Node* node = ref.node();\n \n for (size_t i=0;i<4;i++)\n {\n const BVH4::NodeRef &child = node->child(i);\n if (node->child(i) != BVH4::emptyNode)\n {\n if (child.isNode())\n updateBVH4Refs(child,old_ptr,new_ptr);\n\n const size_t dest_offset = (size_t)&child - old_ptr; \n const size_t new_ref = (size_t)child - old_ptr + new_ptr;\n size_t *ptr = (size_t*)((char*)new_ptr + dest_offset);\n *ptr = new_ref; \n }\n }\n }\n\n \/* build lazy subtree over patch *\/\n size_t SubdivPatch1CachedIntersector1::lazyBuildPatch(Precalculations &pre,\n\t\t\t\t\t\t\t SubdivPatch1Cached* const subdiv_patch, \n\t\t\t\t\t\t\t const Scene* scene)\n {\n \/* unlock previous patch *\/\n if (pre.current_patch)\n {\n assert(SharedLazyTessellationCache::sharedLazyTessellationCache.isLocked(pre.t_state));\n SharedLazyTessellationCache::sharedLazyTessellationCache.unlockThread(pre.t_state);\n }\n\n while(1)\n {\n\n SharedLazyTessellationCache::sharedLazyTessellationCache.lockThreadLoop(pre.t_state);\n \n const size_t globalTime = scene->commitCounter;\n if (void* ptr = SharedLazyTessellationCache::lookup(&subdiv_patch->root_ref,globalTime))\n return (size_t) ptr;\n \n SharedLazyTessellationCache::sharedLazyTessellationCache.unlockThread(pre.t_state);\t\t \n\n if (subdiv_patch->try_write_lock())\n {\n if (!SharedLazyTessellationCache::validTag(subdiv_patch->root_ref,globalTime)) \n {\n \/* generate vertex grid, lock and allocate memory in the cache *\/\n size_t new_root_ref = (size_t)buildSubdivPatchTreeCompact(*subdiv_patch,pre.t_state,scene->getSubdivMesh(subdiv_patch->geom)); \n \n \/* get current commit index *\/\n \/\/const size_t commitIndex = SharedLazyTessellationCache::sharedLazyTessellationCache.getCurrentIndex();\n const size_t combinedTime = SharedLazyTessellationCache::sharedLazyTessellationCache.getTime(globalTime);\n\n __memory_barrier();\n \/* write new root ref *\/\n subdiv_patch->root_ref = SharedLazyTessellationCache::Tag((void*)new_root_ref,combinedTime);\n \n#if _DEBUG\n const size_t patchIndex = subdiv_patch - pre.array;\n assert(patchIndex < pre.numPrimitives);\n CACHE_STATS(SharedTessellationCacheStats::incPatchBuild(patchIndex,pre.numPrimitives));\n#endif\n assert(SharedLazyTessellationCache::sharedLazyTessellationCache.isLocked(pre.t_state));\n\n \/* unlock current patch *\/\n subdiv_patch->write_unlock();\n\n \/* memory region still locked, forward progress guaranteed *\/\n return new_root_ref;\n }\n \/* unlock current patch *\/\n subdiv_patch->write_unlock();\n }\n }\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n BVH4::NodeRef SubdivPatch1CachedIntersector1::buildSubdivPatchTreeCompact(const SubdivPatch1Cached &patch,\n ThreadWorkState *t_state,\n\t\t\t\t\t\t\t\t\t const SubdivMesh* const geom, BBox3fa* bounds_o)\n { \n assert( patch.grid_size_simd_blocks >= 1 );\n\n const size_t array_elements = patch.grid_size_simd_blocks * vfloat::size;\n dynamic_large_stack_array(float,local_grid_u,array_elements+vfloat::size,64*64);\n dynamic_large_stack_array(float,local_grid_v,array_elements+vfloat::size,64*64);\n dynamic_large_stack_array(float,local_grid_x,array_elements+vfloat::size,64*64);\n dynamic_large_stack_array(float,local_grid_y,array_elements+vfloat::size,64*64);\n dynamic_large_stack_array(float,local_grid_z,array_elements+vfloat::size,64*64);\n\n \/* compute vertex grid (+displacement) *\/\n evalGrid(patch,0,patch.grid_u_res-1,0,patch.grid_v_res-1,patch.grid_u_res,patch.grid_v_res,local_grid_x,local_grid_y,local_grid_z,local_grid_u,local_grid_v,geom);\n\n \/* lock the cache *\/\n SharedLazyTessellationCache::sharedLazyTessellationCache.lockThreadLoop(t_state);\n\n \/* allocate memory in cache and get current commit index *\/\n void *const lazymem = SharedLazyTessellationCache::sharedLazyTessellationCache.allocLoop(t_state,64*patch.grid_subtree_size_64b_blocks);\n\n \/* copy temporary data to tessellation cache *\/\n const size_t grid_offset = patch.grid_bvh_size_64b_blocks * 16;\n\n float *const grid_x = (float*)lazymem + grid_offset + 0 * array_elements;\n float *const grid_y = (float*)lazymem + grid_offset + 1 * array_elements;\n float *const grid_z = (float*)lazymem + grid_offset + 2 * array_elements;\n int *const grid_uv = (int*) lazymem + grid_offset + 3 * array_elements;\n assert( patch.grid_subtree_size_64b_blocks * 16 >= grid_offset + 4 * array_elements);\n\n memcpy(grid_x ,local_grid_x ,array_elements*sizeof(float));\n memcpy(grid_y ,local_grid_y ,array_elements*sizeof(float));\n memcpy(grid_z ,local_grid_z ,array_elements*sizeof(float));\n\n for (size_t i=0;i= delta_u) \n\t\tu_start -= delta_u; \n\t else\n\t\tu_start = 0;\n\t }\n if (unlikely(v_end-v_start+1 < 3)) \n\t { \n\t const unsigned int delta_v = 3 - (v_end-v_start+1);\n\t if (v_start >= delta_v) \n\t\tv_start -= delta_v; \n\t else\n\t\tv_start = 0;\n\t }\n\n\t const unsigned int u_size = u_end-u_start+1;\n\t const unsigned int v_size = v_end-v_start+1;\n \n\t assert(u_size >= 1);\n\t assert(v_size >= 1);\n \n\t const size_t grid_offset3x3 = v_start * patch.grid_u_res + u_start;\n\n\n\t size_t offset_bytes = (size_t)&grid_x_array[ grid_offset3x3 ] - (size_t)SharedLazyTessellationCache::sharedLazyTessellationCache.getDataPtr();\n\t assert(offset_bytes < 0xffffffff);\n\t assert((offset_bytes & 3) == 0);\n size_t value = (offset_bytes << 2) + (size_t)SharedLazyTessellationCache::sharedLazyTessellationCache.getDataPtr();\n assert( (value & 2) == 0 );\n\t curNode = BVH4::encodeTypedLeaf((void*)value,2);\n\n\t assert( std::isfinite(bounds.lower.x) );\n\t assert( std::isfinite(bounds.lower.y) );\n\t assert( std::isfinite(bounds.lower.z) );\n\t \n\t assert( std::isfinite(bounds.upper.x) );\n\t assert( std::isfinite(bounds.upper.y) );\n\t assert( std::isfinite(bounds.upper.z) );\n\n\t return bounds;\n\t}\n \n \n \/* allocate new bvh4 node *\/\n const size_t currentIndex = localCounter;\n \n \/* 128 bytes == 2 x 64 bytes cachelines *\/\n localCounter += 2; \n \n BVH4::Node *node = (BVH4::Node *)&lazymem[currentIndex*16];\n \n curNode = BVH4::encodeNode( node );\n \n node->clear();\n \n GridRange r[4];\n \n const unsigned int children = range.splitIntoSubRanges(r);\n \n \/* create four subtrees *\/\n BBox3fa bounds( empty );\n \n for (unsigned int i=0;ichild(i), \n\t\t\t\t\t\t\t lazymem, \n\t\t\t\t\t\t\t patch, \n\t\t\t\t\t\t\t grid_array,\n\t\t\t\t\t\t\t grid_array_elements,\n\t\t\t\t\t\t\t r[i],\t\t\t\t\t\t \n\t\t\t\t\t\t\t localCounter);\n\t node->set(i, bounds_subtree);\n\t bounds.extend( bounds_subtree );\n\t}\n \n return bounds;\n }\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fixedhyper.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-22 15:24:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef SVTOOLS_FIXEDHYPER_HXX\n#define SVTOOLS_FIXEDHYPER_HXX\n\n#ifndef INCLUDED_SVTDLLAPI_H\n#include \"svtools\/svtdllapi.h\"\n#endif\n\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n\n\/\/.........................................................................\nnamespace svt\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= FixedHyperlink\n \/\/=====================================================================\n class SVT_DLLPUBLIC FixedHyperlink : public FixedText\n {\n private:\n long m_nTextLen;\n Pointer m_aOldPointer;\n Link m_aClickHdl;\n String m_sURL;\n\n \/** initializes the font (link color and underline).\n\n Called by the Ctors.\n *\/\n void Initialize();\n\n protected:\n \/** overwrites Window::MouseMove().\n\n Changes the pointer only over the text.\n *\/\n virtual void MouseMove( const MouseEvent& rMEvt );\n\n \/** overwrites Window::MouseButtonUp().\n\n Calls the set link if the mouse is over the text.\n *\/\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n\n \/** overwrites Window::RequestHelp().\n\n Shows tooltip only if the mouse is over the text.\n *\/\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n public:\n \/** ctors\n\n With ResId or WinBits.\n *\/\n FixedHyperlink( Window* pParent, const ResId& rId );\n FixedHyperlink( Window* pParent, WinBits nWinStyle = 0 );\n\n \/** dtor\n\n *\/\n virtual ~FixedHyperlink();\n\n \/** overwrites Window::GetFocus().\n\n Changes the color of the text and shows a focus rectangle.\n *\/\n virtual void GetFocus();\n\n \/** overwrites Window::LoseFocus().\n\n Changes the color of the text and hides the focus rectangle.\n *\/\n virtual void LoseFocus();\n\n \/** overwrites Window::KeyInput().\n\n KEY_RETURN and KEY_SPACE calls the link handler.\n *\/\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n \/** sets m_aClickHdl<\/member> with rLink<\/arg>.\n\n m_aClickHdl<\/member> is called if the text is clicked.\n *\/\n inline void SetClickHdl( const Link& rLink ) { m_aClickHdl = rLink; }\n\n \/** returns m_aClickHdl<\/member>.\n\n @return\n m_aClickHdl<\/member>\n *\/\n inline const Link& GetClickHdl() const { return m_aClickHdl; }\n\n \/** sets the URL of the hyperlink and uses it as tooltip. *\/\n void SetURL( const String& rNewURL );\n\n \/** returns the URL of the hyperlink.\n\n @return\n m_sURL<\/member>\n *\/\n inline String GetURL() const { return m_sURL; }\n\n \/** sets new text and recalculates the text length. *\/\n void SetDescription( const String& rNewDescription );\n };\n\n\/\/.........................................................................\n} \/\/ namespace svt\n\/\/.........................................................................\n\n#endif\n\nINTEGRATION: CWS fwk80_SRC680 (1.3.34); FILE MERGED 2008\/01\/11 15:12:37 pb 1.3.34.1: fix: #i83756# new base ::toolkit::FixedHyperlinkBase\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fixedhyper.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2008-01-29 15:24:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef SVTOOLS_FIXEDHYPER_HXX\n#define SVTOOLS_FIXEDHYPER_HXX\n\n#ifndef INCLUDED_SVTDLLAPI_H\n#include \"svtools\/svtdllapi.h\"\n#endif\n\n#include \n\n\/\/.........................................................................\nnamespace svt\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= FixedHyperlink\n \/\/=====================================================================\n class SVT_DLLPUBLIC FixedHyperlink : public ::toolkit::FixedHyperlinkBase\n {\n private:\n long m_nTextLen;\n Pointer m_aOldPointer;\n Link m_aClickHdl;\n String m_sURL;\n\n \/** initializes the font (link color and underline).\n\n Called by the Ctors.\n *\/\n void Initialize();\n\n protected:\n \/** overwrites Window::MouseMove().\n\n Changes the pointer only over the text.\n *\/\n virtual void MouseMove( const MouseEvent& rMEvt );\n\n \/** overwrites Window::MouseButtonUp().\n\n Calls the set link if the mouse is over the text.\n *\/\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n\n \/** overwrites Window::RequestHelp().\n\n Shows tooltip only if the mouse is over the text.\n *\/\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n public:\n \/** ctors\n\n With ResId or WinBits.\n *\/\n FixedHyperlink( Window* pParent, const ResId& rId );\n FixedHyperlink( Window* pParent, WinBits nWinStyle = 0 );\n\n \/** dtor\n\n *\/\n virtual ~FixedHyperlink();\n\n \/** overwrites Window::GetFocus().\n\n Changes the color of the text and shows a focus rectangle.\n *\/\n virtual void GetFocus();\n\n \/** overwrites Window::LoseFocus().\n\n Changes the color of the text and hides the focus rectangle.\n *\/\n virtual void LoseFocus();\n\n \/** overwrites Window::KeyInput().\n\n KEY_RETURN and KEY_SPACE calls the link handler.\n *\/\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n \/** sets m_aClickHdl<\/member> with rLink<\/arg>.\n\n m_aClickHdl<\/member> is called if the text is clicked.\n *\/\n inline void SetClickHdl( const Link& rLink ) { m_aClickHdl = rLink; }\n\n \/** returns m_aClickHdl<\/member>.\n\n @return\n m_aClickHdl<\/member>\n *\/\n inline const Link& GetClickHdl() const { return m_aClickHdl; }\n\n \/\/ ::toolkit::FixedHyperbaseLink\n\n \/** sets the URL of the hyperlink and uses it as tooltip. *\/\n virtual void SetURL( const String& rNewURL );\n\n \/** returns the URL of the hyperlink.\n\n @return\n m_sURL<\/member>\n *\/\n virtual String GetURL() const;\n\n \/** sets new text and recalculates the text length. *\/\n virtual void SetDescription( const String& rNewDescription );\n };\n\n\/\/.........................................................................\n} \/\/ namespace svt\n\/\/.........................................................................\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: genericpropertyhandler.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: ihi $ $Date: 2008-01-14 14:59:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX\n#define EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX\n\n#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PROPERTYHANDLER_HXX\n#include \"propertyhandler.hxx\"\n#endif\n#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PCRCOMMONTYPES_HXX\n#include \"pcrcommontypes.hxx\"\n#endif\n#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_\n#include \"pcrcommon.hxx\"\n#endif\n#ifndef EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX\n#include \"pcrcomponentcontext.hxx\"\n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XINTROSPECTIONACCESS_HPP_\n#include \n#endif\n\/** === end UNO includes === **\/\n\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_\n#include \n#endif\n#ifndef _RTL_REF_HXX_\n#include \n#endif\n\n#include \n\n\/\/........................................................................\nnamespace pcr\n{\n\/\/........................................................................\n\n struct TypeLess : ::std::binary_function< ::com::sun::star::uno::Type, ::com::sun::star::uno::Type, bool >\n {\n bool operator()( const ::com::sun::star::uno::Type& _rLHS, const ::com::sun::star::uno::Type& _rRHS ) const\n {\n return _rLHS.getTypeName() < _rRHS.getTypeName();\n }\n };\n\n class IPropertyInfoService;\n class IPropertyEnumRepresentation;\n \/\/====================================================================\n \/\/= GenericPropertyHandler\n \/\/====================================================================\n typedef ::cppu::WeakComponentImplHelper2 < ::com::sun::star::inspection::XPropertyHandler\n , ::com::sun::star::lang::XServiceInfo\n > GenericPropertyHandler_Base;\n class GenericPropertyHandler : public GenericPropertyHandler_Base\n {\n private:\n mutable ::osl::Mutex m_aMutex;\n\n private:\n \/\/\/ the service factory for creating services\n ComponentContext m_aContext;\n \/\/\/ need this to keep alive as long as m_xComponent lives\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess > m_xComponentIntrospectionAccess;\n \/\/\/ the properties of the object we're handling\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xComponent;\n \/\/\/ cached interface of ->m_xComponent\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState > m_xPropertyState;\n \/\/\/ type converter, needed on various occasions\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter > m_xTypeConverter;\n \/\/\/ cache of our supported properties\n PropertyMap m_aProperties;\n \/\/\/ property change listeners\n ::cppu::OInterfaceContainerHelper m_aPropertyListeners;\n ::std::map< ::com::sun::star::uno::Type, ::rtl::Reference< IPropertyEnumRepresentation >, TypeLess >\n m_aEnumConverters;\n\n \/\/\/ has ->m_aProperties been initialized?\n bool m_bPropertyMapInitialized : 1;\n\n public:\n \/\/ XServiceInfo - static versions\n static ::rtl::OUString SAL_CALL getImplementationName_static( ) throw (::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static( ) throw (::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );\n\n protected:\n GenericPropertyHandler(\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext\n );\n\n ~GenericPropertyHandler();\n\n protected:\n \/\/ XPropertyHandler overridables\n virtual void SAL_CALL inspect( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxIntrospectee ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL convertToPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rControlValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL convertToControlValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >\n SAL_CALL getSupportedProperties() throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >\n SAL_CALL getSupersededProperties() throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getActuatingProperties() throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::inspection::LineDescriptor SAL_CALL describePropertyLine( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual ::sal_Bool SAL_CALL isComposable( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::inspection::InteractiveSelectionResult\n SAL_CALL onInteractivePropertySelection( const ::rtl::OUString& _rPropertyName, sal_Bool _bPrimary, ::com::sun::star::uno::Any& _rData, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL actuatingPropertyChanged( const ::rtl::OUString& _rActuatingPropertyName, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI, sal_Bool _bFirstTimeInit ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL suspend( sal_Bool _bSuspend ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponent\n DECLARE_XCOMPONENT()\n virtual void SAL_CALL disposing();\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n private:\n \/** ensures that ->m_aProperties is initialized\n @precond\n our mutex is locked\n *\/\n void impl_ensurePropertyMap();\n\n \/** retrieves the enum converter for the given ENUM type\n *\/\n ::rtl::Reference< IPropertyEnumRepresentation >\n impl_getEnumConverter( const ::com::sun::star::uno::Type& _rEnumType );\n\n private:\n GenericPropertyHandler(); \/\/ never implemented\n GenericPropertyHandler( const GenericPropertyHandler& ); \/\/ never implemented\n GenericPropertyHandler& operator=( const GenericPropertyHandler& ); \/\/ never implemented\n };\n\n\/\/........................................................................\n} \/\/ namespace pcr\n\/\/........................................................................\n\n#endif \/\/ EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX\n\nINTEGRATION: CWS changefileheader (1.4.48); FILE MERGED 2008\/04\/01 15:15:18 thb 1.4.48.3: #i85898# Stripping all external header guards 2008\/04\/01 12:29:50 thb 1.4.48.2: #i85898# Stripping all external header guards 2008\/03\/31 12:31:44 rt 1.4.48.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: genericpropertyhandler.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX\n#define EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX\n\n#include \"propertyhandler.hxx\"\n#include \"pcrcommontypes.hxx\"\n#include \"pcrcommon.hxx\"\n#include \"pcrcomponentcontext.hxx\"\n\n\/** === begin UNO includes === **\/\n#include \n#include \n#include \n\/** === end UNO includes === **\/\n#include \n#include \n#include \n\n#include \n\n\/\/........................................................................\nnamespace pcr\n{\n\/\/........................................................................\n\n struct TypeLess : ::std::binary_function< ::com::sun::star::uno::Type, ::com::sun::star::uno::Type, bool >\n {\n bool operator()( const ::com::sun::star::uno::Type& _rLHS, const ::com::sun::star::uno::Type& _rRHS ) const\n {\n return _rLHS.getTypeName() < _rRHS.getTypeName();\n }\n };\n\n class IPropertyInfoService;\n class IPropertyEnumRepresentation;\n \/\/====================================================================\n \/\/= GenericPropertyHandler\n \/\/====================================================================\n typedef ::cppu::WeakComponentImplHelper2 < ::com::sun::star::inspection::XPropertyHandler\n , ::com::sun::star::lang::XServiceInfo\n > GenericPropertyHandler_Base;\n class GenericPropertyHandler : public GenericPropertyHandler_Base\n {\n private:\n mutable ::osl::Mutex m_aMutex;\n\n private:\n \/\/\/ the service factory for creating services\n ComponentContext m_aContext;\n \/\/\/ need this to keep alive as long as m_xComponent lives\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess > m_xComponentIntrospectionAccess;\n \/\/\/ the properties of the object we're handling\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xComponent;\n \/\/\/ cached interface of ->m_xComponent\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState > m_xPropertyState;\n \/\/\/ type converter, needed on various occasions\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter > m_xTypeConverter;\n \/\/\/ cache of our supported properties\n PropertyMap m_aProperties;\n \/\/\/ property change listeners\n ::cppu::OInterfaceContainerHelper m_aPropertyListeners;\n ::std::map< ::com::sun::star::uno::Type, ::rtl::Reference< IPropertyEnumRepresentation >, TypeLess >\n m_aEnumConverters;\n\n \/\/\/ has ->m_aProperties been initialized?\n bool m_bPropertyMapInitialized : 1;\n\n public:\n \/\/ XServiceInfo - static versions\n static ::rtl::OUString SAL_CALL getImplementationName_static( ) throw (::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static( ) throw (::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > Create( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );\n\n protected:\n GenericPropertyHandler(\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext\n );\n\n ~GenericPropertyHandler();\n\n protected:\n \/\/ XPropertyHandler overridables\n virtual void SAL_CALL inspect( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxIntrospectee ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL convertToPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rControlValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL convertToControlValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& _rxListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >\n SAL_CALL getSupportedProperties() throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >\n SAL_CALL getSupersededProperties() throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getActuatingProperties() throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::inspection::LineDescriptor SAL_CALL describePropertyLine( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual ::sal_Bool SAL_CALL isComposable( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::inspection::InteractiveSelectionResult\n SAL_CALL onInteractivePropertySelection( const ::rtl::OUString& _rPropertyName, sal_Bool _bPrimary, ::com::sun::star::uno::Any& _rData, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL actuatingPropertyChanged( const ::rtl::OUString& _rActuatingPropertyName, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI, sal_Bool _bFirstTimeInit ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL suspend( sal_Bool _bSuspend ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponent\n DECLARE_XCOMPONENT()\n virtual void SAL_CALL disposing();\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n private:\n \/** ensures that ->m_aProperties is initialized\n @precond\n our mutex is locked\n *\/\n void impl_ensurePropertyMap();\n\n \/** retrieves the enum converter for the given ENUM type\n *\/\n ::rtl::Reference< IPropertyEnumRepresentation >\n impl_getEnumConverter( const ::com::sun::star::uno::Type& _rEnumType );\n\n private:\n GenericPropertyHandler(); \/\/ never implemented\n GenericPropertyHandler( const GenericPropertyHandler& ); \/\/ never implemented\n GenericPropertyHandler& operator=( const GenericPropertyHandler& ); \/\/ never implemented\n };\n\n\/\/........................................................................\n} \/\/ namespace pcr\n\/\/........................................................................\n\n#endif \/\/ EXTENSIONS_SOURCE_PROPCTRLR_GENERICPROPERTYHANDLER_HXX\n\n<|endoftext|>"} {"text":"Be precise here, maximum value means it is still allowed to have<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: EnhancedPDFExportHelper.hxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _ENHANCEDPDFEXPORTHELPER_HXX\n#define _ENHANCEDPDFEXPORTHELPER_HXX\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nclass vcl::PDFExtOutDevData;\nclass OutputDevice;\nclass SwFrm;\nclass SwLinePortion;\nclass SwTxtPainter;\nclass SwEditShell;\nclass rtl::OUString;\nclass MultiSelection;\nclass SwTxtNode;\nclass SwNumRule;\nclass SwTable;\nclass SwNumberTreeNode;\nclass String;\nclass SvxLanguageItem;\n\n\n\/*\n * Mapping of OOo elements to tagged pdf elements:\n *\n * OOo element tagged pdf element\n * ----------- ------------------\n *\n * Grouping elements:\n *\n * SwRootFrm Document\n * Part\n * Art\n * SwSection Sect\n * SwFtnContFrm and SwFlyFrm Div\n * SwFmt \"Quotations\" BlockQuote\n * SwFmt \"Caption\" Caption\n * SwSection (TOC) TOC\n * SwTxtNode in TOC TOCI\n * SwSection (Index) Index\n *\n * Block-Level Structure Elements:\n *\n * SwTxtNode P\n * SwFmt \"Heading\" H\n * SwTxtNode with Outline H1 - H6\n * SwTxtNode with NumRule L, LI, LBody\n * SwTable Table\n * SwRowFrm TR\n * SwCellFrm in Headline row or\n * SwFtm \"Table Heading\" TH\n * SwCellFrm TD\n *\n * Inline-Level Structure Elements:\n *\n * SwTxtPortion Span\n * SwFmt \"Quotation\" Quote\n * SwFtnFrm Note\n * Form\n * Reference\n * SwFldPortion (AuthorityField) BibEntry\n * SwFmt \"Source Text\" Code\n * SwFtnPortion, SwFldPortion (RefField) Link\n *\n * Illustration elements:\n *\n * SwFlyFrm with SwNoTxtFrm Figure\n * SwFlyFrm with Math OLE Object Formula\n *\n *\/\n\nstruct Num_Info\n{\n const SwFrm& mrFrm;\n Num_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};\n};\n\nstruct Frm_Info\n{\n const SwFrm& mrFrm;\n Frm_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};\n};\n\nstruct Por_Info\n{\n const SwLinePortion& mrPor;\n const SwTxtPainter& mrTxtPainter;\n Por_Info( const SwLinePortion& rPor, const SwTxtPainter& rTxtPainer )\n : mrPor( rPor ), mrTxtPainter( rTxtPainer ) {};\n};\n\nstruct lt_TableColumn\n{\n bool operator()( long nVal1, long nVal2 ) const\n {\n return nVal1 + ( MINLAY - 1 ) < nVal2;\n }\n};\n\n\/*************************************************************************\n * class SwTaggedPDFHelper\n * Analyses a given frame during painting and generates the appropriate\n * structure elements.\n *************************************************************************\/\n\nclass SwTaggedPDFHelper\n{\n private:\n\n \/\/ This will be incremented for each BeginTag() call.\n \/\/ It denotes the number of tags to close during EndStructureElements();\n BYTE nEndStructureElement;\n\n \/\/ If an already existing tag is reopened for follows of flow frames,\n \/\/ this value stores the tag id which has to be restored.\n sal_Int32 nRestoreCurrentTag;\n\n vcl::PDFExtOutDevData* mpPDFExtOutDevData;\n\n const Num_Info* mpNumInfo;\n const Frm_Info* mpFrmInfo;\n const Por_Info* mpPorInfo;\n\n void BeginTag( vcl::PDFWriter::StructElement, const String* pUserDefined = 0 );\n void EndTag();\n\n void SetAttributes( vcl::PDFWriter::StructElement eType );\n\n \/\/ These functions are called by the c'tor, d'tor\n void BeginNumberedListStructureElements();\n void BeginBlockStructureElements();\n void BeginInlineStructureElements();\n void EndStructureElements();\n\n bool CheckReopenTag();\n bool CheckRestoreTag() const;\n\n public:\n\n \/\/ pFrmInfo != 0 => BeginBlockStructureElement\n \/\/ pPorInfo != 0 => BeginInlineStructureElement\n \/\/ pFrmInfo, pPorInfo = 0 => BeginNonStructureElement\n SwTaggedPDFHelper( const Num_Info* pNumInfo, const Frm_Info* pFrmInfo, const Por_Info* pPorInfo,\n OutputDevice& rOut );\n ~SwTaggedPDFHelper();\n\n static bool IsExportTaggedPDF( const OutputDevice& rOut );\n};\n\n\/*************************************************************************\n * class SwEnhancedPDFExportHelper\n * Analyses the document structure and export Notes, Hyperlinks, References,\n * and Outline. Link ids created during pdf export are stored in\n * aReferenceIdMap and aHyperlinkIdMap, in order to use them during\n * tagged pdf output. Therefore the SwEnhancedPDFExportHelper is used\n * before painting. Unfortunately links from the EditEngine into the\n * Writer document require to be exported after they have been painted.\n * Therefore SwEnhancedPDFExportHelper also has to be used after the\n * painting process, the parameter bEditEngineOnly indicated that only\n * the bookmarks from the EditEngine have to be processed.\n *************************************************************************\/\n\ntypedef std::set< long, lt_TableColumn > TableColumnsMapEntry;\ntypedef std::pair< SwRect, sal_Int32 > IdMapEntry;\ntypedef std::vector< IdMapEntry > LinkIdMap;\ntypedef std::map< const SwTable*, TableColumnsMapEntry > TableColumnsMap;\ntypedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListIdMap;\ntypedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListBodyIdMap;\ntypedef std::map< const void*, sal_Int32 > FrmTagIdMap;\n\nclass SwEnhancedPDFExportHelper\n{\n private:\n\n SwEditShell& mrSh;\n OutputDevice& mrOut;\n\n MultiSelection* pPageRange;\n\n bool mbSkipEmptyPages;\n bool mbEditEngineOnly;\n\n static TableColumnsMap aTableColumnsMap;\n static LinkIdMap aLinkIdMap;\n static NumListIdMap aNumListIdMap;\n static NumListBodyIdMap aNumListBodyIdMap;\n static FrmTagIdMap aFrmTagIdMap;\n\n static LanguageType eLanguageDefault;\n\n void EnhancedPDFExport();\n sal_Int32 CalcOutputPageNum( const SwRect& rRect ) const;\n\n void MakeHeaderFooterLinks( vcl::PDFExtOutDevData& rPDFExtOutDevData,\n const SwTxtNode& rTNd, const SwRect& rLinkRect,\n sal_Int32 nDestId, const String& rURL, bool bIntern ) const;\n\n public:\n\n SwEnhancedPDFExportHelper( SwEditShell& rSh,\n OutputDevice& rOut,\n const rtl::OUString& rPageRange,\n bool bSkipEmptyPages,\n bool bEditEngineOnly );\n\n ~SwEnhancedPDFExportHelper();\n\n static TableColumnsMap& GetTableColumnsMap() {return aTableColumnsMap; }\n static LinkIdMap& GetLinkIdMap() { return aLinkIdMap; }\n static NumListIdMap& GetNumListIdMap() {return aNumListIdMap; }\n static NumListBodyIdMap& GetNumListBodyIdMap() {return aNumListBodyIdMap; }\n static FrmTagIdMap& GetFrmTagIdMap() { return aFrmTagIdMap; }\n\n static const LanguageType GetDefaultLanguage() {return eLanguageDefault; }\n};\n\n#endif\nINTEGRATION: CWS c17v003_DEV300 (1.7.1068.1.22); FILE MERGED 2008\/04\/17 20:25:27 fme 1.7.1068.1.22.1: #b6688018# #b6688132# Interrupted and restart lists in tagged pdf \/ better caption handling\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: EnhancedPDFExportHelper.hxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _ENHANCEDPDFEXPORTHELPER_HXX\n#define _ENHANCEDPDFEXPORTHELPER_HXX\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nclass vcl::PDFExtOutDevData;\nclass OutputDevice;\nclass SwFrm;\nclass SwLinePortion;\nclass SwTxtPainter;\nclass SwEditShell;\nclass rtl::OUString;\nclass MultiSelection;\nclass SwTxtNode;\nclass SwNumRule;\nclass SwTable;\nclass SwNumberTreeNode;\nclass String;\nclass SvxLanguageItem;\n\n\n\/*\n * Mapping of OOo elements to tagged pdf elements:\n *\n * OOo element tagged pdf element\n * ----------- ------------------\n *\n * Grouping elements:\n *\n * SwRootFrm Document\n * Part\n * Art\n * SwSection Sect\n * SwFtnContFrm and SwFlyFrm Div\n * SwFmt \"Quotations\" BlockQuote\n * SwFmt \"Caption\" Caption\n * SwSection (TOC) TOC\n * SwTxtNode in TOC TOCI\n * SwSection (Index) Index\n *\n * Block-Level Structure Elements:\n *\n * SwTxtNode P\n * SwFmt \"Heading\" H\n * SwTxtNode with Outline H1 - H6\n * SwTxtNode with NumRule L, LI, LBody\n * SwTable Table\n * SwRowFrm TR\n * SwCellFrm in Headline row or\n * SwFtm \"Table Heading\" TH\n * SwCellFrm TD\n *\n * Inline-Level Structure Elements:\n *\n * SwTxtPortion Span\n * SwFmt \"Quotation\" Quote\n * SwFtnFrm Note\n * Form\n * Reference\n * SwFldPortion (AuthorityField) BibEntry\n * SwFmt \"Source Text\" Code\n * SwFtnPortion, SwFldPortion (RefField) Link\n *\n * Illustration elements:\n *\n * SwFlyFrm with SwNoTxtFrm Figure\n * SwFlyFrm with Math OLE Object Formula\n *\n *\/\n\nstruct Num_Info\n{\n const SwFrm& mrFrm;\n Num_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};\n};\n\nstruct Frm_Info\n{\n const SwFrm& mrFrm;\n Frm_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};\n};\n\nstruct Por_Info\n{\n const SwLinePortion& mrPor;\n const SwTxtPainter& mrTxtPainter;\n Por_Info( const SwLinePortion& rPor, const SwTxtPainter& rTxtPainer )\n : mrPor( rPor ), mrTxtPainter( rTxtPainer ) {};\n};\n\nstruct lt_TableColumn\n{\n bool operator()( long nVal1, long nVal2 ) const\n {\n return nVal1 + ( MINLAY - 1 ) < nVal2;\n }\n};\n\n\/*************************************************************************\n * class SwTaggedPDFHelper\n * Analyses a given frame during painting and generates the appropriate\n * structure elements.\n *************************************************************************\/\n\nclass SwTaggedPDFHelper\n{\n private:\n\n \/\/ This will be incremented for each BeginTag() call.\n \/\/ It denotes the number of tags to close during EndStructureElements();\n BYTE nEndStructureElement;\n\n \/\/ If an already existing tag is reopened for follows of flow frames,\n \/\/ this value stores the tag id which has to be restored.\n sal_Int32 nRestoreCurrentTag;\n\n vcl::PDFExtOutDevData* mpPDFExtOutDevData;\n\n const Num_Info* mpNumInfo;\n const Frm_Info* mpFrmInfo;\n const Por_Info* mpPorInfo;\n\n void BeginTag( vcl::PDFWriter::StructElement aTagRole, const String& rTagName );\n void EndTag();\n\n void SetAttributes( vcl::PDFWriter::StructElement eType );\n\n \/\/ These functions are called by the c'tor, d'tor\n void BeginNumberedListStructureElements();\n void BeginBlockStructureElements();\n void BeginInlineStructureElements();\n void EndStructureElements();\n\n bool CheckReopenTag();\n bool CheckRestoreTag() const;\n\n public:\n\n \/\/ pFrmInfo != 0 => BeginBlockStructureElement\n \/\/ pPorInfo != 0 => BeginInlineStructureElement\n \/\/ pFrmInfo, pPorInfo = 0 => BeginNonStructureElement\n SwTaggedPDFHelper( const Num_Info* pNumInfo, const Frm_Info* pFrmInfo, const Por_Info* pPorInfo,\n OutputDevice& rOut );\n ~SwTaggedPDFHelper();\n\n static bool IsExportTaggedPDF( const OutputDevice& rOut );\n};\n\n\/*************************************************************************\n * class SwEnhancedPDFExportHelper\n * Analyses the document structure and export Notes, Hyperlinks, References,\n * and Outline. Link ids created during pdf export are stored in\n * aReferenceIdMap and aHyperlinkIdMap, in order to use them during\n * tagged pdf output. Therefore the SwEnhancedPDFExportHelper is used\n * before painting. Unfortunately links from the EditEngine into the\n * Writer document require to be exported after they have been painted.\n * Therefore SwEnhancedPDFExportHelper also has to be used after the\n * painting process, the parameter bEditEngineOnly indicated that only\n * the bookmarks from the EditEngine have to be processed.\n *************************************************************************\/\n\ntypedef std::set< long, lt_TableColumn > TableColumnsMapEntry;\ntypedef std::pair< SwRect, sal_Int32 > IdMapEntry;\ntypedef std::vector< IdMapEntry > LinkIdMap;\ntypedef std::map< const SwTable*, TableColumnsMapEntry > TableColumnsMap;\ntypedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListIdMap;\ntypedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListBodyIdMap;\ntypedef std::map< const void*, sal_Int32 > FrmTagIdMap;\n\nclass SwEnhancedPDFExportHelper\n{\n private:\n\n SwEditShell& mrSh;\n OutputDevice& mrOut;\n\n MultiSelection* pPageRange;\n\n bool mbSkipEmptyPages;\n bool mbEditEngineOnly;\n\n static TableColumnsMap aTableColumnsMap;\n static LinkIdMap aLinkIdMap;\n static NumListIdMap aNumListIdMap;\n static NumListBodyIdMap aNumListBodyIdMap;\n static FrmTagIdMap aFrmTagIdMap;\n\n static LanguageType eLanguageDefault;\n\n void EnhancedPDFExport();\n sal_Int32 CalcOutputPageNum( const SwRect& rRect ) const;\n\n void MakeHeaderFooterLinks( vcl::PDFExtOutDevData& rPDFExtOutDevData,\n const SwTxtNode& rTNd, const SwRect& rLinkRect,\n sal_Int32 nDestId, const String& rURL, bool bIntern ) const;\n\n public:\n\n SwEnhancedPDFExportHelper( SwEditShell& rSh,\n OutputDevice& rOut,\n const rtl::OUString& rPageRange,\n bool bSkipEmptyPages,\n bool bEditEngineOnly );\n\n ~SwEnhancedPDFExportHelper();\n\n static TableColumnsMap& GetTableColumnsMap() {return aTableColumnsMap; }\n static LinkIdMap& GetLinkIdMap() { return aLinkIdMap; }\n static NumListIdMap& GetNumListIdMap() {return aNumListIdMap; }\n static NumListBodyIdMap& GetNumListBodyIdMap() {return aNumListBodyIdMap; }\n static FrmTagIdMap& GetFrmTagIdMap() { return aFrmTagIdMap; }\n\n static const LanguageType GetDefaultLanguage() {return eLanguageDefault; }\n};\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ fuer SwFmtChg\n#include \n#include \n\n\/\/ --> OD 2009-07-13 #i73249#\n#include \n\/\/ <--\n\nSwNoTxtNode::SwNoTxtNode( const SwNodeIndex & rWhere,\n const sal_uInt8 nNdType,\n SwGrfFmtColl *pGrfColl,\n SwAttrSet* pAutoAttr ) :\n SwCntntNode( rWhere, nNdType, pGrfColl ),\n pContour( 0 ),\n bAutomaticContour( sal_False ),\n bContourMapModeValid( sal_True ),\n bPixelContour( sal_False )\n{\n \/\/ soll eine Harte-Attributierung gesetzt werden?\n if( pAutoAttr )\n SetAttr( *pAutoAttr );\n}\n\n\nSwNoTxtNode::~SwNoTxtNode()\n{\n delete pContour;\n}\n\n\n\/\/ erzeugt fuer alle Ableitungen einen AttrSet mit Bereichen\n\/\/ fuer Frame- und Grafik-Attributen\nvoid SwNoTxtNode::NewAttrSet( SwAttrPool& rPool )\n{\n ASSERT( !mpAttrSet.get(), \"AttrSet ist doch gesetzt\" );\n SwAttrSet aNewAttrSet( rPool, aNoTxtNodeSetRange );\n\n \/\/ put names of parent style and conditional style:\n const SwFmtColl* pFmtColl = GetFmtColl();\n String sVal;\n SwStyleNameMapper::FillProgName( pFmtColl->GetName(), sVal, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL, sal_True );\n SfxStringItem aFmtColl( RES_FRMATR_STYLE_NAME, sVal );\n aNewAttrSet.Put( aFmtColl );\n\n aNewAttrSet.SetParent( &GetFmtColl()->GetAttrSet() );\n mpAttrSet = GetDoc()->GetIStyleAccess().getAutomaticStyle( aNewAttrSet, IStyleAccess::AUTO_STYLE_NOTXT );\n}\n\n\/\/ Dummies fuer das Laden\/Speichern von persistenten Daten\n\/\/ bei Grafiken und OLE-Objekten\n\n\nsal_Bool SwNoTxtNode::RestorePersistentData()\n{\n return sal_True;\n}\n\n\nsal_Bool SwNoTxtNode::SavePersistentData()\n{\n return sal_True;\n}\n\n\nvoid SwNoTxtNode::SetContour( const PolyPolygon *pPoly, sal_Bool bAutomatic )\n{\n delete pContour;\n if ( pPoly )\n pContour = new PolyPolygon( *pPoly );\n else\n pContour = 0;\n bAutomaticContour = bAutomatic;\n bContourMapModeValid = sal_True;\n bPixelContour = sal_False;\n}\n\n\nvoid SwNoTxtNode::CreateContour()\n{\n ASSERT( !pContour, \"Contour available.\" );\n pContour = new PolyPolygon(SvxContourDlg::CreateAutoContour(GetGraphic()));\n bAutomaticContour = sal_True;\n bContourMapModeValid = sal_True;\n bPixelContour = sal_False;\n}\n\nconst PolyPolygon *SwNoTxtNode::HasContour() const\n{\n if( !bContourMapModeValid )\n {\n const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );\n sal_Bool bPixelGrf = aGrfMap.GetMapUnit() == MAP_PIXEL;\n const MapMode aContourMap( bPixelGrf ? MAP_PIXEL : MAP_100TH_MM );\n if( bPixelGrf ? !bPixelContour : aGrfMap != aContourMap )\n {\n ASSERT( !bPixelGrf || aGrfMap == aContourMap,\n \"scale factor for pixel unsupported\" );\n OutputDevice* pOutDev =\n (bPixelGrf || bPixelContour) ? Application::GetDefaultDevice()\n : 0;\n sal_uInt16 nPolyCount = pContour->Count();\n for( sal_uInt16 j=0; jLogicToPixel( rPoly[i],\n aContourMap );\n else if( bPixelContour )\n rPoly[i] = pOutDev->PixelToLogic( rPoly[i], aGrfMap );\n else\n rPoly[i] = OutputDevice::LogicToLogic( rPoly[i],\n aContourMap,\n aGrfMap );\n }\n }\n }\n ((SwNoTxtNode *)this)->bContourMapModeValid = sal_True;\n ((SwNoTxtNode *)this)->bPixelContour = sal_False;\n }\n\n return pContour;\n}\n\nvoid SwNoTxtNode::GetContour( PolyPolygon &rPoly ) const\n{\n ASSERT( pContour, \"Contour not available.\" );\n rPoly = *HasContour();\n}\n\nvoid SwNoTxtNode::SetContourAPI( const PolyPolygon *pPoly )\n{\n delete pContour;\n if ( pPoly )\n pContour = new PolyPolygon( *pPoly );\n else\n pContour = 0;\n bContourMapModeValid = sal_False;\n}\n\nsal_Bool SwNoTxtNode::GetContourAPI( PolyPolygon &rContour ) const\n{\n if( !pContour )\n return sal_False;\n\n rContour = *pContour;\n if( bContourMapModeValid )\n {\n const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );\n const MapMode aContourMap( MAP_100TH_MM );\n ASSERT( aGrfMap.GetMapUnit() != MAP_PIXEL ||\n aGrfMap == MapMode( MAP_PIXEL ),\n \"scale factor for pixel unsupported\" );\n if( aGrfMap.GetMapUnit() != MAP_PIXEL &&\n aGrfMap != aContourMap )\n {\n sal_uInt16 nPolyCount = rContour.Count();\n for( sal_uInt16 j=0; jSwapIn( sal_True );\n aRet = ((SwGrfNode*)this)->GetGrf();\n }\n else\n {\n ASSERT( GetOLENode(), \"new type of Node?\" );\n aRet = *((SwOLENode*)this)->SwOLENode::GetGraphic();\n }\n return aRet;\n}\n\n\/\/ --> OD 2009-07-14 #i73249#\nvoid SwNoTxtNode::SetTitle( const String& rTitle, bool bBroadcast )\n{\n \/\/ Title attribute of replaces own AlternateText attribute\n SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return;\n }\n\n pFlyFmt->SetObjTitle( rTitle, bBroadcast );\n}\n\nconst String SwNoTxtNode::GetTitle() const\n{\n const SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return aEmptyStr;\n }\n\n return pFlyFmt->GetObjTitle();\n}\n\nvoid SwNoTxtNode::SetDescription( const String& rDescription, bool bBroadcast )\n{\n SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return;\n }\n\n pFlyFmt->SetObjDescription( rDescription, bBroadcast );\n}\n\nconst String SwNoTxtNode::GetDescription() const\n{\n const SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return aEmptyStr;\n }\n\n return pFlyFmt->GetObjDescription();\n}\n\/\/ <--\nsw34bf05: #i102238# - correct contour polypolygon conversion in case that graphic's map made is not MAP_PIXEL\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ fuer SwFmtChg\n#include \n#include \n\n\/\/ --> OD 2009-07-13 #i73249#\n#include \n\/\/ <--\n\nSwNoTxtNode::SwNoTxtNode( const SwNodeIndex & rWhere,\n const sal_uInt8 nNdType,\n SwGrfFmtColl *pGrfColl,\n SwAttrSet* pAutoAttr ) :\n SwCntntNode( rWhere, nNdType, pGrfColl ),\n pContour( 0 ),\n bAutomaticContour( sal_False ),\n bContourMapModeValid( sal_True ),\n bPixelContour( sal_False )\n{\n \/\/ soll eine Harte-Attributierung gesetzt werden?\n if( pAutoAttr )\n SetAttr( *pAutoAttr );\n}\n\n\nSwNoTxtNode::~SwNoTxtNode()\n{\n delete pContour;\n}\n\n\n\/\/ erzeugt fuer alle Ableitungen einen AttrSet mit Bereichen\n\/\/ fuer Frame- und Grafik-Attributen\nvoid SwNoTxtNode::NewAttrSet( SwAttrPool& rPool )\n{\n ASSERT( !mpAttrSet.get(), \"AttrSet ist doch gesetzt\" );\n SwAttrSet aNewAttrSet( rPool, aNoTxtNodeSetRange );\n\n \/\/ put names of parent style and conditional style:\n const SwFmtColl* pFmtColl = GetFmtColl();\n String sVal;\n SwStyleNameMapper::FillProgName( pFmtColl->GetName(), sVal, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL, sal_True );\n SfxStringItem aFmtColl( RES_FRMATR_STYLE_NAME, sVal );\n aNewAttrSet.Put( aFmtColl );\n\n aNewAttrSet.SetParent( &GetFmtColl()->GetAttrSet() );\n mpAttrSet = GetDoc()->GetIStyleAccess().getAutomaticStyle( aNewAttrSet, IStyleAccess::AUTO_STYLE_NOTXT );\n}\n\n\/\/ Dummies fuer das Laden\/Speichern von persistenten Daten\n\/\/ bei Grafiken und OLE-Objekten\n\n\nsal_Bool SwNoTxtNode::RestorePersistentData()\n{\n return sal_True;\n}\n\n\nsal_Bool SwNoTxtNode::SavePersistentData()\n{\n return sal_True;\n}\n\n\nvoid SwNoTxtNode::SetContour( const PolyPolygon *pPoly, sal_Bool bAutomatic )\n{\n delete pContour;\n if ( pPoly )\n pContour = new PolyPolygon( *pPoly );\n else\n pContour = 0;\n bAutomaticContour = bAutomatic;\n bContourMapModeValid = sal_True;\n bPixelContour = sal_False;\n}\n\n\nvoid SwNoTxtNode::CreateContour()\n{\n ASSERT( !pContour, \"Contour available.\" );\n pContour = new PolyPolygon(SvxContourDlg::CreateAutoContour(GetGraphic()));\n bAutomaticContour = sal_True;\n bContourMapModeValid = sal_True;\n bPixelContour = sal_False;\n}\n\nconst PolyPolygon *SwNoTxtNode::HasContour() const\n{\n if( !bContourMapModeValid )\n {\n const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );\n sal_Bool bPixelGrf = aGrfMap.GetMapUnit() == MAP_PIXEL;\n const MapMode aContourMap( bPixelGrf ? MAP_PIXEL : MAP_100TH_MM );\n if( bPixelGrf ? !bPixelContour : aGrfMap != aContourMap )\n {\n \/\/ --> OD #i102238#\n double nGrfDPIx = 0.0;\n double nGrfDPIy = 0.0;\n {\n if ( !bPixelGrf && bPixelContour )\n {\n const Size aGrfPixelSize( GetGraphic().GetSizePixel() );\n const Size aGrfPrefMapModeSize( GetGraphic().GetPrefSize() );\n if ( aGrfMap.GetMapUnit() == MAP_INCH )\n {\n nGrfDPIx = aGrfPixelSize.Width() \/ ( (double)aGrfMap.GetScaleX() * aGrfPrefMapModeSize.Width() );\n nGrfDPIy = aGrfPixelSize.Height() \/ ( (double)aGrfMap.GetScaleY() * aGrfPrefMapModeSize.Height() );\n }\n else\n {\n const Size aGrf1000thInchSize =\n OutputDevice::LogicToLogic( aGrfPrefMapModeSize,\n aGrfMap, MAP_1000TH_INCH );\n nGrfDPIx = 1000.0 * aGrfPixelSize.Width() \/ aGrf1000thInchSize.Width();\n nGrfDPIy = 1000.0 * aGrfPixelSize.Height() \/ aGrf1000thInchSize.Height();\n }\n }\n }\n \/\/ <--\n ASSERT( !bPixelGrf || aGrfMap == aContourMap,\n \"scale factor for pixel unsupported\" );\n OutputDevice* pOutDev =\n (bPixelGrf || bPixelContour) ? Application::GetDefaultDevice()\n : 0;\n sal_uInt16 nPolyCount = pContour->Count();\n for( sal_uInt16 j=0; jLogicToPixel( rPoly[i],\n aContourMap );\n else if( bPixelContour )\n {\n rPoly[i] = pOutDev->PixelToLogic( rPoly[i], aGrfMap );\n \/\/ --> OD #i102238#\n if ( nGrfDPIx != 0 && nGrfDPIy != 0 )\n {\n rPoly[i] = Point( rPoly[i].X() * pOutDev->ImplGetDPIX() \/ nGrfDPIx,\n rPoly[i].Y() * pOutDev->ImplGetDPIY() \/ nGrfDPIy );\n }\n \/\/ <--\n }\n else\n rPoly[i] = OutputDevice::LogicToLogic( rPoly[i],\n aContourMap,\n aGrfMap );\n }\n }\n }\n ((SwNoTxtNode *)this)->bContourMapModeValid = sal_True;\n ((SwNoTxtNode *)this)->bPixelContour = sal_False;\n }\n\n return pContour;\n}\n\nvoid SwNoTxtNode::GetContour( PolyPolygon &rPoly ) const\n{\n ASSERT( pContour, \"Contour not available.\" );\n rPoly = *HasContour();\n}\n\nvoid SwNoTxtNode::SetContourAPI( const PolyPolygon *pPoly )\n{\n delete pContour;\n if ( pPoly )\n pContour = new PolyPolygon( *pPoly );\n else\n pContour = 0;\n bContourMapModeValid = sal_False;\n}\n\nsal_Bool SwNoTxtNode::GetContourAPI( PolyPolygon &rContour ) const\n{\n if( !pContour )\n return sal_False;\n\n rContour = *pContour;\n if( bContourMapModeValid )\n {\n const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );\n const MapMode aContourMap( MAP_100TH_MM );\n ASSERT( aGrfMap.GetMapUnit() != MAP_PIXEL ||\n aGrfMap == MapMode( MAP_PIXEL ),\n \"scale factor for pixel unsupported\" );\n if( aGrfMap.GetMapUnit() != MAP_PIXEL &&\n aGrfMap != aContourMap )\n {\n sal_uInt16 nPolyCount = rContour.Count();\n for( sal_uInt16 j=0; j OD #i102238# - use the right instance\n Polygon& rPoly = rContour[j];\n \/\/ <--\n\n sal_uInt16 nCount = rPoly.GetSize();\n for( sal_uInt16 i=0 ; iSwapIn( sal_True );\n aRet = ((SwGrfNode*)this)->GetGrf();\n }\n else\n {\n ASSERT( GetOLENode(), \"new type of Node?\" );\n aRet = *((SwOLENode*)this)->SwOLENode::GetGraphic();\n }\n return aRet;\n}\n\n\/\/ --> OD 2009-07-14 #i73249#\nvoid SwNoTxtNode::SetTitle( const String& rTitle, bool bBroadcast )\n{\n \/\/ Title attribute of replaces own AlternateText attribute\n SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return;\n }\n\n pFlyFmt->SetObjTitle( rTitle, bBroadcast );\n}\n\nconst String SwNoTxtNode::GetTitle() const\n{\n const SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return aEmptyStr;\n }\n\n return pFlyFmt->GetObjTitle();\n}\n\nvoid SwNoTxtNode::SetDescription( const String& rDescription, bool bBroadcast )\n{\n SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return;\n }\n\n pFlyFmt->SetObjDescription( rDescription, bBroadcast );\n}\n\nconst String SwNoTxtNode::GetDescription() const\n{\n const SwFlyFrmFmt* pFlyFmt = dynamic_cast(GetFlyFmt());\n ASSERT( pFlyFmt,\n \" - missing instance\" );\n if ( !pFlyFmt )\n {\n return aEmptyStr;\n }\n\n return pFlyFmt->GetObjDescription();\n}\n\/\/ <--\n<|endoftext|>"} {"text":"coverity#704880 Dereference after null check<|endoftext|>"} {"text":"sw: unused includes in calcmove<|endoftext|>"} {"text":"sw: SwLayHelper should not consider the page after first page a first page<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \"simple_strategy.hh\"\n#include \"utils\/class_registrator.hh\"\n#include \n#include \"utils\/sequenced_set.hh\"\n\nnamespace locator {\n\nsimple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map& config_options) :\n abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {\n for (auto& config_pair : config_options) {\n auto& key = config_pair.first;\n auto& val = config_pair.second;\n\n if (boost::iequals(key, \"replication_factor\")) {\n _replication_factor = std::stol(val);\n\n break;\n }\n }\n}\n\nstd::vector simple_strategy::calculate_natural_endpoints(const token& t) {\n const std::vector& tokens = _token_metadata.sorted_tokens();\n\n if (tokens.empty()) {\n return std::vector();\n }\n\n size_t replicas = get_replication_factor();\n utils::sequenced_set endpoints;\n endpoints.reserve(replicas);\n\n for (auto& token : _token_metadata.ring_range(t)) {\n auto ep = _token_metadata.get_endpoint(token);\n assert(ep);\n\n endpoints.push_back(*ep);\n }\n\n return std::move(endpoints.get_vector());\n}\n\nsize_t simple_strategy::get_replication_factor() const {\n return _replication_factor;\n}\n\nusing registry = class_registrator&>;\nstatic registry registrator(\"org.apache.cassandra.locator.SimpleStrategy\");\nstatic registry registrator_short_name(\"SimpleStrategy\");\n\n}\ncalculate_natural_endpoints limit retuned ips by replication factor\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \"simple_strategy.hh\"\n#include \"utils\/class_registrator.hh\"\n#include \n#include \"utils\/sequenced_set.hh\"\n\nnamespace locator {\n\nsimple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map& config_options) :\n abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {\n for (auto& config_pair : config_options) {\n auto& key = config_pair.first;\n auto& val = config_pair.second;\n\n if (boost::iequals(key, \"replication_factor\")) {\n _replication_factor = std::stol(val);\n\n break;\n }\n }\n}\n\nstd::vector simple_strategy::calculate_natural_endpoints(const token& t) {\n const std::vector& tokens = _token_metadata.sorted_tokens();\n\n if (tokens.empty()) {\n return std::vector();\n }\n\n size_t replicas = get_replication_factor();\n utils::sequenced_set endpoints;\n endpoints.reserve(replicas);\n\n for (auto& token : _token_metadata.ring_range(t)) {\n auto ep = _token_metadata.get_endpoint(token);\n assert(ep);\n\n endpoints.push_back(*ep);\n if (endpoints.size() == replicas) break;\n }\n\n return std::move(endpoints.get_vector());\n}\n\nsize_t simple_strategy::get_replication_factor() const {\n return _replication_factor;\n}\n\nusing registry = class_registrator&>;\nstatic registry registrator(\"org.apache.cassandra.locator.SimpleStrategy\");\nstatic registry registrator_short_name(\"SimpleStrategy\");\n\n}\n<|endoftext|>"} {"text":"\/*=============================================================*\/\n\/* SECTION: Includes *\/\n\/*=============================================================*\/\n\n#define _WIN32_WINNT 0x0600\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"cmdformatter.h\"\n\n\/*=============================================================*\/\n\/* SECTION: Local Data *\/\n\/*=============================================================*\/\n\n\/\/\/ Stores saved alias windows.\nQHash gSavedWins;\n\n\/\/\/ The application version string.\nQString gVerStr(\"0.5.0-alpha\");\n\n\/*=============================================================*\/\n\/* SECTION: Local Prototypes *\/\n\/*=============================================================*\/\n\nstatic BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);\nstatic BOOL IsAltTabWindow(HWND hwnd);\n\n\/*=============================================================*\/\n\/* SECTION: Function Definitions *\/\n\/*=============================================================*\/\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n proxy(new QSortFilterProxyModel(parent)),\n model(new QStandardItemModel(0, 4, parent))\n{\n \/\/ Set the window style.\n Qt::WindowFlags flags = windowFlags();\n setWindowFlags(flags | Qt::WindowStaysOnTopHint | Qt::ToolTip);\n\n \/\/ Set up system tray.\n trayIconMenu = new QMenu(this);\n aboutAction = new QAction(tr(\"&About\"), this);\n quitAction = new QAction(tr(\"&Quit\"), this);\n connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutMain()));\n connect(quitAction, SIGNAL(triggered()), this, SLOT(quitMain()));\n trayIconMenu->addAction(aboutAction);\n trayIconMenu->addAction(quitAction);\n trayIcon = new QSystemTrayIcon(this);\n trayIcon->setContextMenu(trayIconMenu);\n trayIcon->setToolTip(QString(\"QuickWin\"));\n trayIcon->setIcon(QIcon(\"icon.png\"));\n trayIcon->show();\n\n \/\/ Set up UI items.\n ui->setupUi(this);\n proxy->setSourceModel(model);\n ui->winView->setModel(proxy);\n proxy->setFilterKeyColumn(1);\n ui->winView->setSortingEnabled(true);\n ui->winView->sortByColumn(0, Qt::AscendingOrder);\n ui->winView->setEditTriggers(QAbstractItemView::NoEditTriggers);\n model->setHeaderData(0, Qt::Horizontal, QObject::tr(\"Number\"));\n model->setHeaderData(1, Qt::Horizontal, QObject::tr(\"Title\"));\n model->setHeaderData(2, Qt::Horizontal, QObject::tr(\"Executable\"));\n model->setHeaderData(3, Qt::Horizontal, QObject::tr(\"Alias\"));\n sizePosMain();\n\n connect(ui->cmdText, SIGNAL(returnPressed()),\n this,SLOT(onTextEnter()));\n connect(ui->cmdText, SIGNAL(textChanged(const QString &)),\n this, SLOT(onTextChanged(const QString &)));\n connect(ui->winView, SIGNAL(activated(QModelIndex)),\n this, SLOT(onWitemActivate(QModelIndex)));\n\n \/\/ Register system-wide hotkey.\n HWND hwnd = (HWND)this->winId();\n RegisterHotKey(hwnd, 100, MOD_CONTROL | MOD_ALT, VK_SPACE);\n\n updateWinList(true);\n}\n\nvoid MainWindow::sizePosMain(void) {\n \/\/ Center window.\n QDesktopWidget *desktop = QApplication::desktop();\n int width = desktop->width() * 0.6;\n int height = desktop->height() * 0.6;\n setFixedSize(width, height);\n move((desktop->width() - width) \/ 2, (desktop->height() - height) \/ 2);\n\n ui->winView->header()->resizeSection(0, width * 0.08);\n ui->winView->header()->resizeSection(1, width * 0.7);\n}\n\nvoid MainWindow::aboutMain(void) {\n QMessageBox::about(this,\n \"About QuickWin\",\n \"QuickWin version `\" + gVerStr + \"`.\\nVisit 'github.com\/jeffrimko\/QuickWin' for more information.\");\n}\n\nvoid MainWindow::quitMain(void) {\n exit(0);\n}\n\nvoid MainWindow::updateWinList(bool clear_note) {\n model->removeRows(0, model->rowCount());\n witems.clear();\n EnumWindows(EnumWindowsProc, (LPARAM)this);\n for(int i = 0; i < witems.size(); i++) {\n model->insertRow(i);\n model->setData(model->index(i, 0), QString::number(witems[i].num));\n model->setData(model->index(i, 1), witems[i].title);\n model->setData(model->index(i, 2), witems[i].exec);\n model->setData(model->index(i, 3), gSavedWins[witems[i].handle]);\n }\n ui->winView->setCurrentIndex(proxy->index(0,0));\n if(clear_note) {\n ui->noteText->clear();\n ui->noteText->append(\"QuickWin \" + gVerStr + \" found \" + QString::number(witems.size()) + \" windows.\");\n }\n}\n\nvoid MainWindow::checkSavedWins(void) {\n if(gSavedWins.size()) {\n QHashIterator i(gSavedWins);\n while (i.hasNext()) {\n i.next();\n bool win_okay = false;\n for(int j = 0; j < witems.size(); j++) {\n if(witems[j].handle == i.key()) {\n win_okay = true;\n break;\n }\n }\n if(false == win_okay) {\n gSavedWins.remove(i.key());\n }\n }\n }\n}\n\nvoid MainWindow::onTextChanged(const QString &text) {\n static QString prev_ptrn = \"\";\n cmds_t cmds;\n QString ptrn = \"\";\n format_cmds(cmds, text.toStdString());\n if(\"\" != cmds[\"number\"]) {\n proxy->setFilterKeyColumn(0);\n ptrn = QString::fromStdString(cmds[\"number\"]);\n } else if(\"\" != cmds[\"executable\"]) {\n proxy->setFilterKeyColumn(2);\n ptrn = QString::fromStdString(cmds[\"executable\"]);\n } else if(cmds.find(\"get\") != cmds.end()) {\n proxy->setFilterKeyColumn(3);\n if(\"\" != cmds[\"get\"]) {\n ptrn = QString::fromStdString(cmds[\"get\"]);\n } else {\n ptrn = \"?\";\n }\n } else {\n proxy->setFilterKeyColumn(1);\n ptrn = QString::fromStdString(cmds[\"title\"]);\n }\n if(prev_ptrn != ptrn) {\n proxy->setFilterRegExp(QRegExp(ptrn, Qt::CaseInsensitive, QRegExp::Wildcard));\n ui->winView->setCurrentIndex(proxy->index(0,0));\n }\n prev_ptrn = ptrn;\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::keyPressEvent(QKeyEvent *event) {\n bool hide_win = (event->key() == Qt::Key_Escape);\n bool quit_app = false;\n\n SelMove mv = SELMOVE_NO;\n if(event->modifiers() && Qt::ControlModifier) {\n switch(event->key()) {\n case Qt::Key_H: mv = SELMOVE_TOP; break;\n case Qt::Key_L: mv = SELMOVE_BTM; break;\n case Qt::Key_K: mv = SELMOVE_UP; break;\n case Qt::Key_J: mv = SELMOVE_DWN; break;\n case Qt::Key_M: mv = SELMOVE_MID; break;\n case Qt::Key_E: mv = SELMOVE_EXE; break;\n case Qt::Key_S: onWitemActivate(ui->winView->currentIndex());\n case Qt::Key_C: hide_win = true; break;\n#ifndef QT_NO_DEBUG\n case Qt::Key_X: quit_app = true; break;\n#endif\n }\n } else {\n switch(event->key()) {\n case Qt::Key_Home: mv = SELMOVE_TOP; break;\n case Qt::Key_End: mv = SELMOVE_BTM; break;\n case Qt::Key_Up: mv = SELMOVE_UP; break;\n case Qt::Key_Down: mv = SELMOVE_DWN; break;\n }\n }\n moveSel(mv);\n\n if(hide_win) {\n hide();\n }\n \/\/ TODO: Debug only! Remove later...\n if(quit_app) {\n quitMain();\n }\n}\n\nvoid MainWindow::moveSel(SelMove mv) {\n \/\/ Handle selection movement.\n int row = ui->winView->currentIndex().row();\n if((SELMOVE_UP == mv) | (SELMOVE_DWN == mv)) {\n if(SELMOVE_UP == mv) {\n if(row == 0) {\n row = proxy->rowCount() - 1;\n } else {\n row -= 1;\n }\n } else {\n row += 1;\n if(row >= proxy->rowCount()) {\n row = 0;\n }\n }\n ui->winView->setCurrentIndex(proxy->index(row,0));\n } else if(SELMOVE_TOP == mv) {\n ui->winView->setCurrentIndex(proxy->index(0,0));\n } else if(SELMOVE_MID == mv) {\n ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()\/2,0));\n } else if(SELMOVE_BTM == mv) {\n ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()-1,0));\n } else if(SELMOVE_EXE == mv) {\n QString exec = witems[row].exec;\n int idx = row + 1;\n while(idx != row) {\n if(idx >= witems.size()) {\n idx = 0;\n }\n if(exec == witems[idx].exec) {\n break;\n }\n idx++;\n }\n ui->winView->setCurrentIndex(proxy->index(idx,0));\n }\n}\n\nvoid MainWindow::showWin(HWND handle) {\n if(IsIconic(handle)) {\n ShowWindow(handle, SW_RESTORE);\n }\n SetForegroundWindow(handle);\n}\n\nvoid MainWindow::onWitemActivate(QModelIndex index) {\n if(proxy->rowCount() == 0)\n return;\n showWin(witems[getSelWinNum()].handle);\n}\n\nuint MainWindow::getSelWinNum(void) {\n uint row = ui->winView->currentIndex().row();\n uint num = proxy->data(proxy->index(row, 0)).toInt() - 1;\n return(num);\n}\n\nvoid MainWindow::onTextEnter()\n{\n bool stay = false;\n cmds_t cmds;\n QString text = ui->cmdText->text();\n format_cmds(cmds, text.toStdString());\n\n if(cmds.find(\"help\") != cmds.end()) {\n QString help = \"Commands: \";\n for(std::string cmd : list_cmd_types()) {\n help += QString::fromStdString(cmd);\n help += \" \";\n }\n ui->noteText->append(help);\n stay = true;\n }\n if(cmds.find(\"delete\") != cmds.end()) {\n gSavedWins.clear();\n ui->noteText->append(\"Aliases deleted.\");\n stay = true;\n }\n if(cmds.find(\"set\") != cmds.end()) {\n uint num = getSelWinNum();\n if(\"\" != cmds[\"set\"]) {\n QString name = QString::fromStdString(cmds[\"set\"]);\n gSavedWins[witems[num].handle] = name;\n ui->noteText->append(\"Set \" + QString::number(num+1) + \" to alias '\" + name + \"'.\");\n } else {\n gSavedWins.remove(witems[num].handle);\n ui->noteText->append(\"Removed alias from \" + QString::number(num+1) + \".\");\n }\n stay = true;\n }\n\n if(!stay) {\n onWitemActivate(ui->winView->currentIndex());\n } else {\n ui->cmdText->clear();\n updateWinList(false);\n }\n}\n\nbool MainWindow::winEvent( MSG * message, long * result ) {\n if(message->message == 786) {\n onHotkey();\n }\n return(false);\n}\n\nvoid MainWindow::onHotkey(void) {\n if((HWND)this->winId() == GetActiveWindow()) {\n \/\/ Already active window.\n moveSel(SELMOVE_DWN);\n }\n else {\n showMain();\n }\n}\n\nvoid MainWindow::showMain(void) {\n sizePosMain();\n show();\n setWindowState( (windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);\n raise(); \/\/ for MacOS\n activateWindow(); \/\/ for Windows\n ui->cmdText->clear();\n ui->cmdText->setFocus();\n}\n\n\/\/ Callback for `EnumWindows` that lists out all window names.\nBOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {\n WinItem witem;\n MainWindow *mainwin = (MainWindow*)lParam;\n DWORD pid;\n\n LPWSTR buff[1024];\n if( (IsWindowVisible(hWnd)) &&\n (IsAltTabWindow(hWnd)) &&\n ((HWND)mainwin->winId() != hWnd) )\n {\n GetWindowText(hWnd, (LPWSTR)buff, sizeof(buff));\n witem.title = QString::fromWCharArray((const LPWSTR)buff);\n witem.handle = hWnd;\n witem.num = mainwin->witems.size() + 1;\n GetWindowThreadProcessId(hWnd, &pid);\n \/\/ NOTE: This call is needed to allow access to metadata of the\n \/\/ process. If original handle is used to for metadata read attempt, it\n \/\/ will likely result in an error.\n HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);\n \/\/ NOTE: Using `GetProcessImageFileName()` here fixes the 32\/64-bit\n \/\/ error.\n if(GetProcessImageFileName(handle, (LPWSTR)buff, sizeof(buff))) {\n witem.exec = QString::fromWCharArray((const LPWSTR)buff);\n witem.exec = witem.exec.mid(witem.exec.lastIndexOf(\"\\\\\") + 1);\n } else {\n witem.exec = QString(\"NA\");\n }\n mainwin->witems.append(witem);\n }\n return TRUE;\n}\n\nvoid MainWindow::windowActivationChange(bool state) {\n if(state) {\n \/\/ Lost focus.\n hide();\n } else {\n \/\/ In focus.\n updateWinList(true);\n checkSavedWins();\n showMain();\n }\n}\n\nBOOL IsAltTabWindow(HWND hwnd)\n{\n long wndStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n if(GetWindowTextLength(hwnd) == 0)\n return false;\n\n \/\/ Ignore desktop window.\n if (hwnd == GetShellWindow())\n return(false);\n\n if(wndStyle & WS_EX_TOOLWINDOW)\n return(false);\n\n \/\/ Start at the root owner\n HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);\n\n \/\/ See if we are the last active visible popup\n HWND hwndTry;\n while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry)\n {\n if (IsWindowVisible(hwndTry))\n break;\n hwndWalk = hwndTry;\n }\n return hwndWalk == hwnd;\n}\n\nWill only display on the primary monitor now.\/*=============================================================*\/\n\/* SECTION: Includes *\/\n\/*=============================================================*\/\n\n#define _WIN32_WINNT 0x0600\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"cmdformatter.h\"\n\n\/*=============================================================*\/\n\/* SECTION: Local Data *\/\n\/*=============================================================*\/\n\n\/\/\/ Stores saved alias windows.\nQHash gSavedWins;\n\n\/\/\/ The application version string.\nQString gVerStr(\"0.5.0-alpha\");\n\n\/*=============================================================*\/\n\/* SECTION: Local Prototypes *\/\n\/*=============================================================*\/\n\nstatic BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);\nstatic BOOL IsAltTabWindow(HWND hwnd);\n\n\/*=============================================================*\/\n\/* SECTION: Function Definitions *\/\n\/*=============================================================*\/\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n proxy(new QSortFilterProxyModel(parent)),\n model(new QStandardItemModel(0, 4, parent))\n{\n \/\/ Set the window style.\n Qt::WindowFlags flags = windowFlags();\n setWindowFlags(flags | Qt::WindowStaysOnTopHint | Qt::ToolTip);\n\n \/\/ Set up system tray.\n trayIconMenu = new QMenu(this);\n aboutAction = new QAction(tr(\"&About\"), this);\n quitAction = new QAction(tr(\"&Quit\"), this);\n connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutMain()));\n connect(quitAction, SIGNAL(triggered()), this, SLOT(quitMain()));\n trayIconMenu->addAction(aboutAction);\n trayIconMenu->addAction(quitAction);\n trayIcon = new QSystemTrayIcon(this);\n trayIcon->setContextMenu(trayIconMenu);\n trayIcon->setToolTip(QString(\"QuickWin\"));\n trayIcon->setIcon(QIcon(\"icon.png\"));\n trayIcon->show();\n\n \/\/ Set up UI items.\n ui->setupUi(this);\n proxy->setSourceModel(model);\n ui->winView->setModel(proxy);\n proxy->setFilterKeyColumn(1);\n ui->winView->setSortingEnabled(true);\n ui->winView->sortByColumn(0, Qt::AscendingOrder);\n ui->winView->setEditTriggers(QAbstractItemView::NoEditTriggers);\n model->setHeaderData(0, Qt::Horizontal, QObject::tr(\"Number\"));\n model->setHeaderData(1, Qt::Horizontal, QObject::tr(\"Title\"));\n model->setHeaderData(2, Qt::Horizontal, QObject::tr(\"Executable\"));\n model->setHeaderData(3, Qt::Horizontal, QObject::tr(\"Alias\"));\n sizePosMain();\n\n connect(ui->cmdText, SIGNAL(returnPressed()),\n this,SLOT(onTextEnter()));\n connect(ui->cmdText, SIGNAL(textChanged(const QString &)),\n this, SLOT(onTextChanged(const QString &)));\n connect(ui->winView, SIGNAL(activated(QModelIndex)),\n this, SLOT(onWitemActivate(QModelIndex)));\n\n \/\/ Register system-wide hotkey.\n HWND hwnd = (HWND)this->winId();\n RegisterHotKey(hwnd, 100, MOD_CONTROL | MOD_ALT, VK_SPACE);\n\n updateWinList(true);\n}\n\nvoid MainWindow::sizePosMain(void) {\n \/\/ Center window.\n QDesktopWidget *desktop = QApplication::desktop();\n int width = desktop->screenGeometry(desktop->primaryScreen()).width() * 0.6;\n int height = desktop->screenGeometry(desktop->primaryScreen()).height() * 0.6;\n setFixedSize(width, height);\n move(\n (desktop->screenGeometry(desktop->primaryScreen()).width() - width) \/ 2,\n (desktop->screenGeometry(desktop->primaryScreen()).height() - height) \/ 2\n );\n\n ui->winView->header()->resizeSection(0, width * 0.08);\n ui->winView->header()->resizeSection(1, width * 0.7);\n}\n\nvoid MainWindow::aboutMain(void) {\n QMessageBox::about(this,\n \"About QuickWin\",\n \"QuickWin version `\" + gVerStr + \"`.\\nVisit 'github.com\/jeffrimko\/QuickWin' for more information.\");\n}\n\nvoid MainWindow::quitMain(void) {\n exit(0);\n}\n\nvoid MainWindow::updateWinList(bool clear_note) {\n model->removeRows(0, model->rowCount());\n witems.clear();\n EnumWindows(EnumWindowsProc, (LPARAM)this);\n for(int i = 0; i < witems.size(); i++) {\n model->insertRow(i);\n model->setData(model->index(i, 0), QString::number(witems[i].num));\n model->setData(model->index(i, 1), witems[i].title);\n model->setData(model->index(i, 2), witems[i].exec);\n model->setData(model->index(i, 3), gSavedWins[witems[i].handle]);\n }\n ui->winView->setCurrentIndex(proxy->index(0,0));\n if(clear_note) {\n ui->noteText->clear();\n ui->noteText->append(\"QuickWin \" + gVerStr + \" found \" + QString::number(witems.size()) + \" windows.\");\n }\n}\n\nvoid MainWindow::checkSavedWins(void) {\n if(gSavedWins.size()) {\n QHashIterator i(gSavedWins);\n while (i.hasNext()) {\n i.next();\n bool win_okay = false;\n for(int j = 0; j < witems.size(); j++) {\n if(witems[j].handle == i.key()) {\n win_okay = true;\n break;\n }\n }\n if(false == win_okay) {\n gSavedWins.remove(i.key());\n }\n }\n }\n}\n\nvoid MainWindow::onTextChanged(const QString &text) {\n static QString prev_ptrn = \"\";\n cmds_t cmds;\n QString ptrn = \"\";\n format_cmds(cmds, text.toStdString());\n if(\"\" != cmds[\"number\"]) {\n proxy->setFilterKeyColumn(0);\n ptrn = QString::fromStdString(cmds[\"number\"]);\n } else if(\"\" != cmds[\"executable\"]) {\n proxy->setFilterKeyColumn(2);\n ptrn = QString::fromStdString(cmds[\"executable\"]);\n } else if(cmds.find(\"get\") != cmds.end()) {\n proxy->setFilterKeyColumn(3);\n if(\"\" != cmds[\"get\"]) {\n ptrn = QString::fromStdString(cmds[\"get\"]);\n } else {\n ptrn = \"?\";\n }\n } else {\n proxy->setFilterKeyColumn(1);\n ptrn = QString::fromStdString(cmds[\"title\"]);\n }\n if(prev_ptrn != ptrn) {\n proxy->setFilterRegExp(QRegExp(ptrn, Qt::CaseInsensitive, QRegExp::Wildcard));\n ui->winView->setCurrentIndex(proxy->index(0,0));\n }\n prev_ptrn = ptrn;\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::keyPressEvent(QKeyEvent *event) {\n bool hide_win = (event->key() == Qt::Key_Escape);\n bool quit_app = false;\n\n SelMove mv = SELMOVE_NO;\n if(event->modifiers() && Qt::ControlModifier) {\n switch(event->key()) {\n case Qt::Key_H: mv = SELMOVE_TOP; break;\n case Qt::Key_L: mv = SELMOVE_BTM; break;\n case Qt::Key_K: mv = SELMOVE_UP; break;\n case Qt::Key_J: mv = SELMOVE_DWN; break;\n case Qt::Key_M: mv = SELMOVE_MID; break;\n case Qt::Key_E: mv = SELMOVE_EXE; break;\n case Qt::Key_S: onWitemActivate(ui->winView->currentIndex());\n case Qt::Key_C: hide_win = true; break;\n#ifndef QT_NO_DEBUG\n case Qt::Key_X: quit_app = true; break;\n#endif\n }\n } else {\n switch(event->key()) {\n case Qt::Key_Home: mv = SELMOVE_TOP; break;\n case Qt::Key_End: mv = SELMOVE_BTM; break;\n case Qt::Key_Up: mv = SELMOVE_UP; break;\n case Qt::Key_Down: mv = SELMOVE_DWN; break;\n }\n }\n moveSel(mv);\n\n if(hide_win) {\n hide();\n }\n \/\/ TODO: Debug only! Remove later...\n if(quit_app) {\n quitMain();\n }\n}\n\nvoid MainWindow::moveSel(SelMove mv) {\n \/\/ Handle selection movement.\n int row = ui->winView->currentIndex().row();\n if((SELMOVE_UP == mv) | (SELMOVE_DWN == mv)) {\n if(SELMOVE_UP == mv) {\n if(row == 0) {\n row = proxy->rowCount() - 1;\n } else {\n row -= 1;\n }\n } else {\n row += 1;\n if(row >= proxy->rowCount()) {\n row = 0;\n }\n }\n ui->winView->setCurrentIndex(proxy->index(row,0));\n } else if(SELMOVE_TOP == mv) {\n ui->winView->setCurrentIndex(proxy->index(0,0));\n } else if(SELMOVE_MID == mv) {\n ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()\/2,0));\n } else if(SELMOVE_BTM == mv) {\n ui->winView->setCurrentIndex(proxy->index(proxy->rowCount()-1,0));\n } else if(SELMOVE_EXE == mv) {\n QString exec = witems[row].exec;\n int idx = row + 1;\n while(idx != row) {\n if(idx >= witems.size()) {\n idx = 0;\n }\n if(exec == witems[idx].exec) {\n break;\n }\n idx++;\n }\n ui->winView->setCurrentIndex(proxy->index(idx,0));\n }\n}\n\nvoid MainWindow::showWin(HWND handle) {\n if(IsIconic(handle)) {\n ShowWindow(handle, SW_RESTORE);\n }\n SetForegroundWindow(handle);\n}\n\nvoid MainWindow::onWitemActivate(QModelIndex index) {\n if(proxy->rowCount() == 0)\n return;\n showWin(witems[getSelWinNum()].handle);\n}\n\nuint MainWindow::getSelWinNum(void) {\n uint row = ui->winView->currentIndex().row();\n uint num = proxy->data(proxy->index(row, 0)).toInt() - 1;\n return(num);\n}\n\nvoid MainWindow::onTextEnter()\n{\n bool stay = false;\n cmds_t cmds;\n QString text = ui->cmdText->text();\n format_cmds(cmds, text.toStdString());\n\n if(cmds.find(\"help\") != cmds.end()) {\n QString help = \"Commands: \";\n for(std::string cmd : list_cmd_types()) {\n help += QString::fromStdString(cmd);\n help += \" \";\n }\n ui->noteText->append(help);\n stay = true;\n }\n if(cmds.find(\"delete\") != cmds.end()) {\n gSavedWins.clear();\n ui->noteText->append(\"Aliases deleted.\");\n stay = true;\n }\n if(cmds.find(\"set\") != cmds.end()) {\n uint num = getSelWinNum();\n if(\"\" != cmds[\"set\"]) {\n QString name = QString::fromStdString(cmds[\"set\"]);\n gSavedWins[witems[num].handle] = name;\n ui->noteText->append(\"Set \" + QString::number(num+1) + \" to alias '\" + name + \"'.\");\n } else {\n gSavedWins.remove(witems[num].handle);\n ui->noteText->append(\"Removed alias from \" + QString::number(num+1) + \".\");\n }\n stay = true;\n }\n\n if(!stay) {\n onWitemActivate(ui->winView->currentIndex());\n } else {\n ui->cmdText->clear();\n updateWinList(false);\n }\n}\n\nbool MainWindow::winEvent( MSG * message, long * result ) {\n if(message->message == 786) {\n onHotkey();\n }\n return(false);\n}\n\nvoid MainWindow::onHotkey(void) {\n if((HWND)this->winId() == GetActiveWindow()) {\n \/\/ Already active window.\n moveSel(SELMOVE_DWN);\n }\n else {\n showMain();\n }\n}\n\nvoid MainWindow::showMain(void) {\n sizePosMain();\n show();\n setWindowState( (windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);\n raise(); \/\/ for MacOS\n activateWindow(); \/\/ for Windows\n ui->cmdText->clear();\n ui->cmdText->setFocus();\n}\n\n\/\/ Callback for `EnumWindows` that lists out all window names.\nBOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {\n WinItem witem;\n MainWindow *mainwin = (MainWindow*)lParam;\n DWORD pid;\n\n LPWSTR buff[1024];\n if( (IsWindowVisible(hWnd)) &&\n (IsAltTabWindow(hWnd)) &&\n ((HWND)mainwin->winId() != hWnd) )\n {\n GetWindowText(hWnd, (LPWSTR)buff, sizeof(buff));\n witem.title = QString::fromWCharArray((const LPWSTR)buff);\n witem.handle = hWnd;\n witem.num = mainwin->witems.size() + 1;\n GetWindowThreadProcessId(hWnd, &pid);\n \/\/ NOTE: This call is needed to allow access to metadata of the\n \/\/ process. If original handle is used to for metadata read attempt, it\n \/\/ will likely result in an error.\n HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);\n \/\/ NOTE: Using `GetProcessImageFileName()` here fixes the 32\/64-bit\n \/\/ error.\n if(GetProcessImageFileName(handle, (LPWSTR)buff, sizeof(buff))) {\n witem.exec = QString::fromWCharArray((const LPWSTR)buff);\n witem.exec = witem.exec.mid(witem.exec.lastIndexOf(\"\\\\\") + 1);\n } else {\n witem.exec = QString(\"NA\");\n }\n mainwin->witems.append(witem);\n }\n return TRUE;\n}\n\nvoid MainWindow::windowActivationChange(bool state) {\n if(state) {\n \/\/ Lost focus.\n hide();\n } else {\n \/\/ In focus.\n updateWinList(true);\n checkSavedWins();\n showMain();\n }\n}\n\nBOOL IsAltTabWindow(HWND hwnd)\n{\n long wndStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n if(GetWindowTextLength(hwnd) == 0)\n return false;\n\n \/\/ Ignore desktop window.\n if (hwnd == GetShellWindow())\n return(false);\n\n if(wndStyle & WS_EX_TOOLWINDOW)\n return(false);\n\n \/\/ Start at the root owner\n HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);\n\n \/\/ See if we are the last active visible popup\n HWND hwndTry;\n while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry)\n {\n if (IsWindowVisible(hwndTry))\n break;\n hwndWalk = hwndTry;\n }\n return hwndWalk == hwnd;\n}\n\n<|endoftext|>"} {"text":"\/\/ Filename: find_root_dir.cxx\n\/\/ Created by: drose (29Jun09)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"find_root_dir.h\"\n#include \"mkdir_complete.h\"\n#include \"get_tinyxml.h\"\n\n#ifdef _WIN32\n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n\n#ifdef _WIN32\n\/\/ From KnownFolders.h (part of Vista SDK):\n#define DEFINE_KNOWN_FOLDER(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \\\n const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }\nDEFINE_KNOWN_FOLDER(FOLDERID_LocalAppData, 0xF1B32785, 0x6FBA, 0x4FCF, 0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91);\nDEFINE_KNOWN_FOLDER(FOLDERID_LocalAppDataLow, 0xA520A1A4, 0x1780, 0x4FF6, 0xBD, 0x18, 0x16, 0x73, 0x43, 0xC5, 0xAF, 0x16);\nDEFINE_KNOWN_FOLDER(FOLDERID_InternetCache, 0x352481E8, 0x33BE, 0x4251, 0xBA, 0x85, 0x60, 0x07, 0xCA, 0xED, 0xCF, 0x9D); \n#endif \/\/ _WIN32\n\n\n#ifdef _WIN32\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: get_csidl_dir\n\/\/ Description: A wrapper around SHGetSpecialFolderPath(), to return\n\/\/ the Panda3D directory under the indicated CSIDL\n\/\/ folder.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic string\nget_csidl_dir(int csidl) {\n static const int buffer_size = MAX_PATH;\n char buffer[buffer_size];\n if (SHGetSpecialFolderPath(NULL, buffer, csidl, true)) {\n string root = buffer;\n root += string(\"\/Panda3D\");\n \n if (mkdir_complete(root, cerr)) {\n return root;\n }\n }\n\n \/\/ Something went wrong.\n return string();\n}\n#endif \/\/ _WIN32\n\n#ifdef _WIN32\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: wstr_to_string\n\/\/ Description: Converts Windows' LPWSTR to a std::string.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic bool\nwstr_to_string(string &result, const LPWSTR wstr) {\n bool success = false;\n int size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,\n NULL, 0, NULL, NULL);\n if (size > 0) {\n char *buffer = new char[size];\n int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,\n buffer, size, NULL, NULL);\n if (rc != 0) {\n buffer[size - 1] = 0;\n result = buffer;\n success = true;\n }\n delete[] buffer;\n }\n\n return success;\n}\n#endif \/\/ _WIN32\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: find_root_dir_default\n\/\/ Description: Returns the path to the system-default for the root\n\/\/ directory. This is where we look first.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic string\nfind_root_dir_default() {\n#ifdef _WIN32\n \/\/ First, use IEIsProtectedModeProcess() to determine if we are\n \/\/ running in IE's \"protected mode\" under Vista.\n\n string root;\n bool is_protected = false;\n HMODULE ieframe = LoadLibrary(\"ieframe.dll\");\n if (ieframe != NULL) {\n typedef HRESULT STDAPICALLTYPE IEIsProtectedModeProcess(BOOL *pbResult);\n IEIsProtectedModeProcess *func = (IEIsProtectedModeProcess *)GetProcAddress(ieframe, \"IEIsProtectedModeProcess\");\n if (func != NULL) {\n BOOL result = false;\n HRESULT hr = (*func)(&result);\n if (hr == S_OK) {\n is_protected = (result != 0);\n }\n \/\/ Any other return value means some error, especially\n \/\/ E_NOTIMPL, which means we're not running under Vista. In\n \/\/ this case we can assume we're not running in protected mode.\n }\n\n if (is_protected) {\n \/\/ If we *are* running in protected mode, we need to use\n \/\/ FOLDERID_LocalAppDataLow.\n \n \/\/ We should be able to use IEGetWriteableFolderPath() to query\n \/\/ this folder, but for some reason, that function returns\n \/\/ E_ACCESSDENIED on FOLDERID_LocalAppDataLow, even though this is\n \/\/ certainly a folder we have write access to.\n \n \/\/ Well, SHGetKnownFolderPath() does work. This function only\n \/\/ exists on Vista and above, though, so we still have to pull it\n \/\/ out of the DLL instead of hard-linking it.\n \n HMODULE shell32 = LoadLibrary(\"shell32.dll\");\n if (shell32 != NULL) {\n typedef HRESULT STDAPICALLTYPE SHGetKnownFolderPath(REFGUID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);\n SHGetKnownFolderPath *func = (SHGetKnownFolderPath *)GetProcAddress(shell32, \"SHGetKnownFolderPath\");\n if (func != NULL) {\n LPWSTR cache_path = NULL;\n HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, 0, NULL, &cache_path);\n \n if (SUCCEEDED(hr)) {\n if (!wstr_to_string(root, cache_path)) {\n \/\/ Couldn't decode the LPWSTR.\n CoTaskMemFree(cache_path);\n } else {\n CoTaskMemFree(cache_path);\n \n root += string(\"\/Panda3D\");\n if (mkdir_complete(root, cerr)) {\n FreeLibrary(shell32);\n FreeLibrary(ieframe);\n return root;\n }\n }\n }\n }\n FreeLibrary(shell32);\n }\n \n \/\/ Couldn't get FOLDERID_LocalAppDataLow for some reason. We're\n \/\/ in fallback mode now. Use IEGetWriteableFolderPath to get\n \/\/ the standard cache folder.\n typedef HRESULT STDAPICALLTYPE IEGetWriteableFolderPath(REFGUID clsidFolderID, LPWSTR* lppwstrPath);\n IEGetWriteableFolderPath *func = (IEGetWriteableFolderPath *)GetProcAddress(ieframe, \"IEGetWriteableFolderPath\");\n if (func != NULL) {\n LPWSTR cache_path = NULL;\n\n \/\/ Since we're here, we'll start by asking for\n \/\/ LocalAppDataLow, even though I know it doesn't work.\n HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, &cache_path);\n if (FAILED(hr)) {\n \/\/ This one should work.\n hr = (*func)(FOLDERID_InternetCache, &cache_path);\n }\n\n if (SUCCEEDED(hr)) {\n if (!wstr_to_string(root, cache_path)) {\n \/\/ Couldn't decode the LPWSTR.\n CoTaskMemFree(cache_path);\n } else {\n CoTaskMemFree(cache_path);\n root += string(\"\/Panda3D\");\n if (mkdir_complete(root, cerr)) {\n FreeLibrary(ieframe);\n return root;\n }\n } \n }\n }\n }\n\n FreeLibrary(ieframe);\n }\n\n \/\/ All right, here we are in the normal, unprotected mode. This is\n \/\/ also the normal XP codepath.\n\n \/\/ e.g., c:\/Documents and Settings\/\/Local Settings\/Application Data\/Panda3D\n root = get_csidl_dir(CSIDL_LOCAL_APPDATA);\n if (!root.empty()) {\n return root;\n }\n\n \/\/ For some crazy reason, we can't get CSIDL_LOCAL_APPDATA. Fall\n \/\/ back to the cache folder.\n\n \/\/ e.g. c:\/Documents and Settings\/\/Local Settings\/Temporary Internet Files\/Panda3D\n root = get_csidl_dir(CSIDL_INTERNET_CACHE);\n if (!root.empty()) {\n return root;\n }\n \n \/\/ If we couldn't get any of those folders, huh. Punt and try for\n \/\/ the old standby GetTempPath, for lack of anything better.\n static const int buffer_size = MAX_PATH;\n char buffer[buffer_size];\n if (GetTempPath(buffer_size, buffer) != 0) {\n root = buffer;\n root += string(\"Panda3D\");\n if (mkdir_complete(root, cerr)) {\n return root;\n }\n }\n\n#elif defined(__APPLE__)\n \/\/ e.g., \/Users\/\/Library\/Caches\/Panda3D\n string root = find_osx_root_dir();\n if (!root.empty()) {\n return root;\n }\n\n#else \/\/ The Linux case\n \/\/ e.g., \/home\/\/.panda3d\n\n string root;\n const char *uname = getlogin();\n if (uname == NULL) uname = getenv(\"USER\");\n\n const passwd *pwdata = getpwnam(uname);\n if (pwdata == NULL) {\n root = getenv(\"HOME\");\n } else {\n root = pwdata->pw_dir;\n }\n \n root += \"\/.panda3d\";\n if (mkdir(root.c_str(), 0700) == 0 || errno == EEXIST) {\n return root;\n }\n\n#endif\n\n \/\/ Couldn't find a directory. Punt.\n return \".\";\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: find_root_dir\n\/\/ Description: Returns the path to the installable Panda3D directory\n\/\/ on the user's machine.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring\nfind_root_dir() {\n string root = find_root_dir_default();\n\n \/\/ Now look for a config.xml file in that directory, which might\n \/\/ redirect us elsewhere.\n string config_filename = root + \"\/config.xml\";\n TiXmlDocument doc(config_filename);\n if (!doc.LoadFile()) {\n \/\/ No config.xml found, or not valid xml.\n return root;\n }\n\n TiXmlElement *xconfig = doc.FirstChildElement(\"config\");\n if (xconfig == NULL) {\n \/\/ No element within config.xml.\n return root;\n }\n\n const char *new_root = xconfig->Attribute(\"root_dir\");\n if (new_root == NULL || *new_root == '\\0') {\n \/\/ No root_dir specified.\n return root;\n }\n\n if (!mkdir_complete(new_root, cerr)) {\n \/\/ The specified root_dir wasn't valid.\n return root;\n }\n\n \/\/ We've been redirected to another location. Respect that.\n return new_root;\n}\nFix segmentation fault that only seems to happen in the buildbot's master shell environment. But I suppose the crash could manifest in other environments where getlogin() fails\/\/ Filename: find_root_dir.cxx\n\/\/ Created by: drose (29Jun09)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"find_root_dir.h\"\n#include \"mkdir_complete.h\"\n#include \"get_tinyxml.h\"\n\n#ifdef _WIN32\n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n\n#ifdef _WIN32\n\/\/ From KnownFolders.h (part of Vista SDK):\n#define DEFINE_KNOWN_FOLDER(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \\\n const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }\nDEFINE_KNOWN_FOLDER(FOLDERID_LocalAppData, 0xF1B32785, 0x6FBA, 0x4FCF, 0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91);\nDEFINE_KNOWN_FOLDER(FOLDERID_LocalAppDataLow, 0xA520A1A4, 0x1780, 0x4FF6, 0xBD, 0x18, 0x16, 0x73, 0x43, 0xC5, 0xAF, 0x16);\nDEFINE_KNOWN_FOLDER(FOLDERID_InternetCache, 0x352481E8, 0x33BE, 0x4251, 0xBA, 0x85, 0x60, 0x07, 0xCA, 0xED, 0xCF, 0x9D); \n#endif \/\/ _WIN32\n\n\n#ifdef _WIN32\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: get_csidl_dir\n\/\/ Description: A wrapper around SHGetSpecialFolderPath(), to return\n\/\/ the Panda3D directory under the indicated CSIDL\n\/\/ folder.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic string\nget_csidl_dir(int csidl) {\n static const int buffer_size = MAX_PATH;\n char buffer[buffer_size];\n if (SHGetSpecialFolderPath(NULL, buffer, csidl, true)) {\n string root = buffer;\n root += string(\"\/Panda3D\");\n \n if (mkdir_complete(root, cerr)) {\n return root;\n }\n }\n\n \/\/ Something went wrong.\n return string();\n}\n#endif \/\/ _WIN32\n\n#ifdef _WIN32\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: wstr_to_string\n\/\/ Description: Converts Windows' LPWSTR to a std::string.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic bool\nwstr_to_string(string &result, const LPWSTR wstr) {\n bool success = false;\n int size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,\n NULL, 0, NULL, NULL);\n if (size > 0) {\n char *buffer = new char[size];\n int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,\n buffer, size, NULL, NULL);\n if (rc != 0) {\n buffer[size - 1] = 0;\n result = buffer;\n success = true;\n }\n delete[] buffer;\n }\n\n return success;\n}\n#endif \/\/ _WIN32\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: find_root_dir_default\n\/\/ Description: Returns the path to the system-default for the root\n\/\/ directory. This is where we look first.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic string\nfind_root_dir_default() {\n#ifdef _WIN32\n \/\/ First, use IEIsProtectedModeProcess() to determine if we are\n \/\/ running in IE's \"protected mode\" under Vista.\n\n string root;\n bool is_protected = false;\n HMODULE ieframe = LoadLibrary(\"ieframe.dll\");\n if (ieframe != NULL) {\n typedef HRESULT STDAPICALLTYPE IEIsProtectedModeProcess(BOOL *pbResult);\n IEIsProtectedModeProcess *func = (IEIsProtectedModeProcess *)GetProcAddress(ieframe, \"IEIsProtectedModeProcess\");\n if (func != NULL) {\n BOOL result = false;\n HRESULT hr = (*func)(&result);\n if (hr == S_OK) {\n is_protected = (result != 0);\n }\n \/\/ Any other return value means some error, especially\n \/\/ E_NOTIMPL, which means we're not running under Vista. In\n \/\/ this case we can assume we're not running in protected mode.\n }\n\n if (is_protected) {\n \/\/ If we *are* running in protected mode, we need to use\n \/\/ FOLDERID_LocalAppDataLow.\n \n \/\/ We should be able to use IEGetWriteableFolderPath() to query\n \/\/ this folder, but for some reason, that function returns\n \/\/ E_ACCESSDENIED on FOLDERID_LocalAppDataLow, even though this is\n \/\/ certainly a folder we have write access to.\n \n \/\/ Well, SHGetKnownFolderPath() does work. This function only\n \/\/ exists on Vista and above, though, so we still have to pull it\n \/\/ out of the DLL instead of hard-linking it.\n \n HMODULE shell32 = LoadLibrary(\"shell32.dll\");\n if (shell32 != NULL) {\n typedef HRESULT STDAPICALLTYPE SHGetKnownFolderPath(REFGUID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);\n SHGetKnownFolderPath *func = (SHGetKnownFolderPath *)GetProcAddress(shell32, \"SHGetKnownFolderPath\");\n if (func != NULL) {\n LPWSTR cache_path = NULL;\n HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, 0, NULL, &cache_path);\n \n if (SUCCEEDED(hr)) {\n if (!wstr_to_string(root, cache_path)) {\n \/\/ Couldn't decode the LPWSTR.\n CoTaskMemFree(cache_path);\n } else {\n CoTaskMemFree(cache_path);\n \n root += string(\"\/Panda3D\");\n if (mkdir_complete(root, cerr)) {\n FreeLibrary(shell32);\n FreeLibrary(ieframe);\n return root;\n }\n }\n }\n }\n FreeLibrary(shell32);\n }\n \n \/\/ Couldn't get FOLDERID_LocalAppDataLow for some reason. We're\n \/\/ in fallback mode now. Use IEGetWriteableFolderPath to get\n \/\/ the standard cache folder.\n typedef HRESULT STDAPICALLTYPE IEGetWriteableFolderPath(REFGUID clsidFolderID, LPWSTR* lppwstrPath);\n IEGetWriteableFolderPath *func = (IEGetWriteableFolderPath *)GetProcAddress(ieframe, \"IEGetWriteableFolderPath\");\n if (func != NULL) {\n LPWSTR cache_path = NULL;\n\n \/\/ Since we're here, we'll start by asking for\n \/\/ LocalAppDataLow, even though I know it doesn't work.\n HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, &cache_path);\n if (FAILED(hr)) {\n \/\/ This one should work.\n hr = (*func)(FOLDERID_InternetCache, &cache_path);\n }\n\n if (SUCCEEDED(hr)) {\n if (!wstr_to_string(root, cache_path)) {\n \/\/ Couldn't decode the LPWSTR.\n CoTaskMemFree(cache_path);\n } else {\n CoTaskMemFree(cache_path);\n root += string(\"\/Panda3D\");\n if (mkdir_complete(root, cerr)) {\n FreeLibrary(ieframe);\n return root;\n }\n } \n }\n }\n }\n\n FreeLibrary(ieframe);\n }\n\n \/\/ All right, here we are in the normal, unprotected mode. This is\n \/\/ also the normal XP codepath.\n\n \/\/ e.g., c:\/Documents and Settings\/\/Local Settings\/Application Data\/Panda3D\n root = get_csidl_dir(CSIDL_LOCAL_APPDATA);\n if (!root.empty()) {\n return root;\n }\n\n \/\/ For some crazy reason, we can't get CSIDL_LOCAL_APPDATA. Fall\n \/\/ back to the cache folder.\n\n \/\/ e.g. c:\/Documents and Settings\/\/Local Settings\/Temporary Internet Files\/Panda3D\n root = get_csidl_dir(CSIDL_INTERNET_CACHE);\n if (!root.empty()) {\n return root;\n }\n \n \/\/ If we couldn't get any of those folders, huh. Punt and try for\n \/\/ the old standby GetTempPath, for lack of anything better.\n static const int buffer_size = MAX_PATH;\n char buffer[buffer_size];\n if (GetTempPath(buffer_size, buffer) != 0) {\n root = buffer;\n root += string(\"Panda3D\");\n if (mkdir_complete(root, cerr)) {\n return root;\n }\n }\n\n#elif defined(__APPLE__)\n \/\/ e.g., \/Users\/\/Library\/Caches\/Panda3D\n string root = find_osx_root_dir();\n if (!root.empty()) {\n return root;\n }\n\n#else \/\/ The Linux\/*BSD case\n \/\/ e.g., \/home\/\/.panda3d\n\n string root;\n const passwd *pwdata = getpwuid(getuid());\n if (pwdata == NULL) {\n char *home = getenv(\"HOME\");\n if (home == NULL) {\n \/\/ Beh. Let's hope it never gets to this point.\n return \".\";\n } else {\n root = home;\n }\n } else {\n root = pwdata->pw_dir;\n }\n \n root += \"\/.panda3d\";\n if (mkdir(root.c_str(), 0700) == 0 || errno == EEXIST) {\n return root;\n }\n\n#endif\n\n \/\/ Couldn't find a directory. Punt.\n return \".\";\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: find_root_dir\n\/\/ Description: Returns the path to the installable Panda3D directory\n\/\/ on the user's machine.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring\nfind_root_dir() {\n string root = find_root_dir_default();\n\n \/\/ Now look for a config.xml file in that directory, which might\n \/\/ redirect us elsewhere.\n string config_filename = root + \"\/config.xml\";\n TiXmlDocument doc(config_filename);\n if (!doc.LoadFile()) {\n \/\/ No config.xml found, or not valid xml.\n return root;\n }\n\n TiXmlElement *xconfig = doc.FirstChildElement(\"config\");\n if (xconfig == NULL) {\n \/\/ No element within config.xml.\n return root;\n }\n\n const char *new_root = xconfig->Attribute(\"root_dir\");\n if (new_root == NULL || *new_root == '\\0') {\n \/\/ No root_dir specified.\n return root;\n }\n\n if (!mkdir_complete(new_root, cerr)) {\n \/\/ The specified root_dir wasn't valid.\n return root;\n }\n\n \/\/ We've been redirected to another location. Respect that.\n return new_root;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2020 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Vulkan Renderer\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tnamespace Vk\n\t{\n\t\ttemplate\n\t\tDeviceObject::DeviceObject() :\n\t\tm_handle(VK_NULL_HANDLE)\n\t\t{\n\t\t}\n\n\t\ttemplate\n\t\tDeviceObject::DeviceObject(DeviceObject&& object) noexcept :\n\t\tm_device(std::move(object.m_device)),\n\t\tm_allocator(object.m_allocator),\n\t\tm_handle(object.m_handle),\n\t\tm_lastErrorCode(object.m_lastErrorCode)\n\t\t{\n\t\t\tobject.m_handle = VK_NULL_HANDLE;\n\t\t}\n\n\t\ttemplate\n\t\tDeviceObject::~DeviceObject()\n\t\t{\n\t\t\tDestroy();\n\t\t}\n\n\t\ttemplate\n\t\tbool DeviceObject::Create(Device& device, const CreateInfo& createInfo, const VkAllocationCallbacks* allocator)\n\t\t{\n\t\t\tm_device = &device;\n\t\t\tm_lastErrorCode = C::CreateHelper(*m_device, &createInfo, allocator, &m_handle);\n\t\t\tif (m_lastErrorCode != VkResult::VK_SUCCESS)\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create Vulkan object: \" + TranslateVulkanError(m_lastErrorCode));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ Store the allocator to access them when needed\n\t\t\tif (allocator)\n\t\t\t\tm_allocator = *allocator;\n\t\t\telse\n\t\t\t\tm_allocator.pfnAllocation = nullptr;\n\n\t\t\treturn true;\n\t\t}\n\n\t\ttemplate\n\t\tvoid DeviceObject::Destroy()\n\t\t{\n\t\t\tif (IsValid())\n\t\t\t{\n\t\t\t\tC::DestroyHelper(*m_device, m_handle, (m_allocator.pfnAllocation) ? &m_allocator : nullptr);\n\t\t\t\tm_handle = VK_NULL_HANDLE;\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tbool DeviceObject::IsValid() const\n\t\t{\n\t\t\treturn m_handle != VK_NULL_HANDLE;\n\t\t}\n\n\t\ttemplate\n\t\tDevice* DeviceObject::GetDevice() const\n\t\t{\n\t\t\treturn m_device;\n\t\t}\n\n\t\ttemplate\n\t\tVkResult DeviceObject::GetLastErrorCode() const\n\t\t{\n\t\t\treturn m_lastErrorCode;\n\t\t}\n\n\t\ttemplate\n\t\tvoid DeviceObject::SetDebugName(const char* name)\n\t\t{\n\t\t\tif (m_device->vkSetDebugUtilsObjectNameEXT)\n\t\t\t{\n\t\t\t\tVkDebugUtilsObjectNameInfoEXT debugName = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT };\n\t\t\t\tdebugName.objectType = ObjectType;\n\t\t\t\tdebugName.objectHandle = static_cast(reinterpret_cast(m_handle));\n\t\t\t\tdebugName.pObjectName = name;\n\n\t\t\t\tm_device->vkSetDebugUtilsObjectNameEXT(*m_device, &debugName);\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tvoid DeviceObject::SetDebugName(const std::string& name)\n\t\t{\n\t\t\treturn SetDebugName(name.data());\n\t\t}\n\n\t\ttemplate\n\t\tauto DeviceObject::operator=(DeviceObject&& object) noexcept -> DeviceObject&\n\t\t{\n\t\t\tstd::swap(m_allocator, object.m_allocator);\n\t\t\tstd::swap(m_device, object.m_device);\n\t\t\tstd::swap(m_handle, object.m_handle);\n\t\t\tstd::swap(m_lastErrorCode, object.m_lastErrorCode);\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate\n\t\tDeviceObject::operator VkType() const\n\t\t{\n\t\t\treturn m_handle;\n\t\t}\n\t}\n}\n\n#include \nVulkan: Fix DeviceObject not destroying previous object\/\/ Copyright (C) 2020 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Vulkan Renderer\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tnamespace Vk\n\t{\n\t\ttemplate\n\t\tDeviceObject::DeviceObject() :\n\t\tm_handle(VK_NULL_HANDLE)\n\t\t{\n\t\t}\n\n\t\ttemplate\n\t\tDeviceObject::DeviceObject(DeviceObject&& object) noexcept :\n\t\tm_device(std::move(object.m_device)),\n\t\tm_allocator(object.m_allocator),\n\t\tm_handle(object.m_handle),\n\t\tm_lastErrorCode(object.m_lastErrorCode)\n\t\t{\n\t\t\tobject.m_handle = VK_NULL_HANDLE;\n\t\t}\n\n\t\ttemplate\n\t\tDeviceObject::~DeviceObject()\n\t\t{\n\t\t\tDestroy();\n\t\t}\n\n\t\ttemplate\n\t\tbool DeviceObject::Create(Device& device, const CreateInfo& createInfo, const VkAllocationCallbacks* allocator)\n\t\t{\n\t\t\tDestroy();\n\n\t\t\tm_device = &device;\n\t\t\tm_lastErrorCode = C::CreateHelper(*m_device, &createInfo, allocator, &m_handle);\n\t\t\tif (m_lastErrorCode != VkResult::VK_SUCCESS)\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create Vulkan object: \" + TranslateVulkanError(m_lastErrorCode));\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ Store the allocator to access them when needed\n\t\t\tif (allocator)\n\t\t\t\tm_allocator = *allocator;\n\t\t\telse\n\t\t\t\tm_allocator.pfnAllocation = nullptr;\n\n\t\t\treturn true;\n\t\t}\n\n\t\ttemplate\n\t\tvoid DeviceObject::Destroy()\n\t\t{\n\t\t\tif (IsValid())\n\t\t\t{\n\t\t\t\tC::DestroyHelper(*m_device, m_handle, (m_allocator.pfnAllocation) ? &m_allocator : nullptr);\n\t\t\t\tm_handle = VK_NULL_HANDLE;\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tbool DeviceObject::IsValid() const\n\t\t{\n\t\t\treturn m_handle != VK_NULL_HANDLE;\n\t\t}\n\n\t\ttemplate\n\t\tDevice* DeviceObject::GetDevice() const\n\t\t{\n\t\t\treturn m_device;\n\t\t}\n\n\t\ttemplate\n\t\tVkResult DeviceObject::GetLastErrorCode() const\n\t\t{\n\t\t\treturn m_lastErrorCode;\n\t\t}\n\n\t\ttemplate\n\t\tvoid DeviceObject::SetDebugName(const char* name)\n\t\t{\n\t\t\tif (m_device->vkSetDebugUtilsObjectNameEXT)\n\t\t\t{\n\t\t\t\tVkDebugUtilsObjectNameInfoEXT debugName = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT };\n\t\t\t\tdebugName.objectType = ObjectType;\n\t\t\t\tdebugName.objectHandle = static_cast(reinterpret_cast(m_handle));\n\t\t\t\tdebugName.pObjectName = name;\n\n\t\t\t\tm_device->vkSetDebugUtilsObjectNameEXT(*m_device, &debugName);\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tvoid DeviceObject::SetDebugName(const std::string& name)\n\t\t{\n\t\t\treturn SetDebugName(name.data());\n\t\t}\n\n\t\ttemplate\n\t\tauto DeviceObject::operator=(DeviceObject&& object) noexcept -> DeviceObject&\n\t\t{\n\t\t\tstd::swap(m_allocator, object.m_allocator);\n\t\t\tstd::swap(m_device, object.m_device);\n\t\t\tstd::swap(m_handle, object.m_handle);\n\t\t\tstd::swap(m_lastErrorCode, object.m_lastErrorCode);\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate\n\t\tDeviceObject::operator VkType() const\n\t\t{\n\t\t\treturn m_handle;\n\t\t}\n\t}\n}\n\n#include \n<|endoftext|>"} {"text":"\/**\n * \\file\n * \\brief MessageQueueBase class header\n *\n * \\author Copyright (C) 2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2015-01-14\n *\/\n\n#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_\n#define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_\n\n#include \"distortos\/Semaphore.hpp\"\n\n#include \"distortos\/allocators\/FeedablePool.hpp\"\n\n#include \"distortos\/estd\/TypeErasedFunctor.hpp\"\n\n#include \n\nnamespace distortos\n{\n\nnamespace synchronization\n{\n\n\/\/\/ MessageQueueBase class implements basic functionality of MessageQueue template class\nclass MessageQueueBase\n{\npublic:\n\n\t\/\/\/ entry in the MessageQueueBase\n\tstruct Entry\n\t{\n\t\t\/**\n\t\t * \\brief Entry's constructor\n\t\t *\n\t\t * \\param [in] priorityy is the priority of the entry\n\t\t * \\param [in] storagee is the storage for the entry\n\t\t *\/\n\n\t\tconstexpr Entry(const uint8_t priorityy, void* const storagee) :\n\t\t\t\tpriority{priorityy},\n\t\t\t\tstorage{storagee}\n\t\t{\n\n\t\t}\n\n\t\t\/\/\/ default copy constructor\n\t\tconstexpr Entry(const Entry&) = default;\n\n\t\t\/\/\/ priority of the entry\n\t\tuint8_t priority;\n\n\t\t\/\/\/ storage for the entry\n\t\tvoid* storage;\n\t};\n\n\t\/**\n\t * \\brief Functor is a type-erased interface for functors which execute some action on queue's storage (like\n\t * copy-constructing, swapping, destroying, emplacing, ...).\n\t *\n\t * The functor will be called by MessageQueueBase internals with one argument - \\a storage - which is a pointer to\n\t * storage with\/for element.\n\t *\/\n\n\tusing Functor = estd::TypeErasedFunctor;\n\n\t\/\/\/ link and Entry\n\tusing LinkAndEntry = std::pair;\n\n\t\/**\n\t * type of uninitialized storage for data\n\t *\n\t * \\param T is the type of data in queue\n\t *\/\n\n\ttemplate\n\tstruct Storage\n\t{\n\t\t\/\/\/ storage for Entry\n\t\ttypename std::aligned_storage::type entryStorage;\n\n\t\t\/\/\/ storage for value\n\t\ttypename std::aligned_storage::type valueStorage;\n\t};\n\n\t\/\/\/ functor which gives descending priority order of elements on the list\n\tstruct DescendingPriority\n\t{\n\t\t\/**\n\t\t * \\brief operator()\n\t\t *\n\t\t * \\param [in] left is the object on the left side of comparison\n\t\t * \\param [in] right is the object on the right side of comparison\n\t\t *\n\t\t * \\return true if left's priority is less than right's priority\n\t\t *\/\n\n\t\tbool operator()(const Entry& left, const Entry& right)\n\t\t{\n\t\t\treturn left.priority < right.priority;\n\t\t}\n\t};\n\n\t\/\/\/ type of pool\n\tusing Pool = allocators::FeedablePool;\n\n\t\/\/\/ type of pool allocator\n\tusing PoolAllocator = allocators::PoolAllocator;\n\n\t\/\/\/ type of entry list\n\tusing EntryList = containers::SortedContainer, DescendingPriority>;\n\n\t\/\/\/ type of free entry list\n\tusing FreeEntryList = std::forward_list;\n\n\t\/**\n\t * \\brief MessageQueueBase's constructor\n\t *\n\t * \\param T is the type of data in queue\n\t *\n\t * \\param [in] storage is an array of Storage elements\n\t * \\param [in] maxElements is the number of elements in \\a storage array\n\t *\/\n\n\ttemplate\n\tMessageQueueBase(Storage* const storage, const size_t maxElements) :\n\t\t\tMessageQueueBase{maxElements}\n\t{\n\t\tfor (size_t i = 0; i < maxElements; ++i)\n\t\t{\n\t\t\tpool_.feed(storage[i].entryStorage);\n\t\t\tfreeEntryList_.emplace_front(uint8_t{}, &storage[i].valueStorage);\n\t\t}\n\t}\n\nprivate:\n\n\t\/**\n\t * \\brief MessageQueueBase's constructor - internal version\n\t *\n\t * \\param [in] maxElements is the maximum number of elements the queue can hold\n\t *\/\n\n\texplicit MessageQueueBase(size_t maxElements);\n\n\t\/\/\/ semaphore guarding access to \"pop\" functions - its value is equal to the number of available elements\n\tSemaphore popSemaphore_;\n\n\t\/\/\/ semaphore guarding access to \"push\" functions - its value is equal to the number of free slots\n\tSemaphore pushSemaphore_;\n\n\t\/\/\/ FeedablePool used by \\a poolAllocator_\n\tPool pool_;\n\n\t\/\/\/ PoolAllocator used by \\a entryList_ and \\a freeList_\n\tPoolAllocator poolAllocator_;\n\n\t\/\/\/ list of available entries, sorted in descending order of priority\n\tEntryList entryList_;\n\n\t\/\/\/ list of \"free\" entries\n\tFreeEntryList freeEntryList_;\n};\n\n}\t\/\/ namespace synchronization\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_\nMessageQueueBase: add MessageQueueBase::InternalFunctor type alias\/**\n * \\file\n * \\brief MessageQueueBase class header\n *\n * \\author Copyright (C) 2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2015-01-14\n *\/\n\n#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_\n#define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_\n\n#include \"distortos\/Semaphore.hpp\"\n\n#include \"distortos\/allocators\/FeedablePool.hpp\"\n\n#include \"distortos\/estd\/TypeErasedFunctor.hpp\"\n\n#include \n\nnamespace distortos\n{\n\nnamespace synchronization\n{\n\n\/\/\/ MessageQueueBase class implements basic functionality of MessageQueue template class\nclass MessageQueueBase\n{\npublic:\n\n\t\/\/\/ entry in the MessageQueueBase\n\tstruct Entry\n\t{\n\t\t\/**\n\t\t * \\brief Entry's constructor\n\t\t *\n\t\t * \\param [in] priorityy is the priority of the entry\n\t\t * \\param [in] storagee is the storage for the entry\n\t\t *\/\n\n\t\tconstexpr Entry(const uint8_t priorityy, void* const storagee) :\n\t\t\t\tpriority{priorityy},\n\t\t\t\tstorage{storagee}\n\t\t{\n\n\t\t}\n\n\t\t\/\/\/ default copy constructor\n\t\tconstexpr Entry(const Entry&) = default;\n\n\t\t\/\/\/ priority of the entry\n\t\tuint8_t priority;\n\n\t\t\/\/\/ storage for the entry\n\t\tvoid* storage;\n\t};\n\n\t\/**\n\t * \\brief Functor is a type-erased interface for functors which execute some action on queue's storage (like\n\t * copy-constructing, swapping, destroying, emplacing, ...).\n\t *\n\t * The functor will be called by MessageQueueBase internals with one argument - \\a storage - which is a pointer to\n\t * storage with\/for element.\n\t *\/\n\n\tusing Functor = estd::TypeErasedFunctor;\n\n\t\/\/\/ link and Entry\n\tusing LinkAndEntry = std::pair;\n\n\t\/**\n\t * type of uninitialized storage for data\n\t *\n\t * \\param T is the type of data in queue\n\t *\/\n\n\ttemplate\n\tstruct Storage\n\t{\n\t\t\/\/\/ storage for Entry\n\t\ttypename std::aligned_storage::type entryStorage;\n\n\t\t\/\/\/ storage for value\n\t\ttypename std::aligned_storage::type valueStorage;\n\t};\n\n\t\/\/\/ functor which gives descending priority order of elements on the list\n\tstruct DescendingPriority\n\t{\n\t\t\/**\n\t\t * \\brief operator()\n\t\t *\n\t\t * \\param [in] left is the object on the left side of comparison\n\t\t * \\param [in] right is the object on the right side of comparison\n\t\t *\n\t\t * \\return true if left's priority is less than right's priority\n\t\t *\/\n\n\t\tbool operator()(const Entry& left, const Entry& right)\n\t\t{\n\t\t\treturn left.priority < right.priority;\n\t\t}\n\t};\n\n\t\/\/\/ type of pool\n\tusing Pool = allocators::FeedablePool;\n\n\t\/\/\/ type of pool allocator\n\tusing PoolAllocator = allocators::PoolAllocator;\n\n\t\/\/\/ type of entry list\n\tusing EntryList = containers::SortedContainer, DescendingPriority>;\n\n\t\/\/\/ type of free entry list\n\tusing FreeEntryList = std::forward_list;\n\n\t\/**\n\t * \\brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push()\n\t * operations.\n\t *\n\t * The functor will be called by MessageQueueBase internals with references to \\a entryList_ and \\a freeEntryList_.\n\t * It should perform common actions and execute the Functor passed from callers.\n\t *\/\n\n\tusing InternalFunctor = estd::TypeErasedFunctor;\n\n\t\/**\n\t * \\brief MessageQueueBase's constructor\n\t *\n\t * \\param T is the type of data in queue\n\t *\n\t * \\param [in] storage is an array of Storage elements\n\t * \\param [in] maxElements is the number of elements in \\a storage array\n\t *\/\n\n\ttemplate\n\tMessageQueueBase(Storage* const storage, const size_t maxElements) :\n\t\t\tMessageQueueBase{maxElements}\n\t{\n\t\tfor (size_t i = 0; i < maxElements; ++i)\n\t\t{\n\t\t\tpool_.feed(storage[i].entryStorage);\n\t\t\tfreeEntryList_.emplace_front(uint8_t{}, &storage[i].valueStorage);\n\t\t}\n\t}\n\nprivate:\n\n\t\/**\n\t * \\brief MessageQueueBase's constructor - internal version\n\t *\n\t * \\param [in] maxElements is the maximum number of elements the queue can hold\n\t *\/\n\n\texplicit MessageQueueBase(size_t maxElements);\n\n\t\/\/\/ semaphore guarding access to \"pop\" functions - its value is equal to the number of available elements\n\tSemaphore popSemaphore_;\n\n\t\/\/\/ semaphore guarding access to \"push\" functions - its value is equal to the number of free slots\n\tSemaphore pushSemaphore_;\n\n\t\/\/\/ FeedablePool used by \\a poolAllocator_\n\tPool pool_;\n\n\t\/\/\/ PoolAllocator used by \\a entryList_ and \\a freeList_\n\tPoolAllocator poolAllocator_;\n\n\t\/\/\/ list of available entries, sorted in descending order of priority\n\tEntryList entryList_;\n\n\t\/\/\/ list of \"free\" entries\n\tFreeEntryList freeEntryList_;\n};\n\n}\t\/\/ namespace synchronization\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst int MAX_PACKET_SIZE = 1000;\n\nstruct message {\n\tbool type;\n\tint seq_num;\n\tint packet_num; \n\tbool last_packet;\n\tchar body[1000];\n};\n\nint main(int argc, char** argv) {\n\tint sockfd, portno, n, seq_num = 0, counter = 0, packet_num = 0;\n\tstruct sockaddr_in serv_addr, client_addr;\n\tsocklen_t len = sizeof(struct sockaddr_in);\n\tstring filename, line, buffer;\n\tchar temp[100];\n\tmessage initial, current;\n\tvector packets;\n\t\n\tif (argc < 2) {\n\t\tcerr << \"ERROR: Incorrect number of arguments\" << endl;\n\t\tcerr << \"sender \" << endl;\n\t\treturn -1;\n\t}\n\n\tportno = atoi(argv[1]);\n\n\t\/\/ Set socket and populate server address\n\tsockfd = socket(AF_INET, SOCK_DGRAM, 0);\n\tbzero((char*) &serv_addr, sizeof(serv_addr));\n\tserv_addr.sin_family = AF_INET;\n\tserv_addr.sin_port = htons(portno);\n\tserv_addr.sin_addr.s_addr = INADDR_ANY;\t\t\t\/\/ Server binds to any\/all interfaces\n\n\t\/\/ Bind server to socket\n\tif (bind(sockfd, (struct sockaddr*) &serv_addr, len) == -1) {\n\t\tcerr << \"ERROR: Failed to bind socket\" << endl; \n\t\treturn -1;\n\t}\n\n\t\/\/ Get file request\n\tdo {\n\t\tn = recvfrom(sockfd, temp, 100, 0, \n\t\t\t(struct sockaddr*) &client_addr, &len);\n\t} while (n == -1);\n\n\tfor (int i = 0; i < strlen(temp); i++) {\n\t\tfilename += temp[i];\n\t}\n\n\tcout << \"Filename: \" << filename << endl;\n\n\t\/\/ Create initial ACK for file request\n\tinitial.type = false;\n\tinitial.seq_num = seq_num;\n\tinitial.packet_num = packet_num; \n\tinitial.last_packet = true;\n\tseq_num++;\t\t\t\t\/\/should we increment?\n\tpacket_num++; \t\t\t\/\/should we increment?\n\n\t\/\/ Send ACK with initial seq number 0\n\tsendto(sockfd, &initial, sizeof(initial), 0,\n\t\t(struct sockaddr*) &client_addr, len);\n\n\tostringstream response;\n\tifstream request(filename.c_str(), ios::in|ios::binary);\n\n\tif (request) {\n\t response << request.rdbuf();\n\t request.close(); \n\t buffer = response.str(); \n\t} else {\n\t\tcerr << \"ERROR: File not found\" << endl;\n\t\treturn -1;\n\t}\n\n\t\/\/ Split data into packets\n\tcurrent.last_packet = false;\n\tcurrent.type = true;\n\tfor (int i = 0; i < buffer.size(); i++) {\n\t\tcurrent.body[counter] = buffer[i];\n\t\tif (counter == MAX_PACKET_SIZE - 2) {\n\t\t\tcout << \"Packet has 999 bytes\" << endl;\n\t\t\tcurrent.body[MAX_PACKET_SIZE - 1] = '\\0';\n\t\t\tcurrent.seq_num = seq_num;\n\t\t\tcurrent.packet_num = packet_num; \n\t\t\tpackets.push_back(current);\n\n\t\t\tcounter = -1;\n\t\t\tseq_num += MAX_PACKET_SIZE;\n\t\t\tpacket_num++; \n\t\t}\n\t\tcounter++;\n\t}\n\n\tif (counter != 0) {\n\t\tcout << \"Last packet is smaller than max packet size\" << endl;\n\t\tcurrent.body[counter] = '\\0';\n\t\t\/\/ cout << \"Last packet data: \" << current.body << endl; \n\t\tcurrent.seq_num = seq_num;\n\t\tcurrent.packet_num = packet_num; \n\t\tcout << \"Last Packet seq_num: \" << current.seq_num << endl;\n\t\tcout << \"Last Packet packet_num: \" << current.packet_num << endl; \n\t\tcurrent.last_packet = true;\n\t\tpackets.push_back(current);\n\t\t\/\/seq_num++; why is this even here o.O\n\t\tpacket_num++; \n\t} else {\n\t\tpackets[packets.size() - 1].last_packet = true;\n\t}\n\n\tint cwnd = 5;\n\tint base = 0;\n\tint next_seq_num = base + cwnd;\n\n\tcout << \"Number of packets: \" << packets.size() << endl;\n\t\/\/ Send initial packets\n\tfor (int i = 0; i < cwnd; i++) {\n\t\tcout << \"Data: \" << packets[i].body << endl;\n\t\tsendto(sockfd, &packets[i], sizeof(packets[i]), 0,\n\t\t\t(struct sockaddr*) &client_addr, len);\n\t}\n\n\twhile (true) {\n\t\t\/\/ Get a packet\n\t\tmessage received;\n\t\tn = recvfrom(sockfd, &received, sizeof(received), 0,\n\t\t\t(struct sockaddr*) &client_addr, &len);\n\t\tif (n == 0)\n\t\t\tcontinue;\t\/\/ No more messages\n\t\telse if (n < 0)\n\t\t\tbreak;\t\/\/ Error\n\n\n\t\t\/\/ TODO: Check corruption and randomly drop packets\n\n\t\tcout << \"Received ACK \" << received.seq_num << endl;\n\n\t\tif (received.seq_num >= base) {\n\t\t\t\/\/ Send up to window size\n\t\t\tbase = received.seq_num + 1;\n\t\t\tfor (int i = next_seq_num; i < base + cwnd; i++) {\n\t\t\t\tsendto(sockfd, &packets[i], sizeof(packets[i]), 0,\n\t\t\t\t\t(struct sockaddr*) &client_addr, len);\n\t\t\t}\n\t\t\tnext_seq_num = base + cwnd;\n\t\t}\n\t}\n\t\n}Finished GBN for sender#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst int MAX_PACKET_SIZE = 1000;\nconst int WINDOW_SIZE = 5;\n\nstruct message {\n\tbool type;\n\tint seq_num;\n\tint packet_num; \n\tbool last_packet;\n\tchar body[1000];\n};\n\nint main(int argc, char** argv) {\n\tint sockfd, portno, n, seq_num = 0, counter = 0, packet_num = 0;\n\tstruct sockaddr_in serv_addr, client_addr;\n\tsocklen_t len = sizeof(struct sockaddr_in);\n\tstring filename, line, buffer;\n\tchar temp[100];\n\tmessage initial, current;\n\tvector packets;\n\t\n\tif (argc < 2) {\n\t\tcerr << \"ERROR: Incorrect number of arguments\" << endl;\n\t\tcerr << \"sender \" << endl;\n\t\treturn -1;\n\t}\n\n\tportno = atoi(argv[1]);\n\n\t\/\/ Set socket and populate server address\n\tsockfd = socket(AF_INET, SOCK_DGRAM, 0);\n\tbzero((char*) &serv_addr, sizeof(serv_addr));\n\tserv_addr.sin_family = AF_INET;\n\tserv_addr.sin_port = htons(portno);\n\tserv_addr.sin_addr.s_addr = INADDR_ANY;\t\t\t\/\/ Server binds to any\/all interfaces\n\n\t\/\/ Bind server to socket\n\tif (bind(sockfd, (struct sockaddr*) &serv_addr, len) == -1) {\n\t\tcerr << \"ERROR: Failed to bind socket\" << endl; \n\t\treturn -1;\n\t}\n\n\t\/\/ Get file request\n\tdo {\n\t\tn = recvfrom(sockfd, temp, 100, 0, \n\t\t\t(struct sockaddr*) &client_addr, &len);\n\t} while (n == -1);\n\n\tfor (int i = 0; i < strlen(temp); i++) {\n\t\tfilename += temp[i];\n\t}\n\n\tcout << \"Filename: \" << filename << endl;\n\n\t\/\/ Create initial ACK for file request\n\tinitial.type = false;\n\tinitial.seq_num = seq_num;\n\tinitial.packet_num = packet_num; \n\tinitial.last_packet = true;\n\tseq_num++;\t\t\t\t\/\/should we increment?\n\tpacket_num++; \t\t\t\/\/should we increment?\n\n\t\/\/ Send ACK with initial seq number 0\n\tsendto(sockfd, &initial, sizeof(initial), 0,\n\t\t(struct sockaddr*) &client_addr, len);\n\n\tostringstream response;\n\tifstream request(filename.c_str(), ios::in|ios::binary);\n\n\tif (request) {\n\t response << request.rdbuf();\n\t request.close(); \n\t buffer = response.str(); \n\t} else {\n\t\tcerr << \"ERROR: File not found\" << endl;\n\t\treturn -1;\n\t}\n\n\t\/\/ Split data into packets\n\tcurrent.last_packet = false;\n\tcurrent.type = true;\n\tfor (int i = 0; i < buffer.size(); i++) {\n\t\tcurrent.body[counter] = buffer[i];\n\t\tif (counter == MAX_PACKET_SIZE - 2) {\n\t\t\tcout << \"Packet has 999 bytes\" << endl;\n\t\t\tcurrent.body[MAX_PACKET_SIZE - 1] = '\\0';\n\t\t\tcurrent.seq_num = seq_num;\n\t\t\tcurrent.packet_num = packet_num; \n\t\t\tpackets.push_back(current);\n\n\t\t\tcounter = -1;\n\t\t\tseq_num += MAX_PACKET_SIZE;\n\t\t\tpacket_num++; \n\t\t}\n\t\tcounter++;\n\t}\n\n\tif (counter != 0) {\n\t\tcout << \"Last packet is smaller than max packet size\" << endl;\n\t\tcurrent.body[counter] = '\\0';\n\t\t\/\/ cout << \"Last packet data: \" << current.body << endl; \n\t\tcurrent.seq_num = seq_num;\n\t\tcurrent.packet_num = packet_num; \n\t\tcout << \"Last Packet seq_num: \" << current.seq_num << endl;\n\t\tcout << \"Last Packet packet_num: \" << current.packet_num << endl; \n\t\tcurrent.last_packet = true;\n\t\tpackets.push_back(current);\n\t\t\/\/seq_num++; why is this even here o.O\n\t\tpacket_num++; \n\t} else {\n\t\tpackets[packets.size() - 1].last_packet = true;\n\t}\n\n\tint base = 0;\n\tint next_packet_num = base + WINDOW_SIZE;\n\n\tcout << \"Number of packets: \" << packets.size() << endl;\n\t\/\/ Send initial packets\n\tfor (int i = 0; i < WINDOW_SIZE; i++) {\n\t\tcout << \"Data: \" << packets[i].body << endl;\n\t\tsendto(sockfd, &packets[i], sizeof(packets[i]), 0,\n\t\t\t(struct sockaddr*) &client_addr, len);\n\t}\n\n\twhile (true) {\n\t\t\/\/ Get a packet\n\t\tmessage received;\n\t\tn = recvfrom(sockfd, &received, sizeof(received), 0,\n\t\t\t(struct sockaddr*) &client_addr, &len);\n\t\tif (n == 0)\n\t\t\tcontinue;\t\/\/ No more messages\n\t\telse if (n < 0)\n\t\t\tbreak;\t\/\/ Error\n\n\n\t\t\/\/ TODO: Check corruption and randomly drop packets\n\n\t\tcout << \"Received ACK \" << received.seq_num << endl;\n\n\t\tif (received.packet_num >= base) {\n\t\t\t\/\/ Send up to window size\n\t\t\tbase = received.packet_num + 1;\n\t\t\tfor (int i = next_packet_num; i < base + WINDOW_SIZE && packets.size(); i++) {\n\t\t\t\tsendto(sockfd, &packets[i], sizeof(packets[i]), 0,\n\t\t\t\t\t(struct sockaddr*) &client_addr, len);\n\t\t\t}\n\t\t\tnext_packet_num = base + WINDOW_SIZE;\n\t\t}\n\t}\n\t\n}<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#ifndef INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX\n#define INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace rptui\n{\nclass OReportController;\n\/*************************************************************************\n|*\n|* Groups and Sorting dialog\n|*\n\\************************************************************************\/\nclass ODateTimeDialog : public ModalDialog\n{\n CheckBox* m_pDate;\n FixedText* m_pFTDateFormat;\n ListBox* m_pDateListBox;\n CheckBox* m_pTime;\n FixedText* m_pFTTimeFormat;\n ListBox* m_pTimeListBox;\n OKButton* m_pPB_OK;\n CancelButton* m_pPB_CANCEL;\n HelpButton* m_pPB_Help;\n\n\n svt::ControlDependencyManager m_aDateControlling;\n svt::ControlDependencyManager m_aTimeControlling;\n\n ::rptui::OReportController* m_pController;\n ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>\n m_xHoldAlive;\n ::com::sun::star::lang::Locale m_nLocale;\n\n \/** returns the frmat string\n *\n * \\param _nNumberFormatKey the number format key\n * \\param _xFormats\n * \\param _bTime\n * \\return\n *\/\n OUString getFormatStringByKey(::sal_Int32 _nNumberFormatKey,const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats>& _xFormats,bool _bTime);\n\n \/** returns the number format key\n @param _nNumberFormatIndex the number format index @see com::sun::star::i18n::NumberFormatIndex\n *\/\n sal_Int32 getFormatKey(sal_Bool _bDate) const;\n\n DECL_LINK( CBClickHdl, CheckBox* );\n ODateTimeDialog(const ODateTimeDialog&);\n void operator =(const ODateTimeDialog&);\n\n \/\/ fill methods\n void InsertEntry(sal_Int16 _nNumberFormatId);\npublic:\n ODateTimeDialog( Window* pParent\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xHoldAlive\n ,::rptui::OReportController* _pController);\n virtual ~ODateTimeDialog();\n virtual short Execute() SAL_OVERRIDE;\n};\n\n} \/\/ namespace rptui\n\n#endif \/\/ INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ncoverity#1210196 Uninitialized pointer field\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#ifndef INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX\n#define INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace rptui\n{\nclass OReportController;\n\/*************************************************************************\n|*\n|* Groups and Sorting dialog\n|*\n\\************************************************************************\/\nclass ODateTimeDialog : public ModalDialog\n{\n CheckBox* m_pDate;\n FixedText* m_pFTDateFormat;\n ListBox* m_pDateListBox;\n CheckBox* m_pTime;\n FixedText* m_pFTTimeFormat;\n ListBox* m_pTimeListBox;\n OKButton* m_pPB_OK;\n\n svt::ControlDependencyManager m_aDateControlling;\n svt::ControlDependencyManager m_aTimeControlling;\n\n ::rptui::OReportController* m_pController;\n ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>\n m_xHoldAlive;\n ::com::sun::star::lang::Locale m_nLocale;\n\n \/** returns the frmat string\n *\n * \\param _nNumberFormatKey the number format key\n * \\param _xFormats\n * \\param _bTime\n * \\return\n *\/\n OUString getFormatStringByKey(::sal_Int32 _nNumberFormatKey,const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats>& _xFormats,bool _bTime);\n\n \/** returns the number format key\n @param _nNumberFormatIndex the number format index @see com::sun::star::i18n::NumberFormatIndex\n *\/\n sal_Int32 getFormatKey(sal_Bool _bDate) const;\n\n DECL_LINK( CBClickHdl, CheckBox* );\n ODateTimeDialog(const ODateTimeDialog&);\n void operator =(const ODateTimeDialog&);\n\n \/\/ fill methods\n void InsertEntry(sal_Int16 _nNumberFormatId);\npublic:\n ODateTimeDialog( Window* pParent\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xHoldAlive\n ,::rptui::OReportController* _pController);\n virtual ~ODateTimeDialog();\n virtual short Execute() SAL_OVERRIDE;\n};\n\n} \/\/ namespace rptui\n\n#endif \/\/ INCLUDED_REPORTDESIGN_SOURCE_UI_INC_DATETIME_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ AUTOGENERATED, DO NOT EDIT\n\/\/\n#ifndef __OPENCV_OCL_CL_RUNTIME_HPP__\n#define __OPENCV_OCL_CL_RUNTIME_HPP__\n\n#ifdef HAVE_OPENCL\n\n#if defined(HAVE_OPENCL12)\n#include \"cl_runtime_opencl12.hpp\"\n#elif defined(HAVE_OPENCL11)\n#include \"cl_runtime_opencl11.hpp\"\n#else\n#error Invalid OpenCL configuration\n#endif\n\n#endif\n\n#endif \/\/ __OPENCV_OCL_CL_RUNTIME_HPP__\nremoved invalid comment#ifndef __OPENCV_OCL_CL_RUNTIME_HPP__\n#define __OPENCV_OCL_CL_RUNTIME_HPP__\n\n#ifdef HAVE_OPENCL\n\n#if defined(HAVE_OPENCL12)\n#include \"cl_runtime_opencl12.hpp\"\n#elif defined(HAVE_OPENCL11)\n#include \"cl_runtime_opencl11.hpp\"\n#else\n#error Invalid OpenCL configuration\n#endif\n\n#endif\n\n#endif \/\/ __OPENCV_OCL_CL_RUNTIME_HPP__\n<|endoftext|>"} {"text":"#include \"Stdafx.h\"\n#include \"BlurMeasure.h\"\n\nusing namespace std;\nusing namespace cv;\n\nnamespace ImageQuality\n{\n\tdouble BlurMeasure::BlurTest(array^ buffer)\n\t{\n\t\tMat image = ReadImage(buffer);\n\t\tresize(image, image, Size(512, 512));\n\n\t\tMat gray;\n\t\tcvtColor(image, gray, CV_BGR2GRAY);\n\n\t\tMat detected_edges;\n\t\tCanny(gray, detected_edges, 0.4, 0.4 * 3, 3);\n\n\t\tdouble maxval;\n\t\tdouble average = mean(detected_edges)[0];\n\t\tint* const maxIdx = (int*)malloc(sizeof(detected_edges));\n\n\t\tminMaxIdx(detected_edges, 0, &maxval, 0, maxIdx);\n\n\t\tdouble blurresult = average \/ maxval;\n\t\treturn blurresult;\n\t}\n\n\tMat BlurMeasure::ReadImage(array^ buffer)\n\t{\n\t\tpin_ptr px = &buffer[0];\n\t\tMat datax(1, buffer->Length, CV_8U, (void*)px, CV_AUTO_STEP);\n\t\treturn imdecode(datax, CV_LOAD_IMAGE_COLOR);\n\t}\n}Blur measure algorithm#include \"Stdafx.h\"\n#include \"BlurMeasure.h\"\n\nusing namespace std;\nusing namespace cv;\n\nnamespace ImageQuality\n{\n\tdouble BlurMeasure::BlurTest(array^ buffer)\n\t{\n\t\tMat image = ReadImage(buffer);\n\t\tresize(image, image, Size(512, 512));\n\n\t\tMat gray;\n\t\tcvtColor(image, gray, CV_BGR2GRAY);\n\n\t\tMat laplacian;\n\t\tLaplacian(gray, laplacian, CV_64F);\n\n\t\tMat mean, stddev;\n\t\tmeanStdDev(laplacian, mean, stddev);\n\t\tdouble val = stddev.at(0, 0);\n\t\treturn val * val;\n\t}\n\n\tMat BlurMeasure::ReadImage(array^ buffer)\n\t{\n\t\tpin_ptr px = &buffer[0];\n\t\tMat datax(1, buffer->Length, CV_8U, (void*)px, CV_AUTO_STEP);\n\t\treturn imdecode(datax, CV_LOAD_IMAGE_COLOR);\n\t}\n}<|endoftext|>"} {"text":"\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva\n\/\/ Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#ifndef ROSETTASTONE_TARGETING_HPP\n#define ROSETTASTONE_TARGETING_HPP\n\n#include \n\nnamespace RosettaStone::Generic\n{\n\/\/! Summons an minion on battlefield.\n\/\/! \\param player The player to summon an minion on battlefield.\n\/\/! \\param minion An minion to summon.\n\/\/! \\param fieldPos The position of minion to summon.\nvoid Summon(Player& player, Minion* minion, int fieldPos);\n} \/\/ namespace RosettaStone::Generic\n\n#endif \/\/ ROSETTASTONE_TARGETING_HPP\nfix: Correct LGTM issues\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva\n\/\/ Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#ifndef ROSETTASTONE_SUMMON_HPP\n#define ROSETTASTONE_SUMMON_HPP\n\n#include \n\nnamespace RosettaStone::Generic\n{\n\/\/! Summons an minion on battlefield.\n\/\/! \\param player The player to summon an minion on battlefield.\n\/\/! \\param minion An minion to summon.\n\/\/! \\param fieldPos The position of minion to summon.\nvoid Summon(Player& player, Minion* minion, int fieldPos);\n} \/\/ namespace RosettaStone::Generic\n\n#endif \/\/ ROSETTASTONE_SUMMON_HPP\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appmain.cxx,v $\n *\n * $Revision: 1.34 $\n *\n * last change: $Author: obo $ $Date: 2008-01-04 15:09:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n\/\/#define TF_NEWDESKTOP\n\n#define _SDINTERN_HXX\n\n#ifndef GCC\n#endif\n#include \n\n#ifndef _URLOBJ_HXX \/\/autogen\n#include \n#endif\n#ifndef _CSTITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _CONFIG_HXX\n#include \n#endif\n#ifndef _EHDL_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"sfxtypes.hxx\"\n#include \"appdata.hxx\"\n#include \n#include \n#include \"arrdecl.hxx\"\n#include \n#include \"sfxresid.hxx\"\n#include \n#include \n#include \"intro.hxx\"\n#include \n#include \n#include \n#include \n#include \"app.hrc\"\n#include \n#include \"workwin.hxx\"\n\n#ifdef UNX\n#define stricmp(a,b) strcmp(a,b)\n#endif\n\n\n\/\/===================================================================\n\nDBG_NAME(SfxAppMainNewMenu)\nDBG_NAME(SfxAppMainBmkMenu)\nDBG_NAME(SfxAppMainWizMenu)\nDBG_NAME(SfxAppMainOLEReg)\nDBG_NAME(SfxAppMainCHAOSReg)\n\n\/\/===================================================================\n\n#define SFX_TEMPNAMEBASE_DIR \"soffice.tmp\"\n#define SFX_KEY_TEMPNAMEBASE \"Temp-Dir\"\n\n\/\/===================================================================\n\n#ifdef TF_POOLABLE\nstatic SfxItemInfo __READONLY_DATA aItemInfos[] =\n{\n { 0, 0 }\n};\n#endif\n\n\/\/===================================================================\n\ntypedef Link* LinkPtr;\nSV_DECL_PTRARR(SfxInitLinkList, LinkPtr, 4, 4)\n\nTYPEINIT2(SfxApplication,SfxShell,SfxBroadcaster);\n\n\/\/--------------------------------------------------------------------\nvoid SfxApplication::Init\n(\n)\n\n\/* [Beschreibung]\n\n Diese virtuelle Methode wird vom SFx aus Application:a:Main() gerufen,\n bevor Execute() ausgef\"uhrt wird und\n - das Intro bereits angezeigt ist,\n - das Applikationsfenster exisitiert, aber noch hidden ist,\n - die Bindings bereits existieren (Controller sind anmeldbar),\n - der Ini- und Config-Manager bereits existiert,\n - die Standard-Controller bereits exisitieren,\n - die SFx-Shells ihre Interfaces bereits registriert haben.\n\n [Querverweise]\n \n \n*\/\n{\n#ifdef DDE_AVAILABLE\n#ifdef PRODUCT\n InitializeDde();\n#else\n if( !InitializeDde() )\n {\n ByteString aStr( \"Kein DDE-Service moeglich. Fehler: \" );\n if( GetDdeService() )\n aStr += GetDdeService()->GetError();\n else\n aStr += '?';\n DBG_ASSERT( sal_False, aStr.GetBuffer() )\n }\n#endif\n#endif\n}\n\n\/\/--------------------------------------------------------------------\n\nvoid SfxApplication::Exit()\n\n\/* [Beschreibung]\n\n Diese virtuelle Methode wird vom SFx aus Application::Main() gerufen,\n nachdem Execute() beendet ist und\n - die Konfiguration (SfxConfigManager) bereits gespeichert wurde,\n - die Fensterpostionen etc. in den SfxIniManager geschrieben wurden,\n - das Applikationsfenster noch existiert, aber hidden ist\n - s\"amtliche Dokumente und deren Views bereits geschlossen sind.\n - Dispatcher, Bindings etc. bereits zerst\"ort sind\n\n [Querverweise]\n \n*\/\n\n{\n}\n\n\/\/---------------------------------------------------------------------------\n\nvoid SfxApplication::PreInit( )\n{\n}\n\n\/\/---------------------------------------------------------------------------\nbool SfxApplication::InitLabelResMgr( const char* _pLabelPrefix, bool _bException )\n{\n bool bRet = false;\n \/\/ Label-DLL mit diversen Resourcen fuer OEM-Ver. etc. (Intro, Titel, About)\n DBG_ASSERT( _pLabelPrefix, \"Wrong initialisation!\" );\n if ( _pLabelPrefix )\n {\n \/\/ versuchen, die Label-DLL zu erzeugen\n pAppData_Impl->pLabelResMgr = CreateResManager( _pLabelPrefix );\n\n \/\/ keine separate Label-DLL vorhanden?\n if ( !pAppData_Impl->pLabelResMgr )\n {\n if ( _bException )\n {\n \/\/ maybe corrupted installation\n throw (::com::sun::star::uno::RuntimeException(\n ::rtl::OUString::createFromAscii(\"iso resource could not be loaded by SfxApplication\"),\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >()));\n }\n }\n else\n bRet = true;\n }\n\n return bRet;\n}\n\nvoid SfxApplication::Main( )\n{\n}\n\n\/\/-------------------------------------------------------------------------\n\nSfxFilterMatcher& SfxApplication::GetFilterMatcher()\n{\n if( !pAppData_Impl->pMatcher )\n {\n pAppData_Impl->pMatcher = new SfxFilterMatcher();\n URIHelper::SetMaybeFileHdl( STATIC_LINK(\n pAppData_Impl->pMatcher, SfxFilterMatcher, MaybeFileHdl_Impl ) );\n }\n return *pAppData_Impl->pMatcher;\n}\nINTEGRATION: CWS custommeta (1.33.70); FILE MERGED 2008\/02\/01 10:38:49 mst 1.33.70.2: RESYNC: (1.33-1.34); FILE MERGED 2008\/01\/25 14:19:26 mst 1.33.70.1: - sfx2\/inc\/sfx2\/{frmhtmlw.hxx,sfxhtml.hxx}, sfx2\/source\/appl\/{appbas.cxx,appcfg.cxx,appmain.cxx,appserv.cxx}, sfx2\/source\/bastyp\/{fltfnc.cxx,frmhtml.cxx}, sfx2\/source\/config\/evntconf.cxx, sfx2\/source\/doc\/new.cxx, sfx2\/source\/doc\/oleprops.cxx: + remove unneeded includes and assorted detritus\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appmain.cxx,v $\n *\n * $Revision: 1.35 $\n *\n * last change: $Author: obo $ $Date: 2008-02-26 15:01:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n\/\/#define TF_NEWDESKTOP\n\n#define _SDINTERN_HXX\n\n#include \n\n#ifndef _URLOBJ_HXX \/\/autogen\n#include \n#endif\n#ifndef _CSTITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _CONFIG_HXX\n#include \n#endif\n#ifndef _EHDL_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"sfxtypes.hxx\"\n#include \"appdata.hxx\"\n#include \n#include \n#include \"arrdecl.hxx\"\n#include \n#include \"sfxresid.hxx\"\n#include \n#include \n#include \"intro.hxx\"\n#include \n#include \n#include \n#include \"app.hrc\"\n#include \n#include \"workwin.hxx\"\n\n#ifdef UNX\n#define stricmp(a,b) strcmp(a,b)\n#endif\n\n\n\/\/===================================================================\n\nDBG_NAME(SfxAppMainNewMenu)\nDBG_NAME(SfxAppMainBmkMenu)\nDBG_NAME(SfxAppMainWizMenu)\nDBG_NAME(SfxAppMainOLEReg)\nDBG_NAME(SfxAppMainCHAOSReg)\n\n\/\/===================================================================\n\n#define SFX_TEMPNAMEBASE_DIR \"soffice.tmp\"\n#define SFX_KEY_TEMPNAMEBASE \"Temp-Dir\"\n\n\/\/===================================================================\n\n#ifdef TF_POOLABLE\nstatic SfxItemInfo __READONLY_DATA aItemInfos[] =\n{\n { 0, 0 }\n};\n#endif\n\n\/\/===================================================================\n\ntypedef Link* LinkPtr;\nSV_DECL_PTRARR(SfxInitLinkList, LinkPtr, 4, 4)\n\nTYPEINIT2(SfxApplication,SfxShell,SfxBroadcaster);\n\n\/\/--------------------------------------------------------------------\nvoid SfxApplication::Init\n(\n)\n\n\/* [Beschreibung]\n\n Diese virtuelle Methode wird vom SFx aus Application:a:Main() gerufen,\n bevor Execute() ausgef\"uhrt wird und\n - das Intro bereits angezeigt ist,\n - das Applikationsfenster exisitiert, aber noch hidden ist,\n - die Bindings bereits existieren (Controller sind anmeldbar),\n - der Ini- und Config-Manager bereits existiert,\n - die Standard-Controller bereits exisitieren,\n - die SFx-Shells ihre Interfaces bereits registriert haben.\n\n [Querverweise]\n \n \n*\/\n{\n#ifdef DDE_AVAILABLE\n#ifdef PRODUCT\n InitializeDde();\n#else\n if( !InitializeDde() )\n {\n ByteString aStr( \"Kein DDE-Service moeglich. Fehler: \" );\n if( GetDdeService() )\n aStr += GetDdeService()->GetError();\n else\n aStr += '?';\n DBG_ASSERT( sal_False, aStr.GetBuffer() )\n }\n#endif\n#endif\n}\n\n\/\/--------------------------------------------------------------------\n\nvoid SfxApplication::Exit()\n\n\/* [Beschreibung]\n\n Diese virtuelle Methode wird vom SFx aus Application::Main() gerufen,\n nachdem Execute() beendet ist und\n - die Konfiguration (SfxConfigManager) bereits gespeichert wurde,\n - die Fensterpostionen etc. in den SfxIniManager geschrieben wurden,\n - das Applikationsfenster noch existiert, aber hidden ist\n - s\"amtliche Dokumente und deren Views bereits geschlossen sind.\n - Dispatcher, Bindings etc. bereits zerst\"ort sind\n\n [Querverweise]\n \n*\/\n\n{\n}\n\n\/\/---------------------------------------------------------------------------\n\nvoid SfxApplication::PreInit( )\n{\n}\n\n\/\/---------------------------------------------------------------------------\nbool SfxApplication::InitLabelResMgr( const char* _pLabelPrefix, bool _bException )\n{\n bool bRet = false;\n \/\/ Label-DLL mit diversen Resourcen fuer OEM-Ver. etc. (Intro, Titel, About)\n DBG_ASSERT( _pLabelPrefix, \"Wrong initialisation!\" );\n if ( _pLabelPrefix )\n {\n \/\/ versuchen, die Label-DLL zu erzeugen\n pAppData_Impl->pLabelResMgr = CreateResManager( _pLabelPrefix );\n\n \/\/ keine separate Label-DLL vorhanden?\n if ( !pAppData_Impl->pLabelResMgr )\n {\n if ( _bException )\n {\n \/\/ maybe corrupted installation\n throw (::com::sun::star::uno::RuntimeException(\n ::rtl::OUString::createFromAscii(\"iso resource could not be loaded by SfxApplication\"),\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >()));\n }\n }\n else\n bRet = true;\n }\n\n return bRet;\n}\n\nvoid SfxApplication::Main( )\n{\n}\n\n\/\/-------------------------------------------------------------------------\n\nSfxFilterMatcher& SfxApplication::GetFilterMatcher()\n{\n if( !pAppData_Impl->pMatcher )\n {\n pAppData_Impl->pMatcher = new SfxFilterMatcher();\n URIHelper::SetMaybeFileHdl( STATIC_LINK(\n pAppData_Impl->pMatcher, SfxFilterMatcher, MaybeFileHdl_Impl ) );\n }\n return *pAppData_Impl->pMatcher;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inettbc.cxx,v $\n *\n * $Revision: 1.31 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:16:35 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"inettbc.hxx\"\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPLLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_\n#include \n#endif\n\n#ifndef _SFXENUMITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXCANCEL_HXX \/\/autogen\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_HISTORYOPTIONS_HXX\n#include \n#endif\n#ifndef SVTOOLS_FOLDER_RESTRICTION_HXX\n#include \n#endif\n#include \n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n#ifndef _VOS_THREAD_HXX \/\/autogen\n#include \n#endif\n#ifndef _VOS_MUTEX_HXX \/\/autogen\n#include \n#endif\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"sfx.hrc\"\n#include \"dispatch.hxx\"\n#include \"viewfrm.hxx\"\n#include \"objsh.hxx\"\n#include \"referers.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"helper.hxx\"\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::task;\n\n\/\/***************************************************************************\n\/\/ SfxURLToolBoxControl_Impl\n\/\/***************************************************************************\n\nSFX_IMPL_TOOLBOX_CONTROL(SfxURLToolBoxControl_Impl,SfxStringItem)\n\nSfxURLToolBoxControl_Impl::SfxURLToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox )\n : SfxToolBoxControl( nSlotId, nId, rBox ),\n pAccExec( 0 )\n{\n addStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:CurrentURL\" )));\n}\n\nSfxURLToolBoxControl_Impl::~SfxURLToolBoxControl_Impl()\n{\n delete pAccExec;\n}\n\nSvtURLBox* SfxURLToolBoxControl_Impl::GetURLBox() const\n{\n return (SvtURLBox*)GetToolBox().GetItemWindow( GetId() );\n}\n\n\/\/***************************************************************************\n\nvoid SfxURLToolBoxControl_Impl::OpenURL( const String& rName, BOOL bNew ) const\n{\n String aName;\n String aFilter;\n String aOptions;\n\n INetURLObject aObj( rName );\n if ( aObj.GetProtocol() == INET_PROT_NOT_VALID )\n {\n String aBaseURL = GetURLBox()->GetBaseURL();\n aName = SvtURLBox::ParseSmart( rName, aBaseURL, SvtPathOptions().GetWorkPath() );\n }\n else\n aName = rName;\n\n if ( !aName.Len() )\n return;\n\n Reference< XDispatchProvider > xDispatchProvider( getFrameInterface(), UNO_QUERY );\n if ( xDispatchProvider.is() && m_xServiceManager.is() )\n {\n URL aTargetURL;\n ::rtl::OUString aTarget( ::rtl::OUString::createFromAscii( \"_default\" ));\n\n aTargetURL.Complete = aName;\n\n getURLTransformer()->parseStrict( aTargetURL );\n Reference< XDispatch > xDispatch = xDispatchProvider->queryDispatch( aTargetURL, aTarget, 0 );\n if ( xDispatch.is() )\n {\n Sequence< PropertyValue > aArgs( 2 );\n aArgs[0].Name = OUString::createFromAscii( \"Referer\" );\n aArgs[0].Value = makeAny( ::rtl::OUString::createFromAscii( SFX_REFERER_USER ));\n aArgs[1].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( \"FileName\" ));\n aArgs[1].Value = makeAny( OUString( aName ));\n\n if ( aFilter.Len() )\n {\n aArgs.realloc( 4 );\n aArgs[2].Name = OUString::createFromAscii( \"FilterOptions\" );\n aArgs[2].Value = makeAny( OUString( aOptions ));\n aArgs[3].Name = OUString::createFromAscii( \"FilterName\" );\n aArgs[3].Value = makeAny( OUString( aFilter ));\n }\n\n SfxURLToolBoxControl_Impl::ExecuteInfo* pExecuteInfo = new SfxURLToolBoxControl_Impl::ExecuteInfo;\n pExecuteInfo->xDispatch = xDispatch;\n pExecuteInfo->aTargetURL = aTargetURL;\n pExecuteInfo->aArgs = aArgs;\n Application::PostUserEvent( STATIC_LINK( 0, SfxURLToolBoxControl_Impl, ExecuteHdl_Impl), pExecuteInfo );\n }\n }\n}\n\n\/\/--------------------------------------------------------------------\n\nIMPL_STATIC_LINK( SfxURLToolBoxControl_Impl, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )\n{\n try\n {\n \/\/ Asynchronous execution as this can lead to our own destruction!\n \/\/ Framework can recycle our current frame and the layout manager disposes all user interface\n \/\/ elements if a component gets detached from its frame!\n pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );\n }\n catch ( Exception& )\n {\n }\n\n delete pExecuteInfo;\n return 0;\n}\n\n\nWindow* SfxURLToolBoxControl_Impl::CreateItemWindow( Window* pParent )\n{\n SvtURLBox* pURLBox = new SvtURLBox( pParent );\n pURLBox->SetOpenHdl( LINK( this, SfxURLToolBoxControl_Impl, OpenHdl ) );\n pURLBox->SetSelectHdl( LINK( this, SfxURLToolBoxControl_Impl, SelectHdl ) );\n\n return pURLBox;\n}\n\nIMPL_LINK( SfxURLToolBoxControl_Impl, SelectHdl, void*, pVoid )\n{\n SvtURLBox* pURLBox = GetURLBox();\n String aName( pURLBox->GetURL() );\n\n if ( !pURLBox->IsTravelSelect() && aName.Len() )\n OpenURL( aName, FALSE );\n\n return 1L;\n}\n\nIMPL_LINK( SfxURLToolBoxControl_Impl, OpenHdl, void*, pVoid )\n{\n SvtURLBox* pURLBox = GetURLBox();\n OpenURL( pURLBox->GetURL(), pURLBox->IsCtrlOpen() );\n\n if ( m_xServiceManager.is() )\n {\n Reference< XFramesSupplier > xDesktop( m_xServiceManager->createInstance(\n OUString::createFromAscii( \"com.sun.star.frame.Desktop\" )),\n UNO_QUERY );\n Reference< XFrame > xFrame( xDesktop->getActiveFrame(), UNO_QUERY );\n if ( xFrame.is() )\n {\n Window* pWin = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );\n if ( pWin )\n {\n pWin->GrabFocus();\n pWin->ToTop( TOTOP_RESTOREWHENMIN );\n }\n }\n }\n\n return 1L;\n}\n\nIMPL_LINK( SfxURLToolBoxControl_Impl, WindowEventListener, VclSimpleEvent*, pEvent )\n{\n if ( pAccExec &&\n pEvent &&\n pEvent->ISA( VclWindowEvent ) &&\n ( pEvent->GetId() == VCLEVENT_WINDOW_KEYINPUT ))\n {\n VclWindowEvent* pWinEvent = static_cast< VclWindowEvent* >( pEvent );\n KeyEvent* pKeyEvent = static_cast< KeyEvent* >( pWinEvent->GetData() );\n\n pAccExec->execute( pKeyEvent->GetKeyCode() );\n }\n\n return 1;\n}\n\n\/\/***************************************************************************\n\nvoid SfxURLToolBoxControl_Impl::StateChanged\n(\n USHORT nSID,\n SfxItemState eState,\n const SfxPoolItem* pState\n)\n{\n if ( nSID == SID_OPENURL )\n {\n \/\/ Disable URL box if command is disabled #111014#\n GetURLBox()->Enable( SFX_ITEM_DISABLED != eState );\n }\n\n if ( GetURLBox()->IsEnabled() )\n {\n if( nSID == SID_FOCUSURLBOX )\n {\n if ( GetURLBox()->IsVisible() )\n GetURLBox()->GrabFocus();\n }\n else if ( !GetURLBox()->IsModified() && SFX_ITEM_AVAILABLE == eState )\n {\n SvtURLBox* pURLBox = GetURLBox();\n pURLBox->Clear();\n\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > lList = SvtHistoryOptions().GetList(eHISTORY);\n for (sal_Int32 i=0; i lProps = lList[i];\n for (sal_Int32 p=0; p>=sURL) || !sURL.getLength())\n continue;\n\n INetURLObject aURL ( sURL );\n String sMainURL( aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET ) );\n String sFile;\n\n if (::utl::LocalFileHelper::ConvertURLToSystemPath(sMainURL,sFile))\n pURLBox->InsertEntry(sFile);\n else\n pURLBox->InsertEntry(sMainURL);\n }\n }\n\n const SfxStringItem *pURL = PTR_CAST(SfxStringItem,pState);\n String aRep( pURL->GetValue() );\n INetURLObject aURL( aRep );\n INetProtocol eProt = aURL.GetProtocol();\n if ( eProt == INET_PROT_FILE )\n {\n pURLBox->SetText( aURL.PathToFileName() );\n }\n else\n pURLBox->SetText( aURL.GetURLNoPass() );\n }\n }\n}\n\n\/\/***************************************************************************\n\/\/ SfxCancelToolBoxControl_Impl\n\/\/***************************************************************************\n\nSFX_IMPL_TOOLBOX_CONTROL(SfxCancelToolBoxControl_Impl,SfxBoolItem)\n\n\/\/***************************************************************************\n\nSfxCancelToolBoxControl_Impl::SfxCancelToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox ) :\n SfxToolBoxControl( nSlotId, nId, rBox )\n{\n}\n\n\/\/***************************************************************************\n\nSfxPopupWindowType SfxCancelToolBoxControl_Impl::GetPopupWindowType() const\n{\n return SFX_POPUPWINDOW_ONTIMEOUT;\n}\n\n\/\/***************************************************************************\n\nSfxPopupWindow* SfxCancelToolBoxControl_Impl::CreatePopupWindow()\n{\n PopupMenu aMenu;\n BOOL bExecute = FALSE, bSeparator = FALSE;\n USHORT nIndex = 1;\n for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();\n pCancelMgr;\n pCancelMgr = pCancelMgr->GetParent() )\n {\n for ( USHORT n=0; nGetCancellableCount(); ++n )\n {\n if ( !n && bSeparator )\n {\n aMenu.InsertSeparator();\n bSeparator = FALSE;\n }\n String aItemText = pCancelMgr->GetCancellable(n)->GetTitle();\n if ( aItemText.Len() > 50 )\n {\n aItemText.Erase( 48 );\n aItemText += DEFINE_CONST_UNICODE(\"...\");\n }\n aMenu.InsertItem( nIndex++, aItemText );\n bExecute = TRUE;\n bSeparator = TRUE;\n }\n }\n\n ToolBox& rToolBox = GetToolBox();\n USHORT nId = bExecute ? nId = aMenu.Execute( &rToolBox, rToolBox.GetPointerPosPixel() ) : 0;\n GetToolBox().EndSelection();\n\/\/ ClearCache();\n\/\/ UpdateSlot();\n if ( nId )\n {\n String aSearchText = aMenu.GetItemText(nId);\n for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();\n pCancelMgr;\n pCancelMgr = pCancelMgr->GetParent() )\n {\n for ( USHORT n = 0; n < pCancelMgr->GetCancellableCount(); ++n )\n {\n SfxCancellable *pCancel = pCancelMgr->GetCancellable(n);\n String aItemText = pCancel->GetTitle();\n if ( aItemText.Len() > 50 )\n {\n aItemText.Erase( 48 );\n aItemText += DEFINE_CONST_UNICODE(\"...\");\n }\n\n if ( aItemText == aSearchText )\n {\n pCancel->Cancel();\n return 0;\n }\n }\n }\n\n }\n\n return 0;\n}\n\n\/\/***************************************************************************\n\nvoid SfxCancelToolBoxControl_Impl::StateChanged\n(\n USHORT nSID,\n SfxItemState eState,\n const SfxPoolItem* pState\n)\n{\n SfxVoidItem aVoidItem( nSID );\n \/\/SfxToolBoxControl::StateChanged( nSID, eState, pState ? &aVoidItem : 0 );\n SfxToolBoxControl::StateChanged( nSID, eState, pState );\n}\nINTEGRATION: CWS warnings01 (1.31.64); FILE MERGED 2005\/11\/28 16:16:37 cd 1.31.64.1: #i55991# Remove warnings\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inettbc.cxx,v $\n *\n * $Revision: 1.32 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 22:35:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"inettbc.hxx\"\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPLLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_\n#include \n#endif\n\n#ifndef _SFXENUMITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXCANCEL_HXX \/\/autogen\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_HISTORYOPTIONS_HXX\n#include \n#endif\n#ifndef SVTOOLS_FOLDER_RESTRICTION_HXX\n#include \n#endif\n#include \n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n#ifndef _VOS_THREAD_HXX \/\/autogen\n#include \n#endif\n#ifndef _VOS_MUTEX_HXX \/\/autogen\n#include \n#endif\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"sfx.hrc\"\n#include \"dispatch.hxx\"\n#include \"viewfrm.hxx\"\n#include \"objsh.hxx\"\n#include \"referers.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"helper.hxx\"\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::task;\n\n\/\/***************************************************************************\n\/\/ SfxURLToolBoxControl_Impl\n\/\/***************************************************************************\n\nSFX_IMPL_TOOLBOX_CONTROL(SfxURLToolBoxControl_Impl,SfxStringItem)\n\nSfxURLToolBoxControl_Impl::SfxURLToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox )\n : SfxToolBoxControl( nSlotId, nId, rBox ),\n pAccExec( 0 )\n{\n addStatusListener( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:CurrentURL\" )));\n}\n\nSfxURLToolBoxControl_Impl::~SfxURLToolBoxControl_Impl()\n{\n delete pAccExec;\n}\n\nSvtURLBox* SfxURLToolBoxControl_Impl::GetURLBox() const\n{\n return (SvtURLBox*)GetToolBox().GetItemWindow( GetId() );\n}\n\n\/\/***************************************************************************\n\nvoid SfxURLToolBoxControl_Impl::OpenURL( const String& rName, BOOL \/*bNew*\/ ) const\n{\n String aName;\n String aFilter;\n String aOptions;\n\n INetURLObject aObj( rName );\n if ( aObj.GetProtocol() == INET_PROT_NOT_VALID )\n {\n String aBaseURL = GetURLBox()->GetBaseURL();\n aName = SvtURLBox::ParseSmart( rName, aBaseURL, SvtPathOptions().GetWorkPath() );\n }\n else\n aName = rName;\n\n if ( !aName.Len() )\n return;\n\n Reference< XDispatchProvider > xDispatchProvider( getFrameInterface(), UNO_QUERY );\n if ( xDispatchProvider.is() && m_xServiceManager.is() )\n {\n URL aTargetURL;\n ::rtl::OUString aTarget( ::rtl::OUString::createFromAscii( \"_default\" ));\n\n aTargetURL.Complete = aName;\n\n getURLTransformer()->parseStrict( aTargetURL );\n Reference< XDispatch > xDispatch = xDispatchProvider->queryDispatch( aTargetURL, aTarget, 0 );\n if ( xDispatch.is() )\n {\n Sequence< PropertyValue > aArgs( 2 );\n aArgs[0].Name = OUString::createFromAscii( \"Referer\" );\n aArgs[0].Value = makeAny( ::rtl::OUString::createFromAscii( SFX_REFERER_USER ));\n aArgs[1].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( \"FileName\" ));\n aArgs[1].Value = makeAny( OUString( aName ));\n\n if ( aFilter.Len() )\n {\n aArgs.realloc( 4 );\n aArgs[2].Name = OUString::createFromAscii( \"FilterOptions\" );\n aArgs[2].Value = makeAny( OUString( aOptions ));\n aArgs[3].Name = OUString::createFromAscii( \"FilterName\" );\n aArgs[3].Value = makeAny( OUString( aFilter ));\n }\n\n SfxURLToolBoxControl_Impl::ExecuteInfo* pExecuteInfo = new SfxURLToolBoxControl_Impl::ExecuteInfo;\n pExecuteInfo->xDispatch = xDispatch;\n pExecuteInfo->aTargetURL = aTargetURL;\n pExecuteInfo->aArgs = aArgs;\n Application::PostUserEvent( STATIC_LINK( 0, SfxURLToolBoxControl_Impl, ExecuteHdl_Impl), pExecuteInfo );\n }\n }\n}\n\n\/\/--------------------------------------------------------------------\n\nIMPL_STATIC_LINK_NOINSTANCE( SfxURLToolBoxControl_Impl, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )\n{\n try\n {\n \/\/ Asynchronous execution as this can lead to our own destruction!\n \/\/ Framework can recycle our current frame and the layout manager disposes all user interface\n \/\/ elements if a component gets detached from its frame!\n pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );\n }\n catch ( Exception& )\n {\n }\n\n delete pExecuteInfo;\n return 0;\n}\n\n\nWindow* SfxURLToolBoxControl_Impl::CreateItemWindow( Window* pParent )\n{\n SvtURLBox* pURLBox = new SvtURLBox( pParent );\n pURLBox->SetOpenHdl( LINK( this, SfxURLToolBoxControl_Impl, OpenHdl ) );\n pURLBox->SetSelectHdl( LINK( this, SfxURLToolBoxControl_Impl, SelectHdl ) );\n\n return pURLBox;\n}\n\nIMPL_LINK( SfxURLToolBoxControl_Impl, SelectHdl, void*, EMPTYARG )\n{\n SvtURLBox* pURLBox = GetURLBox();\n String aName( pURLBox->GetURL() );\n\n if ( !pURLBox->IsTravelSelect() && aName.Len() )\n OpenURL( aName, FALSE );\n\n return 1L;\n}\n\nIMPL_LINK( SfxURLToolBoxControl_Impl, OpenHdl, void*, EMPTYARG )\n{\n SvtURLBox* pURLBox = GetURLBox();\n OpenURL( pURLBox->GetURL(), pURLBox->IsCtrlOpen() );\n\n if ( m_xServiceManager.is() )\n {\n Reference< XFramesSupplier > xDesktop( m_xServiceManager->createInstance(\n OUString::createFromAscii( \"com.sun.star.frame.Desktop\" )),\n UNO_QUERY );\n Reference< XFrame > xFrame( xDesktop->getActiveFrame(), UNO_QUERY );\n if ( xFrame.is() )\n {\n Window* pWin = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );\n if ( pWin )\n {\n pWin->GrabFocus();\n pWin->ToTop( TOTOP_RESTOREWHENMIN );\n }\n }\n }\n\n return 1L;\n}\n\nIMPL_LINK( SfxURLToolBoxControl_Impl, WindowEventListener, VclSimpleEvent*, pEvent )\n{\n if ( pAccExec &&\n pEvent &&\n pEvent->ISA( VclWindowEvent ) &&\n ( pEvent->GetId() == VCLEVENT_WINDOW_KEYINPUT ))\n {\n VclWindowEvent* pWinEvent = static_cast< VclWindowEvent* >( pEvent );\n KeyEvent* pKeyEvent = static_cast< KeyEvent* >( pWinEvent->GetData() );\n\n pAccExec->execute( pKeyEvent->GetKeyCode() );\n }\n\n return 1;\n}\n\n\/\/***************************************************************************\n\nvoid SfxURLToolBoxControl_Impl::StateChanged\n(\n USHORT nSID,\n SfxItemState eState,\n const SfxPoolItem* pState\n)\n{\n if ( nSID == SID_OPENURL )\n {\n \/\/ Disable URL box if command is disabled #111014#\n GetURLBox()->Enable( SFX_ITEM_DISABLED != eState );\n }\n\n if ( GetURLBox()->IsEnabled() )\n {\n if( nSID == SID_FOCUSURLBOX )\n {\n if ( GetURLBox()->IsVisible() )\n GetURLBox()->GrabFocus();\n }\n else if ( !GetURLBox()->IsModified() && SFX_ITEM_AVAILABLE == eState )\n {\n SvtURLBox* pURLBox = GetURLBox();\n pURLBox->Clear();\n\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > lList = SvtHistoryOptions().GetList(eHISTORY);\n for (sal_Int32 i=0; i lProps = lList[i];\n for (sal_Int32 p=0; p>=sURL) || !sURL.getLength())\n continue;\n\n INetURLObject aURL ( sURL );\n String sMainURL( aURL.GetMainURL( INetURLObject::DECODE_WITH_CHARSET ) );\n String sFile;\n\n if (::utl::LocalFileHelper::ConvertURLToSystemPath(sMainURL,sFile))\n pURLBox->InsertEntry(sFile);\n else\n pURLBox->InsertEntry(sMainURL);\n }\n }\n\n const SfxStringItem *pURL = PTR_CAST(SfxStringItem,pState);\n String aRep( pURL->GetValue() );\n INetURLObject aURL( aRep );\n INetProtocol eProt = aURL.GetProtocol();\n if ( eProt == INET_PROT_FILE )\n {\n pURLBox->SetText( aURL.PathToFileName() );\n }\n else\n pURLBox->SetText( aURL.GetURLNoPass() );\n }\n }\n}\n\n\/\/***************************************************************************\n\/\/ SfxCancelToolBoxControl_Impl\n\/\/***************************************************************************\n\nSFX_IMPL_TOOLBOX_CONTROL(SfxCancelToolBoxControl_Impl,SfxBoolItem)\n\n\/\/***************************************************************************\n\nSfxCancelToolBoxControl_Impl::SfxCancelToolBoxControl_Impl( USHORT nSlotId, USHORT nId, ToolBox& rBox ) :\n SfxToolBoxControl( nSlotId, nId, rBox )\n{\n}\n\n\/\/***************************************************************************\n\nSfxPopupWindowType SfxCancelToolBoxControl_Impl::GetPopupWindowType() const\n{\n return SFX_POPUPWINDOW_ONTIMEOUT;\n}\n\n\/\/***************************************************************************\n\nSfxPopupWindow* SfxCancelToolBoxControl_Impl::CreatePopupWindow()\n{\n PopupMenu aMenu;\n BOOL bExecute = FALSE, bSeparator = FALSE;\n USHORT nIndex = 1;\n for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();\n pCancelMgr;\n pCancelMgr = pCancelMgr->GetParent() )\n {\n for ( USHORT n=0; nGetCancellableCount(); ++n )\n {\n if ( !n && bSeparator )\n {\n aMenu.InsertSeparator();\n bSeparator = FALSE;\n }\n String aItemText = pCancelMgr->GetCancellable(n)->GetTitle();\n if ( aItemText.Len() > 50 )\n {\n aItemText.Erase( 48 );\n aItemText += DEFINE_CONST_UNICODE(\"...\");\n }\n aMenu.InsertItem( nIndex++, aItemText );\n bExecute = TRUE;\n bSeparator = TRUE;\n }\n }\n\n ToolBox& rToolBox = GetToolBox();\n USHORT nId = bExecute ? nId = aMenu.Execute( &rToolBox, rToolBox.GetPointerPosPixel() ) : 0;\n GetToolBox().EndSelection();\n\/\/ ClearCache();\n\/\/ UpdateSlot();\n if ( nId )\n {\n String aSearchText = aMenu.GetItemText(nId);\n for ( SfxCancelManager *pCancelMgr = SfxViewFrame::Current()->GetTopViewFrame()->GetCancelManager();\n pCancelMgr;\n pCancelMgr = pCancelMgr->GetParent() )\n {\n for ( USHORT n = 0; n < pCancelMgr->GetCancellableCount(); ++n )\n {\n SfxCancellable *pCancel = pCancelMgr->GetCancellable(n);\n String aItemText = pCancel->GetTitle();\n if ( aItemText.Len() > 50 )\n {\n aItemText.Erase( 48 );\n aItemText += DEFINE_CONST_UNICODE(\"...\");\n }\n\n if ( aItemText == aSearchText )\n {\n pCancel->Cancel();\n return 0;\n }\n }\n }\n\n }\n\n return 0;\n}\n\n\/\/***************************************************************************\n\nvoid SfxCancelToolBoxControl_Impl::StateChanged\n(\n USHORT nSID,\n SfxItemState eState,\n const SfxPoolItem* pState\n)\n{\n SfxVoidItem aVoidItem( nSID );\n \/\/SfxToolBoxControl::StateChanged( nSID, eState, pState ? &aVoidItem : 0 );\n SfxToolBoxControl::StateChanged( nSID, eState, pState );\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"ch_frb_io.hpp\"\n\n#include \"assembled_chunk_msgpack.hpp\"\n\n\nusing namespace std;\nusing namespace ch_frb_io;\n\nint main(int argc, char **argv)\n{\n \/*\n cout << \"Warning: this will create a ~100 MB file in the current directory!\\n\"\n << \"If this is OK press return. If not, press control-C!\\n\"\n << \"I AM WAITING, HUMAN: \"\n << flush;\n string dummy;\n getline(cin, dummy);\n *\/\n\n uint64_t beam_id = 42;\n int nupfreq = 16;\n int nt_per_packet = 16;\n int fpga_counts_per_sample = 400;\n uint64_t ichunk = 1000;\n\n std::random_device rd;\n std::mt19937 rng(rd());\n\n shared_ptr chunk = assembled_chunk::make(beam_id, nupfreq, nt_per_packet, fpga_counts_per_sample, ichunk);\n chunk->randomize(rng);\n\n \/*\n const char *filename = \"test_assembled_chunk.hdf5\";\n chunk->write_hdf5_file(string(filename));\n *\/\n\n chunk->msgpack_bitshuffle = true;\n string fn = \"test_assembled_chunk.msgpack\";\n chunk->write_msgpack_file(fn);\n cout << \"Wrote to \" << fn << endl;\n\n shared_ptr inchunk = assembled_chunk::read_msgpack_file(fn);\n cout << \"Read \" << inchunk << endl;\n if (memcmp(inchunk->data, chunk->data, chunk->ndata)) {\n cout << \"MISMATCH in data\" << endl;\n }\n\n \/\/ Now fill with constant values and see that it compresses\n memset(chunk->data, 42, chunk->ndata);\n\n fn = \"test_assembled_chunk_2.msgpack\";\n chunk->write_msgpack_file(fn);\n cout << \"Wrote to \" << fn << endl;\n\n shared_ptr inchunk2 = assembled_chunk::read_msgpack_file(fn);\n cout << \"Read \" << inchunk2 << endl;\n if (memcmp(inchunk2->data, chunk->data, chunk->ndata)) {\n cout << \"MISMATCH in data 2\" << endl;\n }\n\n\n\n return 0;\n}\nadd test code to write out downsampled assembled_chunks.#include \n#include \n#include \"ch_frb_io.hpp\"\n\n#include \"assembled_chunk_msgpack.hpp\"\n\n#include \"ch_frb_io_internals.hpp\"\n\n\nusing namespace std;\nusing namespace ch_frb_io;\n\nint main(int argc, char **argv)\n{\n \/*\n cout << \"Warning: this will create a ~100 MB file in the current directory!\\n\"\n << \"If this is OK press return. If not, press control-C!\\n\"\n << \"I AM WAITING, HUMAN: \"\n << flush;\n string dummy;\n getline(cin, dummy);\n *\/\n\n uint64_t beam_id = 42;\n int nupfreq = 16;\n int nt_per_packet = 16;\n int fpga_counts_per_sample = 400;\n uint64_t ichunk = 1000;\n\n std::random_device rd;\n std::mt19937 rng(rd());\n\n unique_ptr chunk = assembled_chunk::make(beam_id, nupfreq, nt_per_packet, fpga_counts_per_sample, ichunk);\n chunk->randomize(rng);\n\n \/*\n const char *filename = \"test_assembled_chunk.hdf5\";\n chunk->write_hdf5_file(string(filename));\n *\/\n\n chunk->msgpack_bitshuffle = true;\n string fn = \"test_assembled_chunk.msgpack\";\n chunk->write_msgpack_file(fn);\n cout << \"Wrote to \" << fn << endl;\n\n shared_ptr inchunk = assembled_chunk::read_msgpack_file(fn);\n \/\/cout << \"Read \" << inchunk << endl;\n if (memcmp(inchunk->data, chunk->data, chunk->ndata)) {\n cout << \"MISMATCH in data\" << endl;\n }\n\n \/\/ Now fill with constant values and see that it compresses\n memset(chunk->data, 42, chunk->ndata);\n\n fn = \"test_assembled_chunk_2.msgpack\";\n chunk->write_msgpack_file(fn);\n cout << \"Wrote to \" << fn << endl;\n\n shared_ptr inchunk2 = assembled_chunk::read_msgpack_file(fn);\n \/\/cout << \"Read \" << inchunk2 << endl;\n if (memcmp(inchunk2->data, chunk->data, chunk->ndata)) {\n cout << \"MISMATCH in data 2\" << endl;\n }\n\n\n unique_ptr uchunk2 = assembled_chunk::make(beam_id, nupfreq, nt_per_packet, fpga_counts_per_sample, ichunk+1);\n\n assembled_chunk* chunk2 = uchunk2.get();\n assembled_chunk* chunk1 = chunk.get();\n\n \/\/ Set up both chunk1 and chunk2 to contain ramps.\n\n for (int i=0; inscales; i++) {\n chunk1->offsets[i] = uniform_rand(rng, 0, 10);\n chunk1->scales [i] = uniform_rand(rng, 1, 2);\n }\n for (int i=0; inscales; i++) {\n chunk2->offsets[i] = uniform_rand(rng, 0, 10);\n chunk2->scales [i] = uniform_rand(rng, 1, 2);\n }\n\n for (int i=0; inupfreq; i++) {\n for (int j=0; jnupfreq) * chunk1->nt_coarse +\n (j \/ nt_per_packet));\n float offset = chunk1->offsets[k];\n float scale = chunk1->scales [k];\n\n float fi = (float)i \/ (float)(constants::nfreq_coarse_tot * chunk1->nupfreq);\n float fj = (float)j \/ (float)constants::nt_per_assembled_chunk;\n float val = 20 + fi * 25 + fj * 50;\n\n chunk1->data[i * constants::nt_per_assembled_chunk + j] = (val - offset) \/ scale;\n\n offset = chunk2->offsets[k];\n scale = chunk2->scales [k];\n\n val = 20 + fi * 25 + (fj+1) * 50;\n chunk2->data[i * constants::nt_per_assembled_chunk + j] = (val - offset) \/ scale;\n }\n }\n\n chunk1->write_msgpack_file(\"test-chunk1.msgpack\");\n chunk2->write_msgpack_file(\"test-chunk2.msgpack\");\n\n assembled_chunk* chunk3 = assembled_chunk::downsample(NULL, chunk1, chunk2);\n chunk3->write_msgpack_file(\"test-chunk3.msgpack\");\n\n float* intensity = (float*)malloc(chunk1->ndata * sizeof(float));\n float* weight = (float*)malloc(chunk1->ndata * sizeof(float));\n\n chunk1->decode(intensity, weight, constants::nt_per_assembled_chunk);\n\n FILE* f = fopen(\"chunk1-decoded.raw\", \"w\");\n fwrite(intensity, 1, chunk1->ndata * sizeof(float), f);\n fclose(f);\n\n chunk2->decode(intensity, weight, constants::nt_per_assembled_chunk);\n\n f = fopen(\"chunk2-decoded.raw\", \"w\");\n fwrite(intensity, 1, chunk1->ndata * sizeof(float), f);\n fclose(f);\n\n chunk3->decode(intensity, weight, constants::nt_per_assembled_chunk);\n f = fopen(\"chunk3-decoded.raw\", \"w\");\n fwrite(intensity, 1, chunk1->ndata * sizeof(float), f);\n fclose(f);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ RUN: cat %s | %cling -Xclang -verify -I%p\n\/\/ XFAIL: vg\n\/\/ We expect for now this to fail, because the access to the invalid memory comes\n\/\/ from the fact that we invalidate the included file cache and when we are in\n\/\/ verify mode the verifier notifies about errors at the end of the source file.\n\/\/\n\/\/ Tests the ChainedConsumer's ability to recover from errors. .x produces \n\/\/ #include \\\"CannotDotX.h\\\" \\n void wrapper() {CannotDotX();}, which causes\n\/\/ a TagDecl to be passed trough the consumers. This TagDecl is caught twice by\n\/\/ the ChainedConsumer and cached is the queue of incoming declaration twice.\n\/\/ If we encounter error the ChainedConsumer shouldn't try to remove the \n\/\/ declaration twice and this test makes sure of that.\n\n.x CannotDotX.h() \/\/ expected-error {{use of undeclared identifier 'CannotDotX'}} \n.x CannotDotX.h() \/\/ expected-error {{use of undeclared identifier 'CannotDotX'}}\n\n \/\/ Uses a bug in the implementation of .L, which must be fixed soon.\n \/\/ Exposes another issue with the VerifyDiagnosticConsumer in the context of \n \/\/ cling. The first .L shouldn't cause errors . However when using the\n \/\/ preprocessor most probably we lose track of the errors source locations\n \/\/ and files.\n.L CannotDotX.h \"\/\/ expected-error {{redefinition of 'MyClass'}} expected-error {{expected member name or ';' after declaration specifiers}} expected-node {{previous definition is here}}\n\n\n.L CannotDotX.h\n\n.q\nDo not issue error in case: .x MyFile() - where no string is between the parenthesis.\/\/ RUN: cat %s | %cling -Xclang -verify -I%p\n\/\/ XFAIL: vg\n.x CannotDotX.h() \/\/ expected-error {{use of undeclared identifier 'CannotDotX'}} \n.x CannotDotX.h() \/\/ expected-error {{use of undeclared identifier 'CannotDotX'}}\n\n \/\/ Uses a bug in the implementation of .L, which must be fixed soon.\n \/\/ Exposes another issue with the VerifyDiagnosticConsumer in the context of \n \/\/ cling. The first .L shouldn't cause errors . However when using the\n \/\/ preprocessor most probably we lose track of the errors source locations\n \/\/ and files.\n.L CannotDotX.h \"\/\/ expected-error {{redefinition of 'MyClass'}} expected-error {{expected member name or ';' after declaration specifiers}} expected-node {{previous definition is here}}\n\n\n.L CannotDotX.h\n\n.q\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Reaper\n\/\/\/\n\/\/\/ Copyright (c) 2015-2020 Thibault Schueller\n\/\/\/ This file is distributed under the MIT License\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"common\/DebugLog.h\"\n#include \"common\/ReaperRoot.h\"\n\n#include \"renderer\/Renderer.h\"\n#include \"renderer\/vulkan\/Test.h\"\n#include \"renderer\/vulkan\/VulkanRenderer.h\"\n\n#include \"core\/Profile.h\"\n\nint main(int \/*ac*\/, char** \/*av*\/)\n{\n#if defined(REAPER_USE_MICROPROFILE)\n MicroProfileOnThreadCreate(\"Main\");\n MicroProfileSetEnableAllGroups(true);\n MicroProfileSetForceMetaCounters(true);\n MicroProfileStartContextSwitchTrace();\n#endif\n\n {\n using namespace Reaper;\n\n ReaperRoot root = {};\n\n root.log = new DebugLog();\n\n log_info(root, \"engine: startup\");\n {\n if (create_renderer(root))\n {\n vulkan_test(root, *root.renderer->backend);\n destroy_renderer(root);\n }\n }\n log_info(root, \"engine: shutdown\");\n\n delete root.log;\n root.log = nullptr;\n }\n\n#if defined(REAPER_USE_MICROPROFILE)\n MicroProfileDumpFileImmediately(\"profile.html\", nullptr, nullptr);\n MicroProfileShutdown();\n#endif\n\n return 0;\n}\nmicroprofile: do not write html at the end of the session\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Reaper\n\/\/\/\n\/\/\/ Copyright (c) 2015-2020 Thibault Schueller\n\/\/\/ This file is distributed under the MIT License\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"common\/DebugLog.h\"\n#include \"common\/ReaperRoot.h\"\n\n#include \"renderer\/Renderer.h\"\n#include \"renderer\/vulkan\/Test.h\"\n#include \"renderer\/vulkan\/VulkanRenderer.h\"\n\n#include \"core\/Profile.h\"\n\nint main(int \/*ac*\/, char** \/*av*\/)\n{\n#if defined(REAPER_USE_MICROPROFILE)\n MicroProfileOnThreadCreate(\"Main\");\n MicroProfileSetEnableAllGroups(true);\n MicroProfileSetForceMetaCounters(true);\n MicroProfileStartContextSwitchTrace();\n#endif\n\n {\n using namespace Reaper;\n\n ReaperRoot root = {};\n\n root.log = new DebugLog();\n\n log_info(root, \"engine: startup\");\n {\n if (create_renderer(root))\n {\n vulkan_test(root, *root.renderer->backend);\n destroy_renderer(root);\n }\n }\n log_info(root, \"engine: shutdown\");\n\n delete root.log;\n root.log = nullptr;\n }\n\n#if defined(REAPER_USE_MICROPROFILE)\n \/\/ MicroProfileDumpFileImmediately(\"profile.html\", nullptr, nullptr);\n MicroProfileShutdown();\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"tx_verify.h\"\n\n#include \"consensus.h\"\n#include \"primitives\/transaction.h\"\n#include \"script\/interpreter.h\"\n#include \"validation.h\"\n\n\/\/ TODO remove the following dependencies\n#include \"chain.h\"\n#include \"coins.h\"\n#include \"utilmoneystr.h\"\n \nbool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)\n{\n if (tx.nLockTime == 0)\n return true;\n if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))\n return true;\n for (const auto& txin : tx.vin) {\n if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))\n return false;\n }\n return true;\n}\n\nstd::pair CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector* prevHeights, const CBlockIndex& block)\n{\n assert(prevHeights->size() == tx.vin.size());\n\n \/\/ Will be set to the equivalent height- and time-based nLockTime\n \/\/ values that would be necessary to satisfy all relative lock-\n \/\/ time constraints given our view of block chain history.\n \/\/ The semantics of nLockTime are the last invalid height\/time, so\n \/\/ use -1 to have the effect of any height or time being valid.\n int nMinHeight = -1;\n int64_t nMinTime = -1;\n\n \/\/ tx.nVersion is signed integer so requires cast to unsigned otherwise\n \/\/ we would be doing a signed comparison and half the range of nVersion\n \/\/ wouldn't support BIP 68.\n bool fEnforceBIP68 = static_cast(tx.nVersion) >= 2\n && flags & LOCKTIME_VERIFY_SEQUENCE;\n\n \/\/ Do not enforce sequence numbers as a relative lock time\n \/\/ unless we have been instructed to\n if (!fEnforceBIP68) {\n return std::make_pair(nMinHeight, nMinTime);\n }\n\n for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {\n const CTxIn& txin = tx.vin[txinIndex];\n\n \/\/ Sequence numbers with the most significant bit set are not\n \/\/ treated as relative lock-times, nor are they given any\n \/\/ consensus-enforced meaning at this point.\n if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {\n \/\/ The height of this input is not relevant for sequence locks\n (*prevHeights)[txinIndex] = 0;\n continue;\n }\n\n int nCoinHeight = (*prevHeights)[txinIndex];\n\n if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {\n int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();\n \/\/ NOTE: Subtract 1 to maintain nLockTime semantics\n \/\/ BIP 68 relative lock times have the semantics of calculating\n \/\/ the first block or time at which the transaction would be\n \/\/ valid. When calculating the effective block time or height\n \/\/ for the entire transaction, we switch to using the\n \/\/ semantics of nLockTime which is the last invalid block\n \/\/ time or height. Thus we subtract 1 from the calculated\n \/\/ time or height.\n\n \/\/ Time-based relative lock-times are measured from the\n \/\/ smallest allowed timestamp of the block containing the\n \/\/ txout being spent, which is the median time past of the\n \/\/ block prior.\n nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);\n } else {\n nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);\n }\n }\n\n return std::make_pair(nMinHeight, nMinTime);\n}\n\nbool EvaluateSequenceLocks(const CBlockIndex& block, std::pair lockPair)\n{\n assert(block.pprev);\n int64_t nBlockTime = block.pprev->GetMedianTimePast();\n if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)\n return false;\n\n return true;\n}\n\nbool SequenceLocks(const CTransaction &tx, int flags, std::vector* prevHeights, const CBlockIndex& block)\n{\n return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));\n}\n\nunsigned int GetLegacySigOpCount(const CTransaction& tx)\n{\n unsigned int nSigOps = 0;\n for (const auto& txin : tx.vin)\n {\n nSigOps += txin.scriptSig.GetSigOpCount(false);\n }\n for (const auto& txout : tx.vout)\n {\n nSigOps += txout.scriptPubKey.GetSigOpCount(false);\n }\n return nSigOps;\n}\n\nunsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)\n{\n if (tx.IsCoinBase())\n return 0;\n\n unsigned int nSigOps = 0;\n for (unsigned int i = 0; i < tx.vin.size(); i++)\n {\n const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);\n assert(!coin.IsSpent());\n const CTxOut &prevout = coin.out;\n if (prevout.scriptPubKey.IsPayToScriptHash())\n nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);\n }\n return nSigOps;\n}\n\nint64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)\n{\n int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;\n\n if (tx.IsCoinBase())\n return nSigOps;\n\n if (flags & SCRIPT_VERIFY_P2SH) {\n nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;\n }\n\n for (unsigned int i = 0; i < tx.vin.size(); i++)\n {\n const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);\n assert(!coin.IsSpent());\n const CTxOut &prevout = coin.out;\n nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);\n }\n return nSigOps;\n}\n\nbool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)\n{\n \/\/ Basic checks that don't depend on any context\n if (tx.vin.empty())\n return state.DoS(10, false, REJECT_INVALID, \"bad-txns-vin-empty\");\n if (tx.vout.empty())\n return state.DoS(10, false, REJECT_INVALID, \"bad-txns-vout-empty\");\n \/\/ Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)\n if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-oversize\");\n\n \/\/ Check for negative or overflow output values\n CAmount nValueOut = 0;\n for (const auto& txout : tx.vout)\n {\n if (txout.nValue < 0)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-vout-negative\");\n if (txout.nValue > MAX_MONEY)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-vout-toolarge\");\n nValueOut += txout.nValue;\n if (!MoneyRange(nValueOut))\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-txouttotal-toolarge\");\n }\n\n \/\/ Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock\n if (fCheckDuplicateInputs) {\n std::set vInOutPoints;\n for (const auto& txin : tx.vin)\n {\n if (!vInOutPoints.insert(txin.prevout).second)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-inputs-duplicate\");\n }\n }\n\n if (tx.IsCoinBase())\n {\n if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)\n return state.DoS(100, false, REJECT_INVALID, \"bad-cb-length\");\n }\n else\n {\n for (const auto& txin : tx.vin)\n if (txin.prevout.IsNull())\n return state.DoS(10, false, REJECT_INVALID, \"bad-txns-prevout-null\");\n }\n\n return true;\n}\n\nbool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)\n{\n \/\/ This doesn't trigger the DoS code on purpose; if it did, it would make it easier\n \/\/ for an attacker to attempt to split the network.\n if (!inputs.HaveInputs(tx))\n return state.Invalid(false, 0, \"\", \"Inputs unavailable\");\n\n CAmount nValueIn = 0;\n CAmount nFees = 0;\n for (unsigned int i = 0; i < tx.vin.size(); i++)\n {\n const COutPoint &prevout = tx.vin[i].prevout;\n const Coin& coin = inputs.AccessCoin(prevout);\n assert(!coin.IsSpent());\n\n \/\/ If prev is coinbase, check that it's matured\n if (coin.IsCoinBase()) {\n if (nSpendHeight - coin.nHeight < COINBASE_MATURITY)\n return state.Invalid(false,\n REJECT_INVALID, \"bad-txns-premature-spend-of-coinbase\",\n strprintf(\"tried to spend coinbase at depth %d\", nSpendHeight - coin.nHeight));\n }\n\n \/\/ Check for negative or overflow input values\n nValueIn += coin.out.nValue;\n if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn))\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-inputvalues-outofrange\");\n\n }\n\n if (nValueIn < tx.GetValueOut())\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-in-belowout\", false,\n strprintf(\"value in (%s) < value out (%s)\", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));\n\n \/\/ Tally transaction fees\n CAmount nTxFee = nValueIn - tx.GetValueOut();\n if (nTxFee < 0)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-fee-negative\");\n nFees += nTxFee;\n if (!MoneyRange(nFees))\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-fee-outofrange\");\n return true;\n}\nProper indentation for CheckTxInputs and other minor fixes\/\/ Copyright (c) 2017-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"tx_verify.h\"\n\n#include \"consensus.h\"\n#include \"primitives\/transaction.h\"\n#include \"script\/interpreter.h\"\n#include \"validation.h\"\n\n\/\/ TODO remove the following dependencies\n#include \"chain.h\"\n#include \"coins.h\"\n#include \"utilmoneystr.h\"\n\nbool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)\n{\n if (tx.nLockTime == 0)\n return true;\n if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))\n return true;\n for (const auto& txin : tx.vin) {\n if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))\n return false;\n }\n return true;\n}\n\nstd::pair CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector* prevHeights, const CBlockIndex& block)\n{\n assert(prevHeights->size() == tx.vin.size());\n\n \/\/ Will be set to the equivalent height- and time-based nLockTime\n \/\/ values that would be necessary to satisfy all relative lock-\n \/\/ time constraints given our view of block chain history.\n \/\/ The semantics of nLockTime are the last invalid height\/time, so\n \/\/ use -1 to have the effect of any height or time being valid.\n int nMinHeight = -1;\n int64_t nMinTime = -1;\n\n \/\/ tx.nVersion is signed integer so requires cast to unsigned otherwise\n \/\/ we would be doing a signed comparison and half the range of nVersion\n \/\/ wouldn't support BIP 68.\n bool fEnforceBIP68 = static_cast(tx.nVersion) >= 2\n && flags & LOCKTIME_VERIFY_SEQUENCE;\n\n \/\/ Do not enforce sequence numbers as a relative lock time\n \/\/ unless we have been instructed to\n if (!fEnforceBIP68) {\n return std::make_pair(nMinHeight, nMinTime);\n }\n\n for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {\n const CTxIn& txin = tx.vin[txinIndex];\n\n \/\/ Sequence numbers with the most significant bit set are not\n \/\/ treated as relative lock-times, nor are they given any\n \/\/ consensus-enforced meaning at this point.\n if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {\n \/\/ The height of this input is not relevant for sequence locks\n (*prevHeights)[txinIndex] = 0;\n continue;\n }\n\n int nCoinHeight = (*prevHeights)[txinIndex];\n\n if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {\n int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();\n \/\/ NOTE: Subtract 1 to maintain nLockTime semantics\n \/\/ BIP 68 relative lock times have the semantics of calculating\n \/\/ the first block or time at which the transaction would be\n \/\/ valid. When calculating the effective block time or height\n \/\/ for the entire transaction, we switch to using the\n \/\/ semantics of nLockTime which is the last invalid block\n \/\/ time or height. Thus we subtract 1 from the calculated\n \/\/ time or height.\n\n \/\/ Time-based relative lock-times are measured from the\n \/\/ smallest allowed timestamp of the block containing the\n \/\/ txout being spent, which is the median time past of the\n \/\/ block prior.\n nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);\n } else {\n nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);\n }\n }\n\n return std::make_pair(nMinHeight, nMinTime);\n}\n\nbool EvaluateSequenceLocks(const CBlockIndex& block, std::pair lockPair)\n{\n assert(block.pprev);\n int64_t nBlockTime = block.pprev->GetMedianTimePast();\n if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)\n return false;\n\n return true;\n}\n\nbool SequenceLocks(const CTransaction &tx, int flags, std::vector* prevHeights, const CBlockIndex& block)\n{\n return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));\n}\n\nunsigned int GetLegacySigOpCount(const CTransaction& tx)\n{\n unsigned int nSigOps = 0;\n for (const auto& txin : tx.vin)\n {\n nSigOps += txin.scriptSig.GetSigOpCount(false);\n }\n for (const auto& txout : tx.vout)\n {\n nSigOps += txout.scriptPubKey.GetSigOpCount(false);\n }\n return nSigOps;\n}\n\nunsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)\n{\n if (tx.IsCoinBase())\n return 0;\n\n unsigned int nSigOps = 0;\n for (unsigned int i = 0; i < tx.vin.size(); i++)\n {\n const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);\n assert(!coin.IsSpent());\n const CTxOut &prevout = coin.out;\n if (prevout.scriptPubKey.IsPayToScriptHash())\n nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);\n }\n return nSigOps;\n}\n\nint64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)\n{\n int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;\n\n if (tx.IsCoinBase())\n return nSigOps;\n\n if (flags & SCRIPT_VERIFY_P2SH) {\n nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;\n }\n\n for (unsigned int i = 0; i < tx.vin.size(); i++)\n {\n const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);\n assert(!coin.IsSpent());\n const CTxOut &prevout = coin.out;\n nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);\n }\n return nSigOps;\n}\n\nbool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)\n{\n \/\/ Basic checks that don't depend on any context\n if (tx.vin.empty())\n return state.DoS(10, false, REJECT_INVALID, \"bad-txns-vin-empty\");\n if (tx.vout.empty())\n return state.DoS(10, false, REJECT_INVALID, \"bad-txns-vout-empty\");\n \/\/ Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)\n if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-oversize\");\n\n \/\/ Check for negative or overflow output values\n CAmount nValueOut = 0;\n for (const auto& txout : tx.vout)\n {\n if (txout.nValue < 0)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-vout-negative\");\n if (txout.nValue > MAX_MONEY)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-vout-toolarge\");\n nValueOut += txout.nValue;\n if (!MoneyRange(nValueOut))\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-txouttotal-toolarge\");\n }\n\n \/\/ Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock\n if (fCheckDuplicateInputs) {\n std::set vInOutPoints;\n for (const auto& txin : tx.vin)\n {\n if (!vInOutPoints.insert(txin.prevout).second)\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-inputs-duplicate\");\n }\n }\n\n if (tx.IsCoinBase())\n {\n if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)\n return state.DoS(100, false, REJECT_INVALID, \"bad-cb-length\");\n }\n else\n {\n for (const auto& txin : tx.vin)\n if (txin.prevout.IsNull())\n return state.DoS(10, false, REJECT_INVALID, \"bad-txns-prevout-null\");\n }\n\n return true;\n}\n\nbool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)\n{\n \/\/ This doesn't trigger the DoS code on purpose; if it did, it would make it easier\n \/\/ for an attacker to attempt to split the network.\n if (!inputs.HaveInputs(tx)) {\n return state.Invalid(false, 0, \"\", \"Inputs unavailable\");\n }\n\n CAmount nValueIn = 0;\n CAmount nFees = 0;\n for (unsigned int i = 0; i < tx.vin.size(); ++i) {\n const COutPoint &prevout = tx.vin[i].prevout;\n const Coin& coin = inputs.AccessCoin(prevout);\n assert(!coin.IsSpent());\n\n \/\/ If prev is coinbase, check that it's matured\n if (coin.IsCoinBase() && nSpendHeight - coin.nHeight < COINBASE_MATURITY) {\n return state.Invalid(false,\n REJECT_INVALID, \"bad-txns-premature-spend-of-coinbase\",\n strprintf(\"tried to spend coinbase at depth %d\", nSpendHeight - coin.nHeight));\n }\n\n \/\/ Check for negative or overflow input values\n nValueIn += coin.out.nValue;\n if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-inputvalues-outofrange\");\n }\n }\n\n if (nValueIn < tx.GetValueOut()) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-in-belowout\", false,\n strprintf(\"value in (%s) < value out (%s)\", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));\n }\n\n \/\/ Tally transaction fees\n CAmount nTxFee = nValueIn - tx.GetValueOut();\n if (nTxFee < 0) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-fee-negative\");\n }\n nFees += nTxFee;\n if (!MoneyRange(nFees)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-txns-fee-outofrange\");\n }\n return true;\n}\n<|endoftext|>"} {"text":"\/\/ RUN: %clangxx_asan -DWAIT4 -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\/\/ RUN: %clangxx_asan -DWAIT4 -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\n\/\/ RUN: %clangxx_asan -DWAIT4_RUSAGE -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\/\/ RUN: %clangxx_asan -DWAIT4_RUSAGE -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\n\/\/ XFAIL: android\n\n#include \n#include \n#include \n\nint main(int argc, char **argv) {\n \/\/ This test passes on some versions of Android NDK and fails on other.\n \/\/ https:\/\/code.google.com\/p\/memory-sanitizer\/issues\/detail?id=64\n \/\/ Make it fail unconditionally on Android.\n#ifdef __ANDROID__\n return 0;\n#endif\n\n pid_t pid = fork();\n if (pid) { \/\/ parent\n int x[3];\n int *status = x + argc * 3;\n int res;\n#if defined(WAIT4)\n res = wait4(pid, status, WNOHANG, NULL);\n#elif defined(WAIT4_RUSAGE)\n struct rusage *ru = (struct rusage*)(x + argc * 3);\n int good_status;\n res = wait4(pid, &good_status, WNOHANG, ru);\n#endif\n \/\/ CHECK: stack-buffer-overflow\n \/\/ CHECK: {{WRITE of size .* at 0x.* thread T0}}\n \/\/ CHECK: {{in .*wait}}\n \/\/ CHECK: {{in main .*wait.cc:}}\n \/\/ CHECK: is located in stack of thread T0 at offset\n \/\/ CHECK: {{in main}}\n return res == -1 ? 1 : 0;\n }\n \/\/ child\n return 0;\n}\n[asan] Fix path in test.\/\/ RUN: %clangxx_asan -DWAIT4 -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\/\/ RUN: %clangxx_asan -DWAIT4 -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\n\/\/ RUN: %clangxx_asan -DWAIT4_RUSAGE -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\/\/ RUN: %clangxx_asan -DWAIT4_RUSAGE -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\n\/\/ XFAIL: android\n\n#include \n#include \n#include \n\nint main(int argc, char **argv) {\n \/\/ This test passes on some versions of Android NDK and fails on other.\n \/\/ https:\/\/code.google.com\/p\/memory-sanitizer\/issues\/detail?id=64\n \/\/ Make it fail unconditionally on Android.\n#ifdef __ANDROID__\n return 0;\n#endif\n\n pid_t pid = fork();\n if (pid) { \/\/ parent\n int x[3];\n int *status = x + argc * 3;\n int res;\n#if defined(WAIT4)\n res = wait4(pid, status, WNOHANG, NULL);\n#elif defined(WAIT4_RUSAGE)\n struct rusage *ru = (struct rusage*)(x + argc * 3);\n int good_status;\n res = wait4(pid, &good_status, WNOHANG, ru);\n#endif\n \/\/ CHECK: stack-buffer-overflow\n \/\/ CHECK: {{WRITE of size .* at 0x.* thread T0}}\n \/\/ CHECK: {{in .*wait}}\n \/\/ CHECK: {{in main .*wait4.cc:}}\n \/\/ CHECK: is located in stack of thread T0 at offset\n \/\/ CHECK: {{in main}}\n return res == -1 ? 1 : 0;\n }\n \/\/ child\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"curvetree_view.h\"\n#include \"curvelist_panel.h\"\n#include \n#include \n\nclass TreeWidgetItem : public QTreeWidgetItem\n{\n public:\n TreeWidgetItem(QTreeWidgetItem *parent) : QTreeWidgetItem(parent) {}\n\n bool operator< (const QTreeWidgetItem &other) const\n {\n return doj::alphanum_impl(this->text(0).toLocal8Bit(),\n other.text(0).toLocal8Bit()) < 0;\n }\n};\n\nCurveTreeView::CurveTreeView(CurveListPanel* parent) : QTreeWidget(parent), CurvesView(parent)\n{\n setColumnCount(2);\n setEditTriggers(NoEditTriggers);\n setDragEnabled(false);\n setDefaultDropAction(Qt::IgnoreAction);\n setDragDropOverwriteMode(false);\n setDragDropMode(NoDragDrop);\n viewport()->installEventFilter(this);\n setSelectionMode(ExtendedSelection);\n\n header()->setVisible(false);\n header()->setStretchLastSection(true);\n header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);\n}\n\nvoid CurveTreeView::addItem(const QString& item_name)\n{\n auto parts = item_name.split('\/', QString::SplitBehavior::SkipEmptyParts);\n if (parts.size() == 0)\n {\n return;\n }\n\n QTreeWidgetItem* tree_parent = this->invisibleRootItem();\n\n for (int i = 0; i < parts.size(); i++)\n {\n bool is_leaf = (i == parts.size() - 1);\n const auto& part = parts[ i ];\n\n QTreeWidgetItem* matching_child = nullptr;\n\n for (int c = 0; c < tree_parent->childCount(); c++)\n {\n QTreeWidgetItem* tree_child = tree_parent->child(c);\n if (tree_child->text(0) == part)\n {\n matching_child = tree_child;\n break;\n }\n }\n\n if (matching_child)\n {\n tree_parent = matching_child;\n }\n else\n {\n QTreeWidgetItem* child_item = new TreeWidgetItem(tree_parent);\n child_item->setText(0, part);\n child_item->setText(1, is_leaf ? \"-\" : \"\");\n\n QFont font = QFontDatabase::systemFont(QFontDatabase::GeneralFont);\n font.setPointSize(_point_size);\n child_item->setFont(0, font);\n\n font = QFontDatabase::systemFont(QFontDatabase::FixedFont);\n font.setPointSize(_point_size);\n child_item->setFont(1, font);\n child_item->setTextAlignment(1, Qt::AlignRight);\n\n tree_parent = child_item;\n\n auto current_flag = child_item->flags();\n\n if (is_leaf)\n {\n child_item->setFlags(current_flag | Qt::ItemIsSelectable);\n child_item->setData(0, Qt::UserRole, item_name);\n }\n else\n {\n child_item->setFlags(current_flag & (~Qt::ItemIsSelectable));\n }\n }\n }\n _leaf_count++;\n}\n\nvoid CurveTreeView::refreshColumns()\n{\n invisibleRootItem()->sortChildren(0, Qt::AscendingOrder);\n treeVisitor([&](QTreeWidgetItem* item){\n item->sortChildren(0, Qt::AscendingOrder);\n } );\n header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n \/\/ TODO emit updateFilter();\n}\n\nstd::vector CurveTreeView::getSelectedNames()\n{\n std::vector non_hidden_list;\n\n for (const auto& item : selectedItems())\n {\n non_hidden_list.push_back(\n item->data(0, Qt::UserRole).toString().toStdString());\n }\n return non_hidden_list;\n}\n\nvoid CurveTreeView::refreshFontSize()\n{\n header()->setSectionResizeMode(0, QHeaderView::Fixed);\n header()->setSectionResizeMode(1, QHeaderView::Fixed);\n\n treeVisitor([this](QTreeWidgetItem* item) {\n auto font = item->font(0);\n font.setPointSize(_point_size);\n item->setFont(0, font);\n font = item->font(1);\n font.setPointSize(_point_size);\n item->setFont(1, font);\n });\n\n header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n header()->setSectionResizeMode(1, QHeaderView::Stretch);\n}\n\nbool CurveTreeView::applyVisibilityFilter(CurvesView::FilterType type,\n const QString& search_string)\n{\n bool updated = false;\n _hidden_count = 0;\n QRegExp regexp(search_string, Qt::CaseInsensitive, QRegExp::Wildcard);\n QRegExpValidator v(regexp, nullptr);\n\n QStringList spaced_items = search_string.split(' ');\n\n auto hideFunc = [&](QTreeWidgetItem* item)\n {\n QString name = item->data(0, Qt::UserRole).toString();\n if( name.isEmpty() )\n {\n return; \/\/ not a leaf\n }\n bool toHide = false;\n\n if (search_string.isEmpty() == false)\n {\n if (type == REGEX)\n {\n int pos = 0;\n toHide = (v.validate(name, pos) != QValidator::Acceptable);\n }\n else if (type == CONTAINS)\n {\n for (const auto& item : spaced_items)\n {\n if (name.contains(item, Qt::CaseInsensitive) == false)\n {\n toHide = true;\n break;\n }\n }\n }\n }\n if (toHide)\n {\n _hidden_count++;\n }\n\n if (toHide != item->isHidden())\n {\n updated = true;\n }\n\n item->setHidden(toHide);\n\n \/\/ hide the parent if necessary\n auto parent = item->parent();\n while( parent )\n {\n bool all_children_hidden = true;\n for (int c = 0; c < parent->childCount(); c++)\n {\n if( !parent->child(c)->isHidden() )\n {\n all_children_hidden = false;\n break;\n }\n }\n auto parent_hidden = parent->isHidden();\n if( all_children_hidden != parent_hidden)\n {\n parent->setHidden( all_children_hidden );\n parent = parent->parent();\n }\n else{\n break;\n }\n }\n };\n\n treeVisitor( hideFunc );\n \/\/-------------\n\n return updated;\n}\n\nvoid CurveTreeView::removeCurve(const QString &to_be_deleted)\n{\n auto removeFunc = [&](QTreeWidgetItem* item)\n {\n QString curve_name = item->data(0, Qt::UserRole).toString();\n if( curve_name == to_be_deleted)\n {\n _leaf_count --;\n auto parent_item = item->parent();\n parent_item->removeChild(item);\n\n while (parent_item->childCount() == 0 &&\n parent_item != invisibleRootItem())\n {\n auto prev_item = parent_item;\n parent_item = parent_item->parent();\n if(!parent_item)\n {\n parent_item = invisibleRootItem();\n }\n parent_item->removeChild(prev_item);\n }\n }\n };\n\n treeVisitor( removeFunc );\n}\n\nvoid CurveTreeView::hideValuesColumn(bool hide)\n{\n if(hide){\n hideColumn(1);\n }\n else {\n showColumn(1);\n }\n}\n\nvoid CurveTreeView::treeVisitor(std::function visitor)\n{\n std::function recursiveFunction;\n recursiveFunction = [&](QTreeWidgetItem* item)\n {\n visitor(item);\n for (int c = 0; c < item->childCount(); c++)\n {\n recursiveFunction(item->child(c));\n }\n };\n\n for (int c = 0; c < invisibleRootItem()->childCount(); c++)\n {\n recursiveFunction(invisibleRootItem()->child(c));\n }\n}\nbug fix#include \"curvetree_view.h\"\n#include \"curvelist_panel.h\"\n#include \n#include \n\nclass TreeWidgetItem : public QTreeWidgetItem\n{\n public:\n TreeWidgetItem(QTreeWidgetItem *parent) : QTreeWidgetItem(parent) {}\n\n bool operator< (const QTreeWidgetItem &other) const\n {\n return doj::alphanum_impl(this->text(0).toLocal8Bit(),\n other.text(0).toLocal8Bit()) < 0;\n }\n};\n\nCurveTreeView::CurveTreeView(CurveListPanel* parent) : QTreeWidget(parent), CurvesView(parent)\n{\n setColumnCount(2);\n setEditTriggers(NoEditTriggers);\n setDragEnabled(false);\n setDefaultDropAction(Qt::IgnoreAction);\n setDragDropOverwriteMode(false);\n setDragDropMode(NoDragDrop);\n viewport()->installEventFilter(this);\n setSelectionMode(ExtendedSelection);\n\n header()->setVisible(false);\n header()->setStretchLastSection(true);\n header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);\n}\n\nvoid CurveTreeView::addItem(const QString& item_name)\n{\n auto parts = item_name.split('\/', QString::SplitBehavior::SkipEmptyParts);\n if (parts.size() == 0)\n {\n return;\n }\n\n QTreeWidgetItem* tree_parent = this->invisibleRootItem();\n\n for (int i = 0; i < parts.size(); i++)\n {\n bool is_leaf = (i == parts.size() - 1);\n const auto& part = parts[ i ];\n\n QTreeWidgetItem* matching_child = nullptr;\n\n for (int c = 0; c < tree_parent->childCount(); c++)\n {\n QTreeWidgetItem* tree_child = tree_parent->child(c);\n if (tree_child->text(0) == part)\n {\n matching_child = tree_child;\n break;\n }\n }\n\n if (matching_child)\n {\n tree_parent = matching_child;\n }\n else\n {\n QTreeWidgetItem* child_item = new TreeWidgetItem(tree_parent);\n child_item->setText(0, part);\n child_item->setText(1, is_leaf ? \"-\" : \"\");\n\n QFont font = QFontDatabase::systemFont(QFontDatabase::GeneralFont);\n font.setPointSize(_point_size);\n child_item->setFont(0, font);\n\n font = QFontDatabase::systemFont(QFontDatabase::FixedFont);\n font.setPointSize(_point_size);\n child_item->setFont(1, font);\n child_item->setTextAlignment(1, Qt::AlignRight);\n\n tree_parent = child_item;\n\n auto current_flag = child_item->flags();\n\n if (is_leaf)\n {\n child_item->setFlags(current_flag | Qt::ItemIsSelectable);\n child_item->setData(0, Qt::UserRole, item_name);\n }\n else\n {\n child_item->setFlags(current_flag & (~Qt::ItemIsSelectable));\n }\n }\n }\n _leaf_count++;\n}\n\nvoid CurveTreeView::refreshColumns()\n{\n invisibleRootItem()->sortChildren(0, Qt::AscendingOrder);\n treeVisitor([&](QTreeWidgetItem* item){\n item->sortChildren(0, Qt::AscendingOrder);\n } );\n header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n \/\/ TODO emit updateFilter();\n}\n\nstd::vector CurveTreeView::getSelectedNames()\n{\n std::vector non_hidden_list;\n\n for (const auto& item : selectedItems())\n {\n non_hidden_list.push_back(\n item->data(0, Qt::UserRole).toString().toStdString());\n }\n return non_hidden_list;\n}\n\nvoid CurveTreeView::refreshFontSize()\n{\n header()->setSectionResizeMode(0, QHeaderView::Fixed);\n header()->setSectionResizeMode(1, QHeaderView::Fixed);\n\n treeVisitor([this](QTreeWidgetItem* item) {\n auto font = item->font(0);\n font.setPointSize(_point_size);\n item->setFont(0, font);\n font = item->font(1);\n font.setPointSize(_point_size);\n item->setFont(1, font);\n });\n\n header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n header()->setSectionResizeMode(1, QHeaderView::Stretch);\n}\n\nbool CurveTreeView::applyVisibilityFilter(CurvesView::FilterType type,\n const QString& search_string)\n{\n bool updated = false;\n _hidden_count = 0;\n QRegExp regexp(search_string, Qt::CaseInsensitive, QRegExp::Wildcard);\n QRegExpValidator v(regexp, nullptr);\n\n QStringList spaced_items = search_string.split(' ');\n\n auto hideFunc = [&](QTreeWidgetItem* item)\n {\n QString name = item->data(0, Qt::UserRole).toString();\n if( name.isEmpty() )\n {\n return; \/\/ not a leaf\n }\n bool toHide = false;\n\n if (search_string.isEmpty() == false)\n {\n if (type == REGEX)\n {\n int pos = 0;\n toHide = (v.validate(name, pos) != QValidator::Acceptable);\n }\n else if (type == CONTAINS)\n {\n for (const auto& item : spaced_items)\n {\n if (name.contains(item, Qt::CaseInsensitive) == false)\n {\n toHide = true;\n break;\n }\n }\n }\n }\n if (toHide)\n {\n _hidden_count++;\n }\n\n if (toHide != item->isHidden())\n {\n updated = true;\n }\n\n item->setHidden(toHide);\n\n \/\/ hide the parent if necessary\n auto parent = item->parent();\n while( parent )\n {\n bool all_children_hidden = true;\n for (int c = 0; c < parent->childCount(); c++)\n {\n if( !parent->child(c)->isHidden() )\n {\n all_children_hidden = false;\n break;\n }\n }\n auto parent_hidden = parent->isHidden();\n if( all_children_hidden != parent_hidden)\n {\n parent->setHidden( all_children_hidden );\n parent = parent->parent();\n }\n else{\n break;\n }\n }\n };\n\n treeVisitor( hideFunc );\n \/\/-------------\n\n return updated;\n}\n\nvoid CurveTreeView::removeCurve(const QString &to_be_deleted)\n{\n auto removeFunc = [&](QTreeWidgetItem* item)\n {\n QString curve_name = item->data(0, Qt::UserRole).toString();\n if( curve_name == to_be_deleted)\n {\n _leaf_count --;\n auto parent_item = item->parent();\n if(!parent_item)\n {\n parent_item = invisibleRootItem();\n }\n parent_item->removeChild(item);\n\n while (parent_item->childCount() == 0 &&\n parent_item != invisibleRootItem())\n {\n auto prev_item = parent_item;\n parent_item = parent_item->parent();\n if(!parent_item)\n {\n parent_item = invisibleRootItem();\n }\n parent_item->removeChild(prev_item);\n }\n }\n };\n\n treeVisitor( removeFunc );\n}\n\nvoid CurveTreeView::hideValuesColumn(bool hide)\n{\n if(hide){\n hideColumn(1);\n }\n else {\n showColumn(1);\n }\n}\n\nvoid CurveTreeView::treeVisitor(std::function visitor)\n{\n std::function recursiveFunction;\n recursiveFunction = [&](QTreeWidgetItem* item)\n {\n visitor(item);\n for (int c = 0; c < item->childCount(); c++)\n {\n recursiveFunction(item->child(c));\n }\n };\n\n for (int c = 0; c < invisibleRootItem()->childCount(); c++)\n {\n recursiveFunction(invisibleRootItem()->child(c));\n }\n}\n<|endoftext|>"} {"text":"\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Łukasz Twarduś \n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"lxqtsensors.h\"\n#include \"lxqtsensorsconfiguration.h\"\n#include \"..\/panel\/ilxqtpanelplugin.h\"\n#include \"..\/panel\/ilxqtpanel.h\"\n#include \n#include \n#include \n#include \n\n\nLXQtSensors::LXQtSensors(ILXQtPanelPlugin *plugin, QWidget* parent):\n QFrame(parent),\n mPlugin(plugin),\n mSettings(plugin->settings())\n{\n\n mDetectedChips = mSensors.getDetectedChips();\n\n \/**\n * We have all needed data to initialize default settings, we have to do it here as later\n * we are using them.\n *\/\n initDefaultSettings();\n\n \/\/ Add GUI elements\n ProgressBar* pg = NULL;\n\n mLayout = new QBoxLayout(QBoxLayout::LeftToRight, this);\n mLayout->setSpacing(0);\n mLayout->setContentsMargins(0, 0, 0, 0);\n\n QString chipFeatureLabel;\n\n mSettings->beginGroup(\"chips\");\n\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n mSettings->beginGroup(mDetectedChips[i].getName());\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n chipFeatureLabel = features[j].getLabel();\n mSettings->beginGroup(chipFeatureLabel);\n\n pg = new ProgressBar(this);\n pg->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n\n \/\/ Hide progress bar if it is not enabled\n if (!mSettings->value(\"enabled\").toBool())\n {\n pg->hide();\n }\n\n pg->setToolTip(chipFeatureLabel);\n pg->setTextVisible(false);\n\n QPalette pal = pg->palette();\n QColor color(mSettings->value(\"color\").toString());\n pal.setColor(QPalette::Active, QPalette::Highlight, color);\n pal.setColor(QPalette::Inactive, QPalette::Highlight, color);\n pg->setPalette(pal);\n\n mTemperatureProgressBars.push_back(pg);\n mLayout->addWidget(pg);\n\n mSettings->endGroup();\n }\n }\n mSettings->endGroup();\n }\n\n mSettings->endGroup();\n\n \/\/ Fit plugin to current panel\n realign();\n\n \/\/ Updated sensors readings to display actual values at start\n updateSensorReadings();\n\n \/\/ Run timer that will be updating sensor readings\n connect(&mUpdateSensorReadingsTimer, SIGNAL(timeout()), this, SLOT(updateSensorReadings()));\n mUpdateSensorReadingsTimer.start(mSettings->value(\"updateInterval\").toInt() * 1000);\n\n \/\/ Run timer that will be showin warning\n mWarningAboutHighTemperatureTimer.setInterval(500);\n connect(&mWarningAboutHighTemperatureTimer, SIGNAL(timeout()), this,\n SLOT(warningAboutHighTemperature()));\n if (mSettings->value(\"warningAboutHighTemperature\").toBool())\n {\n mWarningAboutHighTemperatureTimer.start();\n }\n}\n\n\nLXQtSensors::~LXQtSensors()\n{\n}\n\n\nvoid LXQtSensors::updateSensorReadings()\n{\n QString tooltip;\n\n double critTemp = 0;\n double maxTemp = 0;\n double minTemp = 0;\n double curTemp = 0;\n bool highTemperature = false;\n\n \/\/ Iterator for temperature progress bars\n QList::iterator temperatureProgressBarsIt =\n mTemperatureProgressBars.begin();\n\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n tooltip = features[j].getLabel() + \" (\" + QChar(0x00B0);\n\n if (mSettings->value(\"useFahrenheitScale\").toBool())\n {\n critTemp = celsiusToFahrenheit(\n features[j].getValue(SENSORS_SUBFEATURE_TEMP_CRIT));\n maxTemp = celsiusToFahrenheit(\n features[j].getValue(SENSORS_SUBFEATURE_TEMP_MAX));\n minTemp = celsiusToFahrenheit(\n features[j].getValue(SENSORS_SUBFEATURE_TEMP_MIN));\n curTemp = celsiusToFahrenheit(\n features[j].getValue(SENSORS_SUBFEATURE_TEMP_INPUT));\n\n tooltip += \"F)\";\n }\n else\n {\n critTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_CRIT);\n maxTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MAX);\n minTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MIN);\n curTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_INPUT);\n\n tooltip += \"C)\";\n }\n\n\n \/\/ Check if temperature is too high\n if (curTemp >= maxTemp)\n {\n if (mSettings->value(\"warningAboutHighTemperature\").toBool())\n {\n \/\/ Add current progress bar to the \"warning container\"\n mHighTemperatureProgressBars.insert(*temperatureProgressBarsIt);\n }\n\n highTemperature = true;\n }\n else\n {\n mHighTemperatureProgressBars.remove(*temperatureProgressBarsIt);\n\n highTemperature = false;\n }\n\n \/\/ Set maximum temperature\n (*temperatureProgressBarsIt)->setMaximum(critTemp);\n \/\/ Set minimum temperature\n (*temperatureProgressBarsIt)->setMinimum(minTemp);\n \/\/ Set current temperature\n (*temperatureProgressBarsIt)->setValue(curTemp);\n\n tooltip += \"

Crit: \";\n tooltip += QString::number((*temperatureProgressBarsIt)->maximum());\n tooltip += \"
Max: \";\n tooltip += QString::number(int(maxTemp));\n tooltip += \"
Cur: \";\n\n \/\/ Mark high temperature in the tooltip\n if (highTemperature)\n {\n tooltip += \"\";\n tooltip += QString::number((*temperatureProgressBarsIt)->value());\n tooltip += \" !<\/span>\";\n }\n else\n {\n tooltip += QString::number((*temperatureProgressBarsIt)->value());\n }\n\n tooltip += \"
Min: \";\n tooltip += QString::number((*temperatureProgressBarsIt)->minimum());\n (*temperatureProgressBarsIt)->setToolTip(tooltip);\n\n \/\/ Go to the next temperature progress bar\n ++temperatureProgressBarsIt;\n }\n }\n }\n\n update();\n}\n\n\nvoid LXQtSensors::warningAboutHighTemperature()\n{\n \/\/ Iterator for temperature progress bars\n QSet::iterator temperatureProgressBarsIt =\n mHighTemperatureProgressBars.begin();\n\n int curValue;\n int maxValue;\n\n for (; temperatureProgressBarsIt != mHighTemperatureProgressBars.end();\n ++temperatureProgressBarsIt)\n {\n curValue = (*temperatureProgressBarsIt)->value();\n maxValue = (*temperatureProgressBarsIt)->maximum();\n\n if (maxValue > curValue)\n {\n (*temperatureProgressBarsIt)->setValue(maxValue);\n }\n else\n {\n (*temperatureProgressBarsIt)->setValue((*temperatureProgressBarsIt)->minimum());\n }\n\n }\n update();\n}\n\n\nvoid LXQtSensors::settingsChanged()\n{\n mUpdateSensorReadingsTimer.setInterval(mSettings->value(\"updateInterval\").toInt() * 1000);\n\n \/\/ Iterator for temperature progress bars\n QList::iterator temperatureProgressBarsIt =\n mTemperatureProgressBars.begin();\n\n mSettings->beginGroup(\"chips\");\n\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n mSettings->beginGroup(mDetectedChips[i].getName());\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n mSettings->beginGroup(features[j].getLabel());\n\n if (mSettings->value(\"enabled\").toBool())\n {\n (*temperatureProgressBarsIt)->show();\n }\n else\n {\n (*temperatureProgressBarsIt)->hide();\n }\n\n QPalette pal = (*temperatureProgressBarsIt)->palette();\n QColor color(mSettings->value(\"color\").toString());\n pal.setColor(QPalette::Active, QPalette::Highlight, color);\n pal.setColor(QPalette::Inactive, QPalette::Highlight, color);\n (*temperatureProgressBarsIt)->setPalette(pal);\n\n mSettings->endGroup();\n\n \/\/ Go to the next temperature progress bar\n ++temperatureProgressBarsIt;\n }\n }\n\n mSettings->endGroup();\n }\n\n mSettings->endGroup();\n\n\n if (mSettings->value(\"warningAboutHighTemperature\").toBool())\n {\n \/\/ Update sensors readings to get the list of high temperature progress bars\n updateSensorReadings();\n\n if (!mWarningAboutHighTemperatureTimer.isActive())\n mWarningAboutHighTemperatureTimer.start();\n }\n else if (mWarningAboutHighTemperatureTimer.isActive())\n {\n mWarningAboutHighTemperatureTimer.stop();\n\n \/\/ Update sensors readings to set progress bar values to \"normal\" height\n updateSensorReadings();\n }\n\n realign();\n update();\n}\n\n\nvoid LXQtSensors::realign()\n{\n \/\/ Default values for LXQtPanel::PositionBottom or LXQtPanel::PositionTop\n Qt::Orientation cur_orient = Qt::Vertical;\n Qt::LayoutDirection cur_layout_dir = Qt::LeftToRight;\n\n if (mPlugin->panel()->isHorizontal())\n {\n mLayout->setDirection(QBoxLayout::LeftToRight);\n }\n else\n {\n mLayout->setDirection(QBoxLayout::TopToBottom);\n }\n\n switch (mPlugin->panel()->position())\n {\n case ILXQtPanel::PositionLeft:\n cur_orient = Qt::Horizontal;\n break;\n\n case ILXQtPanel::PositionRight:\n cur_orient = Qt::Horizontal;\n cur_layout_dir = Qt::RightToLeft;\n break;\n\n default:\n break;\n }\n\n for (int i = 0; i < mTemperatureProgressBars.size(); ++i)\n {\n mTemperatureProgressBars[i]->setOrientation(cur_orient);\n mTemperatureProgressBars[i]->setLayoutDirection(cur_layout_dir);\n\n if (mPlugin->panel()->isHorizontal())\n {\n mTemperatureProgressBars[i]->setFixedWidth(mPlugin->settings()->value(\"tempBarWidth\").toInt());\n mTemperatureProgressBars[i]->setFixedHeight(QWIDGETSIZE_MAX);\n }\n else\n {\n mTemperatureProgressBars[i]->setFixedHeight(mPlugin->settings()->value(\"tempBarWidth\").toInt());\n mTemperatureProgressBars[i]->setFixedWidth(QWIDGETSIZE_MAX);\n }\n }\n}\n\n\ndouble LXQtSensors::celsiusToFahrenheit(double celsius)\n{\n \/\/ Fahrenheit = 32 * (9\/5) * Celsius\n return 32 + 1.8 * celsius;\n}\n\n\nvoid LXQtSensors::initDefaultSettings()\n{\n if (!mSettings->contains(\"updateInterval\"))\n {\n mSettings->setValue(\"updateInterval\", 1);\n }\n\n if (!mSettings->contains(\"tempBarWidth\"))\n {\n mSettings->setValue(\"tempBarWidth\", 8);\n }\n\n if (!mSettings->contains(\"useFahrenheitScale\"))\n {\n mSettings->setValue(\"useFahrenheitScale\", false);\n }\n\n mSettings->beginGroup(\"chips\");\n\n \/\/ Initialize default sensors settings\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n mSettings->beginGroup(mDetectedChips[i].getName());\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n mSettings->beginGroup(features[j].getLabel());\n if (!mSettings->contains(\"enabled\"))\n {\n mSettings->setValue(\"enabled\", true);\n }\n\n if (!mSettings->contains(\"color\"))\n {\n \/\/ This is the default from QtDesigner\n mSettings->setValue(\"color\", QColor(qRgb(98, 140, 178)).name());\n }\n mSettings->endGroup();\n }\n }\n mSettings->endGroup();\n }\n\n mSettings->endGroup();\n\n if (!mSettings->contains(\"warningAboutHighTemperature\"))\n {\n mSettings->setValue(\"warningAboutHighTemperature\", true);\n }\n}\n\n\nProgressBar::ProgressBar(QWidget *parent):\n QProgressBar(parent)\n{\n}\n\n\nQSize ProgressBar::sizeHint() const\n{\n return QSize(20, 20);\n}\nsensors: Add minor code optimization\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Łukasz Twarduś \n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"lxqtsensors.h\"\n#include \"lxqtsensorsconfiguration.h\"\n#include \"..\/panel\/ilxqtpanelplugin.h\"\n#include \"..\/panel\/ilxqtpanel.h\"\n#include \n#include \n#include \n#include \n\n\nLXQtSensors::LXQtSensors(ILXQtPanelPlugin *plugin, QWidget* parent):\n QFrame(parent),\n mPlugin(plugin),\n mSettings(plugin->settings())\n{\n\n mDetectedChips = mSensors.getDetectedChips();\n\n \/**\n * We have all needed data to initialize default settings, we have to do it here as later\n * we are using them.\n *\/\n initDefaultSettings();\n\n \/\/ Add GUI elements\n ProgressBar* pg = NULL;\n\n mLayout = new QBoxLayout(QBoxLayout::LeftToRight, this);\n mLayout->setSpacing(0);\n mLayout->setContentsMargins(0, 0, 0, 0);\n\n QString chipFeatureLabel;\n\n mSettings->beginGroup(\"chips\");\n\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n mSettings->beginGroup(mDetectedChips[i].getName());\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n chipFeatureLabel = features[j].getLabel();\n mSettings->beginGroup(chipFeatureLabel);\n\n pg = new ProgressBar(this);\n pg->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n\n \/\/ Hide progress bar if it is not enabled\n if (!mSettings->value(\"enabled\").toBool())\n {\n pg->hide();\n }\n\n pg->setToolTip(chipFeatureLabel);\n pg->setTextVisible(false);\n\n QPalette pal = pg->palette();\n QColor color(mSettings->value(\"color\").toString());\n pal.setColor(QPalette::Active, QPalette::Highlight, color);\n pal.setColor(QPalette::Inactive, QPalette::Highlight, color);\n pg->setPalette(pal);\n\n mTemperatureProgressBars.push_back(pg);\n mLayout->addWidget(pg);\n\n mSettings->endGroup();\n }\n }\n mSettings->endGroup();\n }\n\n mSettings->endGroup();\n\n \/\/ Fit plugin to current panel\n realign();\n\n \/\/ Updated sensors readings to display actual values at start\n updateSensorReadings();\n\n \/\/ Run timer that will be updating sensor readings\n connect(&mUpdateSensorReadingsTimer, SIGNAL(timeout()), this, SLOT(updateSensorReadings()));\n mUpdateSensorReadingsTimer.start(mSettings->value(\"updateInterval\").toInt() * 1000);\n\n \/\/ Run timer that will be showin warning\n mWarningAboutHighTemperatureTimer.setInterval(500);\n connect(&mWarningAboutHighTemperatureTimer, SIGNAL(timeout()), this,\n SLOT(warningAboutHighTemperature()));\n if (mSettings->value(\"warningAboutHighTemperature\").toBool())\n {\n mWarningAboutHighTemperatureTimer.start();\n }\n}\n\n\nLXQtSensors::~LXQtSensors()\n{\n}\n\n\nvoid LXQtSensors::updateSensorReadings()\n{\n QString tooltip;\n\n double critTemp = 0;\n double maxTemp = 0;\n double minTemp = 0;\n double curTemp = 0;\n bool highTemperature = false;\n\n \/\/ Iterator for temperature progress bars\n QList::iterator temperatureProgressBarsIt =\n mTemperatureProgressBars.begin();\n const bool use_fahrenheit = mSettings->value(\"useFahrenheitScale\").toBool();\n const bool warn_high = mSettings->value(\"warningAboutHighTemperature\").toBool();\n\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n tooltip = features[j].getLabel() + \" (\" + QChar(0x00B0);\n\n critTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_CRIT);\n maxTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MAX);\n minTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MIN);\n curTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_INPUT);\n\n \/\/ Check if temperature is too high\n if (curTemp >= maxTemp)\n {\n if (warn_high)\n {\n \/\/ Add current progress bar to the \"warning container\"\n mHighTemperatureProgressBars.insert(*temperatureProgressBarsIt);\n }\n\n highTemperature = true;\n }\n else\n {\n mHighTemperatureProgressBars.remove(*temperatureProgressBarsIt);\n\n highTemperature = false;\n }\n\n if (use_fahrenheit)\n {\n critTemp = celsiusToFahrenheit(critTemp);\n maxTemp = celsiusToFahrenheit(maxTemp);\n minTemp = celsiusToFahrenheit(minTemp);\n curTemp = celsiusToFahrenheit(curTemp);\n\n tooltip += \"F)\";\n }\n else\n {\n tooltip += \"C)\";\n }\n\n \/\/ Set maximum temperature\n (*temperatureProgressBarsIt)->setMaximum(critTemp);\n \/\/ Set minimum temperature\n (*temperatureProgressBarsIt)->setMinimum(minTemp);\n \/\/ Set current temperature\n (*temperatureProgressBarsIt)->setValue(curTemp);\n\n tooltip += \"

Crit: \";\n tooltip += QString::number((*temperatureProgressBarsIt)->maximum());\n tooltip += \"
Max: \";\n tooltip += QString::number(int(maxTemp));\n tooltip += \"
Cur: \";\n\n \/\/ Mark high temperature in the tooltip\n if (highTemperature)\n {\n tooltip += \"\";\n tooltip += QString::number((*temperatureProgressBarsIt)->value());\n tooltip += \" !<\/span>\";\n }\n else\n {\n tooltip += QString::number((*temperatureProgressBarsIt)->value());\n }\n\n tooltip += \"
Min: \";\n tooltip += QString::number((*temperatureProgressBarsIt)->minimum());\n (*temperatureProgressBarsIt)->setToolTip(tooltip);\n\n \/\/ Go to the next temperature progress bar\n ++temperatureProgressBarsIt;\n }\n }\n }\n\n update();\n}\n\n\nvoid LXQtSensors::warningAboutHighTemperature()\n{\n \/\/ Iterator for temperature progress bars\n QSet::iterator temperatureProgressBarsIt =\n mHighTemperatureProgressBars.begin();\n\n int curValue;\n int maxValue;\n\n for (; temperatureProgressBarsIt != mHighTemperatureProgressBars.end();\n ++temperatureProgressBarsIt)\n {\n curValue = (*temperatureProgressBarsIt)->value();\n maxValue = (*temperatureProgressBarsIt)->maximum();\n\n if (maxValue > curValue)\n {\n (*temperatureProgressBarsIt)->setValue(maxValue);\n }\n else\n {\n (*temperatureProgressBarsIt)->setValue((*temperatureProgressBarsIt)->minimum());\n }\n\n }\n update();\n}\n\n\nvoid LXQtSensors::settingsChanged()\n{\n mUpdateSensorReadingsTimer.setInterval(mSettings->value(\"updateInterval\").toInt() * 1000);\n\n \/\/ Iterator for temperature progress bars\n QList::iterator temperatureProgressBarsIt =\n mTemperatureProgressBars.begin();\n\n mSettings->beginGroup(\"chips\");\n\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n mSettings->beginGroup(mDetectedChips[i].getName());\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n mSettings->beginGroup(features[j].getLabel());\n\n if (mSettings->value(\"enabled\").toBool())\n {\n (*temperatureProgressBarsIt)->show();\n }\n else\n {\n (*temperatureProgressBarsIt)->hide();\n }\n\n QPalette pal = (*temperatureProgressBarsIt)->palette();\n QColor color(mSettings->value(\"color\").toString());\n pal.setColor(QPalette::Active, QPalette::Highlight, color);\n pal.setColor(QPalette::Inactive, QPalette::Highlight, color);\n (*temperatureProgressBarsIt)->setPalette(pal);\n\n mSettings->endGroup();\n\n \/\/ Go to the next temperature progress bar\n ++temperatureProgressBarsIt;\n }\n }\n\n mSettings->endGroup();\n }\n\n mSettings->endGroup();\n\n\n if (mSettings->value(\"warningAboutHighTemperature\").toBool())\n {\n \/\/ Update sensors readings to get the list of high temperature progress bars\n updateSensorReadings();\n\n if (!mWarningAboutHighTemperatureTimer.isActive())\n mWarningAboutHighTemperatureTimer.start();\n }\n else if (mWarningAboutHighTemperatureTimer.isActive())\n {\n mWarningAboutHighTemperatureTimer.stop();\n\n \/\/ Update sensors readings to set progress bar values to \"normal\" height\n updateSensorReadings();\n }\n\n realign();\n update();\n}\n\n\nvoid LXQtSensors::realign()\n{\n \/\/ Default values for LXQtPanel::PositionBottom or LXQtPanel::PositionTop\n Qt::Orientation cur_orient = Qt::Vertical;\n Qt::LayoutDirection cur_layout_dir = Qt::LeftToRight;\n\n if (mPlugin->panel()->isHorizontal())\n {\n mLayout->setDirection(QBoxLayout::LeftToRight);\n }\n else\n {\n mLayout->setDirection(QBoxLayout::TopToBottom);\n }\n\n switch (mPlugin->panel()->position())\n {\n case ILXQtPanel::PositionLeft:\n cur_orient = Qt::Horizontal;\n break;\n\n case ILXQtPanel::PositionRight:\n cur_orient = Qt::Horizontal;\n cur_layout_dir = Qt::RightToLeft;\n break;\n\n default:\n break;\n }\n\n for (int i = 0; i < mTemperatureProgressBars.size(); ++i)\n {\n mTemperatureProgressBars[i]->setOrientation(cur_orient);\n mTemperatureProgressBars[i]->setLayoutDirection(cur_layout_dir);\n\n if (mPlugin->panel()->isHorizontal())\n {\n mTemperatureProgressBars[i]->setFixedWidth(mPlugin->settings()->value(\"tempBarWidth\").toInt());\n mTemperatureProgressBars[i]->setFixedHeight(QWIDGETSIZE_MAX);\n }\n else\n {\n mTemperatureProgressBars[i]->setFixedHeight(mPlugin->settings()->value(\"tempBarWidth\").toInt());\n mTemperatureProgressBars[i]->setFixedWidth(QWIDGETSIZE_MAX);\n }\n }\n}\n\n\ndouble LXQtSensors::celsiusToFahrenheit(double celsius)\n{\n \/\/ Fahrenheit = 32 * (9\/5) * Celsius\n return 32 + 1.8 * celsius;\n}\n\n\nvoid LXQtSensors::initDefaultSettings()\n{\n if (!mSettings->contains(\"updateInterval\"))\n {\n mSettings->setValue(\"updateInterval\", 1);\n }\n\n if (!mSettings->contains(\"tempBarWidth\"))\n {\n mSettings->setValue(\"tempBarWidth\", 8);\n }\n\n if (!mSettings->contains(\"useFahrenheitScale\"))\n {\n mSettings->setValue(\"useFahrenheitScale\", false);\n }\n\n mSettings->beginGroup(\"chips\");\n\n \/\/ Initialize default sensors settings\n for (int i = 0; i < mDetectedChips.size(); ++i)\n {\n mSettings->beginGroup(mDetectedChips[i].getName());\n const QList& features = mDetectedChips[i].getFeatures();\n\n for (int j = 0; j < features.size(); ++j)\n {\n if (features[j].getType() == SENSORS_FEATURE_TEMP)\n {\n mSettings->beginGroup(features[j].getLabel());\n if (!mSettings->contains(\"enabled\"))\n {\n mSettings->setValue(\"enabled\", true);\n }\n\n if (!mSettings->contains(\"color\"))\n {\n \/\/ This is the default from QtDesigner\n mSettings->setValue(\"color\", QColor(qRgb(98, 140, 178)).name());\n }\n mSettings->endGroup();\n }\n }\n mSettings->endGroup();\n }\n\n mSettings->endGroup();\n\n if (!mSettings->contains(\"warningAboutHighTemperature\"))\n {\n mSettings->setValue(\"warningAboutHighTemperature\", true);\n }\n}\n\n\nProgressBar::ProgressBar(QWidget *parent):\n QProgressBar(parent)\n{\n}\n\n\nQSize ProgressBar::sizeHint() const\n{\n return QSize(20, 20);\n}\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/core\/bad_client\/bad_client.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/ext\/filters\/http\/server\/http_server_filter.h\"\n#include \"src\/core\/ext\/transport\/chttp2\/transport\/chttp2_transport.h\"\n#include \"src\/core\/lib\/channel\/channel_stack.h\"\n#include \"src\/core\/lib\/iomgr\/endpoint_pair.h\"\n#include \"src\/core\/lib\/slice\/slice_internal.h\"\n#include \"src\/core\/lib\/support\/murmur_hash.h\"\n#include \"src\/core\/lib\/support\/string.h\"\n#include \"src\/core\/lib\/surface\/completion_queue.h\"\n#include \"src\/core\/lib\/surface\/server.h\"\n#include \"test\/core\/end2end\/cq_verifier.h\"\n\n#define MIN_HTTP2_FRAME_SIZE 9\n\n\/* Args to provide to thread running server side validator *\/\ntypedef struct {\n grpc_server* server;\n grpc_completion_queue* cq;\n grpc_bad_client_server_side_validator validator;\n void* registered_method;\n gpr_event done_thd;\n} thd_args;\n\n\/* Run the server side validator and set done_thd once done *\/\nstatic void thd_func(void* arg) {\n thd_args* a = (thd_args*)arg;\n if (a->validator != nullptr) {\n a->validator(a->server, a->cq, a->registered_method);\n }\n gpr_event_set(&a->done_thd, (void*)1);\n}\n\n\/* Sets the done_write event *\/\nstatic void set_done_write(void* arg, grpc_error* error) {\n gpr_log(GPR_INFO, \"done writing\");\n gpr_event* done_write = (gpr_event*)arg;\n gpr_event_set(done_write, (void*)1);\n}\n\nstatic void server_setup_transport(void* ts, grpc_transport* transport) {\n thd_args* a = (thd_args*)ts;\n grpc_core::ExecCtx exec_ctx;\n grpc_server_setup_transport(a->server, transport, nullptr,\n grpc_server_get_channel_args(a->server));\n}\n\n\/* Sets the read_done event *\/\nstatic void set_read_done(void* arg, grpc_error* error) {\n gpr_event* read_done = (gpr_event*)arg;\n gpr_event_set(read_done, (void*)1);\n}\n\n\/* Runs client side validator *\/\nvoid grpc_run_client_side_validator(grpc_bad_client_arg* arg, uint32_t flags,\n grpc_endpoint_pair* sfd,\n grpc_completion_queue* client_cq) {\n char* hex;\n gpr_event done_write;\n if (arg->client_payload_length < 4 * 1024) {\n hex = gpr_dump(arg->client_payload, arg->client_payload_length,\n GPR_DUMP_HEX | GPR_DUMP_ASCII);\n \/* Add a debug log *\/\n gpr_log(GPR_INFO, \"TEST: %s\", hex);\n gpr_free(hex);\n } else {\n gpr_log(GPR_INFO, \"TEST: (%\" PRIdPTR \" byte long string)\",\n arg->client_payload_length);\n }\n\n grpc_slice slice = grpc_slice_from_copied_buffer(arg->client_payload,\n arg->client_payload_length);\n grpc_slice_buffer outgoing;\n grpc_closure done_write_closure;\n gpr_event_init(&done_write);\n\n grpc_slice_buffer_init(&outgoing);\n grpc_slice_buffer_add(&outgoing, slice);\n GRPC_CLOSURE_INIT(&done_write_closure, set_done_write, &done_write,\n grpc_schedule_on_exec_ctx);\n\n \/* Write data *\/\n grpc_endpoint_write(sfd->client, &outgoing, &done_write_closure);\n grpc_core::ExecCtx::Get()->Flush();\n\n \/* Await completion, unless the request is large and write may not finish\n * before the peer shuts down. *\/\n if (!(flags & GRPC_BAD_CLIENT_LARGE_REQUEST)) {\n GPR_ASSERT(\n gpr_event_wait(&done_write, grpc_timeout_seconds_to_deadline(5)));\n }\n\n if (flags & GRPC_BAD_CLIENT_DISCONNECT) {\n grpc_endpoint_shutdown(\n sfd->client, GRPC_ERROR_CREATE_FROM_STATIC_STRING(\"Forced Disconnect\"));\n grpc_endpoint_destroy(sfd->client);\n grpc_core::ExecCtx::Get()->Flush();\n sfd->client = nullptr;\n }\n\n if (sfd->client != nullptr) {\n \/* Validate client stream, if requested. *\/\n if (arg->client_validator != nullptr) {\n gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);\n grpc_slice_buffer incoming;\n grpc_slice_buffer_init(&incoming);\n \/* We may need to do multiple reads to read the complete server\n * response. *\/\n while (true) {\n gpr_event read_done_event;\n gpr_event_init(&read_done_event);\n grpc_closure read_done_closure;\n GRPC_CLOSURE_INIT(&read_done_closure, set_read_done, &read_done_event,\n grpc_schedule_on_exec_ctx);\n grpc_endpoint_read(sfd->client, &incoming, &read_done_closure);\n grpc_core::ExecCtx::Get()->Flush();\n do {\n GPR_ASSERT(gpr_time_cmp(deadline, gpr_now(deadline.clock_type)) > 0);\n \/* Perform a cq next just to provide a thread that can read incoming\n bytes on the client fd *\/\n GPR_ASSERT(grpc_completion_queue_next(\n client_cq, grpc_timeout_milliseconds_to_deadline(100),\n nullptr)\n .type == GRPC_QUEUE_TIMEOUT);\n } while (!gpr_event_get(&read_done_event));\n if (arg->client_validator(&incoming, arg->client_validator_arg)) break;\n gpr_log(GPR_INFO,\n \"client validator failed; trying additional read \"\n \"in case we didn't get all the data\");\n }\n grpc_slice_buffer_destroy_internal(&incoming);\n }\n grpc_core::ExecCtx::Get()->Flush();\n }\n GPR_ASSERT(gpr_event_wait(&done_write, grpc_timeout_seconds_to_deadline(1)));\n grpc_slice_buffer_destroy_internal(&outgoing);\n grpc_core::ExecCtx::Get()->Flush();\n}\n\nvoid grpc_run_bad_client_test(\n grpc_bad_client_server_side_validator server_validator,\n grpc_bad_client_arg args[], int num_args, uint32_t flags) {\n grpc_endpoint_pair sfd;\n thd_args a;\n grpc_transport* transport;\n grpc_core::ExecCtx exec_ctx;\n grpc_completion_queue* shutdown_cq;\n grpc_completion_queue* client_cq;\n\n \/* Init grpc *\/\n grpc_init();\n\n \/* Create endpoints *\/\n sfd = grpc_iomgr_create_endpoint_pair(\"fixture\", nullptr);\n\n \/* Create server, completion events *\/\n a.server = grpc_server_create(nullptr, nullptr);\n a.cq = grpc_completion_queue_create_for_next(nullptr);\n client_cq = grpc_completion_queue_create_for_next(nullptr);\n\n grpc_server_register_completion_queue(a.server, a.cq, nullptr);\n a.registered_method =\n grpc_server_register_method(a.server, GRPC_BAD_CLIENT_REGISTERED_METHOD,\n GRPC_BAD_CLIENT_REGISTERED_HOST,\n GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER, 0);\n grpc_server_start(a.server);\n transport = grpc_create_chttp2_transport(nullptr, sfd.server, false);\n server_setup_transport(&a, transport);\n grpc_chttp2_transport_start_reading(transport, nullptr, nullptr);\n\n \/* Bind fds to pollsets *\/\n grpc_endpoint_add_to_pollset(sfd.client, grpc_cq_pollset(client_cq));\n grpc_endpoint_add_to_pollset(sfd.server, grpc_cq_pollset(a.cq));\n\n \/* Check a ground truth *\/\n GPR_ASSERT(grpc_server_has_open_connections(a.server));\n\n gpr_thd_id id;\n gpr_event_init(&a.done_thd);\n a.validator = server_validator;\n \/* Start validator *\/\n gpr_thd_new(&id, \"grpc_bad_client\", thd_func, &a, nullptr);\n for (int i = 0; i < num_args; i++) {\n grpc_run_client_side_validator(&args[i], flags, &sfd, client_cq);\n }\n \/* Wait for server thread to finish *\/\n GPR_ASSERT(gpr_event_wait(&a.done_thd, grpc_timeout_seconds_to_deadline(1)));\n\n \/* Shutdown. *\/\n if (sfd.client != nullptr) {\n grpc_endpoint_shutdown(\n sfd.client, GRPC_ERROR_CREATE_FROM_STATIC_STRING(\"Test Shutdown\"));\n grpc_endpoint_destroy(sfd.client);\n grpc_core::ExecCtx::Get()->Flush();\n }\n\n shutdown_cq = grpc_completion_queue_create_for_pluck(nullptr);\n grpc_server_shutdown_and_notify(a.server, shutdown_cq, nullptr);\n GPR_ASSERT(grpc_completion_queue_pluck(shutdown_cq, nullptr,\n grpc_timeout_seconds_to_deadline(1),\n nullptr)\n .type == GRPC_OP_COMPLETE);\n grpc_completion_queue_destroy(shutdown_cq);\n grpc_server_destroy(a.server);\n grpc_completion_queue_destroy(a.cq);\n grpc_completion_queue_destroy(client_cq);\n grpc_shutdown();\n}\n\nbool client_connection_preface_validator(grpc_slice_buffer* incoming,\n void* arg) {\n if (incoming->count < 1) {\n return false;\n }\n grpc_slice slice = incoming->slices[0];\n \/* There should be atleast a settings frame present *\/\n if (GRPC_SLICE_LENGTH(slice) < MIN_HTTP2_FRAME_SIZE) {\n return false;\n }\n const uint8_t* p = GRPC_SLICE_START_PTR(slice);\n \/* Check the frame type (SETTINGS) *\/\n if (*(p + 3) != 4) {\n return false;\n }\n return true;\n}\n\n\/* connection preface and settings frame to be sent by the client *\/\n#define CONNECTION_PREFACE_FROM_CLIENT \\\n \"PRI * HTTP\/2.0\\r\\n\\r\\nSM\\r\\n\\r\\n\" \\\n \"\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\"\n\ngrpc_bad_client_arg connection_preface_arg = {\n client_connection_preface_validator, nullptr,\n CONNECTION_PREFACE_FROM_CLIENT, sizeof(CONNECTION_PREFACE_FROM_CLIENT) - 1};\n\nbool rst_stream_client_validator(grpc_slice_buffer* incoming, void* arg) {\n \/\/ Get last frame from incoming slice buffer.\n grpc_slice_buffer last_frame_buffer;\n grpc_slice_buffer_init(&last_frame_buffer);\n grpc_slice_buffer_trim_end(incoming, 13, &last_frame_buffer);\n GPR_ASSERT(last_frame_buffer.count == 1);\n grpc_slice last_frame = last_frame_buffer.slices[0];\n\n const uint8_t* p = GRPC_SLICE_START_PTR(last_frame);\n bool success =\n \/\/ Length == 4\n *p++ != 0 || *p++ != 0 || *p++ != 4 ||\n \/\/ Frame type (RST_STREAM)\n *p++ != 3 ||\n \/\/ Flags\n *p++ != 0 ||\n \/\/ Stream ID.\n *p++ != 0 || *p++ != 0 || *p++ != 0 || *p++ != 1 ||\n \/\/ Payload (error code)\n *p++ == 0 || *p++ == 0 || *p++ == 0 || *p == 0 || *p == 11;\n\n if (!success) {\n gpr_log(GPR_INFO, \"client expected RST_STREAM frame, not found\");\n }\n\n grpc_slice_buffer_destroy(&last_frame_buffer);\n return success;\n}\n\nstatic void* tag(intptr_t t) { return (void*)t; }\n\nvoid server_verifier_request_call(grpc_server* server,\n grpc_completion_queue* cq,\n void* registered_method) {\n grpc_call_error error;\n grpc_call* s;\n grpc_call_details call_details;\n cq_verifier* cqv = cq_verifier_create(cq);\n grpc_metadata_array request_metadata_recv;\n\n grpc_call_details_init(&call_details);\n grpc_metadata_array_init(&request_metadata_recv);\n\n error = grpc_server_request_call(server, &s, &call_details,\n &request_metadata_recv, cq, cq, tag(101));\n GPR_ASSERT(GRPC_CALL_OK == error);\n CQ_EXPECT_COMPLETION(cqv, tag(101), 1);\n cq_verify(cqv);\n\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.host, \"localhost\"));\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, \"\/foo\/bar\"));\n\n grpc_metadata_array_destroy(&request_metadata_recv);\n grpc_call_details_destroy(&call_details);\n grpc_call_unref(s);\n cq_verifier_destroy(cqv);\n}\nremove unnecessary assert\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/core\/bad_client\/bad_client.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/ext\/filters\/http\/server\/http_server_filter.h\"\n#include \"src\/core\/ext\/transport\/chttp2\/transport\/chttp2_transport.h\"\n#include \"src\/core\/lib\/channel\/channel_stack.h\"\n#include \"src\/core\/lib\/iomgr\/endpoint_pair.h\"\n#include \"src\/core\/lib\/slice\/slice_internal.h\"\n#include \"src\/core\/lib\/support\/murmur_hash.h\"\n#include \"src\/core\/lib\/support\/string.h\"\n#include \"src\/core\/lib\/surface\/completion_queue.h\"\n#include \"src\/core\/lib\/surface\/server.h\"\n#include \"test\/core\/end2end\/cq_verifier.h\"\n\n#define MIN_HTTP2_FRAME_SIZE 9\n\n\/* Args to provide to thread running server side validator *\/\ntypedef struct {\n grpc_server* server;\n grpc_completion_queue* cq;\n grpc_bad_client_server_side_validator validator;\n void* registered_method;\n gpr_event done_thd;\n} thd_args;\n\n\/* Run the server side validator and set done_thd once done *\/\nstatic void thd_func(void* arg) {\n thd_args* a = (thd_args*)arg;\n if (a->validator != nullptr) {\n a->validator(a->server, a->cq, a->registered_method);\n }\n gpr_event_set(&a->done_thd, (void*)1);\n}\n\n\/* Sets the done_write event *\/\nstatic void set_done_write(void* arg, grpc_error* error) {\n gpr_event* done_write = (gpr_event*)arg;\n gpr_event_set(done_write, (void*)1);\n}\n\nstatic void server_setup_transport(void* ts, grpc_transport* transport) {\n thd_args* a = (thd_args*)ts;\n grpc_core::ExecCtx exec_ctx;\n grpc_server_setup_transport(a->server, transport, nullptr,\n grpc_server_get_channel_args(a->server));\n}\n\n\/* Sets the read_done event *\/\nstatic void set_read_done(void* arg, grpc_error* error) {\n gpr_event* read_done = (gpr_event*)arg;\n gpr_event_set(read_done, (void*)1);\n}\n\n\/* Runs client side validator *\/\nvoid grpc_run_client_side_validator(grpc_bad_client_arg* arg, uint32_t flags,\n grpc_endpoint_pair* sfd,\n grpc_completion_queue* client_cq) {\n char* hex;\n gpr_event done_write;\n if (arg->client_payload_length < 4 * 1024) {\n hex = gpr_dump(arg->client_payload, arg->client_payload_length,\n GPR_DUMP_HEX | GPR_DUMP_ASCII);\n \/* Add a debug log *\/\n gpr_log(GPR_INFO, \"TEST: %s\", hex);\n gpr_free(hex);\n } else {\n gpr_log(GPR_INFO, \"TEST: (%\" PRIdPTR \" byte long string)\",\n arg->client_payload_length);\n }\n\n grpc_slice slice = grpc_slice_from_copied_buffer(arg->client_payload,\n arg->client_payload_length);\n grpc_slice_buffer outgoing;\n grpc_closure done_write_closure;\n gpr_event_init(&done_write);\n\n grpc_slice_buffer_init(&outgoing);\n grpc_slice_buffer_add(&outgoing, slice);\n GRPC_CLOSURE_INIT(&done_write_closure, set_done_write, &done_write,\n grpc_schedule_on_exec_ctx);\n\n \/* Write data *\/\n grpc_endpoint_write(sfd->client, &outgoing, &done_write_closure);\n grpc_core::ExecCtx::Get()->Flush();\n\n \/* Await completion, unless the request is large and write may not finish\n * before the peer shuts down. *\/\n if (!(flags & GRPC_BAD_CLIENT_LARGE_REQUEST)) {\n GPR_ASSERT(\n gpr_event_wait(&done_write, grpc_timeout_seconds_to_deadline(5)));\n }\n\n if (flags & GRPC_BAD_CLIENT_DISCONNECT) {\n grpc_endpoint_shutdown(\n sfd->client, GRPC_ERROR_CREATE_FROM_STATIC_STRING(\"Forced Disconnect\"));\n grpc_endpoint_destroy(sfd->client);\n grpc_core::ExecCtx::Get()->Flush();\n sfd->client = nullptr;\n }\n\n if (sfd->client != nullptr) {\n \/* Validate client stream, if requested. *\/\n if (arg->client_validator != nullptr) {\n gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);\n grpc_slice_buffer incoming;\n grpc_slice_buffer_init(&incoming);\n \/* We may need to do multiple reads to read the complete server\n * response. *\/\n while (true) {\n gpr_event read_done_event;\n gpr_event_init(&read_done_event);\n grpc_closure read_done_closure;\n GRPC_CLOSURE_INIT(&read_done_closure, set_read_done, &read_done_event,\n grpc_schedule_on_exec_ctx);\n grpc_endpoint_read(sfd->client, &incoming, &read_done_closure);\n grpc_core::ExecCtx::Get()->Flush();\n do {\n GPR_ASSERT(gpr_time_cmp(deadline, gpr_now(deadline.clock_type)) > 0);\n \/* Perform a cq next just to provide a thread that can read incoming\n bytes on the client fd *\/\n GPR_ASSERT(grpc_completion_queue_next(\n client_cq, grpc_timeout_milliseconds_to_deadline(100),\n nullptr)\n .type == GRPC_QUEUE_TIMEOUT);\n } while (!gpr_event_get(&read_done_event));\n if (arg->client_validator(&incoming, arg->client_validator_arg)) break;\n gpr_log(GPR_INFO,\n \"client validator failed; trying additional read \"\n \"in case we didn't get all the data\");\n }\n grpc_slice_buffer_destroy_internal(&incoming);\n }\n grpc_core::ExecCtx::Get()->Flush();\n }\n grpc_slice_buffer_destroy_internal(&outgoing);\n grpc_core::ExecCtx::Get()->Flush();\n}\n\nvoid grpc_run_bad_client_test(\n grpc_bad_client_server_side_validator server_validator,\n grpc_bad_client_arg args[], int num_args, uint32_t flags) {\n grpc_endpoint_pair sfd;\n thd_args a;\n grpc_transport* transport;\n grpc_core::ExecCtx exec_ctx;\n grpc_completion_queue* shutdown_cq;\n grpc_completion_queue* client_cq;\n\n \/* Init grpc *\/\n grpc_init();\n\n \/* Create endpoints *\/\n sfd = grpc_iomgr_create_endpoint_pair(\"fixture\", nullptr);\n\n \/* Create server, completion events *\/\n a.server = grpc_server_create(nullptr, nullptr);\n a.cq = grpc_completion_queue_create_for_next(nullptr);\n client_cq = grpc_completion_queue_create_for_next(nullptr);\n\n grpc_server_register_completion_queue(a.server, a.cq, nullptr);\n a.registered_method =\n grpc_server_register_method(a.server, GRPC_BAD_CLIENT_REGISTERED_METHOD,\n GRPC_BAD_CLIENT_REGISTERED_HOST,\n GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER, 0);\n grpc_server_start(a.server);\n transport = grpc_create_chttp2_transport(nullptr, sfd.server, false);\n server_setup_transport(&a, transport);\n grpc_chttp2_transport_start_reading(transport, nullptr, nullptr);\n\n \/* Bind fds to pollsets *\/\n grpc_endpoint_add_to_pollset(sfd.client, grpc_cq_pollset(client_cq));\n grpc_endpoint_add_to_pollset(sfd.server, grpc_cq_pollset(a.cq));\n\n \/* Check a ground truth *\/\n GPR_ASSERT(grpc_server_has_open_connections(a.server));\n\n gpr_thd_id id;\n gpr_event_init(&a.done_thd);\n a.validator = server_validator;\n \/* Start validator *\/\n gpr_thd_new(&id, \"grpc_bad_client\", thd_func, &a, nullptr);\n for (int i = 0; i < num_args; i++) {\n grpc_run_client_side_validator(&args[i], flags, &sfd, client_cq);\n }\n \/* Wait for server thread to finish *\/\n GPR_ASSERT(gpr_event_wait(&a.done_thd, grpc_timeout_seconds_to_deadline(1)));\n\n \/* Shutdown. *\/\n if (sfd.client != nullptr) {\n grpc_endpoint_shutdown(\n sfd.client, GRPC_ERROR_CREATE_FROM_STATIC_STRING(\"Test Shutdown\"));\n grpc_endpoint_destroy(sfd.client);\n grpc_core::ExecCtx::Get()->Flush();\n }\n\n shutdown_cq = grpc_completion_queue_create_for_pluck(nullptr);\n grpc_server_shutdown_and_notify(a.server, shutdown_cq, nullptr);\n GPR_ASSERT(grpc_completion_queue_pluck(shutdown_cq, nullptr,\n grpc_timeout_seconds_to_deadline(1),\n nullptr)\n .type == GRPC_OP_COMPLETE);\n grpc_completion_queue_destroy(shutdown_cq);\n grpc_server_destroy(a.server);\n grpc_completion_queue_destroy(a.cq);\n grpc_completion_queue_destroy(client_cq);\n grpc_shutdown();\n}\n\nbool client_connection_preface_validator(grpc_slice_buffer* incoming,\n void* arg) {\n if (incoming->count < 1) {\n return false;\n }\n grpc_slice slice = incoming->slices[0];\n \/* There should be atleast a settings frame present *\/\n if (GRPC_SLICE_LENGTH(slice) < MIN_HTTP2_FRAME_SIZE) {\n return false;\n }\n const uint8_t* p = GRPC_SLICE_START_PTR(slice);\n \/* Check the frame type (SETTINGS) *\/\n if (*(p + 3) != 4) {\n return false;\n }\n return true;\n}\n\n\/* connection preface and settings frame to be sent by the client *\/\n#define CONNECTION_PREFACE_FROM_CLIENT \\\n \"PRI * HTTP\/2.0\\r\\n\\r\\nSM\\r\\n\\r\\n\" \\\n \"\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\"\n\ngrpc_bad_client_arg connection_preface_arg = {\n client_connection_preface_validator, nullptr,\n CONNECTION_PREFACE_FROM_CLIENT, sizeof(CONNECTION_PREFACE_FROM_CLIENT) - 1};\n\nbool rst_stream_client_validator(grpc_slice_buffer* incoming, void* arg) {\n \/\/ Get last frame from incoming slice buffer.\n grpc_slice_buffer last_frame_buffer;\n grpc_slice_buffer_init(&last_frame_buffer);\n grpc_slice_buffer_trim_end(incoming, 13, &last_frame_buffer);\n GPR_ASSERT(last_frame_buffer.count == 1);\n grpc_slice last_frame = last_frame_buffer.slices[0];\n\n const uint8_t* p = GRPC_SLICE_START_PTR(last_frame);\n bool success =\n \/\/ Length == 4\n *p++ != 0 || *p++ != 0 || *p++ != 4 ||\n \/\/ Frame type (RST_STREAM)\n *p++ != 3 ||\n \/\/ Flags\n *p++ != 0 ||\n \/\/ Stream ID.\n *p++ != 0 || *p++ != 0 || *p++ != 0 || *p++ != 1 ||\n \/\/ Payload (error code)\n *p++ == 0 || *p++ == 0 || *p++ == 0 || *p == 0 || *p == 11;\n\n if (!success) {\n gpr_log(GPR_INFO, \"client expected RST_STREAM frame, not found\");\n }\n\n grpc_slice_buffer_destroy(&last_frame_buffer);\n return success;\n}\n\nstatic void* tag(intptr_t t) { return (void*)t; }\n\nvoid server_verifier_request_call(grpc_server* server,\n grpc_completion_queue* cq,\n void* registered_method) {\n grpc_call_error error;\n grpc_call* s;\n grpc_call_details call_details;\n cq_verifier* cqv = cq_verifier_create(cq);\n grpc_metadata_array request_metadata_recv;\n\n grpc_call_details_init(&call_details);\n grpc_metadata_array_init(&request_metadata_recv);\n\n error = grpc_server_request_call(server, &s, &call_details,\n &request_metadata_recv, cq, cq, tag(101));\n GPR_ASSERT(GRPC_CALL_OK == error);\n CQ_EXPECT_COMPLETION(cqv, tag(101), 1);\n cq_verify(cqv);\n\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.host, \"localhost\"));\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, \"\/foo\/bar\"));\n\n grpc_metadata_array_destroy(&request_metadata_recv);\n grpc_call_details_destroy(&call_details);\n grpc_call_unref(s);\n cq_verifier_destroy(cqv);\n}\n<|endoftext|>"} {"text":"#include \"AppInfo.h\"\n#include \"FileUtils.h\"\n#include \"Log.h\"\n#include \"Platform.h\"\n#include \"ProcessUtils.h\"\n#include \"StringUtils.h\"\n#include \"UpdateScript.h\"\n#include \"UpdaterOptions.h\"\n\n#include \"tinythread.h\"\n\n#if defined(PLATFORM_LINUX)\n #include \"UpdateDialogGtkWrapper.h\"\n #include \"UpdateDialogAscii.h\"\n#endif\n\n#if defined(PLATFORM_MAC)\n #include \"MacBundle.h\"\n #include \"UpdateDialogCocoa.h\"\n#endif\n\n#if defined(PLATFORM_WINDOWS)\n #include \"UpdateDialogWin32.h\"\n#endif\n\n#include \n\n#define UPDATER_VERSION \"0.7\"\n\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer);\n\nvoid runUpdaterThread(void* arg)\n{\n#ifdef PLATFORM_MAC\n\t\/\/ create an autorelease pool to free any temporary objects\n\t\/\/ created by Cocoa whilst handling notifications from the UpdateInstaller\n\tvoid* pool = UpdateDialogCocoa::createAutoreleasePool();\n#endif\n\n\ttry\n\t{\n\t\tUpdateInstaller* installer = static_cast(arg);\n\t\tinstaller->run();\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tLOG(Error,\"Unexpected exception \" + std::string(ex.what()));\n\t}\n\n#ifdef PLATFORM_MAC\n\tUpdateDialogCocoa::releaseAutoreleasePool(pool);\n#endif\n}\n\n#ifdef PLATFORM_MAC\nextern unsigned char Info_plist[];\nextern unsigned int Info_plist_len;\n\nextern unsigned char mac_icns[];\nextern unsigned int mac_icns_len;\n\nbool unpackBundle(int argc, char** argv)\n{\n\tMacBundle bundle(FileUtils::tempPath(),AppInfo::name());\n\tstd::string currentExePath = ProcessUtils::currentProcessPath();\n\n\tif (currentExePath.find(bundle.bundlePath()) != std::string::npos)\n\t{\n\t\t\/\/ already running from a bundle\n\t\treturn false;\n\t}\n\tLOG(Info,\"Creating bundle \" + bundle.bundlePath());\n\n\t\/\/ create a Mac app bundle\n\tstd::string plistContent(reinterpret_cast(Info_plist),Info_plist_len);\n\tstd::string iconContent(reinterpret_cast(mac_icns),mac_icns_len);\n\tbundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath());\n\n\tstd::list args;\n\tfor (int i = 1; i < argc; i++)\n\t{\n\t\targs.push_back(argv[i]);\n\t}\n\tProcessUtils::runSync(bundle.executablePath(),args);\n\treturn true;\n}\n#endif\n\nint main(int argc, char** argv)\n{\n#ifdef PLATFORM_MAC\n\tvoid* pool = UpdateDialogCocoa::createAutoreleasePool();\n#endif\n\t\n\tLog::instance()->open(AppInfo::logFilePath());\n\n#ifdef PLATFORM_MAC\n\t\/\/ when the updater is run for the first time, create a Mac app bundle\n\t\/\/ and re-launch the application from the bundle. This permits\n\t\/\/ setting up bundle properties (such as application icon)\n\tif (unpackBundle(argc,argv))\n\t{\n\t\treturn 0;\n\t}\n#endif\n\n\tUpdaterOptions options;\n\toptions.parse(argc,argv);\n\tif (options.showVersion)\n\t{\n\t\tstd::cout << \"Update installer version \" << UPDATER_VERSION << std::endl;\n\t\treturn 0;\n\t}\n\n\tUpdateInstaller installer;\n\tUpdateScript script;\n\n\tif (!options.scriptPath.empty())\n\t{\n\t\tscript.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str()));\n\t}\n\n\tLOG(Info,\"started updater. install-dir: \" + options.installDir\n\t + \", package-dir: \" + options.packageDir\n\t + \", wait-pid: \" + intToStr(options.waitPid)\n\t + \", script-path: \" + options.scriptPath\n\t + \", mode: \" + intToStr(options.mode));\n\n\tinstaller.setMode(options.mode);\n\tinstaller.setInstallDir(options.installDir);\n\tinstaller.setPackageDir(options.packageDir);\n\tinstaller.setScript(&script);\n\tinstaller.setWaitPid(options.waitPid);\n\tinstaller.setForceElevated(options.forceElevated);\n\n\tif (options.mode == UpdateInstaller::Main)\n\t{\n\t\trunWithUi(argc,argv,&installer);\n\t}\n\telse\n\t{\n\t\tinstaller.run();\n\t}\n\n#ifdef PLATFORM_MAC\n\tUpdateDialogCocoa::releaseAutoreleasePool(pool);\n#endif\n\n\treturn 0;\n}\n\n#ifdef PLATFORM_LINUX\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer)\n{\n\tUpdateDialogAscii asciiDialog;\n\tUpdateDialogGtkWrapper dialog;\n\tbool useGtk = dialog.init(argc,argv);\n\tif (useGtk)\n\t{\n\t\tinstaller->setObserver(&dialog);\n\t}\n\telse\n\t{\n\t\tasciiDialog.init();\n\t\tinstaller->setObserver(&asciiDialog);\n\t}\n\ttthread::thread updaterThread(runUpdaterThread,installer);\n\tif (useGtk)\n\t{\n\t\tdialog.exec();\n\t}\n\tupdaterThread.join();\n}\n#endif\n\n#ifdef PLATFORM_MAC\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer)\n{\n\tUpdateDialogCocoa dialog;\n\tinstaller->setObserver(&dialog);\n\tdialog.init();\n\ttthread::thread updaterThread(runUpdaterThread,installer);\n\tdialog.exec();\n\tupdaterThread.join();\n}\n#endif\n\n#ifdef PLATFORM_WINDOWS\n\/\/ application entry point under Windows\nint CALLBACK WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPSTR lpCmdLine,\n int nCmdShow)\n{\n\tint argc = 0;\n\tchar** argv;\n\tProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv);\n\treturn main(argc,argv);\n}\n\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer)\n{\n\tUpdateDialogWin32 dialog;\n\tinstaller->setObserver(&dialog);\n\tdialog.init();\n\ttthread::thread updaterThread(runUpdaterThread,installer);\n\tdialog.exec();\n\tupdaterThread.join();\n}\n#endif\nBump the trunk version number to 0.8#include \"AppInfo.h\"\n#include \"FileUtils.h\"\n#include \"Log.h\"\n#include \"Platform.h\"\n#include \"ProcessUtils.h\"\n#include \"StringUtils.h\"\n#include \"UpdateScript.h\"\n#include \"UpdaterOptions.h\"\n\n#include \"tinythread.h\"\n\n#if defined(PLATFORM_LINUX)\n #include \"UpdateDialogGtkWrapper.h\"\n #include \"UpdateDialogAscii.h\"\n#endif\n\n#if defined(PLATFORM_MAC)\n #include \"MacBundle.h\"\n #include \"UpdateDialogCocoa.h\"\n#endif\n\n#if defined(PLATFORM_WINDOWS)\n #include \"UpdateDialogWin32.h\"\n#endif\n\n#include \n\n#define UPDATER_VERSION \"0.8\"\n\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer);\n\nvoid runUpdaterThread(void* arg)\n{\n#ifdef PLATFORM_MAC\n\t\/\/ create an autorelease pool to free any temporary objects\n\t\/\/ created by Cocoa whilst handling notifications from the UpdateInstaller\n\tvoid* pool = UpdateDialogCocoa::createAutoreleasePool();\n#endif\n\n\ttry\n\t{\n\t\tUpdateInstaller* installer = static_cast(arg);\n\t\tinstaller->run();\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tLOG(Error,\"Unexpected exception \" + std::string(ex.what()));\n\t}\n\n#ifdef PLATFORM_MAC\n\tUpdateDialogCocoa::releaseAutoreleasePool(pool);\n#endif\n}\n\n#ifdef PLATFORM_MAC\nextern unsigned char Info_plist[];\nextern unsigned int Info_plist_len;\n\nextern unsigned char mac_icns[];\nextern unsigned int mac_icns_len;\n\nbool unpackBundle(int argc, char** argv)\n{\n\tMacBundle bundle(FileUtils::tempPath(),AppInfo::name());\n\tstd::string currentExePath = ProcessUtils::currentProcessPath();\n\n\tif (currentExePath.find(bundle.bundlePath()) != std::string::npos)\n\t{\n\t\t\/\/ already running from a bundle\n\t\treturn false;\n\t}\n\tLOG(Info,\"Creating bundle \" + bundle.bundlePath());\n\n\t\/\/ create a Mac app bundle\n\tstd::string plistContent(reinterpret_cast(Info_plist),Info_plist_len);\n\tstd::string iconContent(reinterpret_cast(mac_icns),mac_icns_len);\n\tbundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath());\n\n\tstd::list args;\n\tfor (int i = 1; i < argc; i++)\n\t{\n\t\targs.push_back(argv[i]);\n\t}\n\tProcessUtils::runSync(bundle.executablePath(),args);\n\treturn true;\n}\n#endif\n\nint main(int argc, char** argv)\n{\n#ifdef PLATFORM_MAC\n\tvoid* pool = UpdateDialogCocoa::createAutoreleasePool();\n#endif\n\t\n\tLog::instance()->open(AppInfo::logFilePath());\n\n#ifdef PLATFORM_MAC\n\t\/\/ when the updater is run for the first time, create a Mac app bundle\n\t\/\/ and re-launch the application from the bundle. This permits\n\t\/\/ setting up bundle properties (such as application icon)\n\tif (unpackBundle(argc,argv))\n\t{\n\t\treturn 0;\n\t}\n#endif\n\n\tUpdaterOptions options;\n\toptions.parse(argc,argv);\n\tif (options.showVersion)\n\t{\n\t\tstd::cout << \"Update installer version \" << UPDATER_VERSION << std::endl;\n\t\treturn 0;\n\t}\n\n\tUpdateInstaller installer;\n\tUpdateScript script;\n\n\tif (!options.scriptPath.empty())\n\t{\n\t\tscript.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str()));\n\t}\n\n\tLOG(Info,\"started updater. install-dir: \" + options.installDir\n\t + \", package-dir: \" + options.packageDir\n\t + \", wait-pid: \" + intToStr(options.waitPid)\n\t + \", script-path: \" + options.scriptPath\n\t + \", mode: \" + intToStr(options.mode));\n\n\tinstaller.setMode(options.mode);\n\tinstaller.setInstallDir(options.installDir);\n\tinstaller.setPackageDir(options.packageDir);\n\tinstaller.setScript(&script);\n\tinstaller.setWaitPid(options.waitPid);\n\tinstaller.setForceElevated(options.forceElevated);\n\n\tif (options.mode == UpdateInstaller::Main)\n\t{\n\t\trunWithUi(argc,argv,&installer);\n\t}\n\telse\n\t{\n\t\tinstaller.run();\n\t}\n\n#ifdef PLATFORM_MAC\n\tUpdateDialogCocoa::releaseAutoreleasePool(pool);\n#endif\n\n\treturn 0;\n}\n\n#ifdef PLATFORM_LINUX\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer)\n{\n\tUpdateDialogAscii asciiDialog;\n\tUpdateDialogGtkWrapper dialog;\n\tbool useGtk = dialog.init(argc,argv);\n\tif (useGtk)\n\t{\n\t\tinstaller->setObserver(&dialog);\n\t}\n\telse\n\t{\n\t\tasciiDialog.init();\n\t\tinstaller->setObserver(&asciiDialog);\n\t}\n\ttthread::thread updaterThread(runUpdaterThread,installer);\n\tif (useGtk)\n\t{\n\t\tdialog.exec();\n\t}\n\tupdaterThread.join();\n}\n#endif\n\n#ifdef PLATFORM_MAC\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer)\n{\n\tUpdateDialogCocoa dialog;\n\tinstaller->setObserver(&dialog);\n\tdialog.init();\n\ttthread::thread updaterThread(runUpdaterThread,installer);\n\tdialog.exec();\n\tupdaterThread.join();\n}\n#endif\n\n#ifdef PLATFORM_WINDOWS\n\/\/ application entry point under Windows\nint CALLBACK WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPSTR lpCmdLine,\n int nCmdShow)\n{\n\tint argc = 0;\n\tchar** argv;\n\tProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv);\n\treturn main(argc,argv);\n}\n\nvoid runWithUi(int argc, char** argv, UpdateInstaller* installer)\n{\n\tUpdateDialogWin32 dialog;\n\tinstaller->setObserver(&dialog);\n\tdialog.init();\n\ttthread::thread updaterThread(runUpdaterThread,installer);\n\tdialog.exec();\n\tupdaterThread.join();\n}\n#endif\n<|endoftext|>"} {"text":"#include \"global_include.h\"\n#include \"action_impl.h\"\n#include \"dronelink_impl.h\"\n#include \"telemetry.h\"\n#include \n\nnamespace dronelink {\n\nActionImpl::ActionImpl() :\n _in_air_state_known(false),\n _in_air(false)\n{\n}\n\nActionImpl::~ActionImpl()\n{\n\n}\n\nvoid ActionImpl::init()\n{\n using namespace std::placeholders; \/\/ for `_1`\n\n _parent->register_mavlink_message_handler(\n MAVLINK_MSG_ID_EXTENDED_SYS_STATE,\n std::bind(&ActionImpl::process_extended_sys_state, this, _1), (void *)this);\n}\n\nvoid ActionImpl::deinit()\n{\n _parent->unregister_all_mavlink_message_handlers((void *)this);\n}\n\nAction::Result ActionImpl::arm() const\n{\n if (!is_arm_allowed()) {\n return Action::Result::COMMAND_DENIED;\n }\n\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::disarm() const\n{\n if (!is_disarm_allowed()) {\n return Action::Result::COMMAND_DENIED;\n }\n\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::kill() const\n{\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::takeoff() const\n{\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_NAV_TAKEOFF,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::land() const\n{\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_NAV_LAND,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::return_to_land() const\n{\n uint8_t mode = MAV_MODE_AUTO_ARMED | VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED;\n uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;\n uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;\n\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_DO_SET_MODE,\n DeviceImpl::CommandParams {float(mode),\n float(custom_mode),\n float(custom_sub_mode),\n NAN, NAN, NAN, NAN}));\n}\n\nvoid ActionImpl::arm_async(const Action::result_callback_t &callback)\n{\n if (!is_arm_allowed()) {\n callback(Action::Result::COMMAND_DENIED);\n return;\n }\n\n _parent->send_command_with_ack_async(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::disarm_async(const Action::result_callback_t &callback)\n{\n if (!is_disarm_allowed()) {\n callback(Action::Result::COMMAND_DENIED);\n return;\n }\n\n _parent->send_command_with_ack_async(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::kill_async(const Action::result_callback_t &callback)\n{\n _parent->send_command_with_ack_async(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::takeoff_async(const Action::result_callback_t &callback)\n{\n _parent->send_command_with_ack_async(\n MAV_CMD_NAV_TAKEOFF,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::land_async(const Action::result_callback_t &callback)\n{\n _parent->send_command_with_ack_async(\n MAV_CMD_NAV_LAND,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::return_to_land_async(const Action::result_callback_t &callback)\n{\n\n uint8_t mode = MAV_MODE_AUTO_ARMED | VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED;\n uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;\n uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;\n\n _parent->send_command_with_ack_async(\n MAV_CMD_DO_SET_MODE,\n DeviceImpl::CommandParams {float(mode),\n float(custom_mode),\n float(custom_sub_mode),\n NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nbool ActionImpl::is_arm_allowed() const\n{\n if (!_in_air_state_known) {\n return false;\n }\n\n if (_in_air) {\n return false;\n }\n\n return true;\n}\n\nbool ActionImpl::is_disarm_allowed() const\n{\n if (!_in_air_state_known) {\n Debug() << \"in air state unknown\";\n return false;\n }\n\n if (_in_air) {\n Debug() << \"still in air\";\n return false;\n }\n\n return true;\n}\n\nvoid ActionImpl::process_extended_sys_state(const mavlink_message_t &message)\n{\n mavlink_extended_sys_state_t extended_sys_state;\n mavlink_msg_extended_sys_state_decode(&message, &extended_sys_state);\n if (extended_sys_state.landed_state == MAV_LANDED_STATE_IN_AIR) {\n _in_air = true;\n } else if (extended_sys_state.landed_state == MAV_LANDED_STATE_ON_GROUND) {\n _in_air = false;\n }\n _in_air_state_known = true;\n}\n\nAction::Result\nActionImpl::action_result_from_command_result(DeviceImpl::CommandResult result)\n{\n switch (result) {\n case DeviceImpl::CommandResult::SUCCESS:\n return Action::Result::SUCCESS;\n case DeviceImpl::CommandResult::NO_DEVICE:\n return Action::Result::NO_DEVICE;\n case DeviceImpl::CommandResult::CONNECTION_ERROR:\n return Action::Result::CONNECTION_ERROR;\n case DeviceImpl::CommandResult::BUSY:\n return Action::Result::BUSY;\n case DeviceImpl::CommandResult::COMMAND_DENIED:\n return Action::Result::COMMAND_DENIED;\n case DeviceImpl::CommandResult::TIMEOUT:\n return Action::Result::TIMEOUT;\n default:\n return Action::Result::UNKNOWN;\n }\n}\n\nvoid ActionImpl::command_result_callback(DeviceImpl::CommandResult command_result,\n const Action::result_callback_t &callback)\n{\n Action::Result action_result = action_result_from_command_result(command_result);\n\n callback(action_result);\n}\n\n\n} \/\/ namespace dronelink\naction: put armed flag correctly in DO_SET_MODE#include \"global_include.h\"\n#include \"action_impl.h\"\n#include \"dronelink_impl.h\"\n#include \"telemetry.h\"\n#include \n\nnamespace dronelink {\n\nActionImpl::ActionImpl() :\n _in_air_state_known(false),\n _in_air(false)\n{\n}\n\nActionImpl::~ActionImpl()\n{\n\n}\n\nvoid ActionImpl::init()\n{\n using namespace std::placeholders; \/\/ for `_1`\n\n _parent->register_mavlink_message_handler(\n MAVLINK_MSG_ID_EXTENDED_SYS_STATE,\n std::bind(&ActionImpl::process_extended_sys_state, this, _1), (void *)this);\n}\n\nvoid ActionImpl::deinit()\n{\n _parent->unregister_all_mavlink_message_handlers((void *)this);\n}\n\nAction::Result ActionImpl::arm() const\n{\n if (!is_arm_allowed()) {\n return Action::Result::COMMAND_DENIED;\n }\n\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::disarm() const\n{\n if (!is_disarm_allowed()) {\n return Action::Result::COMMAND_DENIED;\n }\n\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::kill() const\n{\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::takeoff() const\n{\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_NAV_TAKEOFF,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::land() const\n{\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_NAV_LAND,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));\n}\n\nAction::Result ActionImpl::return_to_land() const\n{\n \/\/ Note: the safety flag is not needed in future versions of the PX4 Firmware\n \/\/ but want to be rather safe than sorry.\n uint8_t flag_safety_armed = _parent->is_armed() ? MAV_MODE_FLAG_SAFETY_ARMED : 0;\n\n uint8_t mode = VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED |\n flag_safety_armed;\n uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;\n uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;\n\n return action_result_from_command_result(\n _parent->send_command_with_ack(\n MAV_CMD_DO_SET_MODE,\n DeviceImpl::CommandParams {float(mode),\n float(custom_mode),\n float(custom_sub_mode),\n NAN, NAN, NAN, NAN}));\n}\n\nvoid ActionImpl::arm_async(const Action::result_callback_t &callback)\n{\n if (!is_arm_allowed()) {\n callback(Action::Result::COMMAND_DENIED);\n return;\n }\n\n _parent->send_command_with_ack_async(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::disarm_async(const Action::result_callback_t &callback)\n{\n if (!is_disarm_allowed()) {\n callback(Action::Result::COMMAND_DENIED);\n return;\n }\n\n _parent->send_command_with_ack_async(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::kill_async(const Action::result_callback_t &callback)\n{\n _parent->send_command_with_ack_async(\n MAV_CMD_COMPONENT_ARM_DISARM,\n DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::takeoff_async(const Action::result_callback_t &callback)\n{\n _parent->send_command_with_ack_async(\n MAV_CMD_NAV_TAKEOFF,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::land_async(const Action::result_callback_t &callback)\n{\n _parent->send_command_with_ack_async(\n MAV_CMD_NAV_LAND,\n DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nvoid ActionImpl::return_to_land_async(const Action::result_callback_t &callback)\n{\n \/\/ Note: the safety flag is not needed in future versions of the PX4 Firmware\n \/\/ but want to be rather safe than sorry.\n uint8_t flag_safety_armed = _parent->is_armed() ? MAV_MODE_FLAG_SAFETY_ARMED : 0;\n\n uint8_t mode = VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED |\n flag_safety_armed;\n uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;\n uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;\n\n _parent->send_command_with_ack_async(\n MAV_CMD_DO_SET_MODE,\n DeviceImpl::CommandParams {float(mode),\n float(custom_mode),\n float(custom_sub_mode),\n NAN, NAN, NAN, NAN},\n std::bind(&ActionImpl::command_result_callback,\n std::placeholders::_1,\n callback));\n}\n\nbool ActionImpl::is_arm_allowed() const\n{\n if (!_in_air_state_known) {\n return false;\n }\n\n if (_in_air) {\n return false;\n }\n\n return true;\n}\n\nbool ActionImpl::is_disarm_allowed() const\n{\n if (!_in_air_state_known) {\n Debug() << \"in air state unknown\";\n return false;\n }\n\n if (_in_air) {\n Debug() << \"still in air\";\n return false;\n }\n\n return true;\n}\n\nvoid ActionImpl::process_extended_sys_state(const mavlink_message_t &message)\n{\n mavlink_extended_sys_state_t extended_sys_state;\n mavlink_msg_extended_sys_state_decode(&message, &extended_sys_state);\n if (extended_sys_state.landed_state == MAV_LANDED_STATE_IN_AIR) {\n _in_air = true;\n } else if (extended_sys_state.landed_state == MAV_LANDED_STATE_ON_GROUND) {\n _in_air = false;\n }\n _in_air_state_known = true;\n}\n\nAction::Result\nActionImpl::action_result_from_command_result(DeviceImpl::CommandResult result)\n{\n switch (result) {\n case DeviceImpl::CommandResult::SUCCESS:\n return Action::Result::SUCCESS;\n case DeviceImpl::CommandResult::NO_DEVICE:\n return Action::Result::NO_DEVICE;\n case DeviceImpl::CommandResult::CONNECTION_ERROR:\n return Action::Result::CONNECTION_ERROR;\n case DeviceImpl::CommandResult::BUSY:\n return Action::Result::BUSY;\n case DeviceImpl::CommandResult::COMMAND_DENIED:\n return Action::Result::COMMAND_DENIED;\n case DeviceImpl::CommandResult::TIMEOUT:\n return Action::Result::TIMEOUT;\n default:\n return Action::Result::UNKNOWN;\n }\n}\n\nvoid ActionImpl::command_result_callback(DeviceImpl::CommandResult command_result,\n const Action::result_callback_t &callback)\n{\n Action::Result action_result = action_result_from_command_result(command_result);\n\n callback(action_result);\n}\n\n\n} \/\/ namespace dronelink\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"..\/DBHandler\/HeaderFiles\/DBHandler.h\"\n#include \"JPetCalibration.h\"\nnamespace JPetCalibration {\n\tusing namespace std;\n\tclass Exception:public exception{\n\tpublic:\n\t\tException(const string&&msg);\n\t\tvirtual ~Exception() throw();\n\t\tvirtual const char* what() const throw();\n\tprivate:\n\t\tstring m_msg;\n\t};\n\n\tusing namespace std;\n\tusing namespace pqxx;\n\tusing namespace DB::SERVICES;\n\tException::Exception(const string&& msg):m_msg(msg){}\n\tException::~Exception()throw(){}\n\tconst char* Exception::what() const throw(){\n\t\treturn m_msg.c_str();\n\t}\n\n\tCalibrationType::CalibrationType(const CalibrationType& source)\n\t:m_name(source.m_name),m_id(source.m_id),m_count(source.m_count),m_formula(source.m_formula){}\n\n\tCalibrationType::CalibrationType(const result::const_iterator&row)\n\t:m_name(row[\"name\"].as()),m_id(row[\"type_id\"].as())\n\t,m_count(row[\"param_count\"].as()),m_formula(row[\"formula\"].as()){}\n\n\tCalibrationType::CalibrationType(const string& n,const size_t count, const string& f)\n\t:m_name(n),m_id(0),m_count(count),m_formula(f){}\n\n\tCalibrationType::CalibrationType(const string&&n,const size_t count,const string&&f)\n\t:m_name(n),m_id(0),m_count(count),m_formula(f){}\n\n\tCalibrationType::~CalibrationType(){}\n\tconst size_t CalibrationType::id()const{return m_id;}\n\tconst string& CalibrationType::name()const{return m_name;}\n\tconst size_t CalibrationType::param_count()const{return m_count;}\n\tconst string& CalibrationType::formula()const{return m_formula;}\n\n\tCalibrationTypeEdit::CalibrationTypeEdit(){}\n\tCalibrationTypeEdit::~CalibrationTypeEdit(){}\n\tconst vector CalibrationTypeEdit::GetTypes()const{\n\t\tresult data=DBHandler::getInstance().querry(\"SELECT * FROM getcalibrationtypes();\");\n\t\tvector res;\n\t\tfor(const auto&row:data)res.push_back(CalibrationType(row));\n\t\treturn res;\n\t}\n\tvoid CalibrationTypeEdit::AddType(const CalibrationType& type){\n\t\tif(type.id()>0)throw Exception(\"CalibrationInterface: attempt to insert CalibrationType that already exists\");\n\t\tstring req=\"SELECT * FROM insert_calibrationtype(\";\n\t\treq+=\"'\"+type.name()+\"',\"+to_string(type.param_count())+\",'\"+type.formula()+\"');\";\n\t\tDBHandler::getInstance().querry(req);\n\t}\n\tvoid CalibrationTypeEdit::AddType(const CalibrationType&& type){AddType(type);}\n\n\n\tCalibration::Calibration(const string&n,const size_t count,const string& f,const string¶ms)\n\t:m_name(n),m_formula(f),m_encoded_params(params){\n\t\tstringstream ss(params);\n\t\tvector tokens;\n\t\tcopy(istream_iterator(ss),\n\t\t istream_iterator(),\n\t\t back_inserter(tokens));\n\t\tfor(const string&token:tokens)\n\t\t\tif(m_params.size()&field_names)\n\t:Calibration(row[field_names[0]].as(),row[field_names[1]].as(),row[field_names[2]].as(),row[field_names[3]].as()){}\n\tCalibration::Calibration(const CalibrationType&type,const parameter_set&values):m_name(type.name()),m_formula(type.formula()){\n\t\tif(0==type.id())throw Exception(\"Calibration: attempt to create calibration of type that is not present in database\");\n\t\tif(values.size()!=type.param_count())\n\t\t\tthrow Exception(\"Calibration: parameters count is not good for selected calibration type\");\n\t\tm_encoded_params=\"\";\n\t\tfor(double p:values){\n\t\t\tm_params.push_back(p);\n\t\t\tm_encoded_params+=to_string(p)+\" \";\n\t\t}\n\t\tinit_formula();\n\t}\n\tCalibration::Calibration(const Calibration& source)\n\t:m_name(source.m_name),m_formula(source.m_formula),m_encoded_params(source.m_encoded_params){\n\t\tfor(double p:source.m_params)m_params.push_back(p);\n\t\tinit_formula();\n\t}\n\tCalibration::~Calibration(){deinit_formula();}\n\tconst string& Calibration::name() const{return m_name;}\n\tconst string& Calibration::formula() const{return m_formula;}\n\tconst vector&Calibration::params() const{return m_params;}\n\tconst string& Calibration::encoded_params() const{return m_encoded_params;}\n\tvoid Calibration::init_formula(){\n\t\tbuf=new double[m_params.size()];\n\t\tfor(size_t i=0;iEvalPar(x,buf);\n\t}\n\tdouble Calibration::operator()(const parameter_set&& X) const{return operator()(X);}\n\n\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector&field_names)\n\t:Calibration(row, field_names), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector&&field_names)\n\t:CalibrationForEquipment(eq_id,row,field_names), m_type_id(0), m_cal_id(0){}\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const CalibrationType&type,const parameter_set&values)\n\t:Calibration(type, values), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set& eq_id,const CalibrationType&type,const parameter_set&&values)\n\t:CalibrationForEquipment(eq_id,type,values){}\n\tCalibrationForEquipment::CalibrationForEquipment(const CalibrationForEquipment&source)\n\t:Calibration(source), m_type_id(0), m_cal_id(0){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipment::~CalibrationForEquipment(){}\n\n\tconst size_t CalibrationForEquipment::calibration_id()const{return m_cal_id;}\n\tconst id_set& CalibrationForEquipment::equipment_ids()const{return m_eq_id;}\n\tconst size_t CalibrationForEquipment::type_id()const{return m_type_id;}\n\n\tCalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector&field_names)\n\t:Calibration(row, field_names),m_run_id(run_id){for(const auto&item:eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector&&field_names)\n\t:CalibrationForEquipmentAndRun(eq_id,run_id,row,field_names){}\n\tCalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const CalibrationForEquipmentAndRun& source)\n\t:Calibration(source),m_run_id(source.m_run_id){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipmentAndRun::~CalibrationForEquipmentAndRun(){}\n\tconst id_set&CalibrationForEquipmentAndRun::equipment_ids()const{return m_eq_id;}\n\tconst size_t CalibrationForEquipmentAndRun::run_id()const{return m_run_id;}\n\n\tAmplificationCalibrationEdit::AmplificationCalibrationEdit()\n\t:m_fields{\"name\",\"param_count\",\"formula\",\"param_values\"}{}\n\tAmplificationCalibrationEdit::~AmplificationCalibrationEdit(){}\n\tconst vector AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id)const{\n\t\tvector res;\n\t\tfor(const auto&row:DBHandler::getInstance().querry(\"select * from getcalibrations_phmampl_allphm(\"+to_string(eq_id[0])+\");\"))\n\t\t\tres.push_back(CalibrationForEquipment(eq_id,row,m_fields));\n\t\treturn res;\n\t}\n\tconst vector AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id,const size_t setup_id)const{\n\t\tvector res;\n\t\tfor(const auto&row:DBHandler::getInstance()\n\t\t\t.querry(\"select * from getcalibrations_phmampl_setupandphm(\"+to_string(setup_id)+\",\"+to_string(eq_id[0])+\");\"))\n\t\t\tres.push_back(CalibrationForEquipmentAndRun(eq_id,setup_id,row,m_fields));\n\t\treturn res;\n\t}\n\tbool AmplificationCalibrationEdit::AddCalibration(const CalibrationForEquipment&&new_calibration){\n\t\tif(\n\t\t\t(new_calibration.calibration_id()==0)&&\n\t\t\t(new_calibration.type_id()!=0)&&\n\t\t\t(new_calibration.equipment_ids()[0]!=0)\n\t\t){\n\t\t\tDBHandler::getInstance().querry(\"select * from insert_calibration_phmampl(\"\n\t\t\t\t+to_string(new_calibration.equipment_ids()[0])+\",\"\n\t\t\t\t+to_string(new_calibration.type_id())+\",\"\n\t\t\t\t+new_calibration.encoded_params()+\");\"\n\t\t\t);\n\t\t\treturn true;\n\t\t}else return false;\n\t}\n\tbool AmplificationCalibrationEdit::ConnectCalibrationToRun(const CalibrationForEquipment&cal,const size_t run_id){\n\t\tif(\n\t\t\t(cal.calibration_id()!=0)&&(cal.type_id()==0)&&\n\t\t\t(cal.equipment_ids()[0]!=0)\n\t\t){\n\t\t\tDBHandler::getInstance().querry(\n\t\t\t\t\"select * from connect_calibration_phmampl(\"\n\t\t\t\t+to_string(cal.calibration_id())+\",\"+to_string(run_id)+\");\"\n\t\t\t);\n\t\t\treturn true;\n\t\t}else return false;\n\t}\n\n\tAmplificationCalibration::AmplificationCalibration()\n\t\t:m_fields{\"name\",\"param_count\",\"formula\",\"param_values\"}{}\n\tAmplificationCalibration::~AmplificationCalibration(){}\n\tconst vector AmplificationCalibration::ForRun(const size_t run_id) const{\n\t\tvector res;\n\t\tfor(const auto&row:\n\t\t\tDBHandler::getInstance().querry(\n\t\t\t\t\"select * from getcalibrations_phmampl_run(\"+to_string(run_id)+\");\"\n\t\t\t)\n\t\t)\n\t\t\tres.push_back(CalibrationForEquipmentAndRun(\n\t\t\t\t{row[\"id_phm\"].as()},run_id,row,m_fields\n\t\t\t));\n\t\treturn res;\n\t}\n\n\n}\nChange position of variable initialization in constructors#include \n#include \n#include \n#include \n#include \n#include \"..\/DBHandler\/HeaderFiles\/DBHandler.h\"\n#include \"JPetCalibration.h\"\nnamespace JPetCalibration {\n\tusing namespace std;\n\tclass Exception:public exception{\n\tpublic:\n\t\tException(const string&&msg);\n\t\tvirtual ~Exception() throw();\n\t\tvirtual const char* what() const throw();\n\tprivate:\n\t\tstring m_msg;\n\t};\n\n\tusing namespace std;\n\tusing namespace pqxx;\n\tusing namespace DB::SERVICES;\n\tException::Exception(const string&& msg):m_msg(msg){}\n\tException::~Exception()throw(){}\n\tconst char* Exception::what() const throw(){\n\t\treturn m_msg.c_str();\n\t}\n\n\tCalibrationType::CalibrationType(const CalibrationType& source)\n\t:m_id(source.m_id), m_count(source.m_count), m_name(source.m_name),m_formula(source.m_formula){}\n\n\tCalibrationType::CalibrationType(const result::const_iterator&row)\n\t:m_id(row[\"type_id\"].as()), m_count(row[\"param_count\"].as()),\n m_name(row[\"name\"].as()), m_formula(row[\"formula\"].as()){}\n\n\tCalibrationType::CalibrationType(const string& n,const size_t count, const string& f)\n\t:m_id(0), m_count(count), m_name(n), m_formula(f){}\n\n\tCalibrationType::CalibrationType(const string&&n,const size_t count,const string&&f)\n\t:m_id(0), m_count(count), m_name(n), m_formula(f){}\n\n\tCalibrationType::~CalibrationType(){}\n\tconst size_t CalibrationType::id()const{return m_id;}\n\tconst string& CalibrationType::name()const{return m_name;}\n\tconst size_t CalibrationType::param_count()const{return m_count;}\n\tconst string& CalibrationType::formula()const{return m_formula;}\n\n\tCalibrationTypeEdit::CalibrationTypeEdit(){}\n\tCalibrationTypeEdit::~CalibrationTypeEdit(){}\n\tconst vector CalibrationTypeEdit::GetTypes()const{\n\t\tresult data=DBHandler::getInstance().querry(\"SELECT * FROM getcalibrationtypes();\");\n\t\tvector res;\n\t\tfor(const auto&row:data)res.push_back(CalibrationType(row));\n\t\treturn res;\n\t}\n\tvoid CalibrationTypeEdit::AddType(const CalibrationType& type){\n\t\tif(type.id()>0)throw Exception(\"CalibrationInterface: attempt to insert CalibrationType that already exists\");\n\t\tstring req=\"SELECT * FROM insert_calibrationtype(\";\n\t\treq+=\"'\"+type.name()+\"',\"+to_string(type.param_count())+\",'\"+type.formula()+\"');\";\n\t\tDBHandler::getInstance().querry(req);\n\t}\n\tvoid CalibrationTypeEdit::AddType(const CalibrationType&& type){AddType(type);}\n\n\n\tCalibration::Calibration(const string&n,const size_t count,const string& f,const string¶ms)\n\t:m_name(n),m_formula(f),m_encoded_params(params){\n\t\tstringstream ss(params);\n\t\tvector tokens;\n\t\tcopy(istream_iterator(ss),\n\t\t istream_iterator(),\n\t\t back_inserter(tokens));\n\t\tfor(const string&token:tokens)\n\t\t\tif(m_params.size()&field_names)\n\t:Calibration(row[field_names[0]].as(),row[field_names[1]].as(),row[field_names[2]].as(),row[field_names[3]].as()){}\n\tCalibration::Calibration(const CalibrationType&type,const parameter_set&values):m_name(type.name()),m_formula(type.formula()){\n\t\tif(0==type.id())throw Exception(\"Calibration: attempt to create calibration of type that is not present in database\");\n\t\tif(values.size()!=type.param_count())\n\t\t\tthrow Exception(\"Calibration: parameters count is not good for selected calibration type\");\n\t\tm_encoded_params=\"\";\n\t\tfor(double p:values){\n\t\t\tm_params.push_back(p);\n\t\t\tm_encoded_params+=to_string(p)+\" \";\n\t\t}\n\t\tinit_formula();\n\t}\n\tCalibration::Calibration(const Calibration& source)\n\t:m_name(source.m_name),m_formula(source.m_formula),m_encoded_params(source.m_encoded_params){\n\t\tfor(double p:source.m_params)m_params.push_back(p);\n\t\tinit_formula();\n\t}\n\tCalibration::~Calibration(){deinit_formula();}\n\tconst string& Calibration::name() const{return m_name;}\n\tconst string& Calibration::formula() const{return m_formula;}\n\tconst vector&Calibration::params() const{return m_params;}\n\tconst string& Calibration::encoded_params() const{return m_encoded_params;}\n\tvoid Calibration::init_formula(){\n\t\tbuf=new double[m_params.size()];\n\t\tfor(size_t i=0;iEvalPar(x,buf);\n\t}\n\tdouble Calibration::operator()(const parameter_set&& X) const{return operator()(X);}\n\n\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector&field_names)\n\t:Calibration(row, field_names), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector&&field_names)\n\t:CalibrationForEquipment(eq_id,row,field_names){}\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const CalibrationType&type,const parameter_set&values)\n\t:Calibration(type, values), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipment::CalibrationForEquipment(const id_set& eq_id,const CalibrationType&type,const parameter_set&&values)\n\t:CalibrationForEquipment(eq_id,type,values){}\n\tCalibrationForEquipment::CalibrationForEquipment(const CalibrationForEquipment&source)\n\t:Calibration(source),m_type_id(0), m_cal_id(0){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipment::~CalibrationForEquipment(){}\n\n\tconst size_t CalibrationForEquipment::calibration_id()const{return m_cal_id;}\n\tconst id_set& CalibrationForEquipment::equipment_ids()const{return m_eq_id;}\n\tconst size_t CalibrationForEquipment::type_id()const{return m_type_id;}\n\n\tCalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector&field_names)\n\t:Calibration(row, field_names),m_run_id(run_id){for(const auto&item:eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector&&field_names)\n\t:CalibrationForEquipmentAndRun(eq_id,run_id,row,field_names){}\n\tCalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const CalibrationForEquipmentAndRun& source)\n\t:Calibration(source),m_run_id(source.m_run_id){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}\n\tCalibrationForEquipmentAndRun::~CalibrationForEquipmentAndRun(){}\n\tconst id_set&CalibrationForEquipmentAndRun::equipment_ids()const{return m_eq_id;}\n\tconst size_t CalibrationForEquipmentAndRun::run_id()const{return m_run_id;}\n\n\tAmplificationCalibrationEdit::AmplificationCalibrationEdit()\n\t:m_fields{\"name\",\"param_count\",\"formula\",\"param_values\"}{}\n\tAmplificationCalibrationEdit::~AmplificationCalibrationEdit(){}\n\tconst vector AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id)const{\n\t\tvector res;\n\t\tfor(const auto&row:DBHandler::getInstance().querry(\"select * from getcalibrations_phmampl_allphm(\"+to_string(eq_id[0])+\");\"))\n\t\t\tres.push_back(CalibrationForEquipment(eq_id,row,m_fields));\n\t\treturn res;\n\t}\n\tconst vector AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id,const size_t setup_id)const{\n\t\tvector res;\n\t\tfor(const auto&row:DBHandler::getInstance()\n\t\t\t.querry(\"select * from getcalibrations_phmampl_setupandphm(\"+to_string(setup_id)+\",\"+to_string(eq_id[0])+\");\"))\n\t\t\tres.push_back(CalibrationForEquipmentAndRun(eq_id,setup_id,row,m_fields));\n\t\treturn res;\n\t}\n\tbool AmplificationCalibrationEdit::AddCalibration(const CalibrationForEquipment&&new_calibration){\n\t\tif(\n\t\t\t(new_calibration.calibration_id()==0)&&\n\t\t\t(new_calibration.type_id()!=0)&&\n\t\t\t(new_calibration.equipment_ids()[0]!=0)\n\t\t){\n\t\t\tDBHandler::getInstance().querry(\"select * from insert_calibration_phmampl(\"\n\t\t\t\t+to_string(new_calibration.equipment_ids()[0])+\",\"\n\t\t\t\t+to_string(new_calibration.type_id())+\",\"\n\t\t\t\t+new_calibration.encoded_params()+\");\"\n\t\t\t);\n\t\t\treturn true;\n\t\t}else return false;\n\t}\n\tbool AmplificationCalibrationEdit::ConnectCalibrationToRun(const CalibrationForEquipment&cal,const size_t run_id){\n\t\tif(\n\t\t\t(cal.calibration_id()!=0)&&(cal.type_id()==0)&&\n\t\t\t(cal.equipment_ids()[0]!=0)\n\t\t){\n\t\t\tDBHandler::getInstance().querry(\n\t\t\t\t\"select * from connect_calibration_phmampl(\"\n\t\t\t\t+to_string(cal.calibration_id())+\",\"+to_string(run_id)+\");\"\n\t\t\t);\n\t\t\treturn true;\n\t\t}else return false;\n\t}\n\n\tAmplificationCalibration::AmplificationCalibration()\n\t\t:m_fields{\"name\",\"param_count\",\"formula\",\"param_values\"}{}\n\tAmplificationCalibration::~AmplificationCalibration(){}\n\tconst vector AmplificationCalibration::ForRun(const size_t run_id) const{\n\t\tvector res;\n\t\tfor(const auto&row:\n\t\t\tDBHandler::getInstance().querry(\n\t\t\t\t\"select * from getcalibrations_phmampl_run(\"+to_string(run_id)+\");\"\n\t\t\t)\n\t\t)\n\t\t\tres.push_back(CalibrationForEquipmentAndRun(\n\t\t\t\t{row[\"id_phm\"].as()},run_id,row,m_fields\n\t\t\t));\n\t\treturn res;\n\t}\n\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ELEMENT_COUNT (50)\n\nstatic SDL_Window* window;\nstatic SDL_Renderer* renderer;\nstatic int windowWidth, windowHeight;\nstatic TTF_Font* font;\n\ntemplate constexpr static inline\nT Map(T x, T minIn, T maxIn, T minOut, T maxOut)\n{\n return (x - minIn) * (maxOut - minOut) \/ (maxIn - minIn) + minOut;\n}\n\nstatic inline\nint Round(float value)\n{\n int result = static_cast(roundf(value));\n\n return result;\n}\n\nstruct Element\n{\n float val;\n int r, g, b;\n\n friend inline bool \n operator <(const Element& lhs, const Element& rhs)\n {\n return lhs.val < rhs.val;\n }\n\n friend inline bool\n operator >(const Element& lhs, const Element& rhs)\n {\n return lhs.val > rhs.val;\n }\n};\n\nusing Elements = std::array;\n\nstatic\nvoid Render(Elements& elements, const char* name)\n{\n auto* nameSurface = TTF_RenderText_Solid(font, name, { 255, 255, 255, 255 });\n auto nameTexture = SDL_CreateTextureFromSurface(renderer, nameSurface);\n\n SDL_FreeSurface(nameSurface);\n\n SDL_Rect r;\n r.x = r.y = 10;\n\n SDL_QueryTexture(nameTexture, 0, 0, &r.w, &r.h);\n\n const auto ELEMENT_WIDTH = (windowWidth \/ ELEMENT_COUNT);\n\n SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);\n SDL_RenderClear(renderer);\n for (size_t i = 0; i < elements.size(); ++i)\n {\n SDL_Rect rect;\n rect.x = i * ELEMENT_WIDTH;\n rect.y = windowHeight;\n rect.w = ELEMENT_WIDTH;\n rect.h = Round(-Map(elements[i].val, 0.0f, static_cast(elements.size()), 100.0f,\n static_cast(windowHeight)));\n\n SDL_SetRenderDrawColor(renderer, elements[i].r, elements[i].g, elements[i].b, 0xff);\n SDL_RenderFillRect(renderer, &rect);\n }\n\n SDL_RenderCopy(renderer, nameTexture, NULL, &r);\n SDL_RenderPresent(renderer);\n}\n\nstatic\nvoid Update()\n{\n SDL_Event e;\n while (SDL_PollEvent(&e))\n {\n if (e.type == SDL_QUIT)\n {\n exit(0);\n }\n }\n}\n\nclass Sort\n{\npublic:\n Sort() { _name = \"\"; }\n Sort(std::string name_) : _name(name_) {}\n\n virtual void\n Run(Elements&, size_t, size_t) = 0; \n\n inline void \n SetName(std::string s) { _name = s; }\n \n inline std::string \n GetName() { return _name; }\n\nprotected:\n std::string _name;\n};\n\nclass InsertionSort : public Sort\n{\npublic:\n InsertionSort() { _name = \"Insertion Sort\"; }\n\n void\n Run(Elements& elements, size_t, size_t)\n {\n Render(elements, _name.c_str());\n\n size_t sortedIndex = 0;\n \n for (size_t i = sortedIndex; i < elements.size(); ++i)\n {\n auto j = i;\n\n while ((j > 0) && (elements[j] < elements[j - 1]))\n {\n for (auto& e : elements)\n {\n e.r = 0xff;\n e.g = 0xff;\n e.b = 0xff;\n }\n\n std::swap(elements[j], elements[j - 1]);\n --j;\n\n elements[j].r = 0xee;\n elements[j].g = 0x00;\n elements[j].b = 0x00;\n\n Render(elements, _name.c_str());\n Update();\n SDL_Delay(25);\n Update();\n }\n }\n }\n};\n\nclass SelectionSort : public Sort\n{\npublic:\n SelectionSort() { _name = \"Selection Sort\"; }\n\n void\n Run(Elements& elements, size_t, size_t)\n {\n Render(elements, _name.c_str());\n\n for (size_t i = 0; i < elements.size(); ++i)\n {\n for (size_t j = 0; j < elements.size(); ++j)\n {\n elements[j].r = 0xff;\n elements[j].g = 0xff;\n elements[j].b = 0xff;\n }\n\n auto minIndex = i;\n\n elements[i].r = 0xee;\n elements[i].g = 0x00;\n elements[i].b = 0x00;\n\n for (auto j = i; j < elements.size(); ++j)\n {\n auto oldR = elements[j].r;\n auto oldG = elements[j].g;\n auto oldB = elements[j].b;\n\n elements[j].r = 0x00;\n elements[j].g = 0x00;\n elements[j].b = 0xee;\n\n if (elements[j] < elements[minIndex])\n {\n elements[minIndex].r = 0xff;\n elements[minIndex].g = 0xff; \n elements[minIndex].b = 0xff;\n\n minIndex = j;\n\n oldR = 0xee;\n oldG = 0;\n oldB = 0;\n\n elements[minIndex].r = 0xee;\n elements[minIndex].g = 0x00; \n elements[minIndex].b = 0x00;\n }\n\n Render(elements, _name.c_str());\n\n elements[j].r = oldR;\n elements[j].g = oldG;\n elements[j].b = oldB;\n\n Update();\n SDL_Delay(35);\n Update();\n }\n\n std::swap(elements[i], elements[minIndex]);\n }\n };\n};\n\nclass BubbleSort : public Sort\n{\npublic:\n BubbleSort() { _name = \"Bubble Sort\"; }\n\n void\n Run(Elements& elements, size_t left, size_t right)\n {\n Render(elements, _name.c_str());\n\n for (size_t i = left; i < right - 1; ++i)\n {\n for (size_t j = left; j < elements.size() - i - 1; ++j)\n {\n if (elements[j].val > elements[j + 1].val)\n {\n std::swap(elements[j].val, elements[j + 1].val);\n\n for (Element& e : elements)\n {\n e.r = 0xff;\n e.g = 0xff;\n e.b = 0xff;\n }\n\n elements[j].r = 0x00;\n elements[j].g = 0xee;\n elements[j].b = 0x00;\n\n Render(elements, _name.c_str());\n Update();\n }\n }\n } \n };\n};\n\nclass QuickSort : public Sort\n{\npublic:\n QuickSort() { _name = \"Quick Sort\"; }\n\n void\n Run(Elements& elements, size_t left, size_t right)\n { \n auto i = left;\n auto j = right;\n auto pivot = elements[(left + right) \/ 2].val;\n\n Render(elements, _name.c_str());\n SDL_Delay(20);\n\n while (i <= j)\n {\n while (elements[i].val < pivot)\n {\n i++;\n }\n\n while (elements[j].val > pivot)\n {\n j--;\n }\n\n if (i <= j)\n {\n std::swap(elements[i], elements[j]);\n\n i++;\n j--;\n }\n\n for (Element& e : elements)\n {\n e.r = 0xff;\n e.g = 0xff;\n e.b = 0xff;\n }\n\n if (left > 0 && left < elements.size())\n {\n elements[left].r = 0x00;\n elements[left].g = 0xee;\n elements[left].b = 0x00;\n }\n\n if (right > 0 && right < elements.size())\n {\n elements[right].r = 0x00;\n elements[right].g = 0xee;\n elements[right].b = 0x00;\n }\n\n if (pivot > 0 && pivot < elements.size())\n {\n elements[pivot].r = 0xee;\n elements[pivot].g = 0x00;\n elements[pivot].g = 0x00;\n }\n\n \n Render(elements, _name.c_str());\n SDL_Delay(60);\n Update();\n }\n\n if (left < j)\n {\n Run(elements, left, j);\n }\n\n if (i < right)\n {\n Run(elements, i, right);\n }\n };\n};\n\nint main()\n{\n SDL_Init(SDL_INIT_EVERYTHING);\n TTF_Init();\n\n font = TTF_OpenFont(\".\/OpenSans-Regular.ttf\", 32);\n\n if (!font)\n {\n std::cerr << \"Could not load font!\" << std::endl;\n }\n\n window = SDL_CreateWindow(\"Visual Sort\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1920, 1080,\n SDL_WINDOW_FULLSCREEN_DESKTOP);\n SDL_GetWindowSize(window, &windowWidth, &windowHeight);\n\n renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n\n Elements elements = {};\n\n std::array sortingFunctions;\n sortingFunctions[0] = new QuickSort();\n sortingFunctions[1] = new BubbleSort();\n sortingFunctions[2] = new SelectionSort();\n sortingFunctions[3] = new InsertionSort();\n\n for (auto& func : sortingFunctions)\n { \n std::srand(static_cast(time(0)));\n\n for (size_t i = 0; i < elements.size(); ++i)\n {\n elements[i].r = 0xff;\n elements[i].g = 0xff;\n elements[i].b = 0xff;\n\n auto val = static_cast(std::rand() % ELEMENT_COUNT);\n\n for (size_t j = 0; j < i; ++j)\n {\n if (val == elements[j].val)\n {\n val = static_cast(std::rand() % ELEMENT_COUNT);\n j = 0;\n }\n }\n\n elements[i].val = val;\n }\n\n func->Run(elements, 0, elements.size());\n\n Update();\n SDL_Delay(1000);\n Update();\n }\n}\nBumped element count up to 75#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ELEMENT_COUNT (75)\n\nstatic SDL_Window* window;\nstatic SDL_Renderer* renderer;\nstatic int windowWidth, windowHeight;\nstatic TTF_Font* font;\n\ntemplate constexpr static inline\nT Map(T x, T minIn, T maxIn, T minOut, T maxOut)\n{\n return (x - minIn) * (maxOut - minOut) \/ (maxIn - minIn) + minOut;\n}\n\nstatic inline\nint Round(float value)\n{\n int result = static_cast(roundf(value));\n\n return result;\n}\n\nstruct Element\n{\n float val;\n int r, g, b;\n\n friend inline bool \n operator <(const Element& lhs, const Element& rhs)\n {\n return lhs.val < rhs.val;\n }\n\n friend inline bool\n operator >(const Element& lhs, const Element& rhs)\n {\n return lhs.val > rhs.val;\n }\n};\n\nusing Elements = std::array;\n\nstatic\nvoid Render(Elements& elements, const char* name)\n{\n auto* nameSurface = TTF_RenderText_Solid(font, name, { 255, 255, 255, 255 });\n auto nameTexture = SDL_CreateTextureFromSurface(renderer, nameSurface);\n\n SDL_FreeSurface(nameSurface);\n\n SDL_Rect r;\n r.x = r.y = 10;\n\n SDL_QueryTexture(nameTexture, 0, 0, &r.w, &r.h);\n\n const auto ELEMENT_WIDTH = (windowWidth \/ ELEMENT_COUNT);\n\n SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);\n SDL_RenderClear(renderer);\n for (size_t i = 0; i < elements.size(); ++i)\n {\n SDL_Rect rect;\n rect.x = i * ELEMENT_WIDTH;\n rect.y = windowHeight;\n rect.w = ELEMENT_WIDTH;\n rect.h = Round(-Map(elements[i].val, 0.0f, static_cast(elements.size()), 100.0f,\n static_cast(windowHeight)));\n\n SDL_SetRenderDrawColor(renderer, elements[i].r, elements[i].g, elements[i].b, 0xff);\n SDL_RenderFillRect(renderer, &rect);\n }\n\n SDL_RenderCopy(renderer, nameTexture, NULL, &r);\n SDL_RenderPresent(renderer);\n}\n\nstatic\nvoid Update()\n{\n SDL_Event e;\n while (SDL_PollEvent(&e))\n {\n if (e.type == SDL_QUIT)\n {\n exit(0);\n }\n }\n}\n\nclass Sort\n{\npublic:\n Sort() { _name = \"\"; }\n Sort(std::string name_) : _name(name_) {}\n\n virtual void\n Run(Elements&, size_t, size_t) = 0; \n\n inline void \n SetName(std::string s) { _name = s; }\n \n inline std::string \n GetName() { return _name; }\n\nprotected:\n std::string _name;\n};\n\nclass InsertionSort : public Sort\n{\npublic:\n InsertionSort() { _name = \"Insertion Sort\"; }\n\n void\n Run(Elements& elements, size_t, size_t)\n {\n Render(elements, _name.c_str());\n\n size_t sortedIndex = 0;\n \n for (size_t i = sortedIndex; i < elements.size(); ++i)\n {\n auto j = i;\n\n while ((j > 0) && (elements[j] < elements[j - 1]))\n {\n for (auto& e : elements)\n {\n e.r = 0xff;\n e.g = 0xff;\n e.b = 0xff;\n }\n\n std::swap(elements[j], elements[j - 1]);\n --j;\n\n elements[j].r = 0xee;\n elements[j].g = 0x00;\n elements[j].b = 0x00;\n\n Render(elements, _name.c_str());\n Update();\n SDL_Delay(25);\n Update();\n }\n }\n }\n};\n\nclass SelectionSort : public Sort\n{\npublic:\n SelectionSort() { _name = \"Selection Sort\"; }\n\n void\n Run(Elements& elements, size_t, size_t)\n {\n Render(elements, _name.c_str());\n\n for (size_t i = 0; i < elements.size(); ++i)\n {\n for (size_t j = 0; j < elements.size(); ++j)\n {\n elements[j].r = 0xff;\n elements[j].g = 0xff;\n elements[j].b = 0xff;\n }\n\n auto minIndex = i;\n\n elements[i].r = 0xee;\n elements[i].g = 0x00;\n elements[i].b = 0x00;\n\n for (auto j = i; j < elements.size(); ++j)\n {\n auto oldR = elements[j].r;\n auto oldG = elements[j].g;\n auto oldB = elements[j].b;\n\n elements[j].r = 0x00;\n elements[j].g = 0x00;\n elements[j].b = 0xee;\n\n if (elements[j] < elements[minIndex])\n {\n elements[minIndex].r = 0xff;\n elements[minIndex].g = 0xff; \n elements[minIndex].b = 0xff;\n\n minIndex = j;\n\n oldR = 0xee;\n oldG = 0;\n oldB = 0;\n\n elements[minIndex].r = 0xee;\n elements[minIndex].g = 0x00; \n elements[minIndex].b = 0x00;\n }\n\n Render(elements, _name.c_str());\n\n elements[j].r = oldR;\n elements[j].g = oldG;\n elements[j].b = oldB;\n\n Update();\n SDL_Delay(35);\n Update();\n }\n\n std::swap(elements[i], elements[minIndex]);\n }\n };\n};\n\nclass BubbleSort : public Sort\n{\npublic:\n BubbleSort() { _name = \"Bubble Sort\"; }\n\n void\n Run(Elements& elements, size_t left, size_t right)\n {\n Render(elements, _name.c_str());\n\n for (size_t i = left; i < right - 1; ++i)\n {\n for (size_t j = left; j < elements.size() - i - 1; ++j)\n {\n if (elements[j].val > elements[j + 1].val)\n {\n std::swap(elements[j].val, elements[j + 1].val);\n\n for (Element& e : elements)\n {\n e.r = 0xff;\n e.g = 0xff;\n e.b = 0xff;\n }\n\n elements[j].r = 0x00;\n elements[j].g = 0xee;\n elements[j].b = 0x00;\n\n Render(elements, _name.c_str());\n Update();\n }\n }\n } \n };\n};\n\nclass QuickSort : public Sort\n{\npublic:\n QuickSort() { _name = \"Quick Sort\"; }\n\n void\n Run(Elements& elements, size_t left, size_t right)\n { \n auto i = left;\n auto j = right;\n auto pivot = elements[(left + right) \/ 2].val;\n\n Render(elements, _name.c_str());\n SDL_Delay(20);\n\n while (i <= j)\n {\n while (elements[i].val < pivot)\n {\n i++;\n }\n\n while (elements[j].val > pivot)\n {\n j--;\n }\n\n if (i <= j)\n {\n std::swap(elements[i], elements[j]);\n\n i++;\n j--;\n }\n\n for (Element& e : elements)\n {\n e.r = 0xff;\n e.g = 0xff;\n e.b = 0xff;\n }\n\n if (left > 0 && left < elements.size())\n {\n elements[left].r = 0x00;\n elements[left].g = 0xee;\n elements[left].b = 0x00;\n }\n\n if (right > 0 && right < elements.size())\n {\n elements[right].r = 0x00;\n elements[right].g = 0xee;\n elements[right].b = 0x00;\n }\n\n if (pivot > 0 && pivot < elements.size())\n {\n elements[pivot].r = 0xee;\n elements[pivot].g = 0x00;\n elements[pivot].g = 0x00;\n }\n\n \n Render(elements, _name.c_str());\n SDL_Delay(60);\n Update();\n }\n\n if (left < j)\n {\n Run(elements, left, j);\n }\n\n if (i < right)\n {\n Run(elements, i, right);\n }\n };\n};\n\nint main()\n{\n SDL_Init(SDL_INIT_EVERYTHING);\n TTF_Init();\n\n font = TTF_OpenFont(\".\/OpenSans-Regular.ttf\", 36);\n\n if (!font)\n {\n std::cerr << \"Could not load font!\" << std::endl;\n }\n\n window = SDL_CreateWindow(\"Visual Sort\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1920, 1080,\n SDL_WINDOW_FULLSCREEN_DESKTOP);\n SDL_GetWindowSize(window, &windowWidth, &windowHeight);\n\n renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n\n Elements elements = {};\n\n std::array sortingFunctions;\n sortingFunctions[0] = new QuickSort();\n sortingFunctions[1] = new BubbleSort();\n sortingFunctions[2] = new SelectionSort();\n sortingFunctions[3] = new InsertionSort();\n\n for (auto& sortingFunc : sortingFunctions)\n { \n std::srand(static_cast(time(0)));\n\n for (size_t i = 0; i < elements.size(); ++i)\n {\n elements[i].r = 0xff;\n elements[i].g = 0xff;\n elements[i].b = 0xff;\n\n auto val = static_cast(std::rand() % ELEMENT_COUNT);\n\n for (size_t j = 0; j < i; ++j)\n {\n if (val == elements[j].val)\n {\n val = static_cast(std::rand() % ELEMENT_COUNT);\n j = 0;\n }\n }\n\n elements[i].val = val;\n }\n\n sortingFunc->Run(elements, 0, elements.size());\n\n Update();\n SDL_Delay(1000);\n Update();\n }\n}\n<|endoftext|>"} {"text":"#include \"protocolsupport.h\"\n#include \"protocolparser.h\"\n\nProtocolSupport::ProtocolSupport() :\n maxdatasize(0),\n int64(true),\n float64(true),\n specialFloat(true),\n bitfield(true),\n longbitfield(false),\n bitfieldtest(false),\n disableunrecognized(false),\n bigendian(true),\n packetStructureSuffix(\"PacketStructure\"),\n packetParameterSuffix(\"Packet\")\n{\n}\n\n\n\/\/! Return the list of attributes understood by ProtocolSupport\nQStringList ProtocolSupport::getAttriblist(void) const\n{\n QStringList attribs;\n\n attribs << \"maxSize\" << \"supportInt64\" << \"supportFloat64\" << \"supportSpecialFloat\" << \"supportBitfield\" << \"supportLongBitfield\" << \"bitfieldTest\" << \"file\" << \"prefix\" << \"packetStructureSuffix\" << \"packetParameterSuffix\" << \"endian\";\n\n return attribs;\n}\n\n\nvoid ProtocolSupport::parse(const QDomNamedNodeMap& map)\n{\n \/\/ Maximum bytes of data in a packet.\n maxdatasize = ProtocolParser::getAttribute(\"maxSize\", map, \"0\").toInt();\n\n \/\/ 64-bit support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportInt64\", map)))\n int64 = false;\n\n \/\/ double support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportFloat64\", map)))\n float64 = false;\n\n \/\/ special float support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportSpecialFloat\", map)))\n specialFloat = false;\n\n \/\/ bitfield support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportBitfield\", map)))\n bitfield = false;\n\n \/\/ long bitfield support can be turned on\n if(int64 && ProtocolParser::isFieldSet(ProtocolParser::getAttribute(\"supportLongBitfield\", map)))\n longbitfield = true;\n\n \/\/ bitfield test support can be turned on\n if(ProtocolParser::isFieldSet(ProtocolParser::getAttribute(\"bitfieldTest\", map)))\n bitfieldtest = true;\n\n \/\/ Global file names can be specified, but cannot have a \".\" in it\n globalFileName = ProtocolParser::getAttribute(\"file\", map);\n globalFileName = globalFileName.left(globalFileName.indexOf(\".\"));\n\n \/\/ Prefix is not required\n prefix = ProtocolParser::getAttribute(\"prefix\", map);\n\n \/\/ Packet pointer type\n pointerType = ProtocolParser::getAttribute(\"pointer\", map);\n\n \/\/ Packet name post fixes\n packetStructureSuffix = ProtocolParser::getAttribute(\"packetStructureSuffix\", map, packetStructureSuffix);\n packetParameterSuffix = ProtocolParser::getAttribute(\"packetParameterSuffix\", map, packetParameterSuffix);\n\n if(ProtocolParser::getAttribute(\"endian\", map).contains(\"little\", Qt::CaseInsensitive))\n bigendian = false;\n\n}\/\/ ProtocolSupport::parse\nAdded default pointer value#include \"protocolsupport.h\"\n#include \"protocolparser.h\"\n\nProtocolSupport::ProtocolSupport() :\n maxdatasize(0),\n int64(true),\n float64(true),\n specialFloat(true),\n bitfield(true),\n longbitfield(false),\n bitfieldtest(false),\n disableunrecognized(false),\n bigendian(true),\n packetStructureSuffix(\"PacketStructure\"),\n packetParameterSuffix(\"Packet\")\n{\n}\n\n\n\/\/! Return the list of attributes understood by ProtocolSupport\nQStringList ProtocolSupport::getAttriblist(void) const\n{\n QStringList attribs;\n\n attribs << \"maxSize\"\n << \"supportInt64\"\n << \"supportFloat64\"\n << \"supportSpecialFloat\"\n << \"supportBitfield\"\n << \"supportLongBitfield\"\n << \"bitfieldTest\"\n << \"file\"\n << \"prefix\"\n << \"packetStructureSuffix\"\n << \"packetParameterSuffix\"\n << \"endian\"\n << \"pointer\";\n\n return attribs;\n}\n\n\nvoid ProtocolSupport::parse(const QDomNamedNodeMap& map)\n{\n \/\/ Maximum bytes of data in a packet.\n maxdatasize = ProtocolParser::getAttribute(\"maxSize\", map, \"0\").toInt();\n\n \/\/ 64-bit support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportInt64\", map)))\n int64 = false;\n\n \/\/ double support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportFloat64\", map)))\n float64 = false;\n\n \/\/ special float support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportSpecialFloat\", map)))\n specialFloat = false;\n\n \/\/ bitfield support can be turned off\n if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute(\"supportBitfield\", map)))\n bitfield = false;\n\n \/\/ long bitfield support can be turned on\n if(int64 && ProtocolParser::isFieldSet(ProtocolParser::getAttribute(\"supportLongBitfield\", map)))\n longbitfield = true;\n\n \/\/ bitfield test support can be turned on\n if(ProtocolParser::isFieldSet(ProtocolParser::getAttribute(\"bitfieldTest\", map)))\n bitfieldtest = true;\n\n \/\/ Global file names can be specified, but cannot have a \".\" in it\n globalFileName = ProtocolParser::getAttribute(\"file\", map);\n globalFileName = globalFileName.left(globalFileName.indexOf(\".\"));\n\n \/\/ Prefix is not required\n prefix = ProtocolParser::getAttribute(\"prefix\", map);\n\n \/\/ Packet pointer type (default is 'void')\n pointerType = ProtocolParser::getAttribute(\"pointer\", map, \"void\");\n\n if(!pointerType.endsWith(\"*\"))\n {\n pointerType += \"*\";\n }\n\n \/\/ Packet name post fixes\n packetStructureSuffix = ProtocolParser::getAttribute(\"packetStructureSuffix\", map, packetStructureSuffix);\n packetParameterSuffix = ProtocolParser::getAttribute(\"packetParameterSuffix\", map, packetParameterSuffix);\n\n if(ProtocolParser::getAttribute(\"endian\", map).contains(\"little\", Qt::CaseInsensitive))\n bigendian = false;\n\n}\/\/ ProtocolSupport::parse\n<|endoftext|>"} {"text":"#include \"Halide.h\"\n\n\/\/ Include the machine-generated .stub.h header file.\n#include \"example.stub.h\"\n\nusing Halide::Buffer;\n\nconst int kSize = 32;\n\nvoid verify(const Buffer &img, float compiletime_factor, float runtime_factor, int channels) {\n for (int i = 0; i < kSize; i++) {\n for (int j = 0; j < kSize; j++) {\n for (int c = 0; c < channels; c++) {\n if (img(i, j, c) !=\n (int32_t)(compiletime_factor * runtime_factor * c * (i > j ? i : j))) {\n printf(\"img[%d, %d, %d] = %d\\n\", i, j, c, img(i, j, c));\n exit(-1);\n }\n }\n }\n }\n}\n\nint main(int argc, char **argv) {\n Halide::JITGeneratorContext context(Halide::get_target_from_environment());\n\n {\n \/\/ Create a Generator and set its Inputs and GeneratorParams.\n \/\/ We could just use initializer-list syntax, but we'll explicitly\n \/\/ set the fields by name for clarity.\n example::Inputs inputs;\n inputs.runtime_factor = 1.f;\n\n \/\/ The fields of the GeneratorParams struct are initialized to the\n \/\/ default values specified in the Generator, so we can just omit\n \/\/ any we don't want to change\n example::GeneratorParams gp;\n gp.compiletime_factor = 2.392f;\n gp.enummy = Enum_enummy::foo;\n \/\/ gp.channels = 3; -- this is the default; no need to set\n\n auto gen = example(context, inputs, gp);\n\n \/\/ We must call schedule() before calling realize()\n gen.schedule();\n\n Halide::Buffer img = gen.realize(kSize, kSize, 3);\n verify(img, 2.392f, 1, 3);\n }\n\n {\n \/\/ Here, we'll use an initializer list for inputs, and omit\n \/\/ the GeneratorParams entirely to use their default values.\n auto gen = example(context, \/* inputs: *\/ { 1.f });\n\n \/\/ We'll set \"vectorize=false\" in the ScheduleParams, just to\n \/\/ show that we can:\n example::ScheduleParams sp;\n sp.vectorize = false;\n gen.schedule(sp);\n\n Halide::Buffer img = gen.realize(kSize, kSize, 3);\n verify(img, 1, 1, 3);\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\nRemove floating point rounding as a source of error#include \"Halide.h\"\n\n\/\/ Include the machine-generated .stub.h header file.\n#include \"example.stub.h\"\n\nusing Halide::Buffer;\n\nconst int kSize = 32;\n\nvoid verify(const Buffer &img, float compiletime_factor, float runtime_factor, int channels) {\n for (int i = 0; i < kSize; i++) {\n for (int j = 0; j < kSize; j++) {\n for (int c = 0; c < channels; c++) {\n if (img(i, j, c) !=\n (int32_t)(compiletime_factor * runtime_factor * c * (i > j ? i : j))) {\n printf(\"img[%d, %d, %d] = %d\\n\", i, j, c, img(i, j, c));\n exit(-1);\n }\n }\n }\n }\n}\n\nint main(int argc, char **argv) {\n Halide::JITGeneratorContext context(Halide::get_target_from_environment());\n\n {\n \/\/ Create a Generator and set its Inputs and GeneratorParams.\n \/\/ We could just use initializer-list syntax, but we'll explicitly\n \/\/ set the fields by name for clarity.\n example::Inputs inputs;\n inputs.runtime_factor = 1.f;\n\n \/\/ The fields of the GeneratorParams struct are initialized to the\n \/\/ default values specified in the Generator, so we can just omit\n \/\/ any we don't want to change\n example::GeneratorParams gp;\n gp.compiletime_factor = 2.5f;\n gp.enummy = Enum_enummy::foo;\n \/\/ gp.channels = 3; -- this is the default; no need to set\n\n auto gen = example(context, inputs, gp);\n\n \/\/ We must call schedule() before calling realize()\n gen.schedule();\n\n Halide::Buffer img = gen.realize(kSize, kSize, 3);\n verify(img, 2.5f, 1, 3);\n }\n\n {\n \/\/ Here, we'll use an initializer list for inputs, and omit\n \/\/ the GeneratorParams entirely to use their default values.\n auto gen = example(context, \/* inputs: *\/ { 1.f });\n\n \/\/ We'll set \"vectorize=false\" in the ScheduleParams, just to\n \/\/ show that we can:\n example::ScheduleParams sp;\n sp.vectorize = false;\n gen.schedule(sp);\n\n Halide::Buffer img = gen.realize(kSize, kSize, 3);\n verify(img, 1, 1, 3);\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#ifndef TUSLANGUAGE_REPLYBUILDER_HPP\n#define TUSLANGUAGE_REPLYBUILDER_HPP\n\n#include \n#include \n\nnamespace TUSLanguage\n{\n\n\/\/ TODO: Refactor me!\n\nclass ReplyBuilder\n : boost::noncopyable\n{\npublic:\n \/**\n * @brief Builds EchoReply.\n *\n * @param a_code The exit code.\n *\n * @return EchoReply.\n *\/\n ICommand::SingleHandle buildEchoReply(\n unsigned short int const a_code\n ) const;\n\n \/**\n * @brief Builds ErrorReply.\n *\n * @param a_code The exit code.\n *\n * @return ErrorReply.\n *\/\n ICommand::SingleHandle buildErrorReply(\n unsigned short int const a_code\n ) const;\n\n \/**\n * @brief Builds CreateLandReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateLandReply.\n *\/\n ICommand::SingleHandle buildCreateLandReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DeleteLandReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DeleteLandReply.\n *\/\n ICommand::SingleHandle buildDeleteLandReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetLandReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetLandReply.\n *\/\n ICommand::SingleHandle buildGetLandReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetLandsReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetLandsReply.\n *\/\n ICommand::SingleHandle buildGetLandsReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds CreateSettlementReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateSettlementReply.\n *\/\n ICommand::SingleHandle buildCreateSettlementReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DeleteSettlementReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DeleteSettlementReply.\n *\/\n ICommand::SingleHandle buildDeleteSettlementReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetSettlementReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetSettlementReply.\n *\/\n ICommand::SingleHandle buildGetSettlementReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetSettlementsReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetSettlementsReply.\n *\/\n ICommand::SingleHandle buildGetSettlementsReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds BuildBuildingReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return BuildBuildingReply.\n *\/\n ICommand::SingleHandle buildBuildBuildingReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DestroyBuildingReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DestroyBuildingReply.\n *\/\n ICommand::SingleHandle buildDestroyBuildingReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetBuildingReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetBuildingReply.\n *\/\n ICommand::SingleHandle buildGetBuildingReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetBuildingsReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetBuildingsReply.\n *\/\n ICommand::SingleHandle buildGetBuildingsReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds DismissHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DismissHumanReply.\n *\/\n ICommand::SingleHandle buildDismissHumanReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds EngageHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return EngageHumanReply.\n *\/\n ICommand::SingleHandle buildEngageHumanReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetHumanReply.\n *\/\n ICommand::SingleHandle buildGetHumanReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetHumansReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetHumansReply.\n *\/\n ICommand::SingleHandle buildGetHumansReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds GetResourceReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetResourceReply.\n *\/\n ICommand::SingleHandle buildGetResourceReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetResourcesReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetResourcesReply.\n *\/\n ICommand::SingleHandle buildGetResourcesReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds CreateUserReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateUserReply.\n *\/\n ICommand::SingleHandle buildCreateUserReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds CreateWorldReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateWorldReply.\n *\/\n ICommand::SingleHandle buildCreateWorldReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds CreateEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateEpochReply.\n *\/\n ICommand::SingleHandle buildCreateEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DeleteEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DeleteEpochReply.\n *\/\n ICommand::SingleHandle buildDeleteEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds ActivateEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return ActivateEpochReply.\n *\/\n ICommand::SingleHandle buildActivateEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DectivateEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DectivateEpochReply.\n *\/\n ICommand::SingleHandle buildDeactivateEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds FinishEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return FinishEpochReply.\n *\/\n ICommand::SingleHandle buildFinishEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds TickEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return TickEpochReply.\n *\/\n ICommand::SingleHandle buildTickEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds TransportHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return TransportHumanReply.\n *\/\n ICommand::SingleHandle buildTransportHumanReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds TransportResourceReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return TransportResourceReply.\n *\/\n ICommand::SingleHandle buildTransportResourceReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetEpochReply.\n *\/\n ICommand::SingleHandle buildGetEpochReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n};\n\n} \/\/ namespace TUSLanguage\n\n#endif \/\/ TUSLANGUAGE_REPLYBUILDER_HPP\nA cosmetic change.\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#ifndef TUSLANGUAGE_REPLYBUILDER_HPP\n#define TUSLANGUAGE_REPLYBUILDER_HPP\n\n#include \n#include \n\nnamespace TUSLanguage\n{\n\n\/\/ TODO: Refactor me!\n\nclass ReplyBuilder\n : boost::noncopyable\n{\npublic:\n \/**\n * @brief Builds EchoReply.\n *\n * @param a_code The exit code.\n *\n * @return EchoReply.\n *\/\n ICommand::SingleHandle buildEchoReply(\n unsigned short int const a_code\n ) const;\n\n \/**\n * @brief Builds ErrorReply.\n *\n * @param a_code The exit code.\n *\n * @return ErrorReply.\n *\/\n ICommand::SingleHandle buildErrorReply(\n unsigned short int const a_code\n ) const;\n\n \/**\n * @brief Builds CreateLandReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateLandReply.\n *\/\n ICommand::SingleHandle buildCreateLandReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DeleteLandReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DeleteLandReply.\n *\/\n ICommand::SingleHandle buildDeleteLandReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetLandReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetLandReply.\n *\/\n ICommand::SingleHandle buildGetLandReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetLandsReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetLandsReply.\n *\/\n ICommand::SingleHandle buildGetLandsReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds CreateSettlementReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateSettlementReply.\n *\/\n ICommand::SingleHandle buildCreateSettlementReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DeleteSettlementReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DeleteSettlementReply.\n *\/\n ICommand::SingleHandle buildDeleteSettlementReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetSettlementReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetSettlementReply.\n *\/\n ICommand::SingleHandle buildGetSettlementReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetSettlementsReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetSettlementsReply.\n *\/\n ICommand::SingleHandle buildGetSettlementsReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds BuildBuildingReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return BuildBuildingReply.\n *\/\n ICommand::SingleHandle buildBuildBuildingReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DestroyBuildingReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DestroyBuildingReply.\n *\/\n ICommand::SingleHandle buildDestroyBuildingReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetBuildingReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetBuildingReply.\n *\/\n ICommand::SingleHandle buildGetBuildingReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetBuildingsReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetBuildingsReply.\n *\/\n ICommand::SingleHandle buildGetBuildingsReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds DismissHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DismissHumanReply.\n *\/\n ICommand::SingleHandle buildDismissHumanReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds EngageHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return EngageHumanReply.\n *\/\n ICommand::SingleHandle buildEngageHumanReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetHumanReply.\n *\/\n ICommand::SingleHandle buildGetHumanReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetHumansReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetHumansReply.\n *\/\n ICommand::SingleHandle buildGetHumansReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds GetResourceReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetResourceReply.\n *\/\n ICommand::SingleHandle buildGetResourceReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds GetResourcesReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_objects The objects.\n *\n * @return GetResourcesReply.\n *\/\n ICommand::SingleHandle buildGetResourcesReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Objects const & a_objects\n ) const;\n\n \/**\n * @brief Builds CreateUserReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateUserReply.\n *\/\n ICommand::SingleHandle buildCreateUserReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds CreateWorldReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateWorldReply.\n *\/\n ICommand::SingleHandle buildCreateWorldReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds CreateEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return CreateEpochReply.\n *\/\n ICommand::SingleHandle buildCreateEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DeleteEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DeleteEpochReply.\n *\/\n ICommand::SingleHandle buildDeleteEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds ActivateEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return ActivateEpochReply.\n *\/\n ICommand::SingleHandle buildActivateEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds DectivateEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return DectivateEpochReply.\n *\/\n ICommand::SingleHandle buildDeactivateEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds FinishEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return FinishEpochReply.\n *\/\n ICommand::SingleHandle buildFinishEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds TickEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return TickEpochReply.\n *\/\n ICommand::SingleHandle buildTickEpochReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds GetEpochReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n * @param a_object The object.\n *\n * @return GetEpochReply.\n *\/\n ICommand::SingleHandle buildGetEpochReply(\n unsigned short int const a_code,\n std::string const a_message,\n ICommand::Object const & a_object\n ) const;\n\n \/**\n * @brief Builds TransportHumanReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return TransportHumanReply.\n *\/\n ICommand::SingleHandle buildTransportHumanReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n\n \/**\n * @brief Builds TransportResourceReply.\n *\n * @param a_code The exit code.\n * @param a_message The status message.\n *\n * @return TransportResourceReply.\n *\/\n ICommand::SingleHandle buildTransportResourceReply(\n unsigned short int const a_code,\n std::string const a_message\n ) const;\n};\n\n} \/\/ namespace TUSLanguage\n\n#endif \/\/ TUSLANGUAGE_REPLYBUILDER_HPP\n<|endoftext|>"} {"text":"\n\n#include \"knotesapp.h\"\n#include \"knoteconfigdlg.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nKNotesApp::\tKNotesApp()\n{\n\t\/\/make sure I copy over the knotesrc to a local\/writeable file- some\n\tQString globalConfigFile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n QString str_confdir = KGlobal::dirs()->saveLocation( \"config\" );\n kdDebug() << \"can save config at: \" << str_confdir << endl;\n\tQDir confdir( str_confdir );\n\t\n\tif( !confdir.exists( \"knotesrc\" ) )\n\t{\n\t\t\/\/copy over the default config file...avoid some problems with session management\n\t\tQFile gconfigfile( globalConfigFile );\n\t gconfigfile.open( IO_ReadOnly );\n \t\n \tQFile nconfigfile( str_confdir + \"knotesrc\" );\n \tnconfigfile.open( IO_WriteOnly );\n\n \tQTextStream input( &gconfigfile );\n \tQTextStream output( &nconfigfile );\n\n \tfor( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )\n\t\t\toutput << curr << endl;\n\n \tgconfigfile.close();\n \tnconfigfile.close();\n \tkdDebug() << \"saved the default config file in KDEHOME\" << endl;\n\t} else kdDebug() << \"default config already exists\" << endl;\n\n\t\/\/create the dock widget....\n\tsetPixmap( KGlobal::iconLoader()->loadIcon( \"knotes\", KIcon::Desktop ) );\n\tKPopupMenu* menu = contextMenu();\n\tmenu->insertTitle( SmallIcon(\"knotes\"), i18n(\"Knotes Options\") );\n\tmenu->insertItem( i18n(\"New Note\"), this, SLOT(slotNewNote(int)) );\n\tmenu->insertItem( i18n(\"Preferences...\"), this, SLOT(slotPreferences(int)) );\t\t\n\t\n \t\/\/initialize saved notes, if none create a note...\n\tQString str_notedir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n \tQDir notedir( str_notedir );\n \tQStringList notes = notedir.entryList( \"*\" );\n\n \tint count = 0;\n \tfor( QStringList::Iterator i = notes.begin(); i != notes.end(); ++i )\n \t{\n \t\tkdDebug() << \"checking file: \" << *i << endl;\n\t\tif( *i != \".\" && *i != \"..\" ) \/\/ignore these\n \t\t{\n \t\t\tQString configfile = notedir.absFilePath( *i );\n \t\t\tkdDebug() << \"restoring note, file: \" << configfile << endl;\n \t\t\tKConfig* tmp = new KConfig( configfile );\n \t\t\tKNote* tmpnote = new KNote( tmp );\n \t\t\tm_NoteList[*i] = tmpnote;\n \t\t\ttmpnote->show();\n\t\t\t++count;\n\t\t}\n\t}\n\t\n\tif( count == 0 )\n\t\tslotNewNote();\n}\n\n\nKNotesApp::~KNotesApp()\n{\n}\n\nvoid KNotesApp::slotNewNote( int \/*id*\/ )\n{\n\tQString globalConfigFile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n\tQString datadir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n\tkdDebug() << \"KNotesApp::slotNewNote, using template: \" << globalConfigFile << endl;\n\t\n \/\/find a new appropriate id for the new note...\n bool exists;\n QString thename;\n QDir appdir( datadir );\n for( int i = 1; i < 51; i++ ) \/\/set the unjust limit to 50 notes...\n {\n thename = QString( \"KNote %1\" ).arg(i);\n exists = false;\n\n if( !appdir.exists( thename ) )\n\t\t{\n\t\t\texists = false;\n\t\t\tbreak;\n\t\t}\n }\n\n if( exists )\n {\n QString msg = i18n(\"\"\n \"You have exeeded the arbitrary and unjustly set limit of 50 knotes.\\n\"\n \"Please complain to the author.\");\n KMessageBox::sorry( NULL, msg );\n return;\n }\n\n \/\/copy the default config file to $KDEHOME\/share\/apps\/knotes2\/notes\/filename\n QFile gconfigfile( globalConfigFile );\n gconfigfile.open( IO_ReadOnly );\n\n QFile nconfigfile( datadir + thename );\n nconfigfile.open( IO_WriteOnly );\n\n QTextStream input( &gconfigfile );\n QTextStream output( &nconfigfile );\n\n for( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )\n\t\toutput << curr << endl;\n\n gconfigfile.close();\n nconfigfile.close();\n\n\n \/\/then create a new KConfig object for the new note, so it can save it's own data\n KConfig* newconfig = new KConfig( datadir + thename );\n newconfig->setGroup( \"Data\" );\n newconfig->writeEntry(\"name\", thename );\n newconfig->sync();\n\n\tKNote* newnote = new KNote( newconfig );\n\t\n\tconnect( newnote, SIGNAL( sigRenamed(QString&, QString&) ),\n\t this, SLOT( slotNoteRenamed(QString&, QString&) ) );\n\tconnect( newnote, SIGNAL( sigNewNote(int) ),\n\t this, SLOT( slotNewNote(int) ) );\t\n\tconnect( newnote, SIGNAL( sigClosed(QString&) ),\n\t this, SLOT( slotNoteClosed(QString&) ) );\n\t\n\tm_NoteList[thename] = newnote;\n\tnewnote->show();\t\n}\n\nvoid KNotesApp::slotNoteRenamed( QString& oldname, QString& newname )\n{\n\tKNote* tmp = m_NoteList[oldname];\n\tm_NoteList[newname] = tmp;\n\tm_NoteList.remove( oldname );\n}\n\nvoid KNotesApp::slotNoteClosed( QString& name )\n{\n\tkdDebug() << \"removed note: \" << name << endl;\n\tm_NoteList.remove( name );\n}\n\nvoid KNotesApp::slotPreferences( int \/*id*\/ )\n{\n\tQString globalConfigFile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n\tkdDebug() << \"globalConfigFile = \" << globalConfigFile << endl;\n\tKConfig GlobalConfig( globalConfigFile );\n\t\n\t\/\/launch preferences dialog...\n\tKNoteConfigDlg tmpconfig( &GlobalConfig, i18n(\"KNotes Defaults\") );\n\ttmpconfig.exec();\n\tkdDebug() << \"after global settings configured\" << endl;\n}\n#include \"knotesapp.moc\"\nTook out title of knote dock menu since KDockWidget is working correctly now\n\n#include \"knotesapp.h\"\n#include \"knoteconfigdlg.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nKNotesApp::\tKNotesApp()\n{\n\t\/\/make sure I copy over the knotesrc to a local\/writeable file- some\n\tQString globalConfigFile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n QString str_confdir = KGlobal::dirs()->saveLocation( \"config\" );\n kdDebug() << \"can save config at: \" << str_confdir << endl;\n\tQDir confdir( str_confdir );\n\t\n\tif( !confdir.exists( \"knotesrc\" ) )\n\t{\n\t\t\/\/copy over the default config file...avoid some problems with session management\n\t\tQFile gconfigfile( globalConfigFile );\n\t gconfigfile.open( IO_ReadOnly );\n \t\n \tQFile nconfigfile( str_confdir + \"knotesrc\" );\n \tnconfigfile.open( IO_WriteOnly );\n\n \tQTextStream input( &gconfigfile );\n \tQTextStream output( &nconfigfile );\n\n \tfor( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )\n\t\t\toutput << curr << endl;\n\n \tgconfigfile.close();\n \tnconfigfile.close();\n \tkdDebug() << \"saved the default config file in KDEHOME\" << endl;\n\t} else kdDebug() << \"default config already exists\" << endl;\n\n\t\/\/create the dock widget....\n\tsetPixmap( KGlobal::iconLoader()->loadIcon( \"knotes\", KIcon::Desktop ) );\n\tKPopupMenu* menu = contextMenu();\n\tmenu->insertItem( i18n(\"New Note\"), this, SLOT(slotNewNote(int)) );\n\tmenu->insertItem( i18n(\"Preferences...\"), this, SLOT(slotPreferences(int)) );\t\t\n\t\n \t\/\/initialize saved notes, if none create a note...\n\tQString str_notedir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n \tQDir notedir( str_notedir );\n \tQStringList notes = notedir.entryList( \"*\" );\n\n \tint count = 0;\n \tfor( QStringList::Iterator i = notes.begin(); i != notes.end(); ++i )\n \t{\n \t\tkdDebug() << \"checking file: \" << *i << endl;\n\t\tif( *i != \".\" && *i != \"..\" ) \/\/ignore these\n \t\t{\n \t\t\tQString configfile = notedir.absFilePath( *i );\n \t\t\tkdDebug() << \"restoring note, file: \" << configfile << endl;\n \t\t\tKConfig* tmp = new KConfig( configfile );\n \t\t\tKNote* tmpnote = new KNote( tmp );\n \t\t\tm_NoteList[*i] = tmpnote;\n \t\t\ttmpnote->show();\n\t\t\t++count;\n\t\t}\n\t}\n\t\n\tif( count == 0 )\n\t\tslotNewNote();\n}\n\n\nKNotesApp::~KNotesApp()\n{\n}\n\nvoid KNotesApp::slotNewNote( int \/*id*\/ )\n{\n\tQString globalConfigFile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n\tQString datadir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n\tkdDebug() << \"KNotesApp::slotNewNote, using template: \" << globalConfigFile << endl;\n\t\n \/\/find a new appropriate id for the new note...\n bool exists;\n QString thename;\n QDir appdir( datadir );\n for( int i = 1; i < 51; i++ ) \/\/set the unjust limit to 50 notes...\n {\n thename = QString( \"KNote %1\" ).arg(i);\n exists = false;\n\n if( !appdir.exists( thename ) )\n\t\t{\n\t\t\texists = false;\n\t\t\tbreak;\n\t\t}\n }\n\n if( exists )\n {\n QString msg = i18n(\"\"\n \"You have exeeded the arbitrary and unjustly set limit of 50 knotes.\\n\"\n \"Please complain to the author.\");\n KMessageBox::sorry( NULL, msg );\n return;\n }\n\n \/\/copy the default config file to $KDEHOME\/share\/apps\/knotes2\/notes\/filename\n QFile gconfigfile( globalConfigFile );\n gconfigfile.open( IO_ReadOnly );\n\n QFile nconfigfile( datadir + thename );\n nconfigfile.open( IO_WriteOnly );\n\n QTextStream input( &gconfigfile );\n QTextStream output( &nconfigfile );\n\n for( QString curr = input.readLine(); curr != QString::null; curr = input.readLine() )\n\t\toutput << curr << endl;\n\n gconfigfile.close();\n nconfigfile.close();\n\n\n \/\/then create a new KConfig object for the new note, so it can save it's own data\n KConfig* newconfig = new KConfig( datadir + thename );\n newconfig->setGroup( \"Data\" );\n newconfig->writeEntry(\"name\", thename );\n newconfig->sync();\n\n\tKNote* newnote = new KNote( newconfig );\n\t\n\tconnect( newnote, SIGNAL( sigRenamed(QString&, QString&) ),\n\t this, SLOT( slotNoteRenamed(QString&, QString&) ) );\n\tconnect( newnote, SIGNAL( sigNewNote(int) ),\n\t this, SLOT( slotNewNote(int) ) );\t\n\tconnect( newnote, SIGNAL( sigClosed(QString&) ),\n\t this, SLOT( slotNoteClosed(QString&) ) );\n\t\n\tm_NoteList[thename] = newnote;\n\tnewnote->show();\t\n}\n\nvoid KNotesApp::slotNoteRenamed( QString& oldname, QString& newname )\n{\n\tKNote* tmp = m_NoteList[oldname];\n\tm_NoteList[newname] = tmp;\n\tm_NoteList.remove( oldname );\n}\n\nvoid KNotesApp::slotNoteClosed( QString& name )\n{\n\tkdDebug() << \"removed note: \" << name << endl;\n\tm_NoteList.remove( name );\n}\n\nvoid KNotesApp::slotPreferences( int \/*id*\/ )\n{\n\tQString globalConfigFile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n\tkdDebug() << \"globalConfigFile = \" << globalConfigFile << endl;\n\tKConfig GlobalConfig( globalConfigFile );\n\t\n\t\/\/launch preferences dialog...\n\tKNoteConfigDlg tmpconfig( &GlobalConfig, i18n(\"KNotes Defaults\") );\n\ttmpconfig.exec();\n\tkdDebug() << \"after global settings configured\" << endl;\n}\n#include \"knotesapp.moc\"\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n#include \"grins_config.h\"\n\n\/\/ GRINS\n#include \"grins\/mesh_builder.h\"\n#include \"grins\/simulation.h\"\n#include \"grins\/simulation_builder.h\"\n#include \"grins\/multiphysics_sys.h\"\n\n\/\/libMesh\n#include \"libmesh\/exact_solution.h\"\n\nvoid test_error_norm( libMesh::ExactSolution& exact_sol,\n const std::string& system_name,\n const std::string& var,\n const std::string& norm,\n const double tol,\n int& return_flag );\n\nint main(int argc, char* argv[])\n{\n GetPot command_line(argc,argv);\n\n if( !command_line.have_variable(\"input\") )\n {\n std::cerr << \"ERROR: Must specify input file on command line with input=.\" << std::endl;\n exit(1);\n }\n\n if( !command_line.have_variable(\"soln-data\") )\n {\n std::cerr << \"ERROR: Must specify solution data on command line with soln-data=.\" << std::endl;\n exit(1);\n }\n\n if( !command_line.have_variable(\"vars\") )\n {\n std::cerr << \"ERROR: Must specify variables on command line with vars='var1 var2'\" << std::endl;\n exit(1);\n }\n\n if( !command_line.have_variable(\"norms\") )\n {\n std::cerr << \"ERROR: Must specify variables on command line with norms='L2 H1'\" << std::endl;\n exit(1);\n }\n\n \/\/ libMesh input file should be first argument\n std::string libMesh_input_filename = command_line(\"input\", \"DIE!\");\n\n {\n std::ifstream i(libMesh_input_filename.c_str());\n if (!i)\n {\n std::cerr << \"Error: Could not read from libMesh input file \"\n << libMesh_input_filename << std::endl;\n exit(1);\n }\n }\n\n \/\/ Create our GetPot object.\n GetPot libMesh_inputfile( libMesh_input_filename );\n\n \/\/ Initialize libMesh library.\n libMesh::LibMeshInit libmesh_init(argc, argv);\n\n GRINS::SimulationBuilder sim_builder;\n\n GRINS::Simulation grins( libMesh_inputfile,\n\t\t\t sim_builder,\n libmesh_init.comm() );\n\n \/\/ Do solve here\n grins.run();\n\n \/\/ Get equation systems to create ExactSolution object\n std::tr1::shared_ptr es = grins.get_equation_system();\n\n \/\/ Create Exact solution object and attach exact solution quantities\n libMesh::ExactSolution exact_sol(*es);\n\n libMesh::EquationSystems es_ref( es->get_mesh() );\n\n \/\/ Filename of file where comparison solution is stashed\n std::string solution_file = command_line(\"soln-data\", \"DIE!\");\n es_ref.read( solution_file );\n\n exact_sol.attach_reference_solution( &es_ref );\n\n \/\/ Now grab the variables for which we want to compare\n unsigned int n_vars = command_line.vector_variable_size(\"vars\");\n std::vector vars(n_vars);\n for( unsigned int v = 0; v < n_vars; v++ )\n {\n vars[v] = command_line(\"vars\", \"DIE!\", v);\n }\n\n \/\/ Now grab the norms to compute for each variable error\n unsigned int n_norms = command_line.vector_variable_size(\"norms\");\n std::vector norms(n_norms);\n for( unsigned int n = 0; n < n_norms; n++ )\n {\n norms[n] = command_line(\"norms\", \"DIE!\", n);\n if( norms[n] != std::string(\"L2\") &&\n norms[n] != std::string(\"H1\") )\n {\n std::cerr << \"ERROR: Invalid norm input \" << norms[n] << std::endl\n << \" Valid values are: L2\" << std::endl\n << \" H1\" << std::endl;\n }\n }\n\n const std::string& system_name = grins.get_multiphysics_system_name();\n\n \/\/ Now compute error for each variable\n for( unsigned int v = 0; v < n_vars; v++ )\n {\n exact_sol.compute_error(system_name, vars[v]);\n }\n\n int return_flag = 0;\n\n double tol = 1.0e-10;\n\n \/\/ Now test error for each variable, for each norm\n for( unsigned int v = 0; v < n_vars; v++ )\n {\n for( unsigned int n = 0; n < n_norms; n++ )\n {\n test_error_norm( exact_sol, system_name, vars[v], norms[n], tol, return_flag );\n }\n }\n\n return return_flag;\n}\n\nvoid test_error_norm( libMesh::ExactSolution& exact_sol,\n const std::string& system_name,\n const std::string& var,\n const std::string& norm,\n const double tol,\n int& return_flag )\n{\n \/\/ We don't set return_flag unless we are setting it 1\n \/\/ since this function gets called multiple times and we don't\n \/\/ want to overwrite a previous \"fail\" (return_flag = 1) with\n \/\/ a \"pass\" (return_flag = 0)\n\n double error = 0.0;\n\n std::cout << \"==========================================================\" << std::endl\n << \"Checking variable \" << var << \" using error norm \" << norm << \" with tol \" << tol << \"...\";\n\n if( norm == std::string(\"L2\") )\n {\n error = exact_sol.l2_error(system_name, var);\n }\n else if( norm == std::string(\"H1\") )\n {\n error = exact_sol.h1_error(system_name, var);\n }\n else\n {\n std::cerr << \"ERROR: Invalid norm \" << norm << std::endl;\n exit(1);\n }\n\n if( error > tol )\n {\n return_flag = 1;\n\n std::cerr << \"Tolerance exceeded for generic regression test!\" << std::endl\n << \"tolerance = \" << tol << std::endl\n << \"norm of error = \" << error << std::endl\n << \"norm type = \" << norm << std::endl\n << \"var = \" << var << std::endl;\n }\n else\n {\n std::cout << \"PASSED!\" << std::endl\n << \"==========================================================\" << std::endl;\n }\n\n return;\n}\nCorrect error message.\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n#include \"grins_config.h\"\n\n\/\/ GRINS\n#include \"grins\/mesh_builder.h\"\n#include \"grins\/simulation.h\"\n#include \"grins\/simulation_builder.h\"\n#include \"grins\/multiphysics_sys.h\"\n\n\/\/libMesh\n#include \"libmesh\/exact_solution.h\"\n\nvoid test_error_norm( libMesh::ExactSolution& exact_sol,\n const std::string& system_name,\n const std::string& var,\n const std::string& norm,\n const double tol,\n int& return_flag );\n\nint main(int argc, char* argv[])\n{\n GetPot command_line(argc,argv);\n\n if( !command_line.have_variable(\"input\") )\n {\n std::cerr << \"ERROR: Must specify input file on command line with input=.\" << std::endl;\n exit(1);\n }\n\n if( !command_line.have_variable(\"soln-data\") )\n {\n std::cerr << \"ERROR: Must specify solution data on command line with soln-data=.\" << std::endl;\n exit(1);\n }\n\n if( !command_line.have_variable(\"vars\") )\n {\n std::cerr << \"ERROR: Must specify variables on command line with vars='var1 var2'\" << std::endl;\n exit(1);\n }\n\n if( !command_line.have_variable(\"norms\") )\n {\n std::cerr << \"ERROR: Must specify error norms on command line with norms='L2 H1'\" << std::endl;\n exit(1);\n }\n\n \/\/ libMesh input file should be first argument\n std::string libMesh_input_filename = command_line(\"input\", \"DIE!\");\n\n {\n std::ifstream i(libMesh_input_filename.c_str());\n if (!i)\n {\n std::cerr << \"Error: Could not read from libMesh input file \"\n << libMesh_input_filename << std::endl;\n exit(1);\n }\n }\n\n \/\/ Create our GetPot object.\n GetPot libMesh_inputfile( libMesh_input_filename );\n\n \/\/ Initialize libMesh library.\n libMesh::LibMeshInit libmesh_init(argc, argv);\n\n GRINS::SimulationBuilder sim_builder;\n\n GRINS::Simulation grins( libMesh_inputfile,\n\t\t\t sim_builder,\n libmesh_init.comm() );\n\n \/\/ Do solve here\n grins.run();\n\n \/\/ Get equation systems to create ExactSolution object\n std::tr1::shared_ptr es = grins.get_equation_system();\n\n \/\/ Create Exact solution object and attach exact solution quantities\n libMesh::ExactSolution exact_sol(*es);\n\n libMesh::EquationSystems es_ref( es->get_mesh() );\n\n \/\/ Filename of file where comparison solution is stashed\n std::string solution_file = command_line(\"soln-data\", \"DIE!\");\n es_ref.read( solution_file );\n\n exact_sol.attach_reference_solution( &es_ref );\n\n \/\/ Now grab the variables for which we want to compare\n unsigned int n_vars = command_line.vector_variable_size(\"vars\");\n std::vector vars(n_vars);\n for( unsigned int v = 0; v < n_vars; v++ )\n {\n vars[v] = command_line(\"vars\", \"DIE!\", v);\n }\n\n \/\/ Now grab the norms to compute for each variable error\n unsigned int n_norms = command_line.vector_variable_size(\"norms\");\n std::vector norms(n_norms);\n for( unsigned int n = 0; n < n_norms; n++ )\n {\n norms[n] = command_line(\"norms\", \"DIE!\", n);\n if( norms[n] != std::string(\"L2\") &&\n norms[n] != std::string(\"H1\") )\n {\n std::cerr << \"ERROR: Invalid norm input \" << norms[n] << std::endl\n << \" Valid values are: L2\" << std::endl\n << \" H1\" << std::endl;\n }\n }\n\n const std::string& system_name = grins.get_multiphysics_system_name();\n\n \/\/ Now compute error for each variable\n for( unsigned int v = 0; v < n_vars; v++ )\n {\n exact_sol.compute_error(system_name, vars[v]);\n }\n\n int return_flag = 0;\n\n double tol = 1.0e-10;\n\n \/\/ Now test error for each variable, for each norm\n for( unsigned int v = 0; v < n_vars; v++ )\n {\n for( unsigned int n = 0; n < n_norms; n++ )\n {\n test_error_norm( exact_sol, system_name, vars[v], norms[n], tol, return_flag );\n }\n }\n\n return return_flag;\n}\n\nvoid test_error_norm( libMesh::ExactSolution& exact_sol,\n const std::string& system_name,\n const std::string& var,\n const std::string& norm,\n const double tol,\n int& return_flag )\n{\n \/\/ We don't set return_flag unless we are setting it 1\n \/\/ since this function gets called multiple times and we don't\n \/\/ want to overwrite a previous \"fail\" (return_flag = 1) with\n \/\/ a \"pass\" (return_flag = 0)\n\n double error = 0.0;\n\n std::cout << \"==========================================================\" << std::endl\n << \"Checking variable \" << var << \" using error norm \" << norm << \" with tol \" << tol << \"...\";\n\n if( norm == std::string(\"L2\") )\n {\n error = exact_sol.l2_error(system_name, var);\n }\n else if( norm == std::string(\"H1\") )\n {\n error = exact_sol.h1_error(system_name, var);\n }\n else\n {\n std::cerr << \"ERROR: Invalid norm \" << norm << std::endl;\n exit(1);\n }\n\n if( error > tol )\n {\n return_flag = 1;\n\n std::cerr << \"Tolerance exceeded for generic regression test!\" << std::endl\n << \"tolerance = \" << tol << std::endl\n << \"norm of error = \" << error << std::endl\n << \"norm type = \" << norm << std::endl\n << \"var = \" << var << std::endl;\n }\n else\n {\n std::cout << \"PASSED!\" << std::endl\n << \"==========================================================\" << std::endl;\n }\n\n return;\n}\n<|endoftext|>"} {"text":"\/*\n nljuk.cpp\n\n Kopete Now Listening To plugin\n\n Copyright (c) 2002,2003 by Will Stephenson \n Copyright (c) 2003 by Ismail Donmez \n Copyright (c) 2002,2003 by the Kopete developers \n\t\n\tPurpose: \n\tThis class abstracts the interface to JuK by\n\timplementing NLMediaPlayer\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \n#include \n\n#include \"nlmediaplayer.h\"\n#include \"nljuk.h\"\n\nNLJuk::NLJuk( DCOPClient *client ) : NLMediaPlayer()\n{\n\tm_client = client;\n\tm_type = Audio;\n\tm_name = \"JuK\";\n}\n\nvoid NLJuk::update()\n{\n\tm_playing = false;\n\tQString newTrack;\n\n\t\/\/ see if JuK is registered with DCOP\n\tif ( m_client->isApplicationRegistered( \"juk\" ) )\n\t{\n\t\t\/\/ see if it's playing\n\t\tQByteArray data, replyData;\n\t\tQCString replyType;\n\t\tQString result;\n\n\t\tif ( m_client->call( \"juk\", \"Player\", \"playingString()\", data,\n\t\t\t\t\treplyType, replyData ) )\n\t\t{\n\t\t\tm_playing = true;\n\t\t\tQDataStream reply( replyData, IO_ReadOnly );\n\n\t\t\tif ( replyType == \"QString\" ) {\n\t\t\t\treply >> result;\n\t\t\t\tm_artist = result.section(\"-\",0,0);\n\t\t\t\tnewTrack = result.section(\"-\",1,1);\n\t\t\t}\n\t\t}\n\n\t\tif ( newTrack != m_track )\n\t\t{\n\t\t\tm_newTrack = true;\n\t\t\tm_track = newTrack;\n\t\t}\n\t\telse\n\t\t\tm_newTrack = false;\n\t}\n\telse\n\t\tkdDebug( 14307 ) << \"Juk is not running!\\n\" << endl;\n}\n\ndetect whether or not JuK is playing from its current track time indicator\/*\n nljuk.cpp\n\n Kopete Now Listening To plugin\n\n Copyright (c) 2002,2003 by Will Stephenson \n Copyright (c) 2003 by Ismail Donmez \n Copyright (c) 2002,2003 by the Kopete developers \n\t\n\tPurpose: \n\tThis class abstracts the interface to JuK by\n\timplementing NLMediaPlayer\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \n#include \n\n#include \"nlmediaplayer.h\"\n#include \"nljuk.h\"\n\nNLJuk::NLJuk( DCOPClient *client ) : NLMediaPlayer()\n{\n\tm_client = client;\n\tm_type = Audio;\n\tm_name = \"JuK\";\n}\n\nvoid NLJuk::update()\n{\n\tm_playing = false;\n\tQString newTrack;\n\n\t\/\/ see if JuK is registered with DCOP\n\tif ( m_client->isApplicationRegistered( \"juk\" ) )\n\t{\n\t\t\/\/ see if it's playing\n\t\tQByteArray data, replyData;\n\t\tQCString replyType;\n\t\tQString result;\n\n\t\tif ( m_client->call( \"juk\", \"Player\", \"currentTime()\", data, \n\t\t\t\t\treplyType, replyData ) )\n\t\t{\n\t\t\tQDataStream reply( replyData, IO_ReadOnly );\n\t\t\tint currentTime;\n\t\t\tif ( replyType == \"int\" ) {\n\t\t\t\treply >> currentTime;\n\t\t\t\tif ( currentTime != -1 )\n\t\t\t\t\tm_playing = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif ( m_client->call( \"juk\", \"Player\", \"playingString()\", data,\n\t\t\t\t\treplyType, replyData ) )\n\t\t{\n\t\t\tQDataStream reply( replyData, IO_ReadOnly );\n\n\t\t\tif ( replyType == \"QString\" ) {\n\t\t\t\treply >> result;\n\t\t\t\tm_artist = result.section(\"-\",0,0);\n\t\t\t\tnewTrack = result.section(\"-\",1,1);\n\t\t\t}\n\t\t}\n\n\t\tif ( newTrack != m_track )\n\t\t{\n\t\t\tm_newTrack = true;\n\t\t\tm_track = newTrack;\n\t\t}\n\t\telse\n\t\t\tm_newTrack = false;\n\t}\n\telse\n\t\tkdDebug( 14307 ) << \"Juk is not running!\\n\" << endl;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"geometry.h\"\n#include \"immintrin.h\"\n#include \"vec.h\"\n#include \"color.h\"\n#include \"render_target.h\"\n#include \"camera.h\"\n#include \"sphere.h\"\n#include \"plane.h\"\n#include \"diff_geom.h\"\n#include \"material.h\"\n#include \"light.h\"\n#include \"occlusion_tester.h\"\n#include \"scene.h\"\n\nint main(int, char**){\n\tconst uint32_t width = 800;\n\tconst uint32_t height = 600;\n\tconst auto scene = Scene{\n\t\t{\n\t\t\tstd::make_shared(Vec3f{0}, 0.5f, 0),\n\t\t\tstd::make_shared(Vec3f{0, -0.5, 0}, Vec3f{0, 1, 0}, 1)\n\t\t},\n\t\t{\n\t\t\tstd::make_shared(Colorf{1, 0, 0}),\n\t\t\tstd::make_shared(Colorf{0, 0, 1})\n\t\t},\n\t\tPointLight{Vec3f{1, 1, -2}, Colorf{50}}\n\t};\n\n\tconst auto camera = PerspectiveCamera{Vec3f{0, 0, -3}, Vec3f{0, 0, 0}, Vec3f{0, 1, 0},\n\t\t60.f, static_cast(width) \/ height};\n\tauto target = RenderTarget{width, height};\n\tconst auto img_dim = Vec2f_8{static_cast(width), static_cast(height)};\n\n\t\/\/ TODO: Z-order 4x4 blocks?\n\tconst int n_pixels = width * height;\n\tfor (int i = 0; i < n_pixels; i += 8){\n\t\tstd::array pixel_x, pixel_y;\n\t\tfor (int j = 0; j < 8; ++j){\n\t\t\tpixel_x[j] = 0.5f + i % width + j;\n\t\t\tpixel_y[j] = 0.5f + i \/ width;\n\t\t}\n\t\tconst auto samples = Vec2f_8{_mm256_loadu_ps(pixel_x.data()),\n\t\t\t_mm256_loadu_ps(pixel_y.data())};\n\t\tRay8 packet;\n\t\tcamera.generate_rays(packet, samples \/ img_dim);\n\n\t\tDiffGeom8 dg;\n\t\tauto hits = scene.intersect(packet, dg);\n\t\t\/\/ If we hit something, shade it\n\t\tif (_mm256_movemask_ps(hits) != 0){\n\t\t\tauto color = Colorf_8{0};\n\t\t\t\/\/ How does ISPC find the unique values for its foreach_unique loop? Would like to do that\n\t\t\t\/\/ if it will be nicer than this\n\t\t\tstd::array mat_ids;\n\t\t\t_mm256_storeu_si256((__m256i*)mat_ids.data(), dg.material_id);\n\t\t\tstd::unique(std::begin(mat_ids), std::end(mat_ids));\n\t\t\tfor (const auto &i : mat_ids){\n\t\t\t\tif (i == -1){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\/\/ Is there a better way to just get the bits of one register casted to another?\n\t\t\t\t\/\/ it seems like the or operations don't let you mix either\n\t\t\t\tconst auto use_mat = _mm256_cmpeq_epi32(dg.material_id, _mm256_set1_epi32(i));\n\t\t\t\tauto shade_mask = *(__m256*)&use_mat;\n\t\t\t\tif (_mm256_movemask_ps(shade_mask) != 0){\n\t\t\t\t\tconst auto w_o = -packet.d;\n\t\t\t\t\tVec3f_8 w_i{0};\n\t\t\t\t\tOcclusionTester occlusion;\n\t\t\t\t\tconst auto li = scene.light.sample(dg.point, w_i, occlusion);\n\t\t\t\t\t\/\/ We just need to flip the sign bit to change occluded mask to unoccluded mask since\n\t\t\t\t\t\/\/ only the sign bit is used by movemask and blendv\n\t\t\t\t\tauto unoccluded = _mm256_xor_ps(occlusion.occluded(scene), _mm256_set1_ps(-0.f));\n\t\t\t\t\tif (_mm256_movemask_ps(unoccluded) != 0){\n\t\t\t\t\t\tconst auto c = scene.materials[i]->shade(w_o, w_i) * li\n\t\t\t\t\t\t\t* _mm256_max_ps(w_i.dot(dg.normal), _mm256_set1_ps(0.f));\n\t\t\t\t\t\tshade_mask = _mm256_and_ps(shade_mask, unoccluded);\n\t\t\t\t\t\tcolor.r = _mm256_blendv_ps(color.r, c.r, shade_mask);\n\t\t\t\t\t\tcolor.g = _mm256_blendv_ps(color.g, c.g, shade_mask);\n\t\t\t\t\t\tcolor.b = _mm256_blendv_ps(color.b, c.b, shade_mask);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttarget.write_samples(samples, color, hits);\n\t\t}\n\t}\n\ttarget.save_image(\"out.bmp\");\n}\n\nstd::unique only removes consecutive duplicates, so sort first#include \n#include \n#include \n#include \n#include \"geometry.h\"\n#include \"immintrin.h\"\n#include \"vec.h\"\n#include \"color.h\"\n#include \"render_target.h\"\n#include \"camera.h\"\n#include \"sphere.h\"\n#include \"plane.h\"\n#include \"diff_geom.h\"\n#include \"material.h\"\n#include \"light.h\"\n#include \"occlusion_tester.h\"\n#include \"scene.h\"\n\nint main(int, char**){\n\tconst uint32_t width = 800;\n\tconst uint32_t height = 600;\n\tconst auto scene = Scene{\n\t\t{\n\t\t\tstd::make_shared(Vec3f{0}, 0.5f, 0),\n\t\t\tstd::make_shared(Vec3f{0, -0.5, 0}, Vec3f{0, 1, 0}, 1)\n\t\t},\n\t\t{\n\t\t\tstd::make_shared(Colorf{1, 0, 0}),\n\t\t\tstd::make_shared(Colorf{0, 0, 1})\n\t\t},\n\t\tPointLight{Vec3f{1, 1, -2}, Colorf{50}}\n\t};\n\n\tconst auto camera = PerspectiveCamera{Vec3f{0, 0, -3}, Vec3f{0, 0, 0}, Vec3f{0, 1, 0},\n\t\t60.f, static_cast(width) \/ height};\n\tauto target = RenderTarget{width, height};\n\tconst auto img_dim = Vec2f_8{static_cast(width), static_cast(height)};\n\n\t\/\/ TODO: Z-order 4x4 blocks?\n\tconst int n_pixels = width * height;\n\tfor (int i = 0; i < n_pixels; i += 8){\n\t\tstd::array pixel_x, pixel_y;\n\t\tfor (int j = 0; j < 8; ++j){\n\t\t\tpixel_x[j] = 0.5f + i % width + j;\n\t\t\tpixel_y[j] = 0.5f + i \/ width;\n\t\t}\n\t\tconst auto samples = Vec2f_8{_mm256_loadu_ps(pixel_x.data()),\n\t\t\t_mm256_loadu_ps(pixel_y.data())};\n\t\tRay8 packet;\n\t\tcamera.generate_rays(packet, samples \/ img_dim);\n\n\t\tDiffGeom8 dg;\n\t\tauto hits = scene.intersect(packet, dg);\n\t\t\/\/ If we hit something, shade it\n\t\tif (_mm256_movemask_ps(hits) != 0){\n\t\t\tauto color = Colorf_8{0};\n\t\t\t\/\/ How does ISPC find the unique values for its foreach_unique loop? Would like to do that\n\t\t\t\/\/ if it will be nicer than this\n\t\t\tstd::array mat_ids;\n\t\t\t_mm256_storeu_si256((__m256i*)mat_ids.data(), dg.material_id);\n\t\t\t\/\/ std::unique just removes consecutive repeated elements, so sort things first so we\n\t\t\t\/\/ don't get something like -1, 0, -1 or such\n\t\t\tstd::sort(std::begin(mat_ids), std::end(mat_ids));\n\t\t\tstd::unique(std::begin(mat_ids), std::end(mat_ids));\n\t\t\tfor (const auto &i : mat_ids){\n\t\t\t\tif (i == -1){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\/\/ Is there a better way to just get the bits of one register casted to another?\n\t\t\t\t\/\/ it seems like the or operations don't let you mix either\n\t\t\t\tconst auto use_mat = _mm256_cmpeq_epi32(dg.material_id, _mm256_set1_epi32(i));\n\t\t\t\tauto shade_mask = *(__m256*)&use_mat;\n\t\t\t\tif (_mm256_movemask_ps(shade_mask) != 0){\n\t\t\t\t\tconst auto w_o = -packet.d;\n\t\t\t\t\tVec3f_8 w_i{0};\n\t\t\t\t\tOcclusionTester occlusion;\n\t\t\t\t\tconst auto li = scene.light.sample(dg.point, w_i, occlusion);\n\t\t\t\t\t\/\/ We just need to flip the sign bit to change occluded mask to unoccluded mask since\n\t\t\t\t\t\/\/ only the sign bit is used by movemask and blendv\n\t\t\t\t\tauto unoccluded = _mm256_xor_ps(occlusion.occluded(scene), _mm256_set1_ps(-0.f));\n\t\t\t\t\tif (_mm256_movemask_ps(unoccluded) != 0){\n\t\t\t\t\t\tconst auto c = scene.materials[i]->shade(w_o, w_i) * li\n\t\t\t\t\t\t\t* _mm256_max_ps(w_i.dot(dg.normal), _mm256_set1_ps(0.f));\n\t\t\t\t\t\tshade_mask = _mm256_and_ps(shade_mask, unoccluded);\n\t\t\t\t\t\tcolor.r = _mm256_blendv_ps(color.r, c.r, shade_mask);\n\t\t\t\t\t\tcolor.g = _mm256_blendv_ps(color.g, c.g, shade_mask);\n\t\t\t\t\t\tcolor.b = _mm256_blendv_ps(color.b, c.b, shade_mask);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttarget.write_samples(samples, color, hits);\n\t\t}\n\t}\n\ttarget.save_image(\"out.bmp\");\n}\n\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * usbpro_test.cpp\n * Allows testing of a usb pro\n * Copyright (C) 2010 Simon Newton\n *\/\n\n#include \n#include \n#include \n#include \"ola\/Logging.h\"\n#include \"ola\/DmxBuffer.h\"\n#include \"ola\/network\/SelectServer.h\"\n#include \"ola\/network\/Socket.h\"\n#include \"plugins\/usbpro\/UsbProWidget.h\"\n#include \"plugins\/usbpro\/UsbProWidgetListener.h\"\n\nusing ola::DmxBuffer;\nusing ola::network::SelectServer;\nusing ola::plugin::usbpro::UsbProWidget;\nusing std::string;\n\n\nclass Listener: public ola::plugin::usbpro::UsbProWidgetListener {\n public:\n Listener(UsbProWidget *widget): m_widget(widget) {}\n void HandleWidgetDmx() {\n const DmxBuffer &buffer = m_widget->FetchDMX();\n OLA_INFO << (int) buffer.Get(0) << \",\" << (int) buffer.Get(1);\n\n }\n\n private:\n UsbProWidget *m_widget;\n};\n\nint main(int argc, char *argv[]) {\n ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);\n string usb_path;\n\n static struct option long_options[] = {\n {\"usb\", required_argument, 0, 'u'},\n {0, 0, 0, 0}\n };\n\n int option_index = 0;\n\n while (1) {\n int c = getopt_long(argc, argv, \"u:\", long_options, &option_index);\n\n if (c == -1)\n break;\n\n switch (c) {\n case 0:\n break;\n case 'u':\n usb_path = optarg;\n break;\n case '?':\n break;\n default:\n break;\n }\n }\n\n SelectServer ss;\n UsbProWidget widget;\n assert(widget.Connect(usb_path));\n assert(ss.AddSocket(widget.GetSocket()));\n assert(widget.ChangeToReceiveMode());\n\n Listener listener(&widget);\n widget.SetListener(&listener);\n ss.Run();\n}\n * make the usbpro_test output more readable.\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * usbpro_test.cpp\n * Allows testing of a usb pro\n * Copyright (C) 2010 Simon Newton\n *\/\n\n#include \n#include \n#include \n#include \"ola\/Logging.h\"\n#include \"ola\/DmxBuffer.h\"\n#include \"ola\/network\/SelectServer.h\"\n#include \"ola\/network\/Socket.h\"\n#include \"plugins\/usbpro\/UsbProWidget.h\"\n#include \"plugins\/usbpro\/UsbProWidgetListener.h\"\n\nusing ola::DmxBuffer;\nusing ola::network::SelectServer;\nusing ola::plugin::usbpro::UsbProWidget;\nusing std::string;\n\n\nclass Listener: public ola::plugin::usbpro::UsbProWidgetListener {\n public:\n Listener(UsbProWidget *widget): m_widget(widget) {}\n void HandleWidgetDmx() {\n const DmxBuffer &buffer = m_widget->FetchDMX();\n OLA_INFO << buffer.ToString();\n }\n\n private:\n UsbProWidget *m_widget;\n};\n\nint main(int argc, char *argv[]) {\n ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);\n string usb_path;\n\n static struct option long_options[] = {\n {\"usb\", required_argument, 0, 'u'},\n {0, 0, 0, 0}\n };\n\n int option_index = 0;\n\n while (1) {\n int c = getopt_long(argc, argv, \"u:\", long_options, &option_index);\n\n if (c == -1)\n break;\n\n switch (c) {\n case 0:\n break;\n case 'u':\n usb_path = optarg;\n break;\n case '?':\n break;\n default:\n break;\n }\n }\n\n SelectServer ss;\n UsbProWidget widget;\n assert(widget.Connect(usb_path));\n assert(ss.AddSocket(widget.GetSocket()));\n assert(widget.ChangeToReceiveMode());\n\n Listener listener(&widget);\n widget.SetListener(&listener);\n ss.Run();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"harness.hh\"\n#include \"lexer.hh\"\n\nTADPOLE_TEST(TadpoleLexer) {\n using TK = tadpole::TokenKind;\n\n#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)\n#define DUMPLEX() do {\\\n for (;;) {\\\n auto t = lex.next_token();\\\n std::fprintf(stdout, \"%-24s | %-32s | %d\\n\",\\\n tadpole::get_kind_name(t.kind()),\\\n t.as_cstring(),\\\n t.lineno());\\\n if (t.kind() == TK::TK_EOF)\\\n break;\\\n }\\\n} while (false)\n\n {\n std::string s =\n \"print(\\\"Welcome to TADPOLE !!!\\\");\\nvar v = 34 * 67 \/ 33.56 + (89 - 23.7) \/ 2.34;\";\n tadpole::Lexer lex(s);\n DUMPLEX();\n }\n\n {\n std::string s = \"var a = 56.78;\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::KW_VAR);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_EQ);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_EOF);\n }\n\n#undef DUMPLEX\n#undef TESTEQ\n}\n:white_check_mark: test(lexer): updated the test for lexer\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"harness.hh\"\n#include \"lexer.hh\"\n\nTADPOLE_TEST(TadpoleLexer) {\n using TK = tadpole::TokenKind;\n\n#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)\n#define DUMPLEX() do {\\\n for (;;) {\\\n auto t = lex.next_token();\\\n std::fprintf(stdout, \"%-24s | %-32s | %d\\n\",\\\n tadpole::get_kind_name(t.kind()),\\\n t.as_cstring(),\\\n t.lineno());\\\n if (t.kind() == TK::TK_EOF)\\\n break;\\\n }\\\n} while (false)\n\n {\n std::string s =\n \"print(\\\"Welcome to TADPOLE !!!\\\");\\nvar v = 34 * 67 \/ 33.56 + (89 - 23.7) \/ 2.34;\";\n tadpole::Lexer lex(s);\n DUMPLEX();\n }\n\n {\n std::string s = \"var a = 56.78;\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::KW_VAR);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_EQ);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_EOF);\n }\n\n {\n std::string s = \"print(\\\"34 + 89.7 =\\\", 34 + 89.7);\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_STRING);\n TESTEQ(TK::TK_COMMA);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_PLUS);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_EOF);\n }\n\n {\n std::string s = \"fn show_message(msg) { print(msg); }\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::KW_FN);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_LBRACE);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_RBRACE);\n TESTEQ(TK::TK_EOF);\n }\n\n {\n std::string s = \"fn do_calc() { print(23 + 45.2 * 8.78 \/ 0.89 - (23 + 67.9)); }\";\n tadpole::Lexer lex(s);\n TESTEQ(TK::KW_FN);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_LBRACE);\n TESTEQ(TK::TK_IDENTIFIER);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_PLUS);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_STAR);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_SLASH);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_MINUS);\n TESTEQ(TK::TK_LPAREN);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_PLUS);\n TESTEQ(TK::TK_NUMERIC);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_RPAREN);\n TESTEQ(TK::TK_SEMI);\n TESTEQ(TK::TK_RBRACE);\n TESTEQ(TK::TK_EOF);\n }\n\n#undef DUMPLEX\n#undef TESTEQ\n}\n<|endoftext|>"} {"text":"\/\/\/ @file\n\/\/\/ @copyright The code is licensed under the BSD License\n\/\/\/ ,\n\/\/\/ Copyright (c) 2013-2015 Alexandre Hamez.\n\/\/\/ @author Alexandre Hamez\n\n#include \n\n#include \"mc\/classic\/dead_states.hh\"\n#include \"mc\/classic\/filter_lt.hh\"\n\nnamespace pnmc { namespace mc { namespace classic {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nSDD\ndead_states(const order& o, const pn::net& net, const SDD& state_space)\n{\n auto and_operands = std::set{};\n auto or_operands = std::set{};\n\n for (const auto& transition : net.transitions())\n {\n \/\/ We are only interested in pre actions.\n for (const auto& arc : transition.pre)\n {\n switch (arc.kind)\n {\n case arc::type::normal:\n case arc::type::read:\n or_operands.insert(function(o, arc.first, filter_lt{arc.second.weight}));\n break;\n\n case arc::type::inhibitor:\n or_operands.insert(function(o, arc.first, filter_ge{arc.second.weight}));\n break;\n\n default:\n throw std::runtime_error{\"Post arc type for pre arc\"};\n }\n }\n\n and_operands.insert(sum(o, or_operands.cbegin(), or_operands.cend()));\n or_operands.clear();\n }\n const auto tmp = intersection(o, and_operands.cbegin(), and_operands.cend());\n\n return sdd::rewrite(o, tmp)(o, state_space); \/\/ compute dead states\n}\n\/*------------------------------------------------------------------------------------------------*\/\n\n}}} \/\/ namespace pnmc::mc::classic\nFix dead states computation\/\/\/ @file\n\/\/\/ @copyright The code is licensed under the BSD License\n\/\/\/ ,\n\/\/\/ Copyright (c) 2013-2015 Alexandre Hamez.\n\/\/\/ @author Alexandre Hamez\n\n#include \n\n#include \"mc\/classic\/dead_states.hh\"\n#include \"mc\/classic\/filter_ge.hh\"\n#include \"mc\/classic\/filter_lt.hh\"\n\nnamespace pnmc { namespace mc { namespace classic {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nSDD\ndead_states(const order& o, const pn::net& net, const SDD& state_space)\n{\n auto and_operands = std::set{};\n auto or_operands = std::set{};\n\n for (const auto& transition : net.transitions())\n {\n \/\/ We are only interested in pre actions.\n for (const auto& arc : transition.pre)\n {\n switch (arc.second.kind)\n {\n case pn::arc::type::normal:\n case pn::arc::type::read:\n or_operands.insert(function(o, arc.first, filter_lt{arc.second.weight}));\n break;\n\n case pn::arc::type::reset:\n \/\/ Does not impose a precondition on firing.\n continue;\n\n case pn::arc::type::inhibitor:\n or_operands.insert(function(o, arc.first, filter_ge{arc.second.weight}));\n break;\n\n case pn::arc::type::stopwatch:\n throw std::runtime_error{\"Unsupported stopwatch pre arc for dead states\"};\n\n case pn::arc::type::stopwatch_inhibitor:\n throw std::runtime_error{\"Unsupported stopwatch inhibitor pre arc for dead states\"};\n }\n }\n\n and_operands.insert(sum(o, or_operands.cbegin(), or_operands.cend()));\n or_operands.clear();\n }\n const auto tmp = intersection(o, and_operands.cbegin(), and_operands.cend());\n\n return sdd::rewrite(o, tmp)(o, state_space); \/\/ compute dead states\n}\n\/*------------------------------------------------------------------------------------------------*\/\n\n}}} \/\/ namespace pnmc::mc::classic\n<|endoftext|>"} {"text":"\/\/ Describing expectations for a valid sparse matrix library\n\n#ifndef SPARSELIB_CONCEPT_HPP\n#define SPARSELIB_CONCEPT_HPP\n\n#include \n#include \n\n\/\/ First, some preliminaries (no predefined Concepts are supplied in library yet)\ntemplate concept bool ForwardIterator =\n requires( T a, T b ) {\n { a != b }\n { a == b }\n { ++a }\n { *a }\n};\n\ntemplate concept bool DereferencesTo =\n requires( T a ) {\n { *a } -> U;\n};\n\ntemplate concept bool ConstructibleFrom =\n std::is_constructible::value;\n\ntemplate concept bool ForwardIterator =\n std::is_convertible::iterator_category,\n std::forward_iterator_tag>::value;\n\ntemplate concept bool Same =\n std::is_same::value;\n\ntemplate concept bool IteratorRange =\n Same && ForwardIterator;\n\ntemplate concept bool SparseLibrary =\n requires( typename L::sparsemat_t mat,\n typename L::lu_t lu,\n typename L::qr_t qr,\n std::ostream& os\n ) {\n \/\/ inner types we expect\n typename L::sparsemat_t;\n typename L::index_t;\n typename L::value_t;\n typename L::triplet_t;\n typename L::lu_t;\n typename L::qr_t;\n \n \/\/ triplets can be constructed\n requires ConstructibleFrom;\n\n \/\/ we can construct QR and LU objects from a sparse matrix\n requires ConstructibleFrom;\n requires ConstructibleFrom;\n\n \/\/ The LU decomposition can perform a solve against a sparse matrix with a sparse result\n { lu.solve( mat ) } -> typename L::sparsemat_t ;\n\n \/\/ The QR decomposition can return a Q of a type convertible to sparse\n { qr.Q() } -> typename L::sparsemat_t;\n\n \/\/ The Q returned from the QR can multiply a sparse matrix on the left, producing another\n \/\/ note this does *not* require that the result be a sparse matrix - just that you can convert it to one\n { qr.Q() * mat } -> typename L::sparsemat_t;\n\n \/\/ you can stream out a sparse matrix\n { os << mat } -> std::ostream &;\n\n};\n\n#endif \/\/ SPARSELIB_CONCEPT_HPP\nAllow triplet type to be aggregate initializable as well as constructible\/\/ Describing expectations for a valid sparse matrix library\n\n#ifndef SPARSELIB_CONCEPT_HPP\n#define SPARSELIB_CONCEPT_HPP\n\n#include \n#include \n\n\/\/ First, some preliminaries (no predefined Concepts are supplied in library yet)\ntemplate concept bool ForwardIterator =\n requires( T a, T b ) {\n { a != b }\n { a == b }\n { ++a }\n { *a }\n};\n\ntemplate concept bool DereferencesTo =\n requires( T a ) {\n { *a } -> U;\n};\n\ntemplate concept bool ConstructibleFrom =\n std::is_constructible::value || \/\/ constructors\n requires(Args... args) { { T{args...} } -> T }; \/\/ aggregate initialization\n\ntemplate concept bool ForwardIterator =\n std::is_convertible::iterator_category,\n std::forward_iterator_tag>::value;\n\ntemplate concept bool Same =\n std::is_same::value;\n\ntemplate concept bool IteratorRange =\n Same && ForwardIterator;\n\ntemplate concept bool SparseLibrary =\n requires( typename L::sparsemat_t mat,\n typename L::lu_t lu,\n typename L::qr_t qr,\n std::ostream& os\n ) {\n \/\/ inner types we expect\n typename L::sparsemat_t;\n typename L::index_t;\n typename L::value_t;\n typename L::triplet_t;\n typename L::lu_t;\n typename L::qr_t;\n \n \/\/ triplets can be constructed\n requires ConstructibleFrom;\n\n \/\/ we can construct QR and LU objects from a sparse matrix\n requires ConstructibleFrom;\n requires ConstructibleFrom;\n\n \/\/ The LU decomposition can perform a solve against a sparse matrix with a sparse result\n { lu.solve( mat ) } -> typename L::sparsemat_t ;\n\n \/\/ The QR decomposition can return a Q of a type convertible to sparse\n { qr.Q() } -> typename L::sparsemat_t;\n\n \/\/ The Q returned from the QR can multiply a sparse matrix on the left, producing another\n \/\/ note this does *not* require that the result be a sparse matrix - just that you can convert it to one\n { qr.Q() * mat } -> typename L::sparsemat_t;\n\n \/\/ you can stream out a sparse matrix\n { os << mat } -> std::ostream &;\n\n};\n\n#endif \/\/ SPARSELIB_CONCEPT_HPP\n<|endoftext|>"} {"text":"#include \"HBaseOperations.h\"\n\n#include \"LogEndian.h\"\n\ntemplate \nstatic inline size_t size_text(const Text& text)\n{\n\treturn sizeof(T) + text.size();\n}\n\ntemplate \nstatic void serialize_text(uint8_t** buffer, const Text& text)\n{\n\tuint32_t size;\n\n\tsize = qMin((uint32_t)text.size(), (uint32_t)(1UL << sizeof(T) * 8) - 1);\n\t*reinterpret_cast(*buffer) = LOG_ENDIAN((T)size);\n\t*buffer += sizeof(T);\n\n\tmemcpy(*buffer, text.data(), size);\n\t*buffer += size;\n}\n\nstatic inline size_t size_smalltext(const Text& text) { return size_text(text); }\nstatic inline void serialize_smalltext(uint8_t** buffer, const Text& text) { serialize_text(buffer, text); }\nstatic inline size_t size_bigtext(const Text& text) { return size_text(text); }\nstatic inline void serialize_bigtext(uint8_t** buffer, const Text& text) { serialize_text(buffer, text); }\n\ntemplate \nstatic inline void serialize_integer(uint8_t** buffer, T val)\n{\n\t*reinterpret_cast(*buffer) = LOG_ENDIAN(val);\n\t*buffer += sizeof(T);\n}\n\nsize_t HBaseOperation::MutateRows::size(bool deletes)\n{\n\tsize_t size = 0;\n\tnum_rows = 0;\n\n\tsize += sizeof(uint8_t); \/\/ Class\n\tsize += size_smalltext(tableName); \/\/ Table\n\tsize += sizeof(uint8_t); \/\/ Number of rows\n\n\tfor (std::vector::const_iterator batch_mutation = row_batches.begin(); batch_mutation != row_batches.end(); batch_mutation++) {\n\t\tsize_t ops_size = 0;\n\t\tstd::map > families;\n\n\t\tops_size += size_bigtext(batch_mutation->row); \/\/ RowKey\n\t\tops_size += sizeof(uint8_t); \/\/ Number of families\n\n\t\tfor (std::vector::const_iterator mutation = batch_mutation->mutations.begin(); mutation != batch_mutation->mutations.end(); mutation++) {\n\t\t\tif (!((mutation->isDelete && deletes) || (!mutation->isDelete && !deletes)))\n\t\t\t\tcontinue;\n\n\t\t\tsize_t pos = mutation->column.find_first_of(':');\n\t\t\tif (pos == std::string::npos || pos == (mutation->column.size() - 1)) {\n\t\t\t\t\/\/ TODO: WARN\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::string family(mutation->column.substr(0, pos));\n\n\t\t\tops_size += size_smalltext(mutation->column.substr(pos + 1)); \/\/ Qualifier\n\t\t\tops_size += size_bigtext(mutation->value); \/\/ Value\n\t\t\tops_size += sizeof(int64_t); \/\/ Timestamp\n\n\t\t\tstd::map >::iterator i = families.find(family);\n\t\t\tif (i != families.end()) {\n\t\t\t\ti->second.push_back(&*mutation);\n\t\t\t} else {\n\t\t\t\tstd::vector mutations;\n\t\t\t\tmutations.push_back(&*mutation);\n\t\t\t\tfamilies[family] = mutations;\n\t\t\t}\n\t\t}\n\n\t\tfor (std::map >::const_iterator i = families.begin(); i != families.end(); i++) {\n\t\t\tops_size += size_smalltext(i->first); \/\/ Family\n\t\t\tops_size += sizeof(uint8_t); \/\/ Number of qualifiers\n\t\t}\n\n\t\tif (families.size() != 0) {\n\t\t\tsize += ops_size;\n\t\t\tnum_rows++;\n\t\t}\n\t\t\n\t\tfamilies_per_row.push_back(families);\n\t}\n\n\tif (!num_rows)\n\t\treturn 0;\n\n\t\/\/ Align size to 64 bits\n\tsize = (size + (sizeof(uint64_t) - 1)) & ~(sizeof(uint64_t) - 1);\n\treturn size;\n}\n\nvoid HBaseOperation::MutateRows::serialize(void* buffer_, bool deletes)\n{\n\tuint8_t* buffer = reinterpret_cast(buffer_);\n\n\tserialize_integer(&buffer, (uint8_t)(deletes ? CLASS_DELETE_BATCH : CLASS_PUT_BATCH));\n\/\/\tprintf(\"%s in table %s (%u rows)\\n\", deletes ? \"DELETE\" : \"PUT\", tableName.c_str(), num_rows);\n\tserialize_smalltext(&buffer, tableName);\n\tserialize_integer(&buffer, num_rows);\n\n\tstd::vector::const_iterator batch_mutation = row_batches.begin();\n\tstd::vector > >::const_iterator families = families_per_row.begin();\n\tfor (; batch_mutation != row_batches.end(); batch_mutation++, families++) {\n\t\tif (families->size() == 0)\n\t\t\tcontinue;\n\t\t\n\/\/\t\tprintf(\"\\trow '%s' (%u families)\\n\", batch_mutation->row.c_str(), (uint8_t)families->size());\n\t\tserialize_bigtext(&buffer, batch_mutation->row);\n\t\tserialize_integer(&buffer, (uint8_t)families->size());\n\n\t\tfor (std::map >::const_iterator family = families->begin(); family != families->end(); family++) {\n\/\/\t\t\tprintf(\"\\t\\tfamily '%s' (%u qualifiers)\\n\", family->first.c_str(), (uint8_t)family->second.size());\n\t\t\tserialize_smalltext(&buffer, family->first);\n\t\t\tserialize_integer(&buffer, (uint8_t)family->second.size());\n\n\t\t\tfor (std::vector::const_iterator qualifier = family->second.begin(); qualifier != family->second.end(); qualifier++) {\n\t\t\t\tsize_t pos = (*qualifier)->column.find_first_of(':');\n\/\/\t\t\t\tprintf(\"\\t\\t\\tqualifier '%s' value '%s' timestamp %lld\\n\", (*qualifier)->column.substr(pos + 1).c_str(), (*qualifier)->value.c_str(), (int64_t)timestamp);\n\t\t\t\tserialize_smalltext(&buffer, (*qualifier)->column.substr(pos + 1));\n\t\t\t\tserialize_bigtext(&buffer, (*qualifier)->value);\n\t\t\t\tserialize_integer(&buffer, (int64_t)timestamp);\n\t\t\t}\n\t\t}\n\t}\n}\n\nIgnore value in deletes#include \"HBaseOperations.h\"\n\n#include \"LogEndian.h\"\n\ntemplate \nstatic inline size_t size_text(const Text& text)\n{\n\treturn sizeof(T) + text.size();\n}\n\ntemplate \nstatic void serialize_text(uint8_t** buffer, const Text& text)\n{\n\tuint32_t size;\n\n\tsize = qMin((uint32_t)text.size(), (uint32_t)(1UL << sizeof(T) * 8) - 1);\n\t*reinterpret_cast(*buffer) = LOG_ENDIAN((T)size);\n\t*buffer += sizeof(T);\n\n\tmemcpy(*buffer, text.data(), size);\n\t*buffer += size;\n}\n\nstatic inline size_t size_smalltext(const Text& text) { return size_text(text); }\nstatic inline void serialize_smalltext(uint8_t** buffer, const Text& text) { serialize_text(buffer, text); }\nstatic inline size_t size_bigtext(const Text& text) { return size_text(text); }\nstatic inline void serialize_bigtext(uint8_t** buffer, const Text& text) { serialize_text(buffer, text); }\n\ntemplate \nstatic inline void serialize_integer(uint8_t** buffer, T val)\n{\n\t*reinterpret_cast(*buffer) = LOG_ENDIAN(val);\n\t*buffer += sizeof(T);\n}\n\nsize_t HBaseOperation::MutateRows::size(bool deletes)\n{\n\tsize_t size = 0;\n\tnum_rows = 0;\n\n\tsize += sizeof(uint8_t); \/\/ Class\n\tsize += size_smalltext(tableName); \/\/ Table\n\tsize += sizeof(uint8_t); \/\/ Number of rows\n\n\tfor (std::vector::const_iterator batch_mutation = row_batches.begin(); batch_mutation != row_batches.end(); batch_mutation++) {\n\t\tsize_t ops_size = 0;\n\t\tstd::map > families;\n\n\t\tops_size += size_bigtext(batch_mutation->row); \/\/ RowKey\n\t\tops_size += sizeof(uint8_t); \/\/ Number of families\n\n\t\tfor (std::vector::const_iterator mutation = batch_mutation->mutations.begin(); mutation != batch_mutation->mutations.end(); mutation++) {\n\t\t\tif (!((mutation->isDelete && deletes) || (!mutation->isDelete && !deletes)))\n\t\t\t\tcontinue;\n\n\t\t\tsize_t pos = mutation->column.find_first_of(':');\n\t\t\tif (pos == std::string::npos || pos == (mutation->column.size() - 1)) {\n\t\t\t\t\/\/ TODO: WARN\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::string family(mutation->column.substr(0, pos));\n\n\t\t\tops_size += size_smalltext(mutation->column.substr(pos + 1)); \/\/ Qualifier\n\t\t\tops_size += sizeof(int64_t); \/\/ Timestamp\n\t\t\tif (!deletes)\n\t\t\t\tops_size += size_bigtext(mutation->value); \/\/ Value\n\n\t\t\tstd::map >::iterator i = families.find(family);\n\t\t\tif (i != families.end()) {\n\t\t\t\ti->second.push_back(&*mutation);\n\t\t\t} else {\n\t\t\t\tstd::vector mutations;\n\t\t\t\tmutations.push_back(&*mutation);\n\t\t\t\tfamilies[family] = mutations;\n\t\t\t}\n\t\t}\n\n\t\tfor (std::map >::const_iterator i = families.begin(); i != families.end(); i++) {\n\t\t\tops_size += size_smalltext(i->first); \/\/ Family\n\t\t\tops_size += sizeof(uint8_t); \/\/ Number of qualifiers\n\t\t}\n\n\t\tif (families.size() != 0) {\n\t\t\tsize += ops_size;\n\t\t\tnum_rows++;\n\t\t}\n\t\t\n\t\tfamilies_per_row.push_back(families);\n\t}\n\n\tif (!num_rows)\n\t\treturn 0;\n\n\t\/\/ Align size to 64 bits\n\tsize = (size + (sizeof(uint64_t) - 1)) & ~(sizeof(uint64_t) - 1);\n\treturn size;\n}\n\nvoid HBaseOperation::MutateRows::serialize(void* buffer_, bool deletes)\n{\n\tuint8_t* buffer = reinterpret_cast(buffer_);\n\n\tserialize_integer(&buffer, (uint8_t)(deletes ? CLASS_DELETE_BATCH : CLASS_PUT_BATCH));\n\/\/\tprintf(\"%s in table %s (%u rows)\\n\", deletes ? \"DELETE\" : \"PUT\", tableName.c_str(), num_rows);\n\tserialize_smalltext(&buffer, tableName);\n\tserialize_integer(&buffer, num_rows);\n\n\tstd::vector::const_iterator batch_mutation = row_batches.begin();\n\tstd::vector > >::const_iterator families = families_per_row.begin();\n\tfor (; batch_mutation != row_batches.end(); batch_mutation++, families++) {\n\t\tif (families->size() == 0)\n\t\t\tcontinue;\n\t\t\n\/\/\t\tprintf(\"\\trow '%s' (%u families)\\n\", batch_mutation->row.c_str(), (uint8_t)families->size());\n\t\tserialize_bigtext(&buffer, batch_mutation->row);\n\t\tserialize_integer(&buffer, (uint8_t)families->size());\n\n\t\tfor (std::map >::const_iterator family = families->begin(); family != families->end(); family++) {\n\/\/\t\t\tprintf(\"\\t\\tfamily '%s' (%u qualifiers)\\n\", family->first.c_str(), (uint8_t)family->second.size());\n\t\t\tserialize_smalltext(&buffer, family->first);\n\t\t\tserialize_integer(&buffer, (uint8_t)family->second.size());\n\n\t\t\tfor (std::vector::const_iterator qualifier = family->second.begin(); qualifier != family->second.end(); qualifier++) {\n\t\t\t\tsize_t pos = (*qualifier)->column.find_first_of(':');\n\/\/\t\t\t\tprintf(\"\\t\\t\\tqualifier '%s' value '%s' timestamp %lld\\n\", (*qualifier)->column.substr(pos + 1).c_str(), (*qualifier)->value.c_str(), (int64_t)timestamp);\n\t\t\t\tserialize_smalltext(&buffer, (*qualifier)->column.substr(pos + 1));\n\t\t\t\tserialize_integer(&buffer, (int64_t)timestamp);\n\t\t\t\tif (!deletes)\n\t\t\t\t\tserialize_bigtext(&buffer, (*qualifier)->value);\n\t\t\t}\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n\n#include \"joynr\/Settings.h\"\n\n#include \n#include \n\n#include \"joynr\/Util.h\"\n\nnamespace ptree = boost::property_tree;\n\nnamespace joynr\n{\n\nSettings::Settings() : filename(), propertyTree(), loaded(false)\n{\n}\n\nSettings::Settings(const std::string& filename) : filename(filename), propertyTree(), loaded(false)\n{\n try {\n ptree::read_ini(filename, propertyTree);\n loaded = true;\n } catch (const ptree::ini_parser_error& e) {\n JOYNR_LOG_ERROR(logger(), \"Could not read settings file: {}\", e.what());\n \/\/ The file does not exist or is an invalid format.\n \/\/ Match the behaviour of QSettings and ignore\/overwrite\n \/\/ But leave loaded as false\n }\n}\n\nbool Settings::isLoaded() const\n{\n return loaded;\n}\n\nbool Settings::contains(const std::string& path) const\n{\n \/\/ Create a '\/' delimited path\n ptree::ptree::path_type treePath = createPath(path);\n\n \/\/ Get the child node with the path\n const auto& child = propertyTree.get_child_optional(treePath);\n\n \/\/ Use boost::optional operator bool()\n return bool(child);\n}\n\nbool Settings::sync()\n{\n try {\n if (contentChanged(propertyTree, filename)) {\n ptree::write_ini(filename, propertyTree);\n return true;\n } else {\n JOYNR_LOG_DEBUG(logger(),\n \"Settings file \\\"{}\\\" not updated because its content did not change\",\n filename);\n }\n } catch (const ptree::ini_parser_error& e) {\n JOYNR_LOG_ERROR(logger(),\n \"settings file \\\"{}\\\" cannot be written due to the following error: {})\",\n filename,\n e.message());\n }\n return false;\n}\n\nvoid Settings::merge(const Settings& from, Settings& to, bool overwrite)\n{\n const ptree::ptree& fromTree = from.propertyTree;\n ptree::ptree& toTree = to.propertyTree;\n\n merge(fromTree, toTree, overwrite);\n to.loaded = true;\n}\n\nbool Settings::contentChanged(const boost::property_tree::ptree& propertyTreeToCompare,\n const std::string& iniFilename) const\n{\n if (!util::fileExists(iniFilename)) {\n return true;\n }\n\n boost::property_tree::ptree otherPropertyTree;\n\n try {\n ptree::read_ini(iniFilename, otherPropertyTree);\n } catch (const ptree::ini_parser_error&) {\n return true;\n }\n\n return propertyTreeToCompare != otherPropertyTree;\n}\n\nvoid Settings::fillEmptySettingsWithDefaults(const std::string& defaultsFilename)\n{\n const std::string cmakeSettingsPath = CMAKE_JOYNR_SETTINGS_INSTALL_DIR;\n Settings cmakeDefaultSettings(cmakeSettingsPath + \"\/\" + defaultsFilename);\n Settings relativeDefaultSettings(\"resources\/\" + defaultsFilename);\n\n Settings::merge(relativeDefaultSettings, *this, false);\n Settings::merge(cmakeDefaultSettings, *this, false);\n}\n\nvoid Settings::merge(const boost::property_tree::ptree& from,\n boost::property_tree::ptree& to,\n bool overwrite)\n{\n \/\/ Is this a single value or a subtree?\n if (!from.data().empty()) {\n \/\/ Single value\n if (overwrite || to.data().empty()) {\n to.put_value(from.data());\n }\n return;\n }\n\n \/\/ Subtree\n for (const auto& fromEntry : from) {\n \/\/ Does the key exist in the destination?\n auto toIt = to.find(fromEntry.first);\n if (toIt == to.not_found()) {\n ptree::ptree child;\n\n \/\/ Recurse into the new child\n merge(fromEntry.second, child, overwrite);\n\n \/\/ Create a path object because ptree uses '.' as a path delimiter\n \/\/ when strings are used\n ptree::ptree::path_type treePath = createPath(fromEntry.first);\n to.add_child(treePath, child);\n } else {\n \/\/ Recurse into the subtrees\n merge(fromEntry.second, toIt->second, overwrite);\n }\n }\n}\n\nboost::property_tree::path Settings::createPath(const std::string& path)\n{\n return boost::property_tree::path(path, '\/');\n}\n\n} \/\/ namespace joynr\n[C++] Log settings filename in Settings constructor\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n\n#include \"joynr\/Settings.h\"\n\n#include \n#include \n\n#include \"joynr\/Util.h\"\n\nnamespace ptree = boost::property_tree;\n\nnamespace joynr\n{\n\nSettings::Settings() : filename(), propertyTree(), loaded(false)\n{\n}\n\nSettings::Settings(const std::string& filename) : filename(filename), propertyTree(), loaded(false)\n{\n try {\n JOYNR_LOG_INFO(logger(), \"attempting to read settings file: {}\", filename);\n ptree::read_ini(filename, propertyTree);\n loaded = true;\n } catch (const ptree::ini_parser_error& e) {\n JOYNR_LOG_ERROR(logger(), \"Could not read settings file: {}\", e.what());\n \/\/ The file does not exist or is an invalid format.\n \/\/ Match the behaviour of QSettings and ignore\/overwrite\n \/\/ But leave loaded as false\n }\n}\n\nbool Settings::isLoaded() const\n{\n return loaded;\n}\n\nbool Settings::contains(const std::string& path) const\n{\n \/\/ Create a '\/' delimited path\n ptree::ptree::path_type treePath = createPath(path);\n\n \/\/ Get the child node with the path\n const auto& child = propertyTree.get_child_optional(treePath);\n\n \/\/ Use boost::optional operator bool()\n return bool(child);\n}\n\nbool Settings::sync()\n{\n try {\n if (contentChanged(propertyTree, filename)) {\n ptree::write_ini(filename, propertyTree);\n return true;\n } else {\n JOYNR_LOG_DEBUG(logger(),\n \"Settings file \\\"{}\\\" not updated because its content did not change\",\n filename);\n }\n } catch (const ptree::ini_parser_error& e) {\n JOYNR_LOG_ERROR(logger(),\n \"settings file \\\"{}\\\" cannot be written due to the following error: {})\",\n filename,\n e.message());\n }\n return false;\n}\n\nvoid Settings::merge(const Settings& from, Settings& to, bool overwrite)\n{\n const ptree::ptree& fromTree = from.propertyTree;\n ptree::ptree& toTree = to.propertyTree;\n\n merge(fromTree, toTree, overwrite);\n to.loaded = true;\n}\n\nbool Settings::contentChanged(const boost::property_tree::ptree& propertyTreeToCompare,\n const std::string& iniFilename) const\n{\n if (!util::fileExists(iniFilename)) {\n return true;\n }\n\n boost::property_tree::ptree otherPropertyTree;\n\n try {\n ptree::read_ini(iniFilename, otherPropertyTree);\n } catch (const ptree::ini_parser_error&) {\n return true;\n }\n\n return propertyTreeToCompare != otherPropertyTree;\n}\n\nvoid Settings::fillEmptySettingsWithDefaults(const std::string& defaultsFilename)\n{\n const std::string cmakeSettingsPath = CMAKE_JOYNR_SETTINGS_INSTALL_DIR;\n Settings cmakeDefaultSettings(cmakeSettingsPath + \"\/\" + defaultsFilename);\n Settings relativeDefaultSettings(\"resources\/\" + defaultsFilename);\n\n Settings::merge(relativeDefaultSettings, *this, false);\n Settings::merge(cmakeDefaultSettings, *this, false);\n}\n\nvoid Settings::merge(const boost::property_tree::ptree& from,\n boost::property_tree::ptree& to,\n bool overwrite)\n{\n \/\/ Is this a single value or a subtree?\n if (!from.data().empty()) {\n \/\/ Single value\n if (overwrite || to.data().empty()) {\n to.put_value(from.data());\n }\n return;\n }\n\n \/\/ Subtree\n for (const auto& fromEntry : from) {\n \/\/ Does the key exist in the destination?\n auto toIt = to.find(fromEntry.first);\n if (toIt == to.not_found()) {\n ptree::ptree child;\n\n \/\/ Recurse into the new child\n merge(fromEntry.second, child, overwrite);\n\n \/\/ Create a path object because ptree uses '.' as a path delimiter\n \/\/ when strings are used\n ptree::ptree::path_type treePath = createPath(fromEntry.first);\n to.add_child(treePath, child);\n } else {\n \/\/ Recurse into the subtrees\n merge(fromEntry.second, toIt->second, overwrite);\n }\n }\n}\n\nboost::property_tree::path Settings::createPath(const std::string& path)\n{\n return boost::property_tree::path(path, '\/');\n}\n\n} \/\/ namespace joynr\n<|endoftext|>"} {"text":"\/*++\n\nModule Name:\n\n snap.cpp\n\nAbstract:\n\n Main entry point for the snap binary. Calls into the indexer, single-end aligner or\n paired-end aligner functions defined in other source files in this directory.\n\nAuthors:\n\n Matei Zaharia, February, 2012\n\nEnvironment:\n`\n User mode service.\n\nRevision History:\n\n Adapted from cSNAP, which was in turn adapted from the scala prototype\n\n--*\/\n\n#include \"stdafx.h\"\n#include \"options.h\"\n#include \"FASTA.h\"\n#include \"GenomeIndex.h\"\n#include \"SingleAligner.h\"\n#include \"PairedAligner.h\"\n\nusing namespace std;\n\nconst char *SNAP_VERSION = \"0.13.7\";\n\nstatic void usage()\n{\n fprintf(stderr,\n \"Usage: snap []\\n\"\n \"Commands:\\n\"\n \" index build a genome index\\n\"\n \" single align single-end reads\\n\"\n \" paired align paired-end reads\\n\"\n \"Type a command without arguments to see its help.\\n\");\n exit(1);\n}\n\n\nint main(int argc, const char **argv)\n{\n printf(\"Welcome to SNAP version %s.\\n\\n\", SNAP_VERSION);\n\n if (argc < 2) {\n usage();\n } else if (strcmp(argv[1], \"index\") == 0) {\n GenomeIndex::runIndexer(argc - 2, argv + 2);\n } else if (strcmp(argv[1], \"single\") == 0) {\n SingleAlignerContext single;\n single.runAlignment(argc - 2, argv + 2, SNAP_VERSION);\n } else if (strcmp(argv[1], \"paired\") == 0) {\n PairedAlignerContext paired;\n paired.runAlignment(argc - 2, argv + 2, SNAP_VERSION);\n } else {\n fprintf(stderr, \"Invalid command: %s\\n\\n\", argv[1]);\n usage();\n }\n}\nUpdate version number, now passes picard test\/*++\n\nModule Name:\n\n snap.cpp\n\nAbstract:\n\n Main entry point for the snap binary. Calls into the indexer, single-end aligner or\n paired-end aligner functions defined in other source files in this directory.\n\nAuthors:\n\n Matei Zaharia, February, 2012\n\nEnvironment:\n`\n User mode service.\n\nRevision History:\n\n Adapted from cSNAP, which was in turn adapted from the scala prototype\n\n--*\/\n\n#include \"stdafx.h\"\n#include \"options.h\"\n#include \"FASTA.h\"\n#include \"GenomeIndex.h\"\n#include \"SingleAligner.h\"\n#include \"PairedAligner.h\"\n\nusing namespace std;\n\nconst char *SNAP_VERSION = \"0.13.8\";\n\nstatic void usage()\n{\n fprintf(stderr,\n \"Usage: snap []\\n\"\n \"Commands:\\n\"\n \" index build a genome index\\n\"\n \" single align single-end reads\\n\"\n \" paired align paired-end reads\\n\"\n \"Type a command without arguments to see its help.\\n\");\n exit(1);\n}\n\n\nint main(int argc, const char **argv)\n{\n printf(\"Welcome to SNAP version %s.\\n\\n\", SNAP_VERSION);\n\n if (argc < 2) {\n usage();\n } else if (strcmp(argv[1], \"index\") == 0) {\n GenomeIndex::runIndexer(argc - 2, argv + 2);\n } else if (strcmp(argv[1], \"single\") == 0) {\n SingleAlignerContext single;\n single.runAlignment(argc - 2, argv + 2, SNAP_VERSION);\n } else if (strcmp(argv[1], \"paired\") == 0) {\n PairedAlignerContext paired;\n paired.runAlignment(argc - 2, argv + 2, SNAP_VERSION);\n } else {\n fprintf(stderr, \"Invalid command: %s\\n\\n\", argv[1]);\n usage();\n }\n}\n<|endoftext|>"} {"text":"\/\/ FONcTransmitter.cc\n\n\/\/ This file is part of BES Netcdf File Out Module\n\n\/\/ Copyright (c) 2004,2005 University Corporation for Atmospheric Research\n\/\/ Author: Patrick West and Jose Garcia \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ You can contact University Corporation for Atmospheric Research at\n\/\/ 3080 Center Green Drive, Boulder, CO 80301\n\n\/\/ (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005\n\/\/ Please read the full copyright statement in the file COPYRIGHT_UCAR.\n\/\/\n\/\/ Authors:\n\/\/ pwest Patrick West \n\/\/ jgarcia Jose Garcia \n\n#include \"config.h\"\n\n#include \n#include \n\n#ifdef HAVE_UNISTD_H\n#include \n#endif\n\n#include \/\/ For umask\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"FONcBaseType.h\"\n#include \"FONcRequestHandler.h\"\n#include \"FONcTransmitter.h\"\n#include \"FONcTransform.h\"\n\nusing namespace ::libdap;\nusing namespace std;\n\n\/\/ size of the buffer used to read from the temporary file built on disk and\n\/\/ send data to the client over the network connection (socket\/stream)\n#define OUTPUT_FILE_BLOCK_SIZE 4096\n\n\/** @brief Construct the FONcTransmitter, adding it with name netcdf to be\n * able to transmit a data response\n *\n * The transmitter is created to add the ability to return OPeNDAP data\n * objects (DataDDS) as a netcdf file.\n *\n * The OPeNDAP data object is written to a netcdf file locally in a\n * temporary directory specified by the BES configuration parameter\n * FONc.Tempdir. If this variable is not found or is not set then it\n * defaults to the macro definition FONC_TEMP_DIR.\n *\/\nFONcTransmitter::FONcTransmitter() :\n BESBasicTransmitter()\n{\n add_method(DATA_SERVICE, FONcTransmitter::send_data);\n}\n\n#if 0\n\/**\n * Hack to ensure the file descriptor for the temporary file is closed.\n *\/\nstruct wrap_file_descriptor {\n int fd;\n wrap_file_descriptor(int i) : fd(i) { }\n ~wrap_file_descriptor() { cerr << \"*** Closing fd\" << endl; close(fd); }\n};\n#endif\n\n\/** @brief The static method registered to transmit OPeNDAP data objects as\n * a netcdf file.\n *\n * This function takes the OPeNDAP DataDDS object, reads in the data (can be\n * used with any data handler), transforms the data into a netcdf file, and\n * streams back that netcdf file back to the requester using the stream\n * specified in the BESDataHandlerInterface.\n *\n * @param obj The BESResponseObject containing the OPeNDAP DataDDS object\n * @param dhi BESDataHandlerInterface containing information about the\n * request and response\n * @throws BESInternalError if the response is not an OPeNDAP DataDDS or if\n * there are any problems reading the data, writing to a netcdf file, or\n * streaming the netcdf file\n *\/\nvoid FONcTransmitter::send_data(BESResponseObject *obj, BESDataHandlerInterface &dhi)\n{\n BESDataDDSResponse *bdds = dynamic_cast(obj);\n if (!bdds) throw BESInternalError(\"cast error\", __FILE__, __LINE__);\n\n libdap::DataDDS *dds = bdds->get_dds();\n if (!dds) throw BESInternalError(\"No DataDDS has been created for transmit\", __FILE__, __LINE__);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Parsing the constraint\" << endl);\n\n ConstraintEvaluator &eval = bdds->get_ce();\n\n string ncVersion = dhi.data[RETURN_CMD];\n\n ostream &strm = dhi.get_output_stream();\n if (!strm) throw BESInternalError(\"Output stream is not set, can not return as\", __FILE__, __LINE__);\n\n \/\/ ticket 1248 jhrg 2\/23\/09\n string ce = www2id(dhi.data[POST_CONSTRAINT], \"%\", \"%20%26\");\n try {\n eval.parse_constraint(ce, *dds);\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to parse the constraint expression: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to parse the constraint expression: Unknown exception caught\", __FILE__,\n __LINE__);\n }\n\n \/\/ The dataset_name is no longer used in the constraint evaluator, so no\n \/\/ need to get here. Plus, just getting the first container's dataset\n \/\/ name would not have worked with multiple containers.\n \/\/ pwest Jan 4, 2009\n \/\/ string dataset_name = \"\";\n\n \/\/ now we need to read the data\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Reading data into DataDDS\" << endl);\n\n \/\/ ADB: remember when we're using a temp DDS\n \/\/ bool using_temp_dds = false; See comment below about set_dds(). jhrg 8\/8\/14\n\n try {\n \/\/ Handle *functional* constraint expressions specially\n if (eval.function_clauses()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Processing functional constraint clause(s).\" << endl);\n DataDDS *tmp_dds = eval.eval_function_clauses(*dds);\n delete dds;\n dds = tmp_dds;\n bdds->set_dds(dds);\n\n \/\/ This next step utilizes a well known function, promote_function_output_structures()\n \/\/ to look for one or more top level Structures whose name indicates (by way of ending\n \/\/ with \"_uwrap\") that their contents should be promoted (aka moved) to the top level.\n \/\/ This is in support of a hack around the current API where server side functions\n \/\/ may only return a single DAP object and not a collection of objects. The name suffix\n \/\/ \"_unwrap\" is used as a signal from the function to the the various response\n \/\/ builders and transmitters that the representation needs to be altered before\n \/\/ transmission, and that in fact is what happens in our friend\n \/\/ promote_function_output_structures()\n promote_function_output_structures(dds);\n\n }\n else {\n \/\/ Iterate through the variables in the DataDDS and read\n \/\/ in the data if the variable has the send flag set.\n\n for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) {\n if ((*i)->send_p()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Interning data for variable: '\" << (*i)->name() << \"'\" << endl);\n (*i)->intern_data(eval, *dds);\n }\n }\n }\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to read data: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n throw;\n }\n catch (std::exception &e) {\n throw BESInternalError(\"Failed to read data: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to read data. Unknown Error\", __FILE__, __LINE__);\n }\n\n \/\/string temp_file_name = FONcTransmitter::temp_dir + '\/' + \"ncXXXXXX\";\n string temp_file_name = FONcRequestHandler::temp_dir + '\/' + \"ncXXXXXX\";\n vector temp_full(temp_file_name.length() + 1);\n string::size_type len = temp_file_name.copy(&temp_full[0], temp_file_name.length());\n temp_full[len] = '\\0';\n \/\/ cover the case where older versions of mkstemp() create the file using\n \/\/ a mode of 666.\n mode_t original_mode = umask(077);\n int fd = mkstemp(&temp_full[0]);\n umask(original_mode);\n#if 0\n \/\/ Trick: We can unlink the file right here - it will persist until the file descriptor\n \/\/ is closed. This means we don't have to litter the code with call to unlink(). jhrg 11\/25\/15\n (void) unlink(&temp_full[0]);\n \/\/ Hack: Use this simple class to 'wrap' the file descriptor so that we can be sure it\n \/\/ is closed no matter how this code is exited. jhrg 11\/25\/15\n wrap_file_descriptor wrapped_fd(fd);\n#endif\n if (fd == -1) throw BESInternalError(\"Failed to open the temporary file: \" + temp_file_name, __FILE__, __LINE__);\n\n \/\/ transform the OPeNDAP DataDDS to the netcdf file\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transforming into temporary file: \" << &temp_full[0] << endl);\n\n try {\n FONcTransform ft(dds, dhi, &temp_full[0], ncVersion);\n ft.transform();\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transmitting temp file \" << &temp_full[0] << endl);\n FONcTransmitter::return_temp_stream(&temp_full[0], strm, ncVersion);\n }\n catch (Error &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESDapError(\"Failed to Transform data to NetCDF: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw;\n }\n catch (std::exception &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF. Unknown Error\", __FILE__, __LINE__);\n }\n\n (void) unlink(&temp_full[0]);\n close(fd);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - done transmitting to netcdf\" << endl);\n}\n\n\/** @brief stream the temporary netcdf file back to the requester\n *\n * Streams the temporary netcdf file specified by filename to the specified\n * C++ ostream\n *\n * @param filename The name of the file to stream back to the requester\n * @param strm C++ ostream to write the contents of the file to\n * @throws BESInternalError if problem opening the file\n *\/\nvoid FONcTransmitter::return_temp_stream(const string &filename, ostream &strm, const string &ncVersion)\n{\n ifstream os;\n os.open(filename.c_str(), ios::binary | ios::in);\n if (!os)\n throw BESInternalError(\"Fileout netcdf: Cannot connect to netcdf file.\", __FILE__, __LINE__);;\n\n char block[OUTPUT_FILE_BLOCK_SIZE];\n\n os.read(block, sizeof block);\n int nbytes = os.gcount();\n if (nbytes > 0) {\n bool found = false;\n string context = \"transmit_protocol\";\n string protocol = BESContextManager::TheManager()->get_context(context, found);\n if (protocol == \"HTTP\") {\n strm << \"HTTP\/1.0 200 OK\\n\";\n strm << \"Content-type: application\/octet-stream\\n\";\n strm << \"Content-Description: \" << \"BES dataset\" << \"\\n\";\n if (ncVersion == RETURNAS_NETCDF4) {\n strm << \"Content-Disposition: filename=\" << filename << \".nc4;\\n\\n\";\n }\n else {\n strm << \"Content-Disposition: filename=\" << filename << \".nc;\\n\\n\";\n }\n strm << flush;\n }\n strm.write(block, nbytes);\n }\n else {\n \/\/ close the stream before we leave.\n os.close();\n throw BESInternalError(\"Fileout netcdf: Failed to stream the response back to the client, got zero count on stream buffer.\", __FILE__, __LINE__);\n }\n\n while (os) {\n os.read(block, sizeof block);\n strm.write(block, os.gcount());\n }\n\n os.close();\n}\n\nDropped use of DataDDS in favor of the DDS class.\/\/ FONcTransmitter.cc\n\n\/\/ This file is part of BES Netcdf File Out Module\n\n\/\/ Copyright (c) 2004,2005 University Corporation for Atmospheric Research\n\/\/ Author: Patrick West and Jose Garcia \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ You can contact University Corporation for Atmospheric Research at\n\/\/ 3080 Center Green Drive, Boulder, CO 80301\n\n\/\/ (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005\n\/\/ Please read the full copyright statement in the file COPYRIGHT_UCAR.\n\/\/\n\/\/ Authors:\n\/\/ pwest Patrick West \n\/\/ jgarcia Jose Garcia \n\n#include \"config.h\"\n\n#include \n#include \n\n#ifdef HAVE_UNISTD_H\n#include \n#endif\n\n#include \/\/ For umask\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"FONcBaseType.h\"\n#include \"FONcRequestHandler.h\"\n#include \"FONcTransmitter.h\"\n#include \"FONcTransform.h\"\n\nusing namespace ::libdap;\nusing namespace std;\n\n\/\/ size of the buffer used to read from the temporary file built on disk and\n\/\/ send data to the client over the network connection (socket\/stream)\n#define OUTPUT_FILE_BLOCK_SIZE 4096\n\n\/** @brief Construct the FONcTransmitter, adding it with name netcdf to be\n * able to transmit a data response\n *\n * The transmitter is created to add the ability to return OPeNDAP data\n * objects (DataDDS) as a netcdf file.\n *\n * The OPeNDAP data object is written to a netcdf file locally in a\n * temporary directory specified by the BES configuration parameter\n * FONc.Tempdir. If this variable is not found or is not set then it\n * defaults to the macro definition FONC_TEMP_DIR.\n *\/\nFONcTransmitter::FONcTransmitter() :\n BESBasicTransmitter()\n{\n add_method(DATA_SERVICE, FONcTransmitter::send_data);\n}\n\n#if 0\n\/**\n * Hack to ensure the file descriptor for the temporary file is closed.\n *\/\nstruct wrap_file_descriptor {\n int fd;\n wrap_file_descriptor(int i) : fd(i) { }\n ~wrap_file_descriptor() { cerr << \"*** Closing fd\" << endl; close(fd); }\n};\n#endif\n\n\/** @brief The static method registered to transmit OPeNDAP data objects as\n * a netcdf file.\n *\n * This function takes the OPeNDAP DataDDS object, reads in the data (can be\n * used with any data handler), transforms the data into a netcdf file, and\n * streams back that netcdf file back to the requester using the stream\n * specified in the BESDataHandlerInterface.\n *\n * @param obj The BESResponseObject containing the OPeNDAP DataDDS object\n * @param dhi BESDataHandlerInterface containing information about the\n * request and response\n * @throws BESInternalError if the response is not an OPeNDAP DataDDS or if\n * there are any problems reading the data, writing to a netcdf file, or\n * streaming the netcdf file\n *\/\nvoid FONcTransmitter::send_data(BESResponseObject *obj, BESDataHandlerInterface &dhi)\n{\n BESDataDDSResponse *bdds = dynamic_cast(obj);\n if (!bdds) throw BESInternalError(\"cast error\", __FILE__, __LINE__);\n\n libdap::DDS *dds = bdds->get_dds();\n if (!dds) throw BESInternalError(\"No DataDDS has been created for transmit\", __FILE__, __LINE__);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Parsing the constraint\" << endl);\n\n ConstraintEvaluator &eval = bdds->get_ce();\n\n string ncVersion = dhi.data[RETURN_CMD];\n\n ostream &strm = dhi.get_output_stream();\n if (!strm) throw BESInternalError(\"Output stream is not set, can not return as\", __FILE__, __LINE__);\n\n \/\/ ticket 1248 jhrg 2\/23\/09\n string ce = www2id(dhi.data[POST_CONSTRAINT], \"%\", \"%20%26\");\n try {\n eval.parse_constraint(ce, *dds);\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to parse the constraint expression: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to parse the constraint expression: Unknown exception caught\", __FILE__,\n __LINE__);\n }\n\n \/\/ The dataset_name is no longer used in the constraint evaluator, so no\n \/\/ need to get here. Plus, just getting the first container's dataset\n \/\/ name would not have worked with multiple containers.\n \/\/ pwest Jan 4, 2009\n \/\/ string dataset_name = \"\";\n\n \/\/ now we need to read the data\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Reading data into DataDDS\" << endl);\n\n \/\/ ADB: remember when we're using a temp DDS\n \/\/ bool using_temp_dds = false; See comment below about set_dds(). jhrg 8\/8\/14\n\n try {\n \/\/ Handle *functional* constraint expressions specially\n if (eval.function_clauses()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Processing functional constraint clause(s).\" << endl);\n DDS *tmp_dds = eval.eval_function_clauses(*dds);\n delete dds;\n dds = tmp_dds;\n bdds->set_dds(dds);\n\n \/\/ This next step utilizes a well known function, promote_function_output_structures()\n \/\/ to look for one or more top level Structures whose name indicates (by way of ending\n \/\/ with \"_uwrap\") that their contents should be promoted (aka moved) to the top level.\n \/\/ This is in support of a hack around the current API where server side functions\n \/\/ may only return a single DAP object and not a collection of objects. The name suffix\n \/\/ \"_unwrap\" is used as a signal from the function to the the various response\n \/\/ builders and transmitters that the representation needs to be altered before\n \/\/ transmission, and that in fact is what happens in our friend\n \/\/ promote_function_output_structures()\n promote_function_output_structures(dds);\n\n }\n else {\n \/\/ Iterate through the variables in the DataDDS and read\n \/\/ in the data if the variable has the send flag set.\n\n for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) {\n if ((*i)->send_p()) {\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data() - Interning data for variable: '\" << (*i)->name() << \"'\" << endl);\n (*i)->intern_data(eval, *dds);\n }\n }\n }\n }\n catch (Error &e) {\n throw BESDapError(\"Failed to read data: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n throw;\n }\n catch (std::exception &e) {\n throw BESInternalError(\"Failed to read data: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n throw BESInternalError(\"Failed to read data. Unknown Error\", __FILE__, __LINE__);\n }\n\n \/\/string temp_file_name = FONcTransmitter::temp_dir + '\/' + \"ncXXXXXX\";\n string temp_file_name = FONcRequestHandler::temp_dir + '\/' + \"ncXXXXXX\";\n vector temp_full(temp_file_name.length() + 1);\n string::size_type len = temp_file_name.copy(&temp_full[0], temp_file_name.length());\n temp_full[len] = '\\0';\n \/\/ cover the case where older versions of mkstemp() create the file using\n \/\/ a mode of 666.\n mode_t original_mode = umask(077);\n int fd = mkstemp(&temp_full[0]);\n umask(original_mode);\n#if 0\n \/\/ Trick: We can unlink the file right here - it will persist until the file descriptor\n \/\/ is closed. This means we don't have to litter the code with call to unlink(). jhrg 11\/25\/15\n (void) unlink(&temp_full[0]);\n \/\/ Hack: Use this simple class to 'wrap' the file descriptor so that we can be sure it\n \/\/ is closed no matter how this code is exited. jhrg 11\/25\/15\n wrap_file_descriptor wrapped_fd(fd);\n#endif\n if (fd == -1) throw BESInternalError(\"Failed to open the temporary file: \" + temp_file_name, __FILE__, __LINE__);\n\n \/\/ transform the OPeNDAP DataDDS to the netcdf file\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transforming into temporary file: \" << &temp_full[0] << endl);\n\n try {\n FONcTransform ft(dds, dhi, &temp_full[0], ncVersion);\n ft.transform();\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - Transmitting temp file \" << &temp_full[0] << endl);\n FONcTransmitter::return_temp_stream(&temp_full[0], strm, ncVersion);\n }\n catch (Error &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESDapError(\"Failed to Transform data to NetCDF: \" + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);\n }\n catch (BESError &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw;\n }\n catch (std::exception &e) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF: STL Error: \" + string(e.what()), __FILE__, __LINE__);\n }\n catch (...) {\n (void) unlink(&temp_full[0]);\n close(fd);\n throw BESInternalError(\"Failed to Transform data to NetCDF. Unknown Error\", __FILE__, __LINE__);\n }\n\n (void) unlink(&temp_full[0]);\n close(fd);\n\n BESDEBUG(\"fonc\", \"FONcTransmitter::send_data - done transmitting to netcdf\" << endl);\n}\n\n\/** @brief stream the temporary netcdf file back to the requester\n *\n * Streams the temporary netcdf file specified by filename to the specified\n * C++ ostream\n *\n * @param filename The name of the file to stream back to the requester\n * @param strm C++ ostream to write the contents of the file to\n * @throws BESInternalError if problem opening the file\n *\/\nvoid FONcTransmitter::return_temp_stream(const string &filename, ostream &strm, const string &ncVersion)\n{\n ifstream os;\n os.open(filename.c_str(), ios::binary | ios::in);\n if (!os)\n throw BESInternalError(\"Fileout netcdf: Cannot connect to netcdf file.\", __FILE__, __LINE__);;\n\n char block[OUTPUT_FILE_BLOCK_SIZE];\n\n os.read(block, sizeof block);\n int nbytes = os.gcount();\n if (nbytes > 0) {\n bool found = false;\n string context = \"transmit_protocol\";\n string protocol = BESContextManager::TheManager()->get_context(context, found);\n if (protocol == \"HTTP\") {\n strm << \"HTTP\/1.0 200 OK\\n\";\n strm << \"Content-type: application\/octet-stream\\n\";\n strm << \"Content-Description: \" << \"BES dataset\" << \"\\n\";\n if (ncVersion == RETURNAS_NETCDF4) {\n strm << \"Content-Disposition: filename=\" << filename << \".nc4;\\n\\n\";\n }\n else {\n strm << \"Content-Disposition: filename=\" << filename << \".nc;\\n\\n\";\n }\n strm << flush;\n }\n strm.write(block, nbytes);\n }\n else {\n \/\/ close the stream before we leave.\n os.close();\n throw BESInternalError(\"Fileout netcdf: Failed to stream the response back to the client, got zero count on stream buffer.\", __FILE__, __LINE__);\n }\n\n while (os) {\n os.read(block, sizeof block);\n strm.write(block, os.gcount());\n }\n\n os.close();\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewstrategy.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 04:37:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_VIEWBEHAVIOR_HXX_\n#define CONFIGMGR_VIEWBEHAVIOR_HXX_\n\n#ifndef CONFIGMGR_VIEWNODE_HXX_\n#include \"viewnode.hxx\"\n#endif\n\n#ifndef CONFIGMGR_GROUPNODEBEHAVIOR_HXX_\n#include \"groupnodeimpl.hxx\"\n#endif\n#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_\n#include \"setnodeimpl.hxx\"\n#endif\n\n#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_\n#include \n#endif\n#ifndef _RTL_REF_HXX_\n#include \n#endif\n\nnamespace configmgr\n{\n\/\/-----------------------------------------------------------------------------\n namespace memory { class Segment; }\n\/\/-----------------------------------------------------------------------------\n namespace configuration\n {\n class SetElementChangeImpl;\n class ValueChangeImpl;\n }\n\/\/-----------------------------------------------------------------------------\n namespace view\n {\n\/\/-----------------------------------------------------------------------------\n struct NodeFactory;\n\/\/-----------------------------------------------------------------------------\n using configuration::Name;\n using configuration::NodeOffset;\n using configuration::TreeDepth;\n\n typedef com::sun::star::uno::Any UnoAny;\n typedef com::sun::star::uno::Type UnoType;\n\/\/-----------------------------------------------------------------------------\n class ViewStrategy : public salhelper::SimpleReferenceObject\n {\n \/\/ node attributes\n public:\n \/\/\/ retrieve the attributes of the node\n Name getName(Node const& _aNode) const;\n\n \/\/\/ retrieve the attributes of the node\n node::Attributes getAttributes(Node const& _aNode) const;\n\n \/\/ tracking pending changes\n public:\n typedef configuration::NodeChanges NodeChanges;\n\n void collectChanges(Tree const& _aTree, NodeChanges& rChanges) const;\n\n bool hasChanges(Tree const& _aTree) const;\n\n bool hasChanges(Node const& _aNode) const;\n\n void markChanged(Node const& _aNode);\n\n \/\/ commit protocol\n public:\n std::auto_ptr preCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);\n\n void finishCommit(Tree const& _aTree, SubtreeChange& rRootChange);\n\n void revertCommit(Tree const& _aTree, SubtreeChange& rRootChange);\n\n void recoverFailedCommit(Tree const& _aTree, SubtreeChange& rRootChange);\n\n \/\/ notification protocol\n public:\n typedef configuration::NodeChangesInformation NodeChangesInformation;\n\n \/\/\/ Adjust the internal representation after external changes to the original data - build NodeChangeInformation objects for notification\n void adjustToChanges(NodeChangesInformation& rLocalChanges, Node const & _aNode, SubtreeChange const& aExternalChange);\n\n \/\/ visitor dispatch\n public:\n typedef configuration::GroupMemberVisitor GroupMemberVisitor;\n typedef configuration::SetNodeVisitor SetNodeVisitor;\n\n GroupMemberVisitor::Result dispatchToValues(GroupNode const& _aNode, GroupMemberVisitor& _aVisitor);\n\n \/\/\/ Call aVisitor.visit(aElement)<\/code> for each element in this set until SetNodeVisitor::DONE is returned.\n SetNodeVisitor::Result dispatchToElements(SetNode const& _aNode, SetNodeVisitor& _aVisitor);\n\n \/\/ value (element) node specific operations\n public:\n \/\/\/ Does this node assume its default value\n \/\/\/ retrieve the current value of this node\n UnoAny getValue(ValueNode const& _aNode) const;\n\n \/\/\/ get the type of this value\n UnoType getValueType(ValueNode const& _aNode) const;\n\n\n \/\/ group node specific operations\n public:\n typedef configuration::ValueMemberNode ValueMemberNode;\n typedef configuration::ValueMemberUpdate ValueMemberUpdate;\n\n \/\/\/ does this hold a child value of the given name\n bool hasValue(GroupNode const& _aNode, Name const& _aName) const;\n\n \/\/\/ does this hold a child value\n bool hasValue(GroupNode const& _aNode) const;\n\n \/\/\/ are defaults for this node available ?\n bool areValueDefaultsAvailable(GroupNode const& _aNode) const;\n\n \/\/\/ retrieve data for the child value of the given name\n ValueMemberNode getValue(GroupNode const& _aNode, Name const& _aName) const;\n\n \/\/\/ retrieve data for updating the child value of the given name\n ValueMemberUpdate getValueForUpdate(GroupNode const & _aNode, Name const& _aName);\n\n \/\/ set node specific operations\n public:\n typedef configuration::ElementTreeData SetNodeElement;\n typedef configuration::SetEntry SetNodeEntry;\n\n \/\/\/ does this set contain any elements (loads elements if needed)\n bool isEmpty(SetNode const& _aNode) const;\n\n \/\/\/ does this set contain an element named aName<\/var> (loads elements if needed)\n SetNodeEntry findElement(SetNode const& _aNode, Name const& aName) const;\n\n \/\/\/ does this set contain an element named aName<\/var> (and is that element loaded ?)\n SetNodeEntry findAvailableElement(SetNode const& _aNode, Name const& aName) const;\n\n \/\/\/ insert a new entry into this set\n void insertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry);\n\n \/\/\/ remove an existing entry into this set\n void removeElement(SetNode const& _aNode, Name const& aName);\n\n \/** Create a Subtree change as 'diff' which allows transforming the set to its default state\n (given that _rDefaultTree<\/var> points to a default instance of this set)\n

Ownership of added trees should be transferred to the SubtreeChange.<\/p>\n *\/\n std::auto_ptr differenceToDefaultState(SetNode const& _aNode, ISubtree& _rDefaultTree) const;\n\n \/\/\/ Get the template that describes elements of this set\n configuration::TemplateHolder getElementTemplate(SetNode const& _aNode) const;\n\n \/\/\/ Get a template provider that can create new elements for this set\n configuration::TemplateProvider getTemplateProvider(SetNode const& _aNode) const;\n\n \/\/ create a view::Tree from a configuration::SetEntry\n Tree extractTree(SetNodeEntry const& _anEntry);\n\n \/\/ creating\/changing state\/strategy\n public:\n NodeFactory& getNodeFactory();\n\n \/\/ direct update access to data\n public:\n void releaseDataSegment();\n\n memory::Segment const * getDataSegment() const;\n memory::Segment * getDataSegmentForUpdate();\n\n data::NodeAddress ::DataType * getDataForUpdate(data::NodeAccessRef const & _aNode);\n data::SetNodeAddress::DataType * getDataForUpdate(data::SetNodeAccess const & _aNode);\n data::GroupNodeAddress::DataType * getDataForUpdate(data::GroupNodeAccess const & _aNode);\n data::ValueNodeAddress::DataType * getDataForUpdate(data::ValueNodeAccess const & _aNode);\n\n \/\/ access to node innards\n protected:\n \/\/\/ provide access to the data of the underlying node\n data::NodeAccessRef getNodeAccessRef(Node const& _aNode) const;\n\n \/\/\/ provide access to the address of the underlying node\n data::NodeAddress getNodeAddress(Node const& _aNode) const;\n\n \/\/\/ retrieve the name of the underlying node\n Name getNodeName(Node const& _aNode) const;\n\n \/\/\/ retrieve the attributes of the underlying node\n node::Attributes getNodeAttributes(Node const& _aNode) const;\n\n protected:\n \/\/helper for migration to new (info based) model for adjusting to changes\n static void addLocalChangeHelper( NodeChangesInformation& rLocalChanges, configuration::NodeChange const& aChange);\n\n private:\n void implAdjustToValueChanges(NodeChangesInformation& rLocalChanges, GroupNode const& _aGroupNode, SubtreeChange const& rExternalChanges);\n void implAdjustToSubChanges(NodeChangesInformation& rLocalChanges, GroupNode const & _aGroupNode, SubtreeChange const& rExternalChanges);\n void implAdjustToElementChanges(NodeChangesInformation& rLocalChanges, SetNode const& _aNode, SubtreeChange const& rExternalChanges, TreeDepth nDepth);\n void implAdjustToElementChange (NodeChangesInformation& rLocalChanges, SetNode const& _aNode, Change const& rElementChange, TreeDepth nElementDepth);\n void implCommitDirectIn(data::TreeAccessor const& _aPlaceHolder, Node const& _aNode);\n\n protected:\n void checkInstance(Tree const& _aTreeForThis) const;\n SetNodeEntry implFindElement(SetNode const& _aNode, Name const& aName) const;\n SetNodeElement implMakeElement(SetNode const& _aNode, SetNodeEntry const& anEntry) const;\n\n \/\/ virtual interface - these functions must be provided\n private:\n \/\/ change handling\n virtual bool doHasChanges(Node const& _aNode) const = 0;\n virtual void doMarkChanged(Node const& _aNode) = 0;\n\n virtual NodeFactory& doGetNodeFactory() = 0;\n\n \/\/ virtual interface - these functions all have default implementations without support for pending changes\n protected:\n virtual void doReleaseDataSegment() = 0;\n\n \/\/ special support for direct changes to underlying data - default is no support\n virtual data::NodeAddress::DataType * implAccessForUpdate(data::NodeAccessRef const & _aDataAccess);\n virtual memory::Segment const * doGetDataSegment() const = 0;\n virtual memory::Segment * doGetDataSegmentForUpdate();\n\n \/\/ change handling\n virtual void doCollectChanges(Node const& _aNode, NodeChanges& rChanges) const;\n\n \/\/ commit protocol\n virtual std::auto_ptr doPreCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);\n virtual void doFailedCommit(Tree const& _aTree, SubtreeChange& rChanges);\n virtual void doFinishCommit(Tree const& _aTree, SubtreeChange& rChanges);\n virtual void doRevertCommit(Tree const& _aTree, SubtreeChange& rChanges);\n\n \/\/ notification protocol\n virtual configuration::ValueChangeImpl* doAdjustToValueChange(GroupNode const& _aGroupNode, Name const& aName, ValueChange const& rExternalChange);\n\n \/\/ common attributes\n virtual node::Attributes doAdjustAttributes(node::Attributes const& _aAttributes) const = 0;\n\n \/\/ group member access\n virtual ValueMemberNode doGetValueMember(GroupNode const& _aNode, Name const& _aName, bool _bForUpdate) const = 0;\n\n \/\/ set element access\n virtual void doInsertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry) = 0;\n virtual void doRemoveElement(SetNode const& _aNode, Name const& aName) = 0;\n\n \/\/ strategy change support\n\/* virtual void doCommitChanges(Node const& _aNode);\n virtual rtl::Reference doCloneDirect() = 0;\n virtual rtl::Reference doCloneIndirect() = 0;\n*\/ };\n\n\/\/-----------------------------------------------------------------------------\n inline Name ViewStrategy::getName(Node const& _aNode) const\n { return getNodeName(_aNode); }\n\n inline node::Attributes ViewStrategy::getAttributes(Node const& _aNode) const\n { return doAdjustAttributes(getNodeAttributes(_aNode)); }\n\n inline bool ViewStrategy::hasChanges(Node const& _aNode) const\n { return doHasChanges(_aNode); }\n\n inline NodeFactory& ViewStrategy::getNodeFactory()\n { return doGetNodeFactory(); }\n\n inline void ViewStrategy::releaseDataSegment()\n { doReleaseDataSegment(); }\n\n inline memory::Segment const * ViewStrategy::getDataSegment() const\n { return doGetDataSegment(); }\n\n inline memory::Segment * ViewStrategy::getDataSegmentForUpdate()\n { return doGetDataSegmentForUpdate(); }\n\n\/\/-----------------------------------------------------------------------------\n }\n\/\/-----------------------------------------------------------------------------\n}\n\n#endif \/\/ CONFIGMGR_CONFIGNODEBEHAVIOR_HXX_\nINTEGRATION: CWS configrefactor01 (1.6.84); FILE MERGED 2007\/02\/07 12:14:55 mmeeks 1.6.84.5: remove obsolete memory::Segment forward decls. 2007\/01\/16 12:18:28 mmeeks 1.6.84.4: Submitted by: mmeeks Kill 'memory::Segment' - no longer needed. Bin some other (empty \/ redundant) headers. 2007\/01\/11 20:16:06 mmeeks 1.6.84.3: Submitted by: mmeeks More re-factoring, lots of locking rationalized, drastically reduced the mutex count, also removed ~300k interlocked increments with a non-interlocking SimpleReferencedObject base 2007\/01\/11 10:35:41 mmeeks 1.6.84.2: Submitted by: mmeeks\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewstrategy.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-23 14:50:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_VIEWBEHAVIOR_HXX_\n#define CONFIGMGR_VIEWBEHAVIOR_HXX_\n\n#ifndef CONFIGMGR_VIEWNODE_HXX_\n#include \"viewnode.hxx\"\n#endif\n\n#ifndef CONFIGMGR_GROUPNODEBEHAVIOR_HXX_\n#include \"groupnodeimpl.hxx\"\n#endif\n#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_\n#include \"setnodeimpl.hxx\"\n#endif\n#ifndef CONFIGMGR_UTILITY_HXX_\n#include \"utility.hxx\"\n#endif\n\n#ifndef _RTL_REF_HXX_\n#include \n#endif\n\nnamespace configmgr\n{\n\/\/-----------------------------------------------------------------------------\n namespace configuration\n {\n class SetElementChangeImpl;\n class ValueChangeImpl;\n }\n\/\/-----------------------------------------------------------------------------\n namespace view\n {\n\/\/-----------------------------------------------------------------------------\n struct NodeFactory;\n\/\/-----------------------------------------------------------------------------\n using configuration::Name;\n using configuration::NodeOffset;\n using configuration::TreeDepth;\n\n typedef com::sun::star::uno::Any UnoAny;\n typedef com::sun::star::uno::Type UnoType;\n\/\/-----------------------------------------------------------------------------\n class ViewStrategy : public configmgr::SimpleReferenceObject\n {\n \/\/ node attributes\n public:\n \/\/\/ retrieve the attributes of the node\n Name getName(Node const& _aNode) const;\n\n \/\/\/ retrieve the attributes of the node\n node::Attributes getAttributes(Node const& _aNode) const;\n\n \/\/ tracking pending changes\n public:\n typedef configuration::NodeChanges NodeChanges;\n\n void collectChanges(Tree const& _aTree, NodeChanges& rChanges) const;\n\n bool hasChanges(Tree const& _aTree) const;\n\n bool hasChanges(Node const& _aNode) const;\n\n void markChanged(Node const& _aNode);\n\n \/\/ commit protocol\n public:\n std::auto_ptr preCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);\n\n void finishCommit(Tree const& _aTree, SubtreeChange& rRootChange);\n\n void revertCommit(Tree const& _aTree, SubtreeChange& rRootChange);\n\n void recoverFailedCommit(Tree const& _aTree, SubtreeChange& rRootChange);\n\n \/\/ notification protocol\n public:\n typedef configuration::NodeChangesInformation NodeChangesInformation;\n\n \/\/\/ Adjust the internal representation after external changes to the original data - build NodeChangeInformation objects for notification\n void adjustToChanges(NodeChangesInformation& rLocalChanges, Node const & _aNode, SubtreeChange const& aExternalChange);\n\n \/\/ visitor dispatch\n public:\n typedef configuration::GroupMemberVisitor GroupMemberVisitor;\n typedef configuration::SetNodeVisitor SetNodeVisitor;\n\n GroupMemberVisitor::Result dispatchToValues(GroupNode const& _aNode, GroupMemberVisitor& _aVisitor);\n\n \/\/\/ Call aVisitor.visit(aElement)<\/code> for each element in this set until SetNodeVisitor::DONE is returned.\n SetNodeVisitor::Result dispatchToElements(SetNode const& _aNode, SetNodeVisitor& _aVisitor);\n\n \/\/ value (element) node specific operations\n public:\n \/\/\/ Does this node assume its default value\n \/\/\/ retrieve the current value of this node\n UnoAny getValue(ValueNode const& _aNode) const;\n\n \/\/\/ get the type of this value\n UnoType getValueType(ValueNode const& _aNode) const;\n\n\n \/\/ group node specific operations\n public:\n typedef configuration::ValueMemberNode ValueMemberNode;\n typedef configuration::ValueMemberUpdate ValueMemberUpdate;\n\n \/\/\/ does this hold a child value of the given name\n bool hasValue(GroupNode const& _aNode, Name const& _aName) const;\n\n \/\/\/ does this hold a child value\n bool hasValue(GroupNode const& _aNode) const;\n\n \/\/\/ are defaults for this node available ?\n bool areValueDefaultsAvailable(GroupNode const& _aNode) const;\n\n \/\/\/ retrieve data for the child value of the given name\n ValueMemberNode getValue(GroupNode const& _aNode, Name const& _aName) const;\n\n \/\/\/ retrieve data for updating the child value of the given name\n ValueMemberUpdate getValueForUpdate(GroupNode const & _aNode, Name const& _aName);\n\n \/\/ set node specific operations\n public:\n typedef configuration::ElementTreeData SetNodeElement;\n typedef configuration::SetEntry SetNodeEntry;\n\n \/\/\/ does this set contain any elements (loads elements if needed)\n bool isEmpty(SetNode const& _aNode) const;\n\n \/\/\/ does this set contain an element named aName<\/var> (loads elements if needed)\n SetNodeEntry findElement(SetNode const& _aNode, Name const& aName) const;\n\n \/\/\/ does this set contain an element named aName<\/var> (and is that element loaded ?)\n SetNodeEntry findAvailableElement(SetNode const& _aNode, Name const& aName) const;\n\n \/\/\/ insert a new entry into this set\n void insertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry);\n\n \/\/\/ remove an existing entry into this set\n void removeElement(SetNode const& _aNode, Name const& aName);\n\n \/** Create a Subtree change as 'diff' which allows transforming the set to its default state\n (given that _rDefaultTree<\/var> points to a default instance of this set)\n

Ownership of added trees should be transferred to the SubtreeChange.<\/p>\n *\/\n std::auto_ptr differenceToDefaultState(SetNode const& _aNode, ISubtree& _rDefaultTree) const;\n\n \/\/\/ Get the template that describes elements of this set\n configuration::TemplateHolder getElementTemplate(SetNode const& _aNode) const;\n\n \/\/\/ Get a template provider that can create new elements for this set\n configuration::TemplateProvider getTemplateProvider(SetNode const& _aNode) const;\n\n \/\/ create a view::Tree from a configuration::SetEntry\n Tree extractTree(SetNodeEntry const& _anEntry);\n\n \/\/ creating\/changing state\/strategy\n public:\n NodeFactory& getNodeFactory();\n\n \/\/ access to node innards\n protected:\n \/\/\/ provide access to the data of the underlying node\n data::NodeAccess getNodeAccess(Node const& _aNode) const;\n\n \/\/\/ provide access to the address of the underlying node\n data::NodeAddress getNodeAddress(Node const& _aNode) const;\n\n \/\/\/ retrieve the name of the underlying node\n Name getNodeName(Node const& _aNode) const;\n\n \/\/\/ retrieve the attributes of the underlying node\n node::Attributes getNodeAttributes(Node const& _aNode) const;\n\n protected:\n \/\/helper for migration to new (info based) model for adjusting to changes\n static void addLocalChangeHelper( NodeChangesInformation& rLocalChanges, configuration::NodeChange const& aChange);\n\n private:\n void implAdjustToValueChanges(NodeChangesInformation& rLocalChanges, GroupNode const& _aGroupNode, SubtreeChange const& rExternalChanges);\n void implAdjustToSubChanges(NodeChangesInformation& rLocalChanges, GroupNode const & _aGroupNode, SubtreeChange const& rExternalChanges);\n void implAdjustToElementChanges(NodeChangesInformation& rLocalChanges, SetNode const& _aNode, SubtreeChange const& rExternalChanges, TreeDepth nDepth);\n void implAdjustToElementChange (NodeChangesInformation& rLocalChanges, SetNode const& _aNode, Change const& rElementChange, TreeDepth nElementDepth);\n void implCommitDirectIn(data::TreeAccessor const& _aPlaceHolder, Node const& _aNode);\n\n protected:\n void checkInstance(Tree const& _aTreeForThis) const;\n SetNodeEntry implFindElement(SetNode const& _aNode, Name const& aName) const;\n SetNodeElement implMakeElement(SetNode const& _aNode, SetNodeEntry const& anEntry) const;\n\n \/\/ virtual interface - these functions must be provided\n private:\n \/\/ change handling\n virtual bool doHasChanges(Node const& _aNode) const = 0;\n virtual void doMarkChanged(Node const& _aNode) = 0;\n\n virtual NodeFactory& doGetNodeFactory() = 0;\n\n \/\/ virtual interface - these functions all have default implementations without support for pending changes\n protected:\n \/\/ change handling\n virtual void doCollectChanges(Node const& _aNode, NodeChanges& rChanges) const;\n\n \/\/ commit protocol\n virtual std::auto_ptr doPreCommitChanges(Tree const& _aTree, configuration::ElementList& _rRemovedElements);\n virtual void doFailedCommit(Tree const& _aTree, SubtreeChange& rChanges);\n virtual void doFinishCommit(Tree const& _aTree, SubtreeChange& rChanges);\n virtual void doRevertCommit(Tree const& _aTree, SubtreeChange& rChanges);\n\n \/\/ notification protocol\n virtual configuration::ValueChangeImpl* doAdjustToValueChange(GroupNode const& _aGroupNode, Name const& aName, ValueChange const& rExternalChange);\n\n \/\/ common attributes\n virtual node::Attributes doAdjustAttributes(node::Attributes const& _aAttributes) const = 0;\n\n \/\/ group member access\n virtual ValueMemberNode doGetValueMember(GroupNode const& _aNode, Name const& _aName, bool _bForUpdate) const = 0;\n\n \/\/ set element access\n virtual void doInsertElement(SetNode const& _aNode, Name const& aName, SetNodeEntry const& aNewEntry) = 0;\n virtual void doRemoveElement(SetNode const& _aNode, Name const& aName) = 0;\n };\n\n\/\/-----------------------------------------------------------------------------\n inline Name ViewStrategy::getName(Node const& _aNode) const\n { return getNodeName(_aNode); }\n\n inline node::Attributes ViewStrategy::getAttributes(Node const& _aNode) const\n { return doAdjustAttributes(getNodeAttributes(_aNode)); }\n\n inline bool ViewStrategy::hasChanges(Node const& _aNode) const\n { return doHasChanges(_aNode); }\n\n inline NodeFactory& ViewStrategy::getNodeFactory()\n { return doGetNodeFactory(); }\n\n\/\/-----------------------------------------------------------------------------\n }\n\/\/-----------------------------------------------------------------------------\n}\n\n#endif \/\/ CONFIGMGR_CONFIGNODEBEHAVIOR_HXX_\n<|endoftext|>"} {"text":"#include \"..\/common\/certs.hpp\"\n#include \"..\/common\/mock_connector.hpp\"\n\n#include \"root_path.hpp\"\n\n#include \n#include \n#include \n\n#include \n\n#include \/\/ this_thread::sleep_for\n#include \n\n#include \n#include \n\n#include \n\nnamespace PXPAgent {\n\n#ifdef TEST_VIRTUAL\n\nnamespace lth_jc = leatherman::json_container;\nnamespace pcp_util = PCPClient::Util;\nnamespace fs = boost::filesystem;\n\nstatic const std::string REVERSE_VALID_MODULE_NAME { \"reverse_valid\" };\n\nTEST_CASE(\"Valid External Module Configuration\", \"[component]\") {\n AGENT_CONFIGURATION.modules_config_dir = VALID_MODULES_CONFIG;\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n\n SECTION(\"retrieves the configuration from file if valid JSON format\") {\n REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME));\n }\n\n SECTION(\"does load the module when the configuration is valid\") {\n REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME));\n REQUIRE(r_p.hasModule(REVERSE_VALID_MODULE_NAME));\n }\n}\n\nTEST_CASE(\"Badly formatted External Module Configuration\", \"[component]\") {\n AGENT_CONFIGURATION.modules_config_dir = BAD_FORMAT_MODULES_CONFIG;\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n\n SECTION(\"stores a null JSON value as the configuration, if it's in an \"\n \"invalid JSON format\") {\n REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == \"null\");\n }\n\n SECTION(\"does not load the module when the configuration is in \"\n \"bad JSON format\") {\n REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == \"null\");\n REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME));\n }\n}\n\nTEST_CASE(\"Invalid (by metadata) External Module Configuration\", \"[component]\") {\n SECTION(\"does not load the module when the configuration is invalid\") {\n AGENT_CONFIGURATION.modules_config_dir = BROKEN_MODULES_CONFIG;\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME));\n REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME));\n }\n}\n\nTEST_CASE(\"Process correctly requests for external modules\", \"[component]\") {\n AGENT_CONFIGURATION.modules_config_dir = \"\";\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n lth_jc::JsonContainer envelope { VALID_ENVELOPE_TXT };\n std::vector debug {};\n\n lth_jc::JsonContainer data {};\n data.set(\"transaction_id\", \"42\");\n\n SECTION(\"correctly process nonblocking requests\") {\n SECTION(\"send a blocking response when the requested action succeeds\") {\n REQUIRE(!c_ptr->sent_blocking_response);\n data.set(\"module\", \"reverse_valid\");\n data.set(\"action\", \"string\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"was\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_NOTHROW(r_p.processRequest(RequestType::Blocking, p_c));\n\n \/\/ Wait a bit to let the execution thread finish\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::microseconds(100000));\n\n REQUIRE(c_ptr->sent_blocking_response);\n }\n\n SECTION(\"send a PXP error in case of action failure\") {\n data.set(\"module\", \"failures_test\");\n data.set(\"action\", \"broken_action\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"bikini\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_THROWS_AS(r_p.processRequest(RequestType::Blocking, p_c),\n MockConnector::pxpError_msg);\n }\n }\n\n SECTION(\"correctly process non-blocking requests\") {\n SECTION(\"send a provisional response when the requested starts successfully\") {\n REQUIRE(!c_ptr->sent_provisional_response);\n\n data.set(\"module\", \"reverse_valid\");\n data.set(\"notify_outcome\", false);\n data.set(\"action\", \"string\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"lemon\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c));\n\n \/\/ Wait a bit to let the execution thread finish\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::microseconds(100000));\n\n REQUIRE(c_ptr->sent_provisional_response);\n }\n\n SECTION(\"send a blocking response when the requested action succeeds\") {\n REQUIRE(!c_ptr->sent_provisional_response);\n REQUIRE(!c_ptr->sent_non_blocking_response);\n\n data.set(\"module\", \"reverse_valid\");\n data.set(\"notify_outcome\", true);\n data.set(\"action\", \"string\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"kondgbia\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c));\n\n \/\/ Wait a bit to let the execution thread finish\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::microseconds(100000));\n\n REQUIRE(c_ptr->sent_provisional_response);\n REQUIRE(c_ptr->sent_non_blocking_response);\n }\n }\n\n fs::remove_all(SPOOL);\n}\n\n#endif \/\/ TEST_VIRTUAL\n\n} \/\/ namespace PXPAgent\n(maint) Correct test title#include \"..\/common\/certs.hpp\"\n#include \"..\/common\/mock_connector.hpp\"\n\n#include \"root_path.hpp\"\n\n#include \n#include \n#include \n\n#include \n\n#include \/\/ this_thread::sleep_for\n#include \n\n#include \n#include \n\n#include \n\nnamespace PXPAgent {\n\n#ifdef TEST_VIRTUAL\n\nnamespace lth_jc = leatherman::json_container;\nnamespace pcp_util = PCPClient::Util;\nnamespace fs = boost::filesystem;\n\nstatic const std::string REVERSE_VALID_MODULE_NAME { \"reverse_valid\" };\n\nTEST_CASE(\"Valid External Module Configuration\", \"[component]\") {\n AGENT_CONFIGURATION.modules_config_dir = VALID_MODULES_CONFIG;\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n\n SECTION(\"retrieves the configuration from file if valid JSON format\") {\n REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME));\n }\n\n SECTION(\"does load the module when the configuration is valid\") {\n REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME));\n REQUIRE(r_p.hasModule(REVERSE_VALID_MODULE_NAME));\n }\n}\n\nTEST_CASE(\"Badly formatted External Module Configuration\", \"[component]\") {\n AGENT_CONFIGURATION.modules_config_dir = BAD_FORMAT_MODULES_CONFIG;\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n\n SECTION(\"stores a null JSON value as the configuration, if it's in an \"\n \"invalid JSON format\") {\n REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == \"null\");\n }\n\n SECTION(\"does not load the module when the configuration is in \"\n \"bad JSON format\") {\n REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == \"null\");\n REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME));\n }\n}\n\nTEST_CASE(\"Invalid (by metadata) External Module Configuration\", \"[component]\") {\n SECTION(\"does not load the module when the configuration is invalid\") {\n AGENT_CONFIGURATION.modules_config_dir = BROKEN_MODULES_CONFIG;\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME));\n REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME));\n }\n}\n\nTEST_CASE(\"Process correctly requests for external modules\", \"[component]\") {\n AGENT_CONFIGURATION.modules_config_dir = \"\";\n auto c_ptr = std::make_shared();\n RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION };\n lth_jc::JsonContainer envelope { VALID_ENVELOPE_TXT };\n std::vector debug {};\n\n lth_jc::JsonContainer data {};\n data.set(\"transaction_id\", \"42\");\n\n SECTION(\"correctly process nonblocking requests\") {\n SECTION(\"send a blocking response when the requested action succeeds\") {\n REQUIRE(!c_ptr->sent_blocking_response);\n data.set(\"module\", \"reverse_valid\");\n data.set(\"action\", \"string\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"was\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_NOTHROW(r_p.processRequest(RequestType::Blocking, p_c));\n\n \/\/ Wait a bit to let the execution thread finish\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::microseconds(100000));\n\n REQUIRE(c_ptr->sent_blocking_response);\n }\n\n SECTION(\"send a PXP error in case of action failure\") {\n data.set(\"module\", \"failures_test\");\n data.set(\"action\", \"broken_action\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"bikini\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_THROWS_AS(r_p.processRequest(RequestType::Blocking, p_c),\n MockConnector::pxpError_msg);\n }\n }\n\n SECTION(\"correctly process non-blocking requests\") {\n SECTION(\"send a provisional response when the requested action starts \"\n \"successfully\") {\n REQUIRE(!c_ptr->sent_provisional_response);\n\n data.set(\"module\", \"reverse_valid\");\n data.set(\"notify_outcome\", false);\n data.set(\"action\", \"string\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"lemon\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c));\n\n \/\/ Wait a bit to let the execution thread finish\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::microseconds(100000));\n\n REQUIRE(c_ptr->sent_provisional_response);\n }\n\n SECTION(\"send a blocking response when the requested action succeeds\") {\n REQUIRE(!c_ptr->sent_provisional_response);\n REQUIRE(!c_ptr->sent_non_blocking_response);\n\n data.set(\"module\", \"reverse_valid\");\n data.set(\"notify_outcome\", true);\n data.set(\"action\", \"string\");\n lth_jc::JsonContainer params {};\n params.set(\"argument\", \"kondgbia\");\n data.set(\"params\", params);\n const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 };\n\n REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c));\n\n \/\/ Wait a bit to let the execution thread finish\n pcp_util::this_thread::sleep_for(\n pcp_util::chrono::microseconds(100000));\n\n REQUIRE(c_ptr->sent_provisional_response);\n REQUIRE(c_ptr->sent_non_blocking_response);\n }\n }\n\n fs::remove_all(SPOOL);\n}\n\n#endif \/\/ TEST_VIRTUAL\n\n} \/\/ namespace PXPAgent\n<|endoftext|>"} {"text":"#include \"drake\/util\/SystemIdentification.h\"\n\n#include \n\nnamespace drake {\nnamespace util {\n\ntemplate\nstd::set::MonomialType>\nSystemIdentification::GetAllCombinationsOfVars(\n const std::vector& polys,\n const std::set& vars_of_interest) {\n std::set interest_monomials;\n for (const PolyType& poly : polys) {\n for (const MonomialType& monomial : poly.getMonomials()) {\n typename PolyType::Monomial interest_monomial;\n interest_monomial.coefficient = 1;\n for (const TermType& term : monomial.terms) {\n if (vars_of_interest.count(term.var)) {\n interest_monomial.terms.push_back(term);\n }\n }\n interest_monomials.insert(interest_monomial);\n }\n }\n return interest_monomials;\n}\n\ntemplate\nbool SystemIdentification::MonomialMatches(\n const MonomialType& haystack,\n const MonomialType& needle,\n const std::set& vars_of_interest) {\n const MonomialType residue = haystack.factor(needle);\n if (residue.coefficient == 0) {\n return false;\n }\n for (const VarType& var : vars_of_interest) {\n if (residue.getDegreeOf(var) > 0) {\n return false;\n }\n }\n return true;\n}\n\ntemplate\nstd::pair::PolyType>\nSystemIdentification::NormalizePolynomial(const PolyType& poly) {\n std::vector monomials = poly.getMonomials();\n const T min_coefficient = std::min_element(\n monomials.begin(), monomials.end(),\n [&](const MonomialType& l, const MonomialType& r){\n return l.coefficient < r.coefficient; })->coefficient;\n for (MonomialType& monomial : monomials) {\n monomial.coefficient \/= min_coefficient;\n }\n return std::make_pair(min_coefficient, PolyType(monomials.begin(),\n monomials.end()));\n}\n\ntemplate\ntypename SystemIdentification::LumpingMapType\nSystemIdentification::GetLumpedParametersFromPolynomial(\n const PolyType& poly,\n const std::set& vars_of_interest) {\n \/\/ Just dispatch to the set version.\n const std::vector> polys = {poly};\n return SystemIdentification::GetLumpedParametersFromPolynomials(\n polys, vars_of_interest);\n}\n\ntemplate\ntypename SystemIdentification::LumpingMapType\nSystemIdentification::GetLumpedParametersFromPolynomials(\n const std::vector& polys,\n const std::set& vars_of_interest) {\n \/\/ Before we begin, check that we can reserve some names (VarType values)\n \/\/ for our lumped parameters.\n std::set all_vars;\n for (const PolyType& poly : polys) {\n const auto& poly_vars = poly.getVariables();\n all_vars.insert(poly_vars.begin(), poly_vars.end());\n }\n const VarType reservation_start = Polynomiald(\"lump\", 1).getSimpleVariable();\n const VarType reservation_end = Polynomiald(\"lump\", 1000).getSimpleVariable();\n for (const VarType& var : all_vars) {\n if ((var >= reservation_start) && (var <= reservation_end)) {\n throw std::runtime_error(\n \"Lumped parameters failed because variable name already in use\");\n }\n }\n\n \/\/ First, extract every combination of the vars_of_interest.\n const std::set interest_monomials =\n GetAllCombinationsOfVars(polys, vars_of_interest);\n\n \/\/ Second, for each of those combinations, find the corresponding\n \/\/ polynomials of parameter (ie, non of-interest) variables in each\n \/\/ polynomial.\n std::set lumped_parameters;\n for (const MonomialType& interest_monomial : interest_monomials) {\n for (const PolyType& poly : polys) {\n std::vector lumped_parameter;\n for (const MonomialType& monomial : poly.getMonomials()) {\n if (MonomialMatches(monomial, interest_monomial, vars_of_interest)) {\n lumped_parameter.push_back(monomial.factor(interest_monomial));\n }\n }\n if (!lumped_parameter.size()) { continue; }\n \/\/ Factor out any coefficients, so that 'a' and '2*a' are not both\n \/\/ considered lumped parameters.\n PolyType lumped_parameter_polynomial(lumped_parameter.begin(),\n lumped_parameter.end());\n PolyType normalized =\n NormalizePolynomial(lumped_parameter_polynomial).second;\n lumped_parameters.insert(normalized);\n }\n }\n\n \/\/ Third, for the set of such parameter polynomials, create a lumped\n \/\/ parameter for each.\n int lump_index = 1;\n typename SystemIdentification::LumpingMapType lumping_map;\n\n for (const PolyType& lump : lumped_parameters) {\n VarType lump_var = PolyType(\"lump\", lump_index).getSimpleVariable();\n lumping_map[lump] = lump_var;\n lump_index++;\n }\n\n return lumping_map;\n}\n\ntemplate\ntypename SystemIdentification::PolyType\nSystemIdentification::RewritePolynomialWithLumpedParameters(\n const PolyType& poly,\n const LumpingMapType& lumped_parameters) {\n std::set vars_of_interest = poly.getVariables();\n for (auto lump_name_pair : lumped_parameters) {\n std::set parameters_in_lump = lump_name_pair.first.getVariables();\n for (const VarType& var : parameters_in_lump) {\n vars_of_interest.erase(var);\n }\n }\n std::set interest_monomials =\n GetAllCombinationsOfVars({poly}, vars_of_interest);\n std::vector working_monomials = poly.getMonomials();\n for (const MonomialType& interest_monomial : interest_monomials) {\n std::vector new_working_monomials;\n std::vector indices_to_erase;\n std::vector factor_monomials;\n for (const MonomialType& working_monomial : working_monomials) {\n if (MonomialMatches(working_monomial, interest_monomial,\n vars_of_interest)) {\n factor_monomials.push_back(working_monomial.factor(interest_monomial));\n } else {\n new_working_monomials.push_back(working_monomial);\n }\n }\n const PolyType factor_polynomial(factor_monomials.begin(),\n factor_monomials.end());\n const auto& normalization = NormalizePolynomial(factor_polynomial);\n const T factor = normalization.first;\n const PolyType& normalized = normalization.second;\n if (!lumped_parameters.count(normalized)) {\n \/\/ No lumping possible for this interest monomial.\n continue;\n }\n TermType lump_term;\n lump_term.var = lumped_parameters.at(normalized);\n lump_term.power = 1;\n MonomialType lumped_monomial;\n lumped_monomial.terms = interest_monomial.terms;\n lumped_monomial.terms.push_back(lump_term);\n lumped_monomial.coefficient = factor;\n new_working_monomials.push_back(lumped_monomial);\n working_monomials = new_working_monomials;\n }\n\n return PolyType(working_monomials.begin(), working_monomials.end());\n}\n\n};\n};\n\ntemplate class DRAKEPOLYNOMIAL_EXPORT drake::util::SystemIdentification;\nchecklisting: Implementation comments, variable name uniqueness, dead code removal#include \"drake\/util\/SystemIdentification.h\"\n\n#include \n\nnamespace drake {\nnamespace util {\n\ntemplate\nstd::set::MonomialType>\nSystemIdentification::GetAllCombinationsOfVars(\n const std::vector& polys,\n const std::set& vars_of_interest) {\n std::set interest_monomials;\n for (const PolyType& poly : polys) {\n for (const MonomialType& monomial : poly.getMonomials()) {\n typename PolyType::Monomial interest_monomial;\n interest_monomial.coefficient = 1;\n for (const TermType& term : monomial.terms) {\n if (vars_of_interest.count(term.var)) {\n interest_monomial.terms.push_back(term);\n }\n }\n interest_monomials.insert(interest_monomial);\n }\n }\n return interest_monomials;\n}\n\ntemplate\nbool SystemIdentification::MonomialMatches(\n const MonomialType& haystack,\n const MonomialType& needle,\n const std::set& vars_of_interest) {\n const MonomialType residue = haystack.factor(needle);\n if (residue.coefficient == 0) {\n return false;\n }\n for (const VarType& var : vars_of_interest) {\n if (residue.getDegreeOf(var) > 0) {\n return false;\n }\n }\n return true;\n}\n\ntemplate\nstd::pair::PolyType>\nSystemIdentification::NormalizePolynomial(const PolyType& poly) {\n std::vector monomials = poly.getMonomials();\n const T min_coefficient = std::min_element(\n monomials.begin(), monomials.end(),\n [&](const MonomialType& l, const MonomialType& r){\n return l.coefficient < r.coefficient; })->coefficient;\n for (MonomialType& monomial : monomials) {\n monomial.coefficient \/= min_coefficient;\n }\n return std::make_pair(min_coefficient, PolyType(monomials.begin(),\n monomials.end()));\n}\n\ntemplate\ntypename SystemIdentification::LumpingMapType\nSystemIdentification::GetLumpedParametersFromPolynomial(\n const PolyType& poly,\n const std::set& vars_of_interest) {\n \/\/ Just dispatch to the set version.\n const std::vector> polys = {poly};\n return SystemIdentification::GetLumpedParametersFromPolynomials(\n polys, vars_of_interest);\n}\n\ntemplate\ntypename SystemIdentification::LumpingMapType\nSystemIdentification::GetLumpedParametersFromPolynomials(\n const std::vector& polys,\n const std::set& vars_of_interest) {\n \/\/ Before we begin, check that we can reserve some names (VarType values)\n \/\/ for our lumped parameters.\n std::set all_vars;\n for (const PolyType& poly : polys) {\n const auto& poly_vars = poly.getVariables();\n all_vars.insert(poly_vars.begin(), poly_vars.end());\n }\n const VarType reservation_start = Polynomiald(\"lump\", 1).getSimpleVariable();\n const VarType reservation_end = Polynomiald(\"lump\", 1000).getSimpleVariable();\n for (const VarType& var : all_vars) {\n if ((var >= reservation_start) && (var <= reservation_end)) {\n throw std::runtime_error(\n \"Lumped parameters failed because variable name already in use\");\n }\n }\n\n \/\/ Extract every combination of the vars_of_interest.\n const std::set interest_monomials =\n GetAllCombinationsOfVars(polys, vars_of_interest);\n\n \/\/ For each of those combinations, find the corresponding polynomials of\n \/\/ parameter (ie, non of-interest) variables in each polynomial.\n std::set lumped_parameters;\n for (const MonomialType& interest_monomial : interest_monomials) {\n for (const PolyType& poly : polys) {\n std::vector lumped_parameter;\n for (const MonomialType& monomial : poly.getMonomials()) {\n if (MonomialMatches(monomial, interest_monomial, vars_of_interest)) {\n lumped_parameter.push_back(monomial.factor(interest_monomial));\n }\n }\n if (!lumped_parameter.size()) { continue; }\n \/\/ Factor out any coefficients, so that 'a' and '2*a' are not both\n \/\/ considered lumped parameters.\n PolyType lumped_parameter_polynomial(lumped_parameter.begin(),\n lumped_parameter.end());\n PolyType normalized =\n NormalizePolynomial(lumped_parameter_polynomial).second;\n lumped_parameters.insert(normalized);\n }\n }\n\n \/\/ For each such parameter polynomial, create a lumped parameter.\n int lump_index = 1;\n typename SystemIdentification::LumpingMapType lumping_map;\n\n for (const PolyType& lump : lumped_parameters) {\n VarType lump_var = PolyType(\"lump\", lump_index).getSimpleVariable();\n lumping_map[lump] = lump_var;\n lump_index++;\n }\n\n return lumping_map;\n}\n\ntemplate\ntypename SystemIdentification::PolyType\nSystemIdentification::RewritePolynomialWithLumpedParameters(\n const PolyType& poly,\n const LumpingMapType& lumped_parameters) {\n \/\/ Reconstruct vars_of_interest, the variables in poly that are not\n \/\/ mentioned by the lumped_parameters.\n std::set vars_of_interest = poly.getVariables();\n for (auto lump_name_pair : lumped_parameters) {\n std::set parameters_in_lump = lump_name_pair.first.getVariables();\n for (const VarType& var : parameters_in_lump) {\n vars_of_interest.erase(var);\n }\n }\n\n \/\/ Loop over the combinations of the variables-of-interest, constructing the\n \/\/ polynomial of parameters that multiply by each combination; if that\n \/\/ polynomial is a lumped variable, substitute in a new monomial of the\n \/\/ lumped variable times the combination instead.\n std::set interest_monomials =\n GetAllCombinationsOfVars({poly}, vars_of_interest);\n std::vector working_monomials = poly.getMonomials();\n for (const MonomialType& interest_monomial : interest_monomials) {\n std::vector new_working_monomials;\n std::vector factor_monomials;\n for (const MonomialType& working_monomial : working_monomials) {\n if (MonomialMatches(working_monomial, interest_monomial,\n vars_of_interest)) {\n \/\/ This monomial matches our interest monomial; we will factor it by\n \/\/ the interest monomial and add the resulting monomial of parameters\n \/\/ to our factor list.\n factor_monomials.push_back(working_monomial.factor(interest_monomial));\n } else {\n \/\/ This monomial does not match our interest monomial; copy it\n \/\/ unchanged.\n new_working_monomials.push_back(working_monomial);\n }\n }\n const PolyType factor_polynomial(factor_monomials.begin(),\n factor_monomials.end());\n const auto& normalization = NormalizePolynomial(factor_polynomial);\n const T coefficient = normalization.first;\n const PolyType& normalized = normalization.second;\n\n if (!lumped_parameters.count(normalized)) {\n \/\/ Factoring out this combination yielded a parameter polynomial that\n \/\/ does not correspond to a lumped variable. Ignore it.\n continue;\n }\n\n \/\/ We have a lumped parameter, so construct a new monomial and replace the\n \/\/ working monomials list.\n TermType lump_term;\n lump_term.var = lumped_parameters.at(normalized);\n lump_term.power = 1;\n MonomialType lumped_monomial;\n lumped_monomial.terms = interest_monomial.terms;\n lumped_monomial.terms.push_back(lump_term);\n lumped_monomial.coefficient = coefficient;\n new_working_monomials.push_back(lumped_monomial);\n working_monomials = new_working_monomials;\n }\n\n return PolyType(working_monomials.begin(), working_monomials.end());\n}\n\n};\n};\n\ntemplate class DRAKEPOLYNOMIAL_EXPORT drake::util::SystemIdentification;\n<|endoftext|>"} {"text":"#include \"nanocv.h\"\n#include \"models\/forward_network.h\"\n#include \n#include \n\nusing namespace ncv;\n\nstatic void test_grad(const string_t& header, const string_t& loss_id, const model_t& model, scalar_t lambda)\n{\n random_t rand(2, 16);\n const size_t n_threads = 1 + (rand() % 2);\n\n accumulator_t acc_params(model, n_threads, accumulator_t::type::vgrad, lambda);\n rmodel_t rmodel_inputs = model.clone();\n\n const size_t n_tests = 64;\n const size_t n_samples = rand();\n\n const rloss_t rloss = loss_manager_t::instance().get(loss_id);\n const loss_t& loss = *rloss;\n\n const size_t psize = model.psize();\n const size_t isize = model.isize();\n const size_t osize = model.osize();\n\n vector_t params(psize);\n vectors_t targets(n_samples, vector_t(osize));\n tensors_t inputs(n_samples, tensor_t(model.idims(), model.irows(), model.icols()));\n\n \/\/ optimization problem (wrt parameters & inputs): size\n auto fn_params_size = [&] ()\n {\n return psize;\n };\n\n auto fn_inputs_size = [&] ()\n {\n return isize;\n };\n\n \/\/ optimization problem (wrt parameters & inputs): function value\n auto fn_params_fval = [&] (const vector_t& x)\n {\n acc_params.reset(x);\n acc_params.update(inputs, targets, loss);\n\n return acc_params.value();\n };\n\n auto fn_inputs_fval = [&] (const vector_t& x)\n {\n rmodel_inputs->load_params(params);\n\n const vector_t target = targets[0];\n const vector_t output = rmodel_inputs->forward(x).vector();\n\n return loss.value(target, output);\n };\n\n \/\/ optimization problem (wrt parameters & inputs): function value & gradient\n auto fn_params_grad = [&] (const vector_t& x, vector_t& gx)\n {\n acc_params.reset(x);\n acc_params.update(inputs, targets, loss);\n\n gx = acc_params.vgrad();\n return acc_params.value();\n };\n\n auto fn_inputs_grad = [&] (const vector_t& x, vector_t& gx)\n {\n rmodel_inputs->load_params(params);\n\n const vector_t target = targets[0];\n const vector_t output = rmodel_inputs->forward(x).vector();\n\n gx = rmodel_inputs->backward(loss.vgrad(target, output)).vector();\n return loss.value(target, output);\n };\n\n \/\/ construct optimization problem: analytic gradient and finite difference approximation\n const opt_problem_t problem_analytic_params(fn_params_size, fn_params_fval, fn_params_grad);\n const opt_problem_t problem_aproxdif_params(fn_params_size, fn_params_fval);\n\n const opt_problem_t problem_analytic_inputs(fn_inputs_size, fn_inputs_fval, fn_inputs_grad);\n const opt_problem_t problem_aproxdif_inputs(fn_inputs_size, fn_inputs_fval);\n\n for (size_t t = 0; t < n_tests; t ++)\n {\n random_t prgen(-1.0, +1.0); \n random_t irgen(-0.1, +0.1);\n random_t trgen(0, osize - 1);\n\n prgen(params.data(), params.data() + psize);\n for (vector_t& target : targets)\n {\n target = ncv::class_target(trgen(), osize);\n }\n for (tensor_t& input : inputs)\n {\n irgen(input.data(), input.data() + isize);\n }\n\n vector_t analytic_params_grad, aproxdif_params_grad;\n vector_t analytic_inputs_grad, aproxdif_inputs_grad;\n\n problem_analytic_params(params, analytic_params_grad);\n problem_aproxdif_params(params, aproxdif_params_grad);\n\n problem_analytic_inputs(inputs[0].vector(), analytic_inputs_grad);\n problem_aproxdif_inputs(inputs[0].vector(), aproxdif_inputs_grad);\n\n const scalar_t dg_params = (analytic_params_grad - aproxdif_params_grad).lpNorm();\n const scalar_t dg_inputs = (analytic_inputs_grad - aproxdif_inputs_grad).lpNorm();\n\n const scalar_t eps = 1e-6;\n\n log_info() << header << \" [\" << (t + 1) << \"\/\" << n_tests\n << \"]: samples = \" << n_samples\n << \", dg_params = \" << dg_params << \" (\" << (dg_params > eps ? \"ERROR\" : \"OK\") << \")\"\n << \", dg_inputs = \" << dg_inputs << \" (\" << (dg_inputs > eps ? \"ERROR\" : \"OK\") << \").\";\n }\n}\n\nstatic void test_grad(const string_t& header, const string_t& loss_id, const model_t& model)\n{\n const scalars_t lambdas = { 0.0, 1e-3, 1e-2, 1e-1, 1.0 };\n for (scalar_t lambda : lambdas)\n {\n test_grad(header, loss_id, model, lambda);\n }\n}\n\nint main(int argc, char *argv[])\n{\n ncv::init();\n\n const strings_t conv_layer_ids { \"\", \"conv\" };\n const strings_t pool_layer_ids { \"\", \"pool-max\", \"pool-min\", \"pool-avg\" };\n const strings_t full_layer_ids { \"\", \"linear\" };\n const strings_t actv_layer_ids { \"\", \"act-unit\", \"act-tanh\", \"act-snorm\", \"act-splus\" };\n const strings_t loss_ids = loss_manager_t::instance().ids();\n\n const color_mode cmd_color = color_mode::luma;\n const size_t cmd_irows = 10;\n const size_t cmd_icols = 10;\n const size_t cmd_outputs = 4;\n const size_t cmd_max_layers = 2;\n\n \/\/ evaluate the analytical gradient vs. the finite difference approximation for various:\n \/\/ * convolution layers\n \/\/ * pooling layers\n \/\/ * fully connected layers\n \/\/ * activation layers\n std::set descs;\n for (size_t n_layers = 0; n_layers <= cmd_max_layers; n_layers ++)\n {\n for (const string_t& actv_layer_id : actv_layer_ids)\n {\n for (const string_t& pool_layer_id : pool_layer_ids)\n {\n for (const string_t& conv_layer_id : conv_layer_ids)\n {\n for (const string_t& full_layer_id : full_layer_ids)\n {\n string_t desc;\n\n \/\/ convolution part\n for (size_t l = 0; l < n_layers && !conv_layer_id.empty(); l ++)\n {\n random_t rgen(2, 3);\n\n string_t params;\n params += \"dims=\" + text::to_string(rgen());\n params += (rgen() % 2 == 0) ? \",rows=3,cols=3\" : \",rows=4,cols=4\";\n\n desc += conv_layer_id + \":\" + params + \";\";\n desc += pool_layer_id + \";\";\n desc += actv_layer_id + \";\";\n }\n\n \/\/ fully-connected part\n for (size_t l = 0; l < n_layers && !full_layer_id.empty(); l ++)\n {\n random_t rgen(1, 8);\n\n string_t params;\n params += \"dims=\" + text::to_string(rgen());\n\n desc += full_layer_id + \":\" + params + \";\";\n desc += actv_layer_id + \";\";\n }\n\n desc += \"linear:dims=\" + text::to_string(cmd_outputs) + \";\";\n desc += \"softmax:type=global;\";\n\n descs.insert(desc);\n }\n }\n }\n }\n }\n\n for (const string_t& desc : descs)\n {\n \/\/ create network\n forward_network_t network(desc);\n network.resize(cmd_irows, cmd_icols, cmd_outputs, cmd_color, true);\n\n \/\/ test network\n for (const string_t& loss_id : loss_ids)\n {\n test_grad(\"[loss = \" + loss_id + \"]\", loss_id, network);\n }\n }\n\n \/\/ OK\n log_info() << done;\n return EXIT_SUCCESS;\n}\nsplit gradient checks for params & inputs#include \"nanocv.h\"\n#include \"models\/forward_network.h\"\n#include \n#include \n\nusing namespace ncv;\n\nstatic void test_grad_params(const string_t& header, const string_t& loss_id, const model_t& model, scalar_t lambda)\n{\n random_t rand(2, 16);\n const size_t n_threads = 1 + (rand() % 2);\n\n accumulator_t acc_params(model, n_threads, accumulator_t::type::vgrad, lambda);\n \n const size_t n_tests = 64;\n const size_t n_samples = rand();\n\n const rloss_t rloss = loss_manager_t::instance().get(loss_id);\n const loss_t& loss = *rloss;\n\n const size_t psize = model.psize();\n const size_t isize = model.isize();\n const size_t osize = model.osize();\n\n vector_t params(psize);\n vectors_t targets(n_samples, vector_t(osize));\n tensors_t inputs(n_samples, tensor_t(model.idims(), model.irows(), model.icols()));\n\n \/\/ optimization problem (wrt parameters & inputs): size\n auto fn_params_size = [&] ()\n {\n return psize;\n };\n\n \/\/ optimization problem (wrt parameters & inputs): function value\n auto fn_params_fval = [&] (const vector_t& x)\n {\n acc_params.reset(x);\n acc_params.update(inputs, targets, loss);\n\n return acc_params.value();\n };\n\n \/\/ optimization problem (wrt parameters & inputs): function value & gradient\n auto fn_params_grad = [&] (const vector_t& x, vector_t& gx)\n {\n acc_params.reset(x);\n acc_params.update(inputs, targets, loss);\n\n gx = acc_params.vgrad();\n return acc_params.value();\n };\n\n \/\/ construct optimization problem: analytic gradient and finite difference approximation\n const opt_problem_t problem_analytic_params(fn_params_size, fn_params_fval, fn_params_grad);\n const opt_problem_t problem_aproxdif_params(fn_params_size, fn_params_fval);\n\n for (size_t t = 0; t < n_tests; t ++)\n {\n random_t prgen(-1.0, +1.0); \n random_t irgen(-0.1, +0.1);\n random_t trgen(0, osize - 1);\n\n prgen(params.data(), params.data() + psize);\n for (vector_t& target : targets)\n {\n target = ncv::class_target(trgen(), osize);\n }\n for (tensor_t& input : inputs)\n {\n irgen(input.data(), input.data() + isize);\n }\n\n vector_t analytic_params_grad, aproxdif_params_grad;\n\n problem_analytic_params(params, analytic_params_grad);\n problem_aproxdif_params(params, aproxdif_params_grad);\n\n const scalar_t dg_params = (analytic_params_grad - aproxdif_params_grad).lpNorm();\n const scalar_t eps = 1e-6;\n\n log_info() << header << \" [\" << (t + 1) << \"\/\" << n_tests\n << \"]: samples = \" << n_samples\n << \", dg_params = \" << dg_params << \" (\" << (dg_params > eps ? \"ERROR\" : \"OK\") << \").\";\n }\n}\n\nstatic void test_grad_inputs(const string_t& header, const string_t& loss_id, const model_t& model)\n{\n rmodel_t rmodel_inputs = model.clone();\n \n const size_t n_tests = 64;\n const size_t n_samples = rand();\n \n const rloss_t rloss = loss_manager_t::instance().get(loss_id);\n const loss_t& loss = *rloss;\n \n const size_t psize = model.psize();\n const size_t isize = model.isize();\n const size_t osize = model.osize();\n \n vector_t params(psize);\n vector_t target(osize);\n tensor_t input(model.idims(), model.irows(), model.icols());\n \n \/\/ optimization problem (wrt parameters & inputs): size\n auto fn_inputs_size = [&] ()\n {\n return isize;\n };\n \n \/\/ optimization problem (wrt parameters & inputs): function value\n auto fn_inputs_fval = [&] (const vector_t& x)\n {\n rmodel_inputs->load_params(params);\n \n const vector_t output = rmodel_inputs->forward(x).vector();\n \n return loss.value(target, output);\n };\n \n \/\/ optimization problem (wrt parameters & inputs): function value & gradient\n auto fn_inputs_grad = [&] (const vector_t& x, vector_t& gx)\n {\n rmodel_inputs->load_params(params);\n \n const vector_t output = rmodel_inputs->forward(x).vector();\n \n gx = rmodel_inputs->backward(loss.vgrad(target, output)).vector();\n return loss.value(target, output);\n };\n \n \/\/ construct optimization problem: analytic gradient and finite difference approximation\n const opt_problem_t problem_analytic_inputs(fn_inputs_size, fn_inputs_fval, fn_inputs_grad);\n const opt_problem_t problem_aproxdif_inputs(fn_inputs_size, fn_inputs_fval);\n \n for (size_t t = 0; t < n_tests; t ++)\n {\n random_t prgen(-1.0, +1.0); \n random_t irgen(-0.1, +0.1);\n random_t trgen(0, osize - 1);\n \n prgen(params.data(), params.data() + psize);\n target = ncv::class_target(trgen(), osize);\n irgen(input.data(), input.data() + isize);\n \n vector_t analytic_inputs_grad, aproxdif_inputs_grad;\n \n problem_analytic_inputs(input.vector(), analytic_inputs_grad);\n problem_aproxdif_inputs(input.vector(), aproxdif_inputs_grad);\n \n const scalar_t dg_inputs = (analytic_inputs_grad - aproxdif_inputs_grad).lpNorm(); \n const scalar_t eps = 1e-6;\n \n log_info() << header << \" [\" << (t + 1) << \"\/\" << n_tests\n << \"]: samples = \" << n_samples\n << \", dg_inputs = \" << dg_inputs << \" (\" << (dg_inputs > eps ? \"ERROR\" : \"OK\") << \").\";\n }\n}\n\nstatic void test_grad(const string_t& header, const string_t& loss_id, const model_t& model)\n{\n const scalars_t lambdas = { 0.0, 1e-3, 1e-2, 1e-1, 1.0 };\n for (scalar_t lambda : lambdas)\n {\n test_grad_params(header, loss_id, model, lambda);\n }\n \n test_grad_inputs(header, loss_id, model);\n}\n\nint main(int argc, char *argv[])\n{\n ncv::init();\n\n const strings_t conv_layer_ids { \"\", \"conv\" };\n const strings_t pool_layer_ids { \"\", \"pool-max\", \"pool-min\", \"pool-avg\" };\n const strings_t full_layer_ids { \"\", \"linear\" };\n const strings_t actv_layer_ids { \"\", \"act-unit\", \"act-tanh\", \"act-snorm\", \"act-splus\" };\n const strings_t loss_ids = loss_manager_t::instance().ids();\n\n const color_mode cmd_color = color_mode::luma;\n const size_t cmd_irows = 10;\n const size_t cmd_icols = 10;\n const size_t cmd_outputs = 4;\n const size_t cmd_max_layers = 2;\n\n \/\/ evaluate the analytical gradient vs. the finite difference approximation for various:\n \/\/ * convolution layers\n \/\/ * pooling layers\n \/\/ * fully connected layers\n \/\/ * activation layers\n std::set descs;\n for (size_t n_layers = 0; n_layers <= cmd_max_layers; n_layers ++)\n {\n for (const string_t& actv_layer_id : actv_layer_ids)\n {\n for (const string_t& pool_layer_id : pool_layer_ids)\n {\n for (const string_t& conv_layer_id : conv_layer_ids)\n {\n for (const string_t& full_layer_id : full_layer_ids)\n {\n string_t desc;\n\n \/\/ convolution part\n for (size_t l = 0; l < n_layers && !conv_layer_id.empty(); l ++)\n {\n random_t rgen(2, 3);\n\n string_t params;\n params += \"dims=\" + text::to_string(rgen());\n params += (rgen() % 2 == 0) ? \",rows=3,cols=3\" : \",rows=4,cols=4\";\n\n desc += conv_layer_id + \":\" + params + \";\";\n desc += pool_layer_id + \";\";\n desc += actv_layer_id + \";\";\n }\n\n \/\/ fully-connected part\n for (size_t l = 0; l < n_layers && !full_layer_id.empty(); l ++)\n {\n random_t rgen(1, 8);\n\n string_t params;\n params += \"dims=\" + text::to_string(rgen());\n\n desc += full_layer_id + \":\" + params + \";\";\n desc += actv_layer_id + \";\";\n }\n\n desc += \"linear:dims=\" + text::to_string(cmd_outputs) + \";\";\n desc += \"softmax:type=global;\";\n\n descs.insert(desc);\n }\n }\n }\n }\n }\n\n for (const string_t& desc : descs)\n {\n \/\/ create network\n forward_network_t network(desc);\n network.resize(cmd_irows, cmd_icols, cmd_outputs, cmd_color, true);\n\n \/\/ test network\n for (const string_t& loss_id : loss_ids)\n {\n test_grad(\"[loss = \" + loss_id + \"]\", loss_id, network);\n }\n }\n\n \/\/ OK\n log_info() << done;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \"WarlordState.h\"\n\n\nWarlordState::WarlordState()\n{\n}\n\n\nWarlordState::~WarlordState()\n{\n}\n\nvoid WarlordState::Init(shared_ptr &player, shared_ptr &game)\n{\n\tint redBuildings = 0;\n\tfor (size_t i = 0, blen = player->GetBuildings()->Size(); i < blen; ++i) {\n\t\tif (player->GetBuildings()->ShowCardByIndex(i).GetColor() == 4)\n\t\t\tredBuildings++;\n\t}\n\tif (redBuildings > 0) {\n\t\tint gold = game->RemoveGold(redBuildings);\n\t\tif (gold != -1) {\n\t\t\tplayer->AddGold(gold);\n\t\t\tplayer->GetClient()->writeline(\"You receive 1 gold coin for each red building, \" + std::to_string(gold) + \" gold received!\");\n\t\t}\n\t}\n\telse {\n\t\tplayer->GetClient()->writeline(\"You do not own any red buildings and therefor receive no gold\");\n\t}\n}\n\nvoid WarlordState::Cleanup(shared_ptr &player, shared_ptr &game)\n{\n\n}\n\nvoid WarlordState::HandleEvents(shared_ptr &player, shared_ptr &game)\n{\n\n}\n\nvoid WarlordState::Update(shared_ptr &player, shared_ptr &game)\n{\n\tRender(player, \"Warlord\");\n\tResetChoices(player, game);\n\t_endTurn = false;\n\tint choice = -1;\n\twhile (!_endTurn) {\n\t\tdo {\n\t\t\tRenderChoices(player);\n\t\t\tchoice = HandleChoice(player, game, GetNumberOfChoices() - 1);\n\t\t} while (choice == -1);\n\t\tHandleTurn(player, game, choice);\n\t}\n}\n\nvoid WarlordState::UseAbility(shared_ptr &player, shared_ptr &game)\n{\n\tif (game->GetOpponent(player)->GetBuildings()->Size() >= 8) {\n\t\tplayer->GetClient()->writeline(\"Your opponent has built 8 or more buildings, you are not allowed to destroy his buildings!\");\n\t}\n\telse if (game->GetOpponent(player)->HasCharacterCard(\"Bishop\")) {\n\t\tplayer->GetClient()->writeline(\"Your opponent has the bishop card, you are not allowed to destroy his buildings!\");\n\t}\n\telse {\n\t\t\/\/ Print opponent cards\n\t\tLookAtOpponent(player, game);\n\n\t\tplayer->GetClient()->writeline(\"Which building do you want to destroy?\");\n\n\t\tint choice = -1;\n\t\tdo {\n\t\t\tchoice = HandleChoice(player, game, player->GetBuildings()->Size() - 1);\n\t\t} while (choice == -1);\n\n\t\tBuildingCard destroy = game->GetOpponent(player)->GetBuildings()->ShowCardByIndex(choice);\n\t\tif (destroy.GetName() == \"Dungeon\")\n\t\t\tplayer->GetClient()->writeline(\"A dungeon cannot be destroyed!\");\n\t\telse {\n\t\t\tif (destroy.GetValue() == 1)\n\t\t\t\tgame->GetOpponent(player)->DestroyByIndex(choice);\n\t\t\telse {\n\t\t\t\tint cost = destroy.GetValue() - 1;\n\t\t\t\tif (player->GetGoldAmount() >= cost) {\n\t\t\t\t\t\/\/ Player has enough gold to destroy building\n\t\t\t\t\tplayer->RemoveGold(cost);\n\t\t\t\t\tgame->AddGold(cost);\n\t\t\t\t\tgame->GetOpponent(player)->DestroyByIndex(choice);\n\t\t\t\t\tplayer->GetClient()->writeline(\"Building destroyed!\");\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ Not enough gold to destroy this building\n\t\t\t\t\tplayer->GetClient()->writeline(\"Not enough gold available to destroy this building!\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}restock card after destroy#include \"WarlordState.h\"\n\n\nWarlordState::WarlordState()\n{\n}\n\n\nWarlordState::~WarlordState()\n{\n}\n\nvoid WarlordState::Init(shared_ptr &player, shared_ptr &game)\n{\n\tint redBuildings = 0;\n\tfor (size_t i = 0, blen = player->GetBuildings()->Size(); i < blen; ++i) {\n\t\tif (player->GetBuildings()->ShowCardByIndex(i).GetColor() == 4)\n\t\t\tredBuildings++;\n\t}\n\tif (redBuildings > 0) {\n\t\tint gold = game->RemoveGold(redBuildings);\n\t\tif (gold != -1) {\n\t\t\tplayer->AddGold(gold);\n\t\t\tplayer->GetClient()->writeline(\"You receive 1 gold coin for each red building, \" + std::to_string(gold) + \" gold received!\");\n\t\t}\n\t}\n\telse {\n\t\tplayer->GetClient()->writeline(\"You do not own any red buildings and therefor receive no gold\");\n\t}\n}\n\nvoid WarlordState::Cleanup(shared_ptr &player, shared_ptr &game)\n{\n\n}\n\nvoid WarlordState::HandleEvents(shared_ptr &player, shared_ptr &game)\n{\n\n}\n\nvoid WarlordState::Update(shared_ptr &player, shared_ptr &game)\n{\n\tRender(player, \"Warlord\");\n\tResetChoices(player, game);\n\t_endTurn = false;\n\tint choice = -1;\n\twhile (!_endTurn) {\n\t\tdo {\n\t\t\tRenderChoices(player);\n\t\t\tchoice = HandleChoice(player, game, GetNumberOfChoices() - 1);\n\t\t} while (choice == -1);\n\t\tHandleTurn(player, game, choice);\n\t}\n}\n\nvoid WarlordState::UseAbility(shared_ptr &player, shared_ptr &game)\n{\n\tif (game->GetOpponent(player)->GetBuildings()->Size() >= 8) {\n\t\tplayer->GetClient()->writeline(\"Your opponent has built 8 or more buildings, you are not allowed to destroy his buildings!\");\n\t}\n\telse if (game->GetOpponent(player)->HasCharacterCard(\"Bishop\")) {\n\t\tplayer->GetClient()->writeline(\"Your opponent has the bishop card, you are not allowed to destroy his buildings!\");\n\t}\n\telse {\n\t\t\/\/ Print opponent cards\n\t\tLookAtOpponent(player, game);\n\n\t\tplayer->GetClient()->writeline(\"Which building do you want to destroy?\");\n\n\t\tint choice = -1;\n\t\tdo {\n\t\t\tchoice = HandleChoice(player, game, player->GetBuildings()->Size() - 1);\n\t\t} while (choice == -1);\n\n\t\tBuildingCard destroy = game->GetOpponent(player)->GetBuildings()->ShowCardByIndex(choice);\n\t\tif (destroy.GetName() == \"Dungeon\")\n\t\t\tplayer->GetClient()->writeline(\"A dungeon cannot be destroyed!\");\n\t\telse {\n\t\t\tif (destroy.GetValue() == 1)\n\t\t\t\tgame->GetOpponent(player)->DestroyByIndex(choice);\n\t\t\telse {\n\t\t\t\tint cost = destroy.GetValue() - 1;\n\t\t\t\tif (player->GetGoldAmount() >= cost) {\n\t\t\t\t\t\/\/ Player has enough gold to destroy building\n\t\t\t\t\tplayer->RemoveGold(cost);\n\t\t\t\t\tgame->AddGold(cost);\n\t\t\t\t\tBuildingCard card = game->GetOpponent(player)->GetBuildings()->GetCardByIndex(choice);\n\t\t\t\t\tgame->AddBuildingCard(card);\n\t\t\t\t\tplayer->GetClient()->writeline(\"Building destroyed!\");\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ Not enough gold to destroy this building\n\t\t\t\t\tplayer->GetClient()->writeline(\"Not enough gold available to destroy this building!\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"#include \n\nusing namespace sirius;\n\n\/\/ backward and forward transform of a random array\nvoid test1()\n{\n std::cout << \"test1\" << std::endl;\n sirius::Global global;\n\n double a1[] = {10, 10, 0};\n double a2[] = {0, 8, 3};\n double a3[] = {1, 7, 15};\n \/\/double a1[] = {42, 42, 0};\n \/\/double a2[] = {42, 0, 42};\n \/\/double a3[] = {0, 42, 42};\n \n global.set_lattice_vectors(a1, a2, a3);\n global.set_pw_cutoff(20.0);\n global.add_atom_type(1, \"H\");\n double pos[] = {0, 0, 0};\n double vf[] = {0, 0, 0};\n \n global.add_atom(1, pos, vf);\n \n global.initialize();\n \n std::cout << \"grid size : \" << global.fft().size() << std::endl;\n std::cout << \"dimensions : \" << global.fft().size(0) << \" \" \n << global.fft().size(1) << \" \" \n << global.fft().size(2) << std::endl;\n\n std::vector fft1(global.fft().size());\n std::vector fft2(global.fft().size());\n \n for (int i = 0; i < global.fft().size(); i++)\n {\n fft1[i] = complex16(double(rand()) \/ RAND_MAX, double(rand()) \/ RAND_MAX);\n fft2[i] = fft1[i];\n }\n \n sirius::Timer* t = new sirius::Timer(std::string(\"test1\"));\n global.fft().input(&fft1[0]);\n global.fft().transform(-1);\n global.fft().output(&fft1[0]);\n\n global.fft().input(&fft1[0]);\n global.fft().transform(1);\n global.fft().output(&fft1[0]);\n\n delete t;\n \n double d = 0.0;\n for (int i = 0; i < global.fft().size(); i++)\n d += abs(fft1[i] - fft2[i]);\n \n std::cout << \"total diff : \" << d << std::endl;\n}\n\n\/\/ transform of a single harmonic and comparison with an exact value \nvoid test2()\n{\n std::cout << \"test2\" << std::endl;\n double a1[] = {10, 0, -7};\n double a2[] = {0, 10, 20};\n double a3[] = {-9, -11, 10};\n\n sirius::Global global;\n\n global.set_lattice_vectors(a1, a2, a3);\n global.set_pw_cutoff(10.0);\n \n global.add_atom_type(1, \"H\");\n double pos[] = {0, 0, 0};\n double vf[] = {0, 0, 0};\n \n global.add_atom(1, pos, vf);\n \n global.initialize();\n\n std::cout << \"grid size : \" << global.fft().size() << std::endl;\n \n double d = 0.0;\n\n std::vector fft1(global.fft().size());\n for (int i0 = -2; i0 <= 2; i0++)\n for (int i1 = -2; i1 <= 2; i1++)\n for (int i2 = -2; i2 <= 2; i2++)\n {\n memset(&fft1[0], 0, fft1.size() * sizeof(complex16));\n fft1[global.fft().index(i0, i1, i2)] = complex16(1.0, 0.0);\n global.fft().input(&fft1[0]);\n global.fft().transform(1);\n global.fft().output(&fft1[0]);\n\n double gv[3];\n int fgv[] = {i0, i1, i2};\n global.get_coordinates(fgv, gv);\n\n mdarray fft2(&fft1[0], global.fft().size(0), global.fft().size(1), global.fft().size(2));\n for (int j0 = 0; j0 < global.fft().size(0); j0++)\n for (int j1 = 0; j1 < global.fft().size(1); j1++)\n for (int j2 = 0; j2 < global.fft().size(2); j2++)\n {\n double frv[] = {double(j0) \/ global.fft().size(0), \n double(j1) \/ global.fft().size(1), \n double(j2) \/ global.fft().size(2)};\n double rv[3];\n global.get_coordinates(frv, rv);\n d += abs(fft2(j0, j1, j2) - exp(complex16(0.0, Utils::scalar_product(rv, gv))));\n }\n }\n\n std::cout << \"total diff : \" << d << std::endl;\n}\n\nint main(int argn, char **argv)\n{\n Platform::initialize(1);\n test1();\n test2();\n sirius::Timer::print();\n}\nclean fft test#include \n\nusing namespace sirius;\n\n\/\/ backward and forward transform of a random array\nvoid test1()\n{\n printf(\"\\ntest1: backward and forward transform of a random array\\n\");\n \n Global global;\n\n double a1[] = {10, 10, 0};\n double a2[] = {0, 8, 3};\n double a3[] = {1, 7, 15};\n \n global.set_lattice_vectors(a1, a2, a3);\n global.set_pw_cutoff(20.0);\n global.add_atom_type(1, \"Si\");\n double pos[] = {0, 0, 0};\n \n global.add_atom(1, pos);\n \n global.initialize(1);\n \n global.Reciprocal_lattice::print_info();\n \n std::vector fft1(global.fft().size());\n std::vector fft2(global.fft().size());\n \n for (int i = 0; i < global.fft().size(); i++)\n {\n fft1[i] = complex16(double(rand()) \/ RAND_MAX, double(rand()) \/ RAND_MAX);\n fft2[i] = fft1[i];\n }\n \n Timer t(\"fft::transform|-1,+1\");\n global.fft().input(&fft1[0]);\n global.fft().transform(-1);\n global.fft().output(&fft1[0]);\n \n global.fft().input(&fft1[0]);\n global.fft().transform(1);\n global.fft().output(&fft1[0]);\n t.stop();\n\n double d = 0.0;\n for (int i = 0; i < global.fft().size(); i++) d += pow(abs(fft1[i] - fft2[i]), 2);\n d = sqrt(d \/ global.fft().size());\n printf(\"\\nRMS difference : %18.10e\", d);\n if (d < 1e-10)\n {\n printf(\" OK\\n\");\n }\n else\n {\n printf(\" Fail\\n\");\n }\n \n Timer::print();\n Timer::clear();\n}\n\nvoid test2()\n{\n printf(\"\\ntest2: straightforward transform of a single harmonic and comparison with FFT result\\n\");\n double a1[] = {10, 0, -7};\n double a2[] = {0, 10, 20};\n double a3[] = {-9, -11, 10};\n\n Global global;\n\n global.set_lattice_vectors(a1, a2, a3);\n global.set_pw_cutoff(10.0);\n \n global.add_atom_type(1, \"Si\");\n double pos[] = {0, 0, 0};\n \n global.add_atom(1, pos);\n \n global.initialize(1);\n \n global.Reciprocal_lattice::print_info();\n printf(\"\\n\");\n\n std::vector fft1(global.fft().size());\n\n \/\/ loop over lowest harmonics in reciprocal space\n for (int i0 = -2; i0 <= 2; i0++)\n {\n for (int i1 = -2; i1 <= 2; i1++)\n {\n for (int i2 = -2; i2 <= 2; i2++)\n {\n double d = 0.0;\n \n memset(&fft1[0], 0, fft1.size() * sizeof(complex16));\n \/\/ load a single harmonic\n fft1[global.fft().index(i0, i1, i2)] = complex16(1.0, 0.0);\n global.fft().input(&fft1[0]);\n global.fft().transform(1);\n global.fft().output(&fft1[0]);\n\n double gv[3];\n int fgv[] = {i0, i1, i2};\n global.get_coordinates(fgv, gv);\n\n \/\/ map FFT buffer to a 3D array\n mdarray fft2(&fft1[0], global.fft().size(0), global.fft().size(1), global.fft().size(2));\n\n \/\/ loop over 3D array (real space)\n for (int j0 = 0; j0 < global.fft().size(0); j0++)\n {\n for (int j1 = 0; j1 < global.fft().size(1); j1++)\n {\n for (int j2 = 0; j2 < global.fft().size(2); j2++)\n {\n \/\/ get real space fractional coordinate\n double frv[] = {double(j0) \/ global.fft().size(0), \n double(j1) \/ global.fft().size(1), \n double(j2) \/ global.fft().size(2)};\n double rv[3];\n global.get_coordinates(frv, rv);\n d += pow(abs(fft2(j0, j1, j2) - exp(complex16(0.0, Utils::scalar_product(rv, gv)))), 2);\n }\n }\n }\n d = sqrt(d \/ global.fft().size());\n printf(\"harmonic %4i %4i %4i, RMS difference : %18.10e\", i0, i1, i2, d);\n if (d < 1e-10)\n {\n printf(\" OK\\n\");\n }\n else\n {\n printf(\" Fail\\n\");\n }\n }\n }\n }\n \n Timer::print();\n Timer::clear();\n}\n\nvoid test3()\n{\n printf(\"\\ntest3: show timers for large unit cell FFT\\n\");\n double a1[] = {60, 0, 0};\n double a2[] = {0, 60, 0};\n double a3[] = {0, 0, 60};\n Global global;\n \n global.set_lattice_vectors(a1, a2, a3);\n global.set_pw_cutoff(9.0);\n global.add_atom_type(1, \"Si\");\n double pos[] = {0, 0, 0};\n \n global.add_atom(1, pos);\n global.initialize(1);\n global.Reciprocal_lattice::print_info();\n\n Timer t(\"fft::transform\");\n global.fft().transform(1);\n t.stop();\n \n Timer::print();\n Timer::clear();\n}\n\nint main(int argn, char **argv)\n{\n Platform::set_num_fft_threads(1);\n Platform::initialize(1);\n test1();\n test2();\n test3();\n}\n<|endoftext|>"} {"text":"\/*\n Auto away-presence setter-class\n Copyright (C) 2011 Martin Klapetek \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"autoaway.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"common\/global-presence.h\"\n\nAutoAway::AutoAway(GlobalPresence* globalPresence, QObject* parent)\n : TelepathyKDEDModulePlugin(globalPresence, parent),\n m_awayTimeoutId(-1),\n m_extAwayTimeoutId(-1)\n{\n setPluginPriority(99);\n readConfig();\n\n connect(KIdleTime::instance(), SIGNAL(timeoutReached(int)),\n this, SLOT(timeoutReached(int)));\n\n connect(KIdleTime::instance(), SIGNAL(resumingFromIdle()),\n this, SLOT(backFromIdle()));\n}\n\nAutoAway::~AutoAway()\n{\n}\n\nvoid AutoAway::timeoutReached(int id)\n{\n if (!isEnabled()) {\n return;\n }\n KIdleTime::instance()->catchNextResumeEvent();\n if (id == m_awayTimeoutId) {\n if (m_globalPresence->currentPresence().type() != Tp::Presence::away().type() ||\n m_globalPresence->currentPresence().type() != Tp::Presence::xa().type() ||\n m_globalPresence->currentPresence().type() != Tp::Presence::hidden().type()) {\n\n setRequestedPresence(Tp::Presence::away());\n setActive(true);\n } else if (id == m_extAwayTimeoutId) {\n if (m_globalPresence->currentPresence().type() == Tp::Presence::away().type()) {\n setRequestedPresence(Tp::Presence::xa());\n setActive(true);\n }\n }\n }\n}\n\nvoid AutoAway::backFromIdle()\n{\n kDebug();\n setActive(false);\n}\n\nvoid AutoAway::readConfig()\n{\n KSharedConfigPtr config = KSharedConfig::openConfig(QLatin1String(\"ktelepathyrc\"));\n KConfigGroup kdedConfig = config->group(\"KDED\");\n\n bool autoAwayEnabled = kdedConfig.readEntry(\"autoAwayEnabled\", true);\n bool autoXAEnabled = kdedConfig.readEntry(\"autoXAEnabled\", true);\n\n \/\/remove all our timeouts and only readd them if auto-away is enabled\n \/\/WARNING: can't use removeAllTimeouts because this runs inside KDED, it would remove other KDED timeouts as well\n KIdleTime::instance()->removeIdleTimeout(m_awayTimeoutId);\n KIdleTime::instance()->removeIdleTimeout(m_extAwayTimeoutId);\n\n if (autoAwayEnabled) {\n int awayTime = kdedConfig.readEntry(\"awayAfter\", 5);\n m_awayTimeoutId = KIdleTime::instance()->addIdleTimeout(awayTime * 60 * 1000);\n setEnabled(true);\n } else {\n setEnabled(false);\n }\n if (autoAwayEnabled && autoXAEnabled) {\n int xaTime = kdedConfig.readEntry(\"xaAfter\", 15);\n m_extAwayTimeoutId = KIdleTime::instance()->addIdleTimeout(xaTime * 60 * 1000);\n }\n}\n\nvoid AutoAway::onSettingsChanged()\n{\n readConfig();\n}\nFix auto-setting presence to Not Available, which didn't work because of a badly positioned bracket\/*\n Auto away-presence setter-class\n Copyright (C) 2011 Martin Klapetek \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"autoaway.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"common\/global-presence.h\"\n\nAutoAway::AutoAway(GlobalPresence* globalPresence, QObject* parent)\n : TelepathyKDEDModulePlugin(globalPresence, parent),\n m_awayTimeoutId(-1),\n m_extAwayTimeoutId(-1)\n{\n setPluginPriority(99);\n readConfig();\n\n connect(KIdleTime::instance(), SIGNAL(timeoutReached(int)),\n this, SLOT(timeoutReached(int)));\n\n connect(KIdleTime::instance(), SIGNAL(resumingFromIdle()),\n this, SLOT(backFromIdle()));\n}\n\nAutoAway::~AutoAway()\n{\n}\n\nvoid AutoAway::timeoutReached(int id)\n{\n if (!isEnabled()) {\n return;\n }\n KIdleTime::instance()->catchNextResumeEvent();\n if (id == m_awayTimeoutId) {\n if (m_globalPresence->currentPresence().type() != Tp::Presence::away().type() ||\n m_globalPresence->currentPresence().type() != Tp::Presence::xa().type() ||\n m_globalPresence->currentPresence().type() != Tp::Presence::hidden().type()) {\n\n setRequestedPresence(Tp::Presence::away());\n setActive(true);\n }\n } else if (id == m_extAwayTimeoutId) {\n if (m_globalPresence->currentPresence().type() == Tp::Presence::away().type()) {\n setRequestedPresence(Tp::Presence::xa());\n setActive(true);\n }\n }\n}\n\nvoid AutoAway::backFromIdle()\n{\n kDebug();\n setActive(false);\n}\n\nvoid AutoAway::readConfig()\n{\n KSharedConfigPtr config = KSharedConfig::openConfig(QLatin1String(\"ktelepathyrc\"));\n KConfigGroup kdedConfig = config->group(\"KDED\");\n\n bool autoAwayEnabled = kdedConfig.readEntry(\"autoAwayEnabled\", true);\n bool autoXAEnabled = kdedConfig.readEntry(\"autoXAEnabled\", true);\n\n \/\/remove all our timeouts and only readd them if auto-away is enabled\n \/\/WARNING: can't use removeAllTimeouts because this runs inside KDED, it would remove other KDED timeouts as well\n KIdleTime::instance()->removeIdleTimeout(m_awayTimeoutId);\n KIdleTime::instance()->removeIdleTimeout(m_extAwayTimeoutId);\n\n if (autoAwayEnabled) {\n int awayTime = kdedConfig.readEntry(\"awayAfter\", 5);\n m_awayTimeoutId = KIdleTime::instance()->addIdleTimeout(awayTime * 60 * 1000);\n setEnabled(true);\n } else {\n setEnabled(false);\n }\n if (autoAwayEnabled && autoXAEnabled) {\n int xaTime = kdedConfig.readEntry(\"xaAfter\", 15);\n m_extAwayTimeoutId = KIdleTime::instance()->addIdleTimeout(xaTime * 60 * 1000);\n }\n}\n\nvoid AutoAway::onSettingsChanged()\n{\n readConfig();\n}\n<|endoftext|>"} {"text":"\/*\n* Top Level window for KArm.\n* Distributed under the GPL.\n*\/\n\n\n\/* \n * $Id$\n *\/\n\n#include \"top.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kaccelmenuwatch.h\"\n#include \"karm.h\"\n#include \"print.h\"\n#include \"docking.h\"\n#include \"preferences.h\"\n\nKarmWindow::KarmWindow()\n : KMainWindow(0),\n\t_accel( new KAccel( this ) ),\n\t_watcher( new KAccelMenuWatch( _accel, this ) ),\n\t_karm( new Karm( this ) ),\n\t_totalTime( 0 ) \n{\n setCentralWidget( _karm );\n connect( _karm, SIGNAL( sessionTimeChanged( long ) ),\n\t\t this, SLOT( updateTime( long ) ) );\n\n \/\/ status bar\n\t\n statusBar()->insertItem( i18n( \"This session: %1\" )\n .arg(QString::fromLatin1(\"0:00\")), 0, 0, true );\n\n \/\/ setup PreferenceDialog.\n _preferences = Preferences::instance();\n \n \/\/ popup menus\n makeMenus();\n _watcher->updateMenus();\n\n \/\/ connections\n connect( _karm, SIGNAL(timerTick()), this, SLOT(updateTime()));\n \n _preferences->load();\n loadGeometry();\n\n \/\/ FIXME: this shouldnt stay. We need to check whether the\n \/\/ file exists and if not, create a blank one and ask whether\n \/\/ we want to add a task.\n _karm->load();\n\n DockWidget *dockWidget = new DockWidget(this,\"doc widget\");\n dockWidget->show();\n}\n\nvoid KarmWindow::save() \n{\n _karm->save();\n saveGeometry();\n}\n\nvoid KarmWindow::quit()\n{\n save();\n kapp->quit();\n}\n\n\t\nKarmWindow::~KarmWindow()\n{\n quit();\n}\n\n\/**\n * Updates the total time tally by one minute.\n *\/\nvoid KarmWindow::updateTime()\n{\n _totalTime++;\n updateStatusBar();\n}\n\n\/**\n * Updates the total time tally by the value specified in newval.\n *\/\nvoid KarmWindow::updateTime( long difference )\n{\n _totalTime += difference;\n updateStatusBar();\n}\n\nvoid KarmWindow::updateStatusBar()\n{\n QString time = Karm::formatTime( _totalTime );\n statusBar()->changeItem( i18n(\"This session: %1\" ).arg(time), 0);\n}\n\nvoid KarmWindow::saveProperties( KConfig* )\n{\n _karm->save();\n}\n\nvoid KarmWindow::keyBindings()\n{\n KKeyDialog::configureKeys( actionCollection(), xmlFile());\n}\n\nvoid KarmWindow::resetSessionTime()\n{\n _totalTime = 0;\n statusBar()->changeItem( i18n(\"This session: %1\").arg(QString::fromLatin1(\"0:00\")), 0 );\n\t_karm->resetSessionTimeForAllTasks();\n}\n\n\nvoid KarmWindow::makeMenus()\n{\n KAction \n *actionKeyBindings,\n *actionResetSession,\n *actionStart,\n *actionStop,\n *actionNew,\n *actionNewSub,\n *actionDelete,\n *actionEdit;\n \n (void) KStdAction::quit(this, SLOT(quit()), actionCollection());\n (void) KStdAction::print(this, SLOT(print()), actionCollection());\n actionKeyBindings = KStdAction::keyBindings(this, SLOT(keyBindings()),actionCollection());\n (void) KStdAction::preferences(_preferences, SLOT(showDialog()),actionCollection());\n (void) KStdAction::save(_preferences, SLOT(save()),actionCollection());\n actionResetSession = new KAction(i18n(\"&Reset Session Time\"), CTRL + Key_R,this,\n SLOT(resetSessionTime()),actionCollection(),\n \"reset_session_time\");\n actionStart = new KAction(i18n(\"&Start\"), QString::fromLatin1(\"1rightarrow\"),\n CTRL + Key_S ,_karm,\n SLOT(startTimer()),actionCollection(),\"start\");\n actionStop = new KAction(i18n(\"S&top\"), QString::fromLatin1(\"stop\"),\n CTRL + Key_T,_karm,\n SLOT(stopCurrentTimer()),actionCollection(),\"stop\");\n actionNew = KStdAction::action( KStdAction::New, _karm,\tSLOT(newTask()),\n actionCollection(),\"new_task\");\n actionNewSub = new KAction(i18n(\"New Subtask\"), QString::fromLatin1(\"kmultiple\"),\n CTRL+ALT+Key_N,\n _karm, SLOT(newSubTask()),\n actionCollection(), \"new_sub_task\");\n actionDelete = new KAction(i18n(\"&Delete\"), QString::fromLatin1(\"editdelete\"),\n Key_Delete,_karm,\n SLOT(deleteTask()),actionCollection(),\"delete_task\");\n actionEdit = new KAction(i18n(\"&Edit\"), QString::fromLatin1(\"edit\"),\n CTRL + Key_E,_karm,\n SLOT(editTask()),actionCollection(),\"edit_task\");\n createGUI( QString::fromLatin1(\"karmui.rc\") );\n \n \/\/ Tool tops must be set after the createGUI.\n actionKeyBindings->setToolTip(i18n(\"Configure key bindings\"));\n actionKeyBindings->setWhatsThis(i18n(\"This will let you configure keybindings which is specific to karm\"));\n\n actionResetSession->setToolTip(i18n(\"Reset session time\"));\n actionResetSession->setWhatsThis(i18n(\"This will reset the session time for all tasks.\"));\n \n actionStart->setToolTip(i18n(\"Start timing for selected task\"));\n actionStart->setWhatsThis(i18n(\"This will start timing for the selected task.\\n\"\n \"It is even possible to time several tasks simultaneously.\\n\\n\"\n \"You may also start timing of a tasks by double clicking the left mouse \"\n \"button on a given task. This will, however, stop timing of other tasks.\"));\n \t\n actionStop->setToolTip(i18n(\"Stop timing of the selected task\"));\n actionStop->setWhatsThis(i18n(\"Stop timing of the selected task\"));\n\n actionNew->setToolTip(i18n(\"Create new top level task\"));\n actionNew->setWhatsThis(i18n(\"This will create a new top level task.\")); \n\n actionDelete->setToolTip(i18n(\"Delete selected task\"));\n actionDelete->setWhatsThis(i18n(\"This will delete the selected task and all its subtasks.\"));\n \t\n actionEdit->setToolTip(i18n(\"Edit name or times for selected task\"));\n actionEdit->setWhatsThis(i18n(\"This will bring up a dialog box where you may edit the parameters for the selected task.\"));\n}\n\nvoid KarmWindow::print() \n{\n MyPrinter printer(_karm);\n printer.print();\n}\n\nvoid KarmWindow::loadGeometry()\n{\n KConfig &config = *kapp->config();\n \n config.setGroup( QString::fromLatin1(\"Main Window Geometry\") );\n int w = config.readNumEntry( QString::fromLatin1(\"Width\"), 100 );\n int h = config.readNumEntry( QString::fromLatin1(\"Height\"), 100 );\n w = QMAX( w, sizeHint().width() );\n h = QMAX( h, sizeHint().height() );\n resize(w, h);\n}\n\n\nvoid KarmWindow::saveGeometry()\n{\n KConfig &config = *KGlobal::config();\n config.setGroup( QString::fromLatin1(\"Main Window Geometry\"));\n config.writeEntry( QString::fromLatin1(\"Width\"), width());\n config.writeEntry( QString::fromLatin1(\"Height\"), height());\n config.sync();\n}\n\n#include \"top.moc\"\nShortcut for Start changed from \"Ctrl-S\" to \"S\" Shortcut for Stop changed from \"Ctrl-T\" to \"ESC\"\/*\n* Top Level window for KArm.\n* Distributed under the GPL.\n*\/\n\n\n\/* \n * $Id$\n *\/\n\n#include \"top.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kaccelmenuwatch.h\"\n#include \"karm.h\"\n#include \"print.h\"\n#include \"docking.h\"\n#include \"preferences.h\"\n\nKarmWindow::KarmWindow()\n : KMainWindow(0),\n\t_accel( new KAccel( this ) ),\n\t_watcher( new KAccelMenuWatch( _accel, this ) ),\n\t_karm( new Karm( this ) ),\n\t_totalTime( 0 ) \n{\n setCentralWidget( _karm );\n connect( _karm, SIGNAL( sessionTimeChanged( long ) ),\n\t\t this, SLOT( updateTime( long ) ) );\n\n \/\/ status bar\n\t\n statusBar()->insertItem( i18n( \"This session: %1\" )\n .arg(QString::fromLatin1(\"0:00\")), 0, 0, true );\n\n \/\/ setup PreferenceDialog.\n _preferences = Preferences::instance();\n \n \/\/ popup menus\n makeMenus();\n _watcher->updateMenus();\n\n \/\/ connections\n connect( _karm, SIGNAL(timerTick()), this, SLOT(updateTime()));\n \n _preferences->load();\n loadGeometry();\n\n \/\/ FIXME: this shouldnt stay. We need to check whether the\n \/\/ file exists and if not, create a blank one and ask whether\n \/\/ we want to add a task.\n _karm->load();\n\n DockWidget *dockWidget = new DockWidget(this,\"doc widget\");\n dockWidget->show();\n}\n\nvoid KarmWindow::save() \n{\n _karm->save();\n saveGeometry();\n}\n\nvoid KarmWindow::quit()\n{\n save();\n kapp->quit();\n}\n\n\t\nKarmWindow::~KarmWindow()\n{\n quit();\n}\n\n\/**\n * Updates the total time tally by one minute.\n *\/\nvoid KarmWindow::updateTime()\n{\n _totalTime++;\n updateStatusBar();\n}\n\n\/**\n * Updates the total time tally by the value specified in newval.\n *\/\nvoid KarmWindow::updateTime( long difference )\n{\n _totalTime += difference;\n updateStatusBar();\n}\n\nvoid KarmWindow::updateStatusBar()\n{\n QString time = Karm::formatTime( _totalTime );\n statusBar()->changeItem( i18n(\"This session: %1\" ).arg(time), 0);\n}\n\nvoid KarmWindow::saveProperties( KConfig* )\n{\n _karm->save();\n}\n\nvoid KarmWindow::keyBindings()\n{\n KKeyDialog::configureKeys( actionCollection(), xmlFile());\n}\n\nvoid KarmWindow::resetSessionTime()\n{\n _totalTime = 0;\n statusBar()->changeItem( i18n(\"This session: %1\").arg(QString::fromLatin1(\"0:00\")), 0 );\n\t_karm->resetSessionTimeForAllTasks();\n}\n\n\nvoid KarmWindow::makeMenus()\n{\n KAction \n *actionKeyBindings,\n *actionResetSession,\n *actionStart,\n *actionStop,\n *actionNew,\n *actionNewSub,\n *actionDelete,\n *actionEdit;\n \n (void) KStdAction::quit(this, SLOT(quit()), actionCollection());\n (void) KStdAction::print(this, SLOT(print()), actionCollection());\n actionKeyBindings = KStdAction::keyBindings(this, SLOT(keyBindings()),actionCollection());\n (void) KStdAction::preferences(_preferences, SLOT(showDialog()),actionCollection());\n (void) KStdAction::save(_preferences, SLOT(save()),actionCollection());\n actionResetSession = new KAction(i18n(\"&Reset Session Time\"), CTRL + Key_R,this,\n SLOT(resetSessionTime()),actionCollection(),\n \"reset_session_time\");\n actionStart = new KAction(i18n(\"&Start\"), QString::fromLatin1(\"1rightarrow\"),\n Key_S ,_karm,\n SLOT(startTimer()),actionCollection(),\"start\");\n actionStop = new KAction(i18n(\"S&top\"), QString::fromLatin1(\"stop\"),\n Key_Escape,_karm,\n SLOT(stopCurrentTimer()),actionCollection(),\"stop\");\n actionNew = KStdAction::action( KStdAction::New, _karm,\tSLOT(newTask()),\n actionCollection(),\"new_task\");\n actionNewSub = new KAction(i18n(\"New Subtask\"), QString::fromLatin1(\"kmultiple\"),\n CTRL+ALT+Key_N,\n _karm, SLOT(newSubTask()),\n actionCollection(), \"new_sub_task\");\n actionDelete = new KAction(i18n(\"&Delete\"), QString::fromLatin1(\"editdelete\"),\n Key_Delete,_karm,\n SLOT(deleteTask()),actionCollection(),\"delete_task\");\n actionEdit = new KAction(i18n(\"&Edit\"), QString::fromLatin1(\"edit\"),\n CTRL + Key_E,_karm,\n SLOT(editTask()),actionCollection(),\"edit_task\");\n createGUI( QString::fromLatin1(\"karmui.rc\") );\n \n \/\/ Tool tops must be set after the createGUI.\n actionKeyBindings->setToolTip(i18n(\"Configure key bindings\"));\n actionKeyBindings->setWhatsThis(i18n(\"This will let you configure keybindings which is specific to karm\"));\n\n actionResetSession->setToolTip(i18n(\"Reset session time\"));\n actionResetSession->setWhatsThis(i18n(\"This will reset the session time for all tasks.\"));\n \n actionStart->setToolTip(i18n(\"Start timing for selected task\"));\n actionStart->setWhatsThis(i18n(\"This will start timing for the selected task.\\n\"\n \"It is even possible to time several tasks simultaneously.\\n\\n\"\n \"You may also start timing of a tasks by double clicking the left mouse \"\n \"button on a given task. This will, however, stop timing of other tasks.\"));\n \t\n actionStop->setToolTip(i18n(\"Stop timing of the selected task\"));\n actionStop->setWhatsThis(i18n(\"Stop timing of the selected task\"));\n\n actionNew->setToolTip(i18n(\"Create new top level task\"));\n actionNew->setWhatsThis(i18n(\"This will create a new top level task.\")); \n\n actionDelete->setToolTip(i18n(\"Delete selected task\"));\n actionDelete->setWhatsThis(i18n(\"This will delete the selected task and all its subtasks.\"));\n \t\n actionEdit->setToolTip(i18n(\"Edit name or times for selected task\"));\n actionEdit->setWhatsThis(i18n(\"This will bring up a dialog box where you may edit the parameters for the selected task.\"));\n}\n\nvoid KarmWindow::print() \n{\n MyPrinter printer(_karm);\n printer.print();\n}\n\nvoid KarmWindow::loadGeometry()\n{\n KConfig &config = *kapp->config();\n \n config.setGroup( QString::fromLatin1(\"Main Window Geometry\") );\n int w = config.readNumEntry( QString::fromLatin1(\"Width\"), 100 );\n int h = config.readNumEntry( QString::fromLatin1(\"Height\"), 100 );\n w = QMAX( w, sizeHint().width() );\n h = QMAX( h, sizeHint().height() );\n resize(w, h);\n}\n\n\nvoid KarmWindow::saveGeometry()\n{\n KConfig &config = *KGlobal::config();\n config.setGroup( QString::fromLatin1(\"Main Window Geometry\"));\n config.writeEntry( QString::fromLatin1(\"Width\"), width());\n config.writeEntry( QString::fromLatin1(\"Height\"), height());\n config.sync();\n}\n\n#include \"top.moc\"\n<|endoftext|>"} {"text":"\/**\n *\n * Terminology (Matroid - Graph) for escalated version of algorithm:\n * Basis - Spanning forest\n * Independent set - Tree (i.e. subset of a basis)\n * Circuit - cycle\n * Cocircuit - minimal edge-cut\n * Hyperplane - maximal set not containing any basis (= complement of a min-cut)\n *\n * Spanning forest - union of spanning trees of each component of an unconnected graph\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"helpers.hpp\"\n#include \"graphcoloring.h\"\n\nusing namespace std;\nusing namespace ogdf;\n\nint m; \/\/ Cocircuit size bound\n\n\/**\n * @brief Takes a csv file with lines \";;;;...\" and transforms it into graph\n * @param sEdgesFileName\n *\/\nvoid csvToGraph(string sEdgesFileName, Graph &G) {\n ifstream fEdges(sEdgesFileName);\n if (!fEdges.is_open())\n throw new invalid_argument(\"Edges file doesn't exist or could not be accessed\");\n\n vector nodes;\n int id, u, v, nSize = 0;\n\n for (string line; getline(fEdges, line);) {\n sscanf(line.c_str(), \"%d;%d;%d;\", &id, &u, &v);\n\n if (u > nSize) {\n nodes.resize(u + 1);\n nSize = u;\n }\n\n if (v > nSize) {\n nodes.resize(v + 1);\n nSize = v;\n }\n\n \/\/ Skip if there already is an edge between these two nodes\n \/*if (nodes.at(u) && nodes.at(v) &&\n (G.searchEdge(nodes.at(u), nodes.at(v)) || G.searchEdge(nodes.at(v), nodes.at(u)))) {\n continue;\n }*\/\n\n if(nodes.at(u) == nullptr)\n nodes[u] = G.newNode(u);\n\n if(nodes[v] == nullptr)\n nodes[v] = G.newNode(v);\n\n\n G.newEdge(nodes[u], nodes[v], id);\n }\n}\n\n\/**\n * Performs BFS to find the shortest path from s to t in graph G without using any edge from the forbidden edges.\n * Returns empty set if no such path exists.\n *\/\nList shortestPath(const Graph &G, const GraphColoring &coloring, node s, node t, const List &forbidden) {\n List path;\n node v, u;\n edge e;\n\n Queue Q;\n\n NodeArray visited(G, false);\n NodeArray predecessor(G);\n\n Q.append(s);\n visited[s] = true;\n\n while(!Q.empty()) {\n v = Q.pop();\n\n if (v == t) {\n \/\/ traceback predecessors and reconstruct path\n for (node n = t; n != s; n = predecessor[n]) {\n e = G.searchEdge(n, predecessor[n]); \/\/ Takes O(min(deg(v), deg(w))) (that's fast on sparse graphs)\n if (coloring[e] != Color::RED)\n path.pushFront(e);\n }\n break;\n }\n\n forall_adj_edges(e, v) {\n \/\/ TODO: Use BST or array (id -> bool) to represent forbidden and fasten the following search? (Probably not\n \/\/ necessary as forbidden size is bound by the constant m)\n if (forbidden.search(e).valid()) continue;\n\n u = e->opposite(v);\n if (!visited[u]) {\n predecessor[u] = v;\n visited[u] = true;\n Q.append(u);\n }\n }\n }\n\n return path;\n}\n\n\/**\n * @brief hideConnectedBlueSubgraph\n * @param G\n * @param coloring\n * @param u\n *\/\nvoid hideConnectedBlueSubgraph(Graph &G, const GraphColoring &coloring, node start) {\n Queue Q;\n Q.append(start);\n\n NodeArray visited(G, false);\n\n node u, v;\n edge e;\n while(!Q.empty()) {\n u = Q.pop();\n forall_adj_edges(e, u) {\n if (coloring[e] == Color::BLUE) {\n v = e->opposite(u);\n if (!visited[v]) {\n visited[v] = true;\n Q.append(v);\n }\n G.hideEdge(e);\n }\n }\n }\n}\n\nbool findPathToAnyBlueAndColorItBlue(const Graph &G, GraphColoring &coloring, node start) {\n Queue Q;\n Q.append(start);\n\n NodeArray visited(G, false);\n NodeArray accessEdge(G);\n\n node u, n;\n edge e;\n while(!Q.empty()) {\n u = Q.pop();\n\n if (coloring[u] == Color::BLUE && u != start) {\n \/\/ reconstruct path and go on\n edge ae;\n node n1, n2;\n for (n1 = u; n1 != start;) {\n \/\/ TODO: Use search edge instead?\n ae = accessEdge[n1];\n n2 = ae->opposite(n1);\n\n coloring[n1] = Color::BLUE;\n coloring[n2] = Color::BLUE;\n coloring[ae] = Color::BLUE;\n n1 = n2;\n }\n return true;\n }\n\n forall_adj_edges(e, u) {\n n = e->opposite(u);\n if (!visited[n]) {\n visited[n] = true;\n accessEdge[n] = e;\n Q.append(n);\n }\n }\n }\n\n return false;\n}\n\n\/**\n * @return bool True for successful reconnection, false otherwise\n *\/\nbool reconnectBlueSubgraph(Graph &G, const List &X, GraphColoring &coloring, node u, node v, edge c) {\n \/\/ if u has blue adjacent edges (except of c) AND v has blue adjacent edges (exc. of c) then\n \/\/ enumerate one blue subgraph, call it G_b1\n \/\/ create graph G_rest = G \\ X \\ G_r \\ G_b1 and BFS in it until blue is found (use hideEdge!)\n \/\/ (or BFS (avoid red and X) from u to first blue edge not in G_b1)\n \/\/ -> path found, color it blue and continue\n \/\/ -> path not found, fail here (return;)\n\n G.hideEdge(c); \/\/ Don't consider c\n\n bool uaIsEmpty = true, vaIsEmpty = true;\n edge e;\n\n forall_adj_edges(e, u) {\n if (coloring[e] == Color::BLUE) {\n uaIsEmpty = false;\n break;\n }\n }\n\n forall_adj_edges(e, v) {\n if (coloring[e] == Color::BLUE) {\n vaIsEmpty = false;\n break;\n }\n }\n\n if (!uaIsEmpty && !vaIsEmpty) {\n \/\/ G_b has been disconnected, hide X, G_r and one component of blue subgraph (TODO: Maintain G_rest through the whole algorithm and not recompute here every time?)\n for(List::const_iterator it = X.begin(); it != X.end(); it++) G.hideEdge(*it);\n forall_edges(e, G) { if(coloring[e] == Color::RED) G.hideEdge(e); }\n hideConnectedBlueSubgraph(G, coloring, u);\n\n \/\/ BFS in G from u to the first found blue edge\n \/\/ -> not found => fail here\n \/\/ -> path found => color it blue and continue\n\n if (!findPathToAnyBlueAndColorItBlue(G, coloring, u)) {\n G.restoreAllEdges();\n return false;\n }\n\n\n } \/\/ else c is just a branch with a single leaf, nothing happened G_b stays connected\n\n G.restoreAllEdges();\n return true;\n}\n\n\nvoid GenCocircuits(List> &Cocircuits, Graph &G, GraphColoring coloring, List X, node red, node blue) {\n if (X.size() > m) return;\n\n \/\/ Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \\ X\n List D = shortestPath(G, coloring, red, blue, X);\n\n if (D.size() > 0) {\n\n \/\/ for each c ∈ D, recursively call GenCocircuits(X ∪ {c}).\n for(List::iterator iterator = D.begin(); iterator != D.end(); iterator++) {\n edge c = *iterator;\n\n List newX = X;\n newX.pushBack(c);\n\n\n \/\/ Coloring red-c path red, determining u and v, coloring the rest blue\n node n1 = red, n2 = blue, \/\/ after the first of the following for cycles these are the\n \/\/ nodes of the last red edge (one of them has to be incident with c)\n \/\/ initialized to red and blue since the first for can have 0 iterations\n u, v; \/\/ c = (u,v), say u is red (and so will be all vertices on the path from the first red to u)\n\n for(List::iterator j = D.begin(); j != iterator; j++) {\n edge e = *j;\n\n n1 = e->source();\n n2 = e->target();\n\n coloring[n1] = Color::RED;\n coloring[n2] = Color::RED;\n }\n\n \/\/ Determine u, v, s.t. u is really red and v blue\n if (c->source() == n1 || c->target() == n1) { \/\/ if n1 is in c then n1 == u\n u = n1;\n } else { \/\/ n2 is in c so n2 == u\n u = n2;\n }\n\n v = c->opposite(u);\n\n \/\/ Color the rest of the path blue\n for(List::iterator j = iterator.succ(); j != D.end(); j++) {\n edge e = *j;\n\n coloring[e->source()] = Color::BLUE;\n coloring[e->target()] = Color::BLUE;\n }\n\n\n \/\/ If c = (u, v) is blue, reconnect blue subgraph (find the shortest path from u to v using only nonred edges)\n if (coloring[c] == Color::BLUE) {\n reconnectBlueSubgraph(G, X, coloring, u, v, c);\n }\n\n GenCocircuits(Cocircuits, G, coloring, newX, u, v);\n }\n\n } else {\n \/\/ If there is no such circuit C above (line 4), then return ‘Cocircuit: X’.\n Cocircuits.pushBack(X);\n }\n}\n\n\/**\n * Returns edges spanning forest of (possibly disconnected) graph G\n * @param G\n *\/\nList spanningEdges(const Graph &G) {\n EdgeArray isBackedge(G, false);\n\n List backedges;\n isAcyclicUndirected(G, backedges);\n\n for(List::iterator i = backedges.begin(); i != backedges.end(); i++) {\n isBackedge[*i] = true;\n }\n\n List spanningEdges;\n edge e;\n forall_edges(e, G) {\n if (!isBackedge[e]) {\n spanningEdges.pushBack(e);\n }\n }\n\n return spanningEdges;\n}\n\nvoid CircuitCocircuit(Graph &G, List> &cocircuits) {\n List base = spanningEdges(G);\n\n edge e;\n for(List::iterator i = base.begin(); i != base.end(); i++) {\n e = *i;\n List X; \/\/ (Indexes might be sufficient? Check later)\n GraphColoring coloring(G);\n X.pushBack(e);\n coloring[e->source()] = Color::RED;\n coloring[e->target()] = Color::BLUE;\n\n GenCocircuits(cocircuits, G, coloring, X, e->source(), e->target());\n }\n}\n\n\/\/ TODO: Read from stdin?\nint main(int argc, char* argv[])\n{\n if (argc != 3 || strcmp(argv[1], \"-h\") == 0 || strcmp(argv[1], \"--help\") == 0) {\n cout << \"Usage: \" << argv[0] << \" \" << endl;\n exit(1);\n }\n\n string graphFile(argv[1]);\n m = stoi(argv[2]);\n if (m < 1) {\n cerr << \"Cocircuit size bound lower than 1. Terminating.\" << endl;\n exit(2);\n }\n\n try {\n Graph G;\n csvToGraph(graphFile, G);\n\n\n List> cocircuits;\n CircuitCocircuit(G, cocircuits);\n\n for(List >::iterator it = cocircuits.begin(); it != cocircuits.end(); ++it) {\n cout << *it << endl;\n }\n\n\n } catch (invalid_argument *e) {\n cerr << \"Error: \" << e->what() << endl;\n return 1;\n }\n\n return 0;\n}\n\nKeep vertices colored\/**\n *\n * Terminology (Matroid - Graph) for escalated version of algorithm:\n * Basis - Spanning forest\n * Independent set - Tree (i.e. subset of a basis)\n * Circuit - cycle\n * Cocircuit - minimal edge-cut\n * Hyperplane - maximal set not containing any basis (= complement of a min-cut)\n *\n * Spanning forest - union of spanning trees of each component of an unconnected graph\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"helpers.hpp\"\n#include \"graphcoloring.h\"\n\nusing namespace std;\nusing namespace ogdf;\n\nint m; \/\/ Cocircuit size bound\n\n\/**\n * @brief Takes a csv file with lines \";;;;...\" and transforms it into graph\n * @param sEdgesFileName\n *\/\nvoid csvToGraph(string sEdgesFileName, Graph &G) {\n ifstream fEdges(sEdgesFileName);\n if (!fEdges.is_open())\n throw new invalid_argument(\"Edges file doesn't exist or could not be accessed\");\n\n vector nodes;\n int id, u, v, nSize = 0;\n\n for (string line; getline(fEdges, line);) {\n sscanf(line.c_str(), \"%d;%d;%d;\", &id, &u, &v);\n\n if (u > nSize) {\n nodes.resize(u + 1);\n nSize = u;\n }\n\n if (v > nSize) {\n nodes.resize(v + 1);\n nSize = v;\n }\n\n \/\/ Skip if there already is an edge between these two nodes\n \/*if (nodes.at(u) && nodes.at(v) &&\n (G.searchEdge(nodes.at(u), nodes.at(v)) || G.searchEdge(nodes.at(v), nodes.at(u)))) {\n continue;\n }*\/\n\n if(nodes.at(u) == nullptr)\n nodes[u] = G.newNode(u);\n\n if(nodes[v] == nullptr)\n nodes[v] = G.newNode(v);\n\n\n G.newEdge(nodes[u], nodes[v], id);\n }\n}\n\n\/**\n * Performs BFS to find the shortest path from s to t in graph G without using any edge from the forbidden edges.\n * Returns empty set if no such path exists.\n *\/\nList shortestPath(const Graph &G, const GraphColoring &coloring, node s, node t, const List &forbidden) {\n List path;\n node v, u;\n edge e;\n\n Queue Q;\n\n NodeArray visited(G, false);\n NodeArray predecessor(G);\n\n Q.append(s);\n visited[s] = true;\n\n while(!Q.empty()) {\n v = Q.pop();\n\n if (v == t) {\n \/\/ traceback predecessors and reconstruct path\n for (node n = t; n != s; n = predecessor[n]) {\n e = G.searchEdge(n, predecessor[n]); \/\/ Takes O(min(deg(v), deg(w))) (that's fast on sparse graphs)\n if (coloring[e] != Color::RED)\n path.pushFront(e);\n }\n break;\n }\n\n forall_adj_edges(e, v) {\n \/\/ TODO: Use BST or array (id -> bool) to represent forbidden and fasten the following search? (Probably not\n \/\/ necessary as forbidden size is bound by the constant m)\n if (forbidden.search(e).valid()) continue;\n\n u = e->opposite(v);\n if (!visited[u]) {\n predecessor[u] = v;\n visited[u] = true;\n Q.append(u);\n }\n }\n }\n\n return path;\n}\n\n\/**\n * @brief hideConnectedBlueSubgraph\n * @param G\n * @param coloring\n * @param u\n *\/\nvoid hideConnectedBlueSubgraph(Graph &G, const GraphColoring &coloring, node start) {\n Queue Q;\n Q.append(start);\n\n NodeArray visited(G, false);\n\n node u, v;\n edge e;\n while(!Q.empty()) {\n u = Q.pop();\n forall_adj_edges(e, u) {\n if (coloring[e] == Color::BLUE) {\n v = e->opposite(u);\n if (!visited[v]) {\n visited[v] = true;\n Q.append(v);\n }\n G.hideEdge(e);\n }\n }\n }\n}\n\nbool findPathToAnyBlueAndColorItBlue(const Graph &G, GraphColoring &coloring, node start) {\n Queue Q;\n Q.append(start);\n\n NodeArray visited(G, false);\n NodeArray accessEdge(G);\n\n node u, n;\n edge e;\n while(!Q.empty()) {\n u = Q.pop();\n\n if (coloring[u] == Color::BLUE && u != start) {\n \/\/ reconstruct path and go on\n edge ae;\n node n1, n2;\n for (n1 = u; n1 != start;) {\n \/\/ TODO: Use search edge instead?\n ae = accessEdge[n1];\n n2 = ae->opposite(n1);\n\n coloring[n1] = Color::BLUE;\n coloring[n2] = Color::BLUE;\n coloring[ae] = Color::BLUE;\n n1 = n2;\n }\n return true;\n }\n\n forall_adj_edges(e, u) {\n n = e->opposite(u);\n if (!visited[n]) {\n visited[n] = true;\n accessEdge[n] = e;\n Q.append(n);\n }\n }\n }\n\n return false;\n}\n\n\/**\n * @return bool True for successful reconnection, false otherwise\n *\/\nbool reconnectBlueSubgraph(Graph &G, const List &X, GraphColoring &coloring, node u, node v, edge c) {\n \/\/ if u has blue adjacent edges (except of c) AND v has blue adjacent edges (exc. of c) then\n \/\/ enumerate one blue subgraph, call it G_b1\n \/\/ create graph G_rest = G \\ X \\ G_r \\ G_b1 and BFS in it until blue is found (use hideEdge!)\n \/\/ (or BFS (avoid red and X) from u to first blue edge not in G_b1)\n \/\/ -> path found, color it blue and continue\n \/\/ -> path not found, fail here (return;)\n\n G.hideEdge(c); \/\/ Don't consider c\n\n bool uaIsEmpty = true, vaIsEmpty = true;\n edge e;\n\n forall_adj_edges(e, u) {\n if (coloring[e] == Color::BLUE) {\n uaIsEmpty = false;\n break;\n }\n }\n\n forall_adj_edges(e, v) {\n if (coloring[e] == Color::BLUE) {\n vaIsEmpty = false;\n break;\n }\n }\n\n if (!uaIsEmpty && !vaIsEmpty) {\n \/\/ G_b has been disconnected, hide X, G_r and one component of blue subgraph (TODO: Maintain G_rest through the whole algorithm and not recompute here every time?)\n for(List::const_iterator it = X.begin(); it != X.end(); it++) G.hideEdge(*it);\n forall_edges(e, G) { if(coloring[e] == Color::RED) G.hideEdge(e); }\n hideConnectedBlueSubgraph(G, coloring, u);\n\n \/\/ BFS in G from u to the first found blue edge\n \/\/ -> not found => fail here\n \/\/ -> path found => color it blue and continue\n\n if (!findPathToAnyBlueAndColorItBlue(G, coloring, u)) {\n G.restoreAllEdges();\n return false;\n }\n\n\n } \/\/ else c is just a branch with a single leaf, nothing happened G_b stays connected\n\n G.restoreAllEdges();\n return true;\n}\n\n\nvoid GenCocircuits(List> &Cocircuits, Graph &G, GraphColoring coloring, List X, node red, node blue) {\n if (X.size() > m) return;\n\n \/\/ Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \\ X\n List D = shortestPath(G, coloring, red, blue, X);\n\n if (D.size() > 0) {\n\n \/\/ for each c ∈ D, recursively call GenCocircuits(X ∪ {c}).\n for(List::iterator iterator = D.begin(); iterator != D.end(); iterator++) {\n edge c = *iterator;\n\n List newX = X;\n newX.pushBack(c);\n\n\n \/\/ Coloring red-c path red, determining u and v, coloring the rest blue\n node n1 = red, n2 = blue, \/\/ after the first of the following for cycles these are the\n \/\/ nodes of the last red edge (one of them has to be incident with c)\n \/\/ initialized to red and blue since the first for can have 0 iterations\n u, v; \/\/ c = (u,v), say u is red (and so will be all vertices on the path from the first red to u)\n\n for(List::iterator j = D.begin(); j != iterator; j++) {\n edge e = *j;\n\n n1 = e->source();\n n2 = e->target();\n\n coloring[n1] = Color::RED;\n coloring[n2] = Color::RED;\n coloring[e] = Color::RED;\n }\n\n \/\/ Determine u, v, s.t. u is really red and v blue\n if (c->source() == n1 || c->target() == n1) { \/\/ if n1 is in c then n1 == u\n u = n1;\n } else { \/\/ n2 is in c so n2 == u\n u = n2;\n }\n\n v = c->opposite(u);\n\n \/\/ Color the rest of the path blue\n for(List::iterator j = iterator.succ(); j != D.end(); j++) {\n edge e = *j;\n\n coloring[e->source()] = Color::BLUE;\n coloring[e->target()] = Color::BLUE;\n coloring[e] = Color::BLUE;\n }\n\n\n \/\/ If c = (u, v) is blue, reconnect blue subgraph (find the shortest path from u to v using only nonred edges)\n if (coloring[c] == Color::BLUE) {\n reconnectBlueSubgraph(G, X, coloring, u, v, c);\n }\n\n GenCocircuits(Cocircuits, G, coloring, newX, u, v);\n }\n\n } else {\n \/\/ If there is no such circuit C above (line 4), then return ‘Cocircuit: X’.\n Cocircuits.pushBack(X);\n }\n}\n\n\/**\n * Returns edges spanning forest of (possibly disconnected) graph G\n * @param G\n *\/\nList spanningEdges(const Graph &G) {\n EdgeArray isBackedge(G, false);\n\n List backedges;\n isAcyclicUndirected(G, backedges);\n\n for(List::iterator i = backedges.begin(); i != backedges.end(); i++) {\n isBackedge[*i] = true;\n }\n\n List spanningEdges;\n edge e;\n forall_edges(e, G) {\n if (!isBackedge[e]) {\n spanningEdges.pushBack(e);\n }\n }\n\n return spanningEdges;\n}\n\nvoid CircuitCocircuit(Graph &G, List> &cocircuits) {\n List base = spanningEdges(G);\n\n edge e;\n for(List::iterator i = base.begin(); i != base.end(); i++) {\n e = *i;\n List X; \/\/ (Indexes might be sufficient? Check later)\n GraphColoring coloring(G);\n X.pushBack(e);\n coloring[e->source()] = Color::RED;\n coloring[e->target()] = Color::BLUE;\n\n GenCocircuits(cocircuits, G, coloring, X, e->source(), e->target());\n }\n}\n\n\/\/ TODO: Read from stdin?\nint main(int argc, char* argv[])\n{\n if (argc != 3 || strcmp(argv[1], \"-h\") == 0 || strcmp(argv[1], \"--help\") == 0) {\n cout << \"Usage: \" << argv[0] << \" \" << endl;\n exit(1);\n }\n\n string graphFile(argv[1]);\n m = stoi(argv[2]);\n if (m < 1) {\n cerr << \"Cocircuit size bound lower than 1. Terminating.\" << endl;\n exit(2);\n }\n\n try {\n Graph G;\n csvToGraph(graphFile, G);\n\n\n List> cocircuits;\n CircuitCocircuit(G, cocircuits);\n\n for(List >::iterator it = cocircuits.begin(); it != cocircuits.end(); ++it) {\n cout << *it << endl;\n }\n\n\n } catch (invalid_argument *e) {\n cerr << \"Error: \" << e->what() << endl;\n return 1;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"Crazyradio.h\"\n\n#include \n#include \n\n#include \n\nenum\n{\n SET_RADIO_CHANNEL = 0x01,\n SET_RADIO_ADDRESS = 0x02,\n SET_DATA_RATE = 0x03,\n SET_RADIO_POWER = 0x04,\n SET_RADIO_ARD = 0x05,\n SET_RADIO_ARC = 0x06,\n ACK_ENABLE = 0x10,\n SET_CONT_CARRIER = 0x20,\n SCANN_CHANNELS = 0x21,\n LAUNCH_BOOTLOADER = 0xFF,\n};\n\nCrazyradio::Crazyradio(\n uint32_t devid)\n : ITransport()\n , USBDevice(0x1915, 0x7777)\n , m_channel(0)\n , m_address(0)\n , m_datarate(Datarate_250KPS)\n{\n open(devid);\n setDatarate(Datarate_2MPS);\n setChannel(2);\n setContCarrier(false);\n setAddress(0xE7E7E7E7E7);\n setPower(Power_0DBM);\n setArc(3);\n setArdBytes(32);\n}\n\nCrazyradio::~Crazyradio()\n{\n}\n\nuint32_t Crazyradio::numDevices()\n{\n return USBDevice::numDevices(0x1915, 0x7777);\n}\n\nvoid Crazyradio::setChannel(uint8_t channel)\n{\n sendVendorSetup(SET_RADIO_CHANNEL, channel, 0, NULL, 0);\n m_channel = channel;\n}\n\nvoid Crazyradio::setAddress(uint64_t address)\n{\n unsigned char a[5];\n a[4] = (address >> 0) & 0xFF;\n a[3] = (address >> 8) & 0xFF;\n a[2] = (address >> 16) & 0xFF;\n a[1] = (address >> 24) & 0xFF;\n a[0] = (address >> 32) & 0xFF;\n\n \/\/ sendVendorSetup(SET_RADIO_ADDRESS, 0, 0, a, 5);\n \/\/ unsigned char a[] = {0xe7, 0xe7, 0xe7, 0xe7, 0x02};\n\n int status = libusb_control_transfer(\n m_handle,\n LIBUSB_REQUEST_TYPE_VENDOR,\n SET_RADIO_ADDRESS,\n 0,\n 0,\n a,\n 5,\n \/*timeout*\/ 1000);\n \/\/ if (status != LIBUSB_SUCCESS) {\n \/\/ std::cerr << \"sendVendorSetup: \" << libusb_error_name(status) << std::endl;\n \/\/ }\n m_address = address;\n}\n\nvoid Crazyradio::setDatarate(Datarate datarate)\n{\n sendVendorSetup(SET_DATA_RATE, datarate, 0, NULL, 0);\n m_datarate = datarate;\n}\n\nvoid Crazyradio::setPower(Power power)\n{\n sendVendorSetup(SET_RADIO_POWER, power, 0, NULL, 0);\n}\n\nvoid Crazyradio::setArc(uint8_t arc)\n{\n sendVendorSetup(SET_RADIO_ARC, arc, 0, NULL, 0);\n}\n\nvoid Crazyradio::setArdTime(uint8_t us)\n{\n \/\/ Auto Retransmit Delay:\n \/\/ 0000 - Wait 250uS\n \/\/ 0001 - Wait 500uS\n \/\/ 0010 - Wait 750uS\n \/\/ ........\n \/\/ 1111 - Wait 4000uS\n\n \/\/ Round down, to value representing a multiple of 250uS\n int t = (us \/ 250) - 1;\n if (t < 0) {\n t = 0;\n }\n if (t > 0xF) {\n t = 0xF;\n }\n sendVendorSetup(SET_RADIO_ARD, t, 0, NULL, 0);\n}\n\nvoid Crazyradio::setArdBytes(uint8_t nbytes)\n{\n sendVendorSetup(SET_RADIO_ARD, 0x80 | nbytes, 0, NULL, 0);\n}\n\nvoid Crazyradio::setAckEnable(bool enable)\n{\n sendVendorSetup(ACK_ENABLE, enable, 0, NULL, 0);\n}\n\nvoid Crazyradio::setContCarrier(bool active)\n{\n sendVendorSetup(SET_CONT_CARRIER, active, 0, NULL, 0);\n}\n\nvoid Crazyradio::sendPacket(\n const uint8_t* data,\n uint32_t length,\n Ack& result)\n{\n int status;\n int transferred;\n\n if (!m_handle) {\n throw std::runtime_error(\"No valid device handle!\");\n }\n\n \/\/ Send data\n status = libusb_bulk_transfer(\n m_handle,\n \/* endpoint*\/ (0x01 | LIBUSB_ENDPOINT_OUT),\n (uint8_t*)data,\n length,\n &transferred,\n \/*timeout*\/ 1000);\n if (status != LIBUSB_SUCCESS) {\n throw std::runtime_error(libusb_error_name(status));\n }\n if (length != transferred) {\n std::stringstream sstr;\n sstr << \"Did transfer \" << transferred << \" but \" << length << \" was requested!\";\n throw std::runtime_error(sstr.str());\n }\n\n \/\/ Read result\n result.ack = false;\n result.size = 0;\n status = libusb_bulk_transfer(\n m_handle,\n \/* endpoint*\/ (0x81 | LIBUSB_ENDPOINT_IN),\n (unsigned char*)&result,\n sizeof(result) - 1,\n &transferred,\n \/*timeout*\/ 1000);\n if (status != LIBUSB_SUCCESS) {\n throw std::runtime_error(libusb_error_name(status));\n }\n\n result.size = transferred - 1;\n}\n\nvoid Crazyradio::sendPacketNoAck(\n const uint8_t* data,\n uint32_t length)\n{\n int status;\n int transferred;\n\n if (!m_handle) {\n throw std::runtime_error(\"No valid device handle!\");\n }\n\n \/\/ Send data\n status = libusb_bulk_transfer(\n m_handle,\n \/* endpoint*\/ (0x01 | LIBUSB_ENDPOINT_OUT),\n (uint8_t*)data,\n length,\n &transferred,\n \/*timeout*\/ 1000);\n if (status != LIBUSB_SUCCESS) {\n throw std::runtime_error(libusb_error_name(status));\n }\n if (length != transferred) {\n std::stringstream sstr;\n sstr << \"Did transfer \" << transferred << \" but \" << length << \" was requested!\";\n throw std::runtime_error(sstr.str());\n }\n}\nHandle LIBUSB_ERROR_TIMEOUT more gracefully#include \"Crazyradio.h\"\n\n#include \n#include \n\n#include \n\nenum\n{\n SET_RADIO_CHANNEL = 0x01,\n SET_RADIO_ADDRESS = 0x02,\n SET_DATA_RATE = 0x03,\n SET_RADIO_POWER = 0x04,\n SET_RADIO_ARD = 0x05,\n SET_RADIO_ARC = 0x06,\n ACK_ENABLE = 0x10,\n SET_CONT_CARRIER = 0x20,\n SCANN_CHANNELS = 0x21,\n LAUNCH_BOOTLOADER = 0xFF,\n};\n\nCrazyradio::Crazyradio(\n uint32_t devid)\n : ITransport()\n , USBDevice(0x1915, 0x7777)\n , m_channel(0)\n , m_address(0)\n , m_datarate(Datarate_250KPS)\n{\n open(devid);\n setDatarate(Datarate_2MPS);\n setChannel(2);\n setContCarrier(false);\n setAddress(0xE7E7E7E7E7);\n setPower(Power_0DBM);\n setArc(3);\n setArdBytes(32);\n}\n\nCrazyradio::~Crazyradio()\n{\n}\n\nuint32_t Crazyradio::numDevices()\n{\n return USBDevice::numDevices(0x1915, 0x7777);\n}\n\nvoid Crazyradio::setChannel(uint8_t channel)\n{\n sendVendorSetup(SET_RADIO_CHANNEL, channel, 0, NULL, 0);\n m_channel = channel;\n}\n\nvoid Crazyradio::setAddress(uint64_t address)\n{\n unsigned char a[5];\n a[4] = (address >> 0) & 0xFF;\n a[3] = (address >> 8) & 0xFF;\n a[2] = (address >> 16) & 0xFF;\n a[1] = (address >> 24) & 0xFF;\n a[0] = (address >> 32) & 0xFF;\n\n \/\/ sendVendorSetup(SET_RADIO_ADDRESS, 0, 0, a, 5);\n \/\/ unsigned char a[] = {0xe7, 0xe7, 0xe7, 0xe7, 0x02};\n\n int status = libusb_control_transfer(\n m_handle,\n LIBUSB_REQUEST_TYPE_VENDOR,\n SET_RADIO_ADDRESS,\n 0,\n 0,\n a,\n 5,\n \/*timeout*\/ 1000);\n \/\/ if (status != LIBUSB_SUCCESS) {\n \/\/ std::cerr << \"sendVendorSetup: \" << libusb_error_name(status) << std::endl;\n \/\/ }\n m_address = address;\n}\n\nvoid Crazyradio::setDatarate(Datarate datarate)\n{\n sendVendorSetup(SET_DATA_RATE, datarate, 0, NULL, 0);\n m_datarate = datarate;\n}\n\nvoid Crazyradio::setPower(Power power)\n{\n sendVendorSetup(SET_RADIO_POWER, power, 0, NULL, 0);\n}\n\nvoid Crazyradio::setArc(uint8_t arc)\n{\n sendVendorSetup(SET_RADIO_ARC, arc, 0, NULL, 0);\n}\n\nvoid Crazyradio::setArdTime(uint8_t us)\n{\n \/\/ Auto Retransmit Delay:\n \/\/ 0000 - Wait 250uS\n \/\/ 0001 - Wait 500uS\n \/\/ 0010 - Wait 750uS\n \/\/ ........\n \/\/ 1111 - Wait 4000uS\n\n \/\/ Round down, to value representing a multiple of 250uS\n int t = (us \/ 250) - 1;\n if (t < 0) {\n t = 0;\n }\n if (t > 0xF) {\n t = 0xF;\n }\n sendVendorSetup(SET_RADIO_ARD, t, 0, NULL, 0);\n}\n\nvoid Crazyradio::setArdBytes(uint8_t nbytes)\n{\n sendVendorSetup(SET_RADIO_ARD, 0x80 | nbytes, 0, NULL, 0);\n}\n\nvoid Crazyradio::setAckEnable(bool enable)\n{\n sendVendorSetup(ACK_ENABLE, enable, 0, NULL, 0);\n}\n\nvoid Crazyradio::setContCarrier(bool active)\n{\n sendVendorSetup(SET_CONT_CARRIER, active, 0, NULL, 0);\n}\n\nvoid Crazyradio::sendPacket(\n const uint8_t* data,\n uint32_t length,\n Ack& result)\n{\n result.ack = false;\n result.size = 0;\n\n int status;\n int transferred;\n\n if (!m_handle) {\n throw std::runtime_error(\"No valid device handle!\");\n }\n\n \/\/ Send data\n status = libusb_bulk_transfer(\n m_handle,\n \/* endpoint*\/ (0x01 | LIBUSB_ENDPOINT_OUT),\n (uint8_t*)data,\n length,\n &transferred,\n \/*timeout*\/ 1000);\n if (status == LIBUSB_ERROR_TIMEOUT) {\n return;\n }\n if (status != LIBUSB_SUCCESS) {\n throw std::runtime_error(libusb_error_name(status));\n }\n if (length != transferred) {\n std::stringstream sstr;\n sstr << \"Did transfer \" << transferred << \" but \" << length << \" was requested!\";\n throw std::runtime_error(sstr.str());\n }\n\n \/\/ Read result\n status = libusb_bulk_transfer(\n m_handle,\n \/* endpoint*\/ (0x81 | LIBUSB_ENDPOINT_IN),\n (unsigned char*)&result,\n sizeof(result) - 1,\n &transferred,\n \/*timeout*\/ 1000);\n if (status == LIBUSB_ERROR_TIMEOUT) {\n return;\n }\n if (status != LIBUSB_SUCCESS) {\n throw std::runtime_error(libusb_error_name(status));\n }\n\n result.size = transferred - 1;\n}\n\nvoid Crazyradio::sendPacketNoAck(\n const uint8_t* data,\n uint32_t length)\n{\n int status;\n int transferred;\n\n if (!m_handle) {\n throw std::runtime_error(\"No valid device handle!\");\n }\n\n \/\/ Send data\n status = libusb_bulk_transfer(\n m_handle,\n \/* endpoint*\/ (0x01 | LIBUSB_ENDPOINT_OUT),\n (uint8_t*)data,\n length,\n &transferred,\n \/*timeout*\/ 1000);\n if (status == LIBUSB_ERROR_TIMEOUT) {\n return;\n }\n if (status != LIBUSB_SUCCESS) {\n throw std::runtime_error(libusb_error_name(status));\n }\n if (length != transferred) {\n std::stringstream sstr;\n sstr << \"Did transfer \" << transferred << \" but \" << length << \" was requested!\";\n throw std::runtime_error(sstr.str());\n }\n}\n<|endoftext|>"} {"text":"\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/function\/CEvaluationNodeObject.cpp,v $\n\/\/ $Revision: 1.31 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2008\/03\/11 23:32:12 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"copasi.h\"\n#include \"CEvaluationNode.h\"\n#include \"CEvaluationTree.h\"\n#include \"CExpression.h\"\n#include \"report\/CCopasiObjectName.h\"\n#include \"report\/CCopasiObject.h\"\n#include \"report\/CCopasiContainer.h\"\n#include \"model\/CModel.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n\n#include \"sbml\/math\/ASTNode.h\"\n#include \"sbml\/SBase.h\"\n#include \"sbml\/SBMLTypeCodes.h\"\n#include \"sbml\/Compartment.h\"\n#include \"sbml\/Species.h\"\n#include \"sbml\/Parameter.h\"\n#include \"sbml\/Reaction.h\"\n\nCEvaluationNodeObject::CEvaluationNodeObject():\n CEvaluationNode(CEvaluationNode::INVALID, \"\"),\n mpValue(NULL),\n mRegisteredObjectCN(\"\")\n{mPrecedence = PRECEDENCE_NUMBER;}\n\nCEvaluationNodeObject::CEvaluationNodeObject(const SubType & subType,\n const Data & data):\n CEvaluationNode((Type) (CEvaluationNode::OBJECT | subType), data),\n mpValue(NULL),\n mRegisteredObjectCN(data.substr(1, data.length() - 2))\n{mPrecedence = PRECEDENCE_NUMBER;}\n\nCEvaluationNodeObject::CEvaluationNodeObject(const CEvaluationNodeObject & src):\n CEvaluationNode(src),\n mpValue(src.mpValue),\n mRegisteredObjectCN(src.mRegisteredObjectCN)\n{}\n\nCEvaluationNodeObject::~CEvaluationNodeObject() {}\n\nbool CEvaluationNodeObject::compile(const CEvaluationTree * pTree)\n{\n const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);\n if (!pExpression) return false;\n\n const CCopasiObject * pObject =\n pExpression->getNodeObject(mRegisteredObjectCN);\n\n if (pObject)\n mpValue = (C_FLOAT64 *) pObject->getValuePointer();\n else\n mpValue = NULL;\n\n if (mpValue == NULL) return false;\n if (!pObject->isValueDbl()) return false;\n\n mData = \"<\" + mRegisteredObjectCN + \">\";\n\n return (getChild() == NULL); \/\/ We must not have any children.\n}\n\nCEvaluationNode::Data CEvaluationNodeObject::getData() const\n{return \"<\" + mRegisteredObjectCN + \">\";}\n\nbool CEvaluationNodeObject::setData(const Data & data)\n{\n mData = data;\n mRegisteredObjectCN = data.substr(1, data.length() - 2);\n\n return true;\n}\n\nstd::string CEvaluationNodeObject::getInfix() const\n {return \"<\" + mRegisteredObjectCN + \">\";}\n\n#if 0\nstd::string CEvaluationNodeObject::getDisplayString(const CEvaluationTree * pTree) const\n {\n const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);\n if (!pExpression) return false;\n\n const CCopasiObject * pObject =\n CCopasiContainer::ObjectFromName(mRegisteredObjectCN);\n\n if (pObject == NULL) return \"<\" + mRegisteredObjectCN + \">\";\n\n return \"<\" + pObject->getObjectDisplayName() + \">\";\n }\n#endif\n\nstd::string CEvaluationNodeObject::getDisplayString(const CEvaluationTree * \/* pTree *\/) const\n {\n return \"<\" + mRegisteredObjectCN + \">\";\n }\n\nstd::string CEvaluationNodeObject::getDisplay_C_String(const CEvaluationTree * \/* pTree *\/) const\n {\n return mData;\n }\n\nstd::string CEvaluationNodeObject::getDisplay_MMD_String(const CEvaluationTree * \/* pTree *\/) const\n {\n return mData;\n }\n\nstd::string CEvaluationNodeObject::getDisplay_XPP_String(const CEvaluationTree * \/* pTree *\/) const\n {\n return mData;\n }\n\nCEvaluationNode* CEvaluationNodeObject::createNodeFromASTTree(const ASTNode& node)\n{\n CEvaluationNodeObject* pNode = NULL;\n ASTNodeType_t type = node.getType();\n switch (type)\n {\n case AST_NAME_TIME:\n case AST_NAME:\n pNode = new CEvaluationNodeObject(ANY, CCopasiObjectName(std::string(\"<\") + node.getName() + std::string(\">\")));\n break;\n default:\n break;\n }\n return pNode;\n}\n\nASTNode* CEvaluationNodeObject::toAST() const\n {\n ASTNode* node = new ASTNode();\n node->setType(AST_NAME);\n \/\/ since I can not get the model in which this node is located, I just\n \/\/ assume that it will always be the current global model.\n CCopasiObject* object = CCopasiContainer::ObjectFromName(mRegisteredObjectCN);\n assert(object);\n \/\/ if it is a reference, we get the parent of the reference\n if (object->isReference())\n {\n object = object->getObjectParent();\n }\n CModelEntity* pME = dynamic_cast(object);\n if (pME != NULL)\n {\n CModel* pModel = dynamic_cast(pME);\n if (pModel != NULL)\n {\n node->setType(AST_NAME_TIME);\n node->setName(\"time\");\n if (pModel->getInitialTime() != 0.0)\n {\n CCopasiMessage(CCopasiMessage::WARNING, MCSBML + 1);\n }\n }\n else\n {\n node->setName(pME->getSBMLId().c_str());\n }\n }\n else\n {\n CCopasiParameter* pPara = dynamic_cast(object);\n if (pPara != NULL)\n {\n node->setName(pPara->getObjectName().c_str());\n }\n else\n {\n fatalError();\n }\n }\n return node;\n }\n\nconst CRegisteredObjectName & CEvaluationNodeObject::getObjectCN() const\n {return mRegisteredObjectCN;}\n\n#include \"utilities\/copasimathml.h\"\n\nvoid CEvaluationNodeObject::writeMathML(std::ostream & out,\n const std::vector > & \/* env *\/,\n bool \/* expand *\/,\n unsigned C_INT32 l) const\n {\n const CCopasiObject* obj = CCopasiContainer::ObjectFromName(mRegisteredObjectCN);\n out << SPC(l) << CMathMl::getMMLName(obj) << std::endl;\n \/\/or use mValue instead?\n }\nFixed Bug 1077. An invalid object no longer will lead to a crash.\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/function\/CEvaluationNodeObject.cpp,v $\n\/\/ $Revision: 1.32 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2008\/09\/08 16:36:55 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"copasi.h\"\n#include \"CEvaluationNode.h\"\n#include \"CEvaluationTree.h\"\n#include \"CExpression.h\"\n#include \"report\/CCopasiObjectName.h\"\n#include \"report\/CCopasiObject.h\"\n#include \"report\/CCopasiContainer.h\"\n#include \"model\/CModel.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n\n#include \"sbml\/math\/ASTNode.h\"\n#include \"sbml\/SBase.h\"\n#include \"sbml\/SBMLTypeCodes.h\"\n#include \"sbml\/Compartment.h\"\n#include \"sbml\/Species.h\"\n#include \"sbml\/Parameter.h\"\n#include \"sbml\/Reaction.h\"\n\nCEvaluationNodeObject::CEvaluationNodeObject():\n CEvaluationNode(CEvaluationNode::INVALID, \"\"),\n mpValue(NULL),\n mRegisteredObjectCN(\"\")\n{mPrecedence = PRECEDENCE_NUMBER;}\n\nCEvaluationNodeObject::CEvaluationNodeObject(const SubType & subType,\n const Data & data):\n CEvaluationNode((Type) (CEvaluationNode::OBJECT | subType), data),\n mpValue(NULL),\n mRegisteredObjectCN(data.substr(1, data.length() - 2))\n{mPrecedence = PRECEDENCE_NUMBER;}\n\nCEvaluationNodeObject::CEvaluationNodeObject(const CEvaluationNodeObject & src):\n CEvaluationNode(src),\n mpValue(src.mpValue),\n mRegisteredObjectCN(src.mRegisteredObjectCN)\n{}\n\nCEvaluationNodeObject::~CEvaluationNodeObject() {}\n\nbool CEvaluationNodeObject::compile(const CEvaluationTree * pTree)\n{\n const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);\n if (!pExpression) return false;\n\n const CCopasiObject * pObject =\n pExpression->getNodeObject(mRegisteredObjectCN);\n\n if (pObject)\n mpValue = (C_FLOAT64 *) pObject->getValuePointer();\n else\n {\n mValue = std::numeric_limits::quiet_NaN();\n mpValue = &mValue;\n }\n\n if (mpValue == NULL) return false;\n if (!pObject->isValueDbl()) return false;\n\n mData = \"<\" + mRegisteredObjectCN + \">\";\n\n return (getChild() == NULL); \/\/ We must not have any children.\n}\n\nCEvaluationNode::Data CEvaluationNodeObject::getData() const\n{return \"<\" + mRegisteredObjectCN + \">\";}\n\nbool CEvaluationNodeObject::setData(const Data & data)\n{\n mData = data;\n mRegisteredObjectCN = data.substr(1, data.length() - 2);\n\n return true;\n}\n\nstd::string CEvaluationNodeObject::getInfix() const\n {return \"<\" + mRegisteredObjectCN + \">\";}\n\n#if 0\nstd::string CEvaluationNodeObject::getDisplayString(const CEvaluationTree * pTree) const\n {\n const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);\n if (!pExpression) return false;\n\n const CCopasiObject * pObject =\n CCopasiContainer::ObjectFromName(mRegisteredObjectCN);\n\n if (pObject == NULL) return \"<\" + mRegisteredObjectCN + \">\";\n\n return \"<\" + pObject->getObjectDisplayName() + \">\";\n }\n#endif\n\nstd::string CEvaluationNodeObject::getDisplayString(const CEvaluationTree * \/* pTree *\/) const\n {\n return \"<\" + mRegisteredObjectCN + \">\";\n }\n\nstd::string CEvaluationNodeObject::getDisplay_C_String(const CEvaluationTree * \/* pTree *\/) const\n {\n return mData;\n }\n\nstd::string CEvaluationNodeObject::getDisplay_MMD_String(const CEvaluationTree * \/* pTree *\/) const\n {\n return mData;\n }\n\nstd::string CEvaluationNodeObject::getDisplay_XPP_String(const CEvaluationTree * \/* pTree *\/) const\n {\n return mData;\n }\n\nCEvaluationNode* CEvaluationNodeObject::createNodeFromASTTree(const ASTNode& node)\n{\n CEvaluationNodeObject* pNode = NULL;\n ASTNodeType_t type = node.getType();\n switch (type)\n {\n case AST_NAME_TIME:\n case AST_NAME:\n pNode = new CEvaluationNodeObject(ANY, CCopasiObjectName(std::string(\"<\") + node.getName() + std::string(\">\")));\n break;\n default:\n break;\n }\n return pNode;\n}\n\nASTNode* CEvaluationNodeObject::toAST() const\n {\n ASTNode* node = new ASTNode();\n node->setType(AST_NAME);\n \/\/ since I can not get the model in which this node is located, I just\n \/\/ assume that it will always be the current global model.\n CCopasiObject* object = CCopasiContainer::ObjectFromName(mRegisteredObjectCN);\n assert(object);\n \/\/ if it is a reference, we get the parent of the reference\n if (object->isReference())\n {\n object = object->getObjectParent();\n }\n CModelEntity* pME = dynamic_cast(object);\n if (pME != NULL)\n {\n CModel* pModel = dynamic_cast(pME);\n if (pModel != NULL)\n {\n node->setType(AST_NAME_TIME);\n node->setName(\"time\");\n if (pModel->getInitialTime() != 0.0)\n {\n CCopasiMessage(CCopasiMessage::WARNING, MCSBML + 1);\n }\n }\n else\n {\n node->setName(pME->getSBMLId().c_str());\n }\n }\n else\n {\n CCopasiParameter* pPara = dynamic_cast(object);\n if (pPara != NULL)\n {\n node->setName(pPara->getObjectName().c_str());\n }\n else\n {\n fatalError();\n }\n }\n return node;\n }\n\nconst CRegisteredObjectName & CEvaluationNodeObject::getObjectCN() const\n {return mRegisteredObjectCN;}\n\n#include \"utilities\/copasimathml.h\"\n\nvoid CEvaluationNodeObject::writeMathML(std::ostream & out,\n const std::vector > & \/* env *\/,\n bool \/* expand *\/,\n unsigned C_INT32 l) const\n {\n const CCopasiObject* obj = CCopasiContainer::ObjectFromName(mRegisteredObjectCN);\n out << SPC(l) << CMathMl::getMMLName(obj) << std::endl;\n \/\/or use mValue instead?\n }\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst int width=640, height=480;\nconst int pipRadius = 10;\nconst int racketWidth = 20;\n\nint pipX = width\/2, pipY = height\/2;\n\nint pipStartSpeed = 300; \/\/ pixels per second\n\nint pipXSpeed, pipYSpeed;\n\nint racketSpeed = 200;\n\nint lastTime = 0;\n\nenum RacketPosition {LEFT, RIGHT};\n\nstruct Racket {\n int y;\n int size;\n int halfSize;\n int speed;\n float r, g, b;\n RacketPosition position;\n \n Racket(RacketPosition position, int y, int size, int speed, float r, float g, float b) {\n this->position = position;\n this->speed = speed;\n this->y = y;\n this->size = size;\n this->halfSize = size\/2;\n this->r = r;\n this->g = g;\n this->b = b;\n }\n};\n\nRacket racket1 = Racket(LEFT, height\/2, 120, 0, 1, 1, 0);\nRacket racket2 = Racket(RIGHT, height\/2, 120, 0, 0, 1, 1);\n\n\nvoid reshape(GLFWwindow* window, int width, int height ) {\n int w, h;\n glfwGetFramebufferSize(window, &w, &h);\n glViewport(0, 0, w, h);\n glMatrixMode(GL_PROJECTION );\n glLoadIdentity();\n glScalef(1.f, -1.f, 1.f);\n glOrtho(0, width, height, 0, 0, 1);\n glMatrixMode(GL_MODELVIEW );\n glLoadIdentity();\n}\n\nvoid drawNet() {\n glPushMatrix();\n \n glColor3f(0, 0, 1);\n glLineWidth(5);\n \n glBegin(GL_LINES);\n glVertex2d(width\/2, 0);\n glVertex2d(width\/2, height);\n glEnd();\n \n glPopMatrix();\n}\n\nvoid drawBall() {\n glPushMatrix();\n \n glColor3f(1.0, 0.0, 0.0);\n \n glBegin(GL_QUADS);\n glVertex2d(pipX - pipRadius, pipY + pipRadius);\n glVertex2d(pipX + pipRadius, pipY + pipRadius);\n glVertex2d(pipX + pipRadius, pipY - pipRadius);\n glVertex2d(pipX - pipRadius, pipY - pipRadius);\n glEnd();\n \n \n glPopMatrix();\n}\n\nvoid drawRacket(Racket racket) {\n glPushMatrix();\n \n glColor3f(racket.r, racket.g, racket.b);\n \n int racketLeft;\n \n switch(racket.position) {\n case RIGHT:\n racketLeft = width - racketWidth;\n break;\n case LEFT:\n racketLeft = 0;\n default:\n break;\n }\n \n glBegin(GL_QUADS);\n glVertex2d(racketLeft, racket.y + racket.halfSize);\n glVertex2d(racketLeft + racketWidth, racket.y + racket.halfSize);\n glVertex2d(racketLeft + racketWidth, racket.y - racket.halfSize);\n glVertex2d(racketLeft, racket.y - racket.halfSize);\n glEnd();\n \n glPopMatrix();\n}\n\nvoid resetPipSpeed() {\n pipXSpeed = (pipStartSpeed + 25 - (rand() % 50)) * (rand()%2 > 0 ? 1 : -1);\n pipYSpeed = (pipStartSpeed + 25 - (rand() % 50)) * (rand()%2 > 0 ? 1 : -1);\n}\n\nint guessWherePipIsGoing() {\n int distanceToWall = 0;\n if (pipXSpeed > 0) {\n distanceToWall = width - (pipRadius * 2) - pipX;\n } else {\n distanceToWall = pipX - (pipRadius * 2);\n }\n float angle = atan(pipYSpeed \/ abs(pipXSpeed));\n int guess = pipY + (tan(angle) * distanceToWall);\n \n cout << \"predicted y: \" << guess << endl;\n \n if (guess > height) {\n guess = height*3\/4;\n } else if (guess < 0) {\n guess = height\/4;\n }\n \n return guess;\n}\n\nvoid moveRacketToY(Racket & racket, int timeDiff) {\n int targetY = height\/2;\n \n racket.speed = 0;\n \n if (racket.position == RIGHT && pipXSpeed > 0) {\n targetY = guessWherePipIsGoing();\n } else if (racket.position == LEFT && pipXSpeed <= 0) {\n targetY = guessWherePipIsGoing();\n }\n \n if(racket.y < targetY) {\n if (height - racket.y <= racket.halfSize) {\n racket.y = height - racket.halfSize;\n } else if (targetY - racket.y > (racketSpeed * timeDiff) \/ 1000) {\n racket.y += (racketSpeed * timeDiff) \/ 1000;\n racket.speed += racketSpeed;\n } else {\n racket.y = targetY;\n }\n } else if(racket.y > targetY) {\n if (racket.y <= racket.halfSize) {\n racket.y = racket.halfSize;\n } else if (racket.y - targetY > (racketSpeed * timeDiff) \/ 1000) {\n racket.y -= (racketSpeed * timeDiff) \/ 1000;\n racket.speed -= racketSpeed;\n } else {\n racket.y = targetY;\n }\n }\n}\n\nbool collidesWithRacket(Racket racket) {\n if (pipY > racket.y + racket.halfSize || pipY < racket.y - racket.halfSize)\n return false;\n \n switch(racket.position) {\n case RIGHT:\n if (pipX < width - racketWidth)\n return false;\n break;\n case LEFT:\n if (pipX > racketWidth)\n return false;\n default:\n break;\n }\n \n pipYSpeed += racket.speed;\n return true;\n\n}\n\nvoid recalculateBall(int timeDiff) {\n pipX += (pipXSpeed * timeDiff)\/1000;\n pipY += (pipYSpeed * timeDiff)\/1000;\n \n if (pipY < pipRadius || pipY > height - pipRadius) {\n if (pipY < pipRadius) pipY = pipRadius;\n if (pipY > height - pipRadius) pipY = height - pipRadius;\n pipYSpeed = -pipYSpeed;\n }\n \n if (collidesWithRacket(racket1) || collidesWithRacket(racket2)) {\n if (pipX < racketWidth + pipRadius) pipX = racketWidth + pipRadius;\n if (pipX > width - racketWidth - pipRadius) pipX = width - racketWidth - pipRadius;\n pipXSpeed = -pipXSpeed;\n } else if (pipX < pipRadius || pipX > width - pipRadius) {\n if (pipX < pipRadius) pipX = pipRadius;\n if (pipX > width - pipRadius) pipX = width - pipRadius;\n pipX = width\/2;\n pipY = height\/2;\n resetPipSpeed();\n }\n}\n\nint main(void) {\n srand(time(NULL));\n \n GLFWwindow* window;\n \n \/* Initialize the library *\/\n if (!glfwInit())\n return -1;\n \n \/* Create a windowed mode window and its OpenGL context *\/\n\n glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);\n window = glfwCreateWindow(width, height, \"Lana Tennis\", NULL, NULL);\n if (!window) {\n glfwTerminate();\n return -1;\n }\n \n \/* Make the window's context current *\/\n glfwMakeContextCurrent(window);\n reshape(window, width, height);\n \n glEnable(GL_BLEND);\n glDisable(GL_DEPTH_TEST);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n \n glfwSetWindowSizeCallback(window, reshape);\n \n resetPipSpeed();\n \n \/* Loop until the user closes the window *\/\n while (!glfwWindowShouldClose(window)) {\n \/* Render here *\/\n glClear(GL_COLOR_BUFFER_BIT);\n \n int newTime = floor(glfwGetTime() * 1000);\n if (newTime - lastTime > 10) {\n recalculateBall(newTime - lastTime);\n\n moveRacketToY(racket1, newTime - lastTime);\n moveRacketToY(racket2, newTime - lastTime);\n \n lastTime = newTime;\n }\n \n drawNet();\n drawBall();\n drawRacket(racket1);\n drawRacket(racket2);\n \n \/* Swap front and back buffers *\/\n glfwSwapBuffers(window);\n \n \/* Poll for and process events *\/\n glfwPollEvents();\n }\n \n glfwTerminate();\n return 0;\n}Reduce racket size to 60\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst int width=640, height=480;\nconst int pipRadius = 10;\nconst int racketWidth = 20;\n\nint pipX = width\/2, pipY = height\/2;\n\nint pipStartSpeed = 300; \/\/ pixels per second\n\nint pipXSpeed, pipYSpeed;\n\nint racketSpeed = 200;\n\nint lastTime = 0;\n\nenum RacketPosition {LEFT, RIGHT};\n\nstruct Racket {\n int y;\n int size;\n int halfSize;\n int speed;\n float r, g, b;\n RacketPosition position;\n \n Racket(RacketPosition position, int y, int size, int speed, float r, float g, float b) {\n this->position = position;\n this->speed = speed;\n this->y = y;\n this->size = size;\n this->halfSize = size\/2;\n this->r = r;\n this->g = g;\n this->b = b;\n }\n};\n\nRacket racket1 = Racket(LEFT, height\/2, 60, 0, 1, 1, 0);\nRacket racket2 = Racket(RIGHT, height\/2, 60, 0, 0, 1, 1);\n\n\nvoid reshape(GLFWwindow* window, int width, int height ) {\n int w, h;\n glfwGetFramebufferSize(window, &w, &h);\n glViewport(0, 0, w, h);\n glMatrixMode(GL_PROJECTION );\n glLoadIdentity();\n glScalef(1.f, -1.f, 1.f);\n glOrtho(0, width, height, 0, 0, 1);\n glMatrixMode(GL_MODELVIEW );\n glLoadIdentity();\n}\n\nvoid drawNet() {\n glPushMatrix();\n \n glColor3f(0, 0, 1);\n glLineWidth(5);\n \n glBegin(GL_LINES);\n glVertex2d(width\/2, 0);\n glVertex2d(width\/2, height);\n glEnd();\n \n glPopMatrix();\n}\n\nvoid drawBall() {\n glPushMatrix();\n \n glColor3f(1.0, 0.0, 0.0);\n \n glBegin(GL_QUADS);\n glVertex2d(pipX - pipRadius, pipY + pipRadius);\n glVertex2d(pipX + pipRadius, pipY + pipRadius);\n glVertex2d(pipX + pipRadius, pipY - pipRadius);\n glVertex2d(pipX - pipRadius, pipY - pipRadius);\n glEnd();\n \n \n glPopMatrix();\n}\n\nvoid drawRacket(Racket racket) {\n glPushMatrix();\n \n glColor3f(racket.r, racket.g, racket.b);\n \n int racketLeft;\n \n switch(racket.position) {\n case RIGHT:\n racketLeft = width - racketWidth;\n break;\n case LEFT:\n racketLeft = 0;\n default:\n break;\n }\n \n glBegin(GL_QUADS);\n glVertex2d(racketLeft, racket.y + racket.halfSize);\n glVertex2d(racketLeft + racketWidth, racket.y + racket.halfSize);\n glVertex2d(racketLeft + racketWidth, racket.y - racket.halfSize);\n glVertex2d(racketLeft, racket.y - racket.halfSize);\n glEnd();\n \n glPopMatrix();\n}\n\nvoid resetPipSpeed() {\n pipXSpeed = (pipStartSpeed + 25 - (rand() % 50)) * (rand()%2 > 0 ? 1 : -1);\n pipYSpeed = (pipStartSpeed + 25 - (rand() % 50)) * (rand()%2 > 0 ? 1 : -1);\n}\n\nint guessWherePipIsGoing() {\n int distanceToWall = 0;\n if (pipXSpeed > 0) {\n distanceToWall = width - (pipRadius * 2) - pipX;\n } else {\n distanceToWall = pipX - (pipRadius * 2);\n }\n float angle = atan(pipYSpeed \/ abs(pipXSpeed));\n int guess = pipY + (tan(angle) * distanceToWall);\n \n cout << \"predicted y: \" << guess << endl;\n \n if (guess > height) {\n guess = height*3\/4;\n } else if (guess < 0) {\n guess = height\/4;\n }\n \n return guess;\n}\n\nvoid moveRacketToY(Racket & racket, int timeDiff) {\n int targetY = height\/2;\n \n racket.speed = 0;\n \n if (racket.position == RIGHT && pipXSpeed > 0) {\n targetY = guessWherePipIsGoing();\n } else if (racket.position == LEFT && pipXSpeed <= 0) {\n targetY = guessWherePipIsGoing();\n }\n \n if(racket.y < targetY) {\n if (height - racket.y <= racket.halfSize) {\n racket.y = height - racket.halfSize;\n } else if (targetY - racket.y > (racketSpeed * timeDiff) \/ 1000) {\n racket.y += (racketSpeed * timeDiff) \/ 1000;\n racket.speed += racketSpeed;\n } else {\n racket.y = targetY;\n }\n } else if(racket.y > targetY) {\n if (racket.y <= racket.halfSize) {\n racket.y = racket.halfSize;\n } else if (racket.y - targetY > (racketSpeed * timeDiff) \/ 1000) {\n racket.y -= (racketSpeed * timeDiff) \/ 1000;\n racket.speed -= racketSpeed;\n } else {\n racket.y = targetY;\n }\n }\n}\n\nbool collidesWithRacket(Racket racket) {\n if (pipY > racket.y + racket.halfSize || pipY < racket.y - racket.halfSize)\n return false;\n \n switch(racket.position) {\n case RIGHT:\n if (pipX < width - racketWidth)\n return false;\n break;\n case LEFT:\n if (pipX > racketWidth)\n return false;\n default:\n break;\n }\n \n pipYSpeed += racket.speed;\n return true;\n\n}\n\nvoid recalculateBall(int timeDiff) {\n pipX += (pipXSpeed * timeDiff)\/1000;\n pipY += (pipYSpeed * timeDiff)\/1000;\n \n if (pipY < pipRadius || pipY > height - pipRadius) {\n if (pipY < pipRadius) pipY = pipRadius;\n if (pipY > height - pipRadius) pipY = height - pipRadius;\n pipYSpeed = -pipYSpeed;\n }\n \n if (collidesWithRacket(racket1) || collidesWithRacket(racket2)) {\n if (pipX < racketWidth + pipRadius) pipX = racketWidth + pipRadius;\n if (pipX > width - racketWidth - pipRadius) pipX = width - racketWidth - pipRadius;\n pipXSpeed = -pipXSpeed;\n } else if (pipX < pipRadius || pipX > width - pipRadius) {\n if (pipX < pipRadius) pipX = pipRadius;\n if (pipX > width - pipRadius) pipX = width - pipRadius;\n pipX = width\/2;\n pipY = height\/2;\n resetPipSpeed();\n }\n}\n\nint main(void) {\n srand(time(NULL));\n \n GLFWwindow* window;\n \n \/* Initialize the library *\/\n if (!glfwInit())\n return -1;\n \n \/* Create a windowed mode window and its OpenGL context *\/\n\n glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);\n window = glfwCreateWindow(width, height, \"Lana Tennis\", NULL, NULL);\n if (!window) {\n glfwTerminate();\n return -1;\n }\n \n \/* Make the window's context current *\/\n glfwMakeContextCurrent(window);\n reshape(window, width, height);\n \n glEnable(GL_BLEND);\n glDisable(GL_DEPTH_TEST);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n \n glfwSetWindowSizeCallback(window, reshape);\n \n resetPipSpeed();\n \n \/* Loop until the user closes the window *\/\n while (!glfwWindowShouldClose(window)) {\n \/* Render here *\/\n glClear(GL_COLOR_BUFFER_BIT);\n \n int newTime = floor(glfwGetTime() * 1000);\n if (newTime - lastTime > 10) {\n recalculateBall(newTime - lastTime);\n\n moveRacketToY(racket1, newTime - lastTime);\n moveRacketToY(racket2, newTime - lastTime);\n \n lastTime = newTime;\n }\n \n drawNet();\n drawBall();\n drawRacket(racket1);\n drawRacket(racket2);\n \n \/* Swap front and back buffers *\/\n glfwSwapBuffers(window);\n \n \/* Poll for and process events *\/\n glfwPollEvents();\n }\n \n glfwTerminate();\n return 0;\n}<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ main.cpp\n\/\/ Description : Main programm, were everything starts\n\/\/ \n\/\/ Author : Stefan Papst\n\/\/ Softwareengeneering and Businessmanagement @ TU GRAZ\n\/\/------------------------------------------------------------------------------ \n\n#include \n#include \n\nint main()\n{\n \/\/Init the win\n sf::RenderWindow window(sf::VideoMode(600, 600), \"SFML PingPong\");\n window.setVerticalSyncEnabled(true);\n \/\/create background with color \"white\n sf::RectangleShape background(sf::Vector2f(600.f, 600.f));\n background.setFillColor(sf::Color::White);\n\n \/\/load texture\n sf::Texture smiley;\n if (!smiley.loadFromFile(\"smiley.png\"))\n {\n std::cout << \"Loading File not possible!\" << std::endl;\n std::cin.get();\n return 1;\n }\n \/\/put texture in sprite\n smiley.setSmooth(true);\n sf::Sprite sprite;\n sprite.setTexture(smiley);\n sprite.setPosition(275.f, 275.f);\n sprite.setScale(.5f,.5f);\n\n \/\/while running loop\n while (window.isOpen())\n {\n\n sf::Event event;\n while (window.pollEvent(event))\n {\n switch (event.type)\n {\n case sf::Event::Closed: \n window.close();\n break;\n case sf::Event::KeyPressed:\n switch (event.key.code)\n {\n case sf::Keyboard::W:\n sprite.move(0.f,-5.f);\n \/\/std::cout << \"notized key W\" << std::endl;\n break;\n case sf::Keyboard::S:\n sprite.move(0.f, 5.f);\n \/\/std::cout << \"notized key S\" << std::endl;\n break;\n case sf::Keyboard::A:\n sprite.move(-5.f, 0.f);\n \/\/std::cout << \"notized key A\" << std::endl;\n break;\n case sf::Keyboard::D:\n sprite.move(5.f, 0.f);\n \/\/std::cout << \"notized key D\" << std::endl;\n break;\n }\n break;\n\n }\n \n }\n\n window.clear();\n window.draw(background);\n window.draw(sprite);\n window.display();\n }\n return 0;\n}-put keyboard handling out of pollevent loop to get smooth movement\/\/------------------------------------------------------------------------------\n\/\/ main.cpp\n\/\/ Description : Main programm, were everything starts\n\/\/ \n\/\/ Author : Stefan Papst\n\/\/ Softwareengeneering and Businessmanagement @ TU GRAZ\n\/\/------------------------------------------------------------------------------ \n\n#include \n#include \n\nint main()\n{\n \/\/Init the win\n sf::RenderWindow window(sf::VideoMode(600, 600), \"SFML PingPong\");\n window.setVerticalSyncEnabled(true);\n \/\/create background with color \"white\n sf::RectangleShape background(sf::Vector2f(600.f, 600.f));\n background.setFillColor(sf::Color::White);\n\n \/\/load texture\n sf::Texture smiley;\n if (!smiley.loadFromFile(\"smiley.png\"))\n {\n std::cout << \"Loading File not possible!\" << std::endl;\n std::cin.get();\n return 1;\n }\n \/\/put texture in sprite\n smiley.setSmooth(true);\n sf::Sprite sprite;\n sprite.setTexture(smiley);\n sprite.setPosition(275.f, 275.f);\n sprite.setScale(.5f,.5f);\n\n \/\/while running loop\n while (window.isOpen())\n {\n\n sf::Event event;\n while (window.pollEvent(event))\n {\n switch (event.type)\n {\n case sf::Event::Closed: \n window.close();\n break;\n }\n \n }\n \/\/smooth movement\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))\n sprite.move(0.f, -5.f);\n \/\/std::cout << \"notized key W\" << std::endl;\n else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))\n sprite.move(0.f, 5.f);\n \/\/std::cout << \"notized key S\" << std::endl;\n else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))\n sprite.move(-5.f, 0.f);\n \/\/std::cout << \"notized key A\" << std::endl;\n else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))\n sprite.move(5.f, 0.f);\n \/\/std::cout << \"notized key D\" << std::endl;\n \n \n \n\n window.clear();\n window.draw(background);\n window.draw(sprite);\n window.display();\n }\n return 0;\n}<|endoftext|>"} {"text":"<<<<<<< HEAD\n#include \n#include \"SDL.h\"\n#include \"SDL_opengl.h\"\n\nbool gameRunning = true;\n\n#define SCREEN_WIDTH 1280\n#define SCREEN_HEIGHT 720\n\/\/#define FULLSCREEN\n\n \/\/window be rendered to\n SDL_Window* window = NULL;\n SDL_Surface* renderSurface = NULL;\n SDL_GLContext mainGLContext = NULL;\n SDL_Renderer* gRenderer = NULL;\n\n const float sh = SCREEN_HEIGHT;\n const float sw = SCREEN_WIDTH;\n\n#include \"gameHeader.h\"\n\n\nint main(int argc, char** argv){\n \/\/runs startup procedures\n if(SDL_Init(SDL_INIT_VIDEO) < 0){\n std::cout << \"SDL was not able to initialize! Error: \" << SDL_GetError() << std::endl;\n }else{\n \/\/Turn on double Buffering\n SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n \/\/create the window\n window = SDL_CreateWindow(\"Sword Swinger\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL\n #ifdef FULLSCREEN\n | SDL_WINDOW_FULLSCREEN\n #endif \/\/ FULLSCREEN\n );\n if(window == NULL){\n std::cout << \"The window failed to generate! Error: \" << SDL_GetError() << std::endl;\n }else{\n \/\/set opengl context\n mainGLContext = SDL_GL_CreateContext(window);\n if(mainGLContext == NULL){\n std::cout << \"The OpenGL context failed to initialize! Error: \" << SDL_GetError() << std::endl;\n }else{\n \/\/get window surface\n renderSurface = SDL_GetWindowSurface(window);\n \/\/set renderer\n gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n if(gRenderer == NULL){\n std::cout << \"The variable 'gRenderer' was not able to initialize! Error: \" << SDL_GetError() << std::endl;\\\n }\n \/\/background white\n SDL_FillRect(renderSurface, NULL, SDL_MapRGB(renderSurface->format, 0xFF, 0xFF, 0xFF));\n\n \/\/update window\n SDL_UpdateWindowSurface(window);\n\n configRender();\n gameLoop();\n }\n }\n\n }\n\n\n \/\/closes the window and frees resources\n SDL_GL_DeleteContext(mainGLContext);\n SDL_DestroyWindow(window);\n SDL_Quit();\n return 0;\n=======\n#include \n#include \n\nint main(int argc,char **argv){\n\tputs(\"Hello, world!\");\n\treturn 0;\n>>>>>>> origin\/master\n}\nUpdate main.cpp#include \n#include \"SDL.h\"\n#include \"SDL_opengl.h\"\n\nbool gameRunning = true;\n\n#define SCREEN_WIDTH 1280\n#define SCREEN_HEIGHT 720\n\/\/#define FULLSCREEN\n\n \/\/window be rendered to\n SDL_Window* window = NULL;\n SDL_Surface* renderSurface = NULL;\n SDL_GLContext mainGLContext = NULL;\n SDL_Renderer* gRenderer = NULL;\n\n const float sh = SCREEN_HEIGHT;\n const float sw = SCREEN_WIDTH;\n\nint main(int argc, char** argv){\n \/\/runs startup procedures\n if(SDL_Init(SDL_INIT_VIDEO) < 0){\n std::cout << \"SDL was not able to initialize! Error: \" << SDL_GetError() << std::endl;\n }else{\n \/\/Turn on double Buffering\n SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n \/\/create the window\n window = SDL_CreateWindow(\"Sword Swinger\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL\n #ifdef FULLSCREEN\n | SDL_WINDOW_FULLSCREEN\n #endif \/\/ FULLSCREEN\n );\n if(window == NULL){\n std::cout << \"The window failed to generate! Error: \" << SDL_GetError() << std::endl;\n }else{\n \/\/set opengl context\n mainGLContext = SDL_GL_CreateContext(window);\n if(mainGLContext == NULL){\n std::cout << \"The OpenGL context failed to initialize! Error: \" << SDL_GetError() << std::endl;\n }else{\n \/\/get window surface\n renderSurface = SDL_GetWindowSurface(window);\n \/\/set renderer\n gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n if(gRenderer == NULL){\n std::cout << \"The variable 'gRenderer' was not able to initialize! Error: \" << SDL_GetError() << std::endl;\\\n }\n \/\/background white\n SDL_FillRect(renderSurface, NULL, SDL_MapRGB(renderSurface->format, 0xFF, 0xFF, 0xFF));\n\n \/\/update window\n SDL_UpdateWindowSurface(window);\n\n }\n }\n\n }\n\n\n \/\/closes the window and frees resources\n SDL_GL_DeleteContext(mainGLContext);\n SDL_DestroyWindow(window);\n SDL_Quit();\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"dsa\/variant.h\"\n#include \"gtest\/gtest.h\"\n\n#include \n\nusing namespace dsa;\n\nTEST(VariantTest, MsgpackEncoding) {\n Variant v(123);\n\n std::vector *encoded_msg = v.to_msgpack();\n uint8_t encoded_buf[1024];\n std::copy(encoded_msg->begin(), encoded_msg->end(), encoded_buf);\n size_t encoded_buf_size = encoded_msg->size();\n\n Variant *v_dash = Variant::from_msgpack(reinterpret_cast(encoded_buf), encoded_buf_size);\n\n EXPECT_TRUE(v_dash->is_int());\n EXPECT_EQ(123, v_dash->get_int());\n}\n\n\nAdd unittests#include \"dsa\/variant.h\"\n#include \"gtest\/gtest.h\"\n\n#include \n\nusing namespace dsa;\ntypedef std::unique_ptr VariantPtr;\n\nTEST(VariantTest, MsgpackEncoding) {\n\n {\n VariantPtr v = VariantPtr(Variant::create(1.23));\n\n std::vector *encoded_msg = v->to_msgpack();\n uint8_t encoded_buf[1024];\n std::copy(encoded_msg->begin(), encoded_msg->end(), encoded_buf);\n size_t encoded_buf_size = encoded_msg->size();\n\n Variant *v_dash = Variant::from_msgpack(reinterpret_cast(encoded_buf), encoded_buf_size);\n\n EXPECT_TRUE(v_dash->is_double());\n EXPECT_EQ(1.23, v_dash->get_double());\n }\n {\n VariantPtr v = VariantPtr(Variant::create(123));\n\n std::vector *encoded_msg = v->to_msgpack();\n uint8_t encoded_buf[1024];\n std::copy(encoded_msg->begin(), encoded_msg->end(), encoded_buf);\n size_t encoded_buf_size = encoded_msg->size();\n\n Variant *v_dash = Variant::from_msgpack(reinterpret_cast(encoded_buf), encoded_buf_size);\n\n EXPECT_TRUE(v_dash->is_int());\n EXPECT_EQ(123, v_dash->get_int());\n }\n}\n\n\n<|endoftext|>"} {"text":"#pragma once\r\n\/\/=========================================================================\/\/\r\n\/*! @file\r\n @brief Test TCP Protocol@n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=========================================================================\/\/\r\n#include \"udp.hpp\"\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief Test TCP プロトコル・クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass test_tcp {\r\n\r\n\t\tint\t\tdesc_;\r\n\t\tbool\tonetime_;\r\n\t\tint\t\topen_delay_;\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttest_tcp() : desc_(-1), onetime_(true), open_delay_(0) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief サービス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tvoid service(ETH& eth, bool server)\r\n\t\t{\r\n\t\t\tif(!onetime_) return;\r\n\r\n\t\t\tif(desc_ < 0) {\r\n\t\t\t\tif(open_delay_ > 0) {\r\n\t\t\t\t\topen_delay_--;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto& ipv4 = eth.at_ipv4();\r\n\t\t\t\tauto& tcp = ipv4.at_tcp();\r\n\t\t\t\tdesc_ = tcp.open(ip_adrs(192,168,3,7), 3000, server);\r\n\t\t\t\tif(desc_ >= 0) {\r\n\t\t\t\t\tutils::format(\"Test TCP Open (%d): %s\\n\")\r\n\t\t\t\t\t\t% desc_ % (server ? \"Server\" : \"Client\");\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tauto& ipv4 = eth.at_ipv4();\r\n\t\t\t\tauto& tcp = ipv4.at_tcp();\r\n\r\n\t\t\t\tchar tmp[256];\r\n\t\t\t\tint len = tcp.recv(desc_, tmp, sizeof(tmp));\r\n\t\t\t\tif(len > 0) {\r\n\t\t\t\t\ttmp[len] = 0;\r\n\t\t\t\t\tutils::format(\"Test TCP Recv (%d): '%s', %d\\n\") % desc_ % tmp % len;\r\n\r\n\t\t\t\t\ttcp.send(desc_, tmp, len);\r\n\t\t\t\t\tutils::format(\"Test TCP Send (%d): '%s', %d\\n\") % desc_ % tmp % len;\r\n\r\n\/\/\/\t\t\t\t\ttcp.close(desc_);\r\n\/\/\/\t\t\t\t\tutils::format(\"Test TCP Close (%d)\\n\") % desc_;\r\n\/\/\/\t\t\t\t\tdesc_ = -1;\r\n\r\n\t\t\t\t\tonetime_ = false;\r\n\t\t\t\t\topen_delay_ = 50;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n}\r\nupdate test code management#pragma once\r\n\/\/=========================================================================\/\/\r\n\/*! @file\r\n @brief Test TCP Protocol@n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=========================================================================\/\/\r\n#include \"udp.hpp\"\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief Test TCP プロトコル・クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass test_tcp {\r\n\r\n\t\tint\t\tdesc_;\r\n\t\tint\t\topen_delay_;\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttest_tcp() : desc_(-1), open_delay_(0) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief サービス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tvoid service(ETH& eth, bool server)\r\n\t\t{\r\n\t\t\tif(desc_ < 0) {\r\n\t\t\t\tif(open_delay_ > 0) {\r\n\t\t\t\t\topen_delay_--;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto& ipv4 = eth.at_ipv4();\r\n\t\t\t\tauto& tcp = ipv4.at_tcp();\r\n\t\t\t\tdesc_ = tcp.open(ip_adrs(192,168,3,7), 3000, server);\r\n\t\t\t\tif(desc_ >= 0) {\r\n\t\t\t\t\tutils::format(\"Test TCP Open (%d): %s\\n\")\r\n\t\t\t\t\t\t% desc_ % (server ? \"Server\" : \"Client\");\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tauto& ipv4 = eth.at_ipv4();\r\n\t\t\t\tauto& tcp = ipv4.at_tcp();\r\n\r\n\t\t\t\tchar tmp[256];\r\n\t\t\t\tint len = tcp.recv(desc_, tmp, sizeof(tmp));\r\n\t\t\t\tif(len > 0) {\r\n\t\t\t\t\ttmp[len] = 0;\r\n\t\t\t\t\tutils::format(\"Test TCP Recv (%d): '%s', %d\\n\") % desc_ % tmp % len;\r\n\r\n\t\t\t\t\ttcp.send(desc_, tmp, len);\r\n\t\t\t\t\tutils::format(\"Test TCP Send (%d): '%s', %d\\n\") % desc_ % tmp % len;\r\n\t\t\t\t}\r\n#if 0\r\n\t\t\t\tif(!tcp.connection(desc_)) {\r\n\t\t\t\t\ttcp.close(desc_);\r\n\t\t\t\t\tutils::format(\"Test TCP Close (%d)\\n\") % desc_;\r\n\t\t\t\t\tdesc_ = -1;\r\n\r\n\t\t\t\t\topen_delay_ = 50;\r\n\t\t\t\t}\r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n}\r\n<|endoftext|>"} {"text":"#include \"DVBInterface.h\"\n#include \"ChannelList.h\"\n#include \"Util.h\"\n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n#include \n#include \n#include \n#include \n#include \n}\n\nstd::mutex newClientsMutex;\nstd::vector newClients;\n\nvoid httpThread(int fd) {\n\tpollfd p;\n\tp.fd = fd;\n\tp.events = POLLIN|POLLHUP;\n\tbool isGet = false, isHead = false, isBad = false, complete = false;\n\twhile(!complete) {\n\t\tchar buf[1024];\n\t\tif(poll(&p, 1, 10000)>0) {\n\t\t\tif(p.revents & POLLHUP) {\n\t\t\t\tclose(fd);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tssize_t count = recv(fd, buf, 1024, 0);\n\t\t\tbuf[count]=0;\n\t\t\tfor(int i=0; i(buf), count);\n\n\t\t\tchar *tmp;\n\t\t\tcomplete = ((count>=2) && buf[count-2]=='\\n' && buf[count-1]=='\\n') || ((count == 1) && buf[0] == '\\n');\n\t\t\tchar *line = strtok_r(buf, \"\\n\", &tmp);\n\t\t\twhile(line) {\n\t\t\t\tUtil::hexdump(reinterpret_cast(line), strlen(line));\n\t\t\t\tif(!strncasecmp(line, \"HEAD \", 5))\n\t\t\t\t\tisHead = true;\n\t\t\t\telse if(!strncasecmp(line, \"GET \", 4))\n\t\t\t\t\tisGet = true;\n\t\t\t\telse if(!isHead && !isGet) {\n\t\t\t\t\tisBad = true; complete = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tline = strtok_r(nullptr, \"\\n\", &tmp);\n\t\t\t}\n\t\t} else {\n\t\t\tclose(fd);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(complete) {\n\t\tif(isGet || isHead) {\n\t\t\tsend(fd, \"HTTP\/1.1 200 OK\\r\\n\", 17, 0);\n\t\t\tsend(fd, \"Cache-Control: no-store, no-cache\\r\\n\", 35, 0);\n\t\t\tsend(fd, \"Content-Type: video\/mp2t\\r\\n\", 26, 0);\n\t\t\tsend(fd, \"\\r\\n\", 2, 0);\n\t\t\tif(isGet) {\n\t\t\t\t\/\/ Start sending the stream...\n\t\t\t\tstd::lock_guard guard(newClientsMutex);\n\t\t\t\tnewClients.push_back(fd);\n\t\t\t\tstd::cerr << \"Client added\" << std::endl;\n\t\t\t} else {\n\t\t\t\tclose(fd);\n\t\t\t}\n\t\t} else {\n\t\t\tsend(fd, \"HTTP\/1.1 400 Bad Request\\r\\n\", 26, 0);\n\t\t\tsend(fd, \"Content-Type: text\/plain\\r\\n\", 26, 0);\n\t\t\tsend(fd, \"\\r\\n\", 2, 0);\n\t\t\tsend(fd, \"Send HEAD or GET\\r\\n\", 18, 0);\n\t\t\tclose(fd);\n\t\t}\n\t}\n}\n\nint main(int argc, char **argv) {\n\tbool useIPv6 = argc>1 && !strcmp(argv[1], \"-6\");\n\tsignal(SIGPIPE, SIG_IGN);\n\n\tDVBInterfaces cards = DVBInterfaces::all();\n\tif(!cards.size()) {\n\t\tstd::cerr << \"No DVB interfaces found\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tChannelList channels(\"channels.dvb\");\n\tif(!channels.size()) {\n\t\tstd::cerr << \"No channel list - run \\\"scan >channels.dvb\\\"\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tauto channel = channels.find(\"Das Erste HD\");\n\tstd::cerr << \"Tuning...\" << std::endl;\n\tcards[0].tune(channel.first);\n\tstd::cerr << \"Setting up channel...\" << std::endl;\n\tcards[0].setup(*channel.second);\n\tstd::cerr << \"Accepting connections\" << std::endl;\n\n\tint dvbFd = open(\"\/dev\/dvb\/adapter0\/dvr0\", O_RDONLY|O_NONBLOCK);\n\tchar dvbbuf[188];\n\n\tint socksize;\n\tint s;\n\tunion {\n\t\tsockaddr addr;\n\t\tsockaddr_in addr_in;\n\t\tsockaddr_in6 addr_in6;\n\t};\n\tunion {\n\t\tsockaddr dest;\n\t\tsockaddr_in dest_in;\n\t\tsockaddr_in6 dest_in6;\n\t};\n\tmemset(&addr, 0, sizeof(addr_in));\n\tif(useIPv6) {\n\t\taddr_in6.sin6_family = AF_INET6;\n\t\taddr_in6.sin6_addr = in6addr_any;\n\t\taddr_in6.sin6_port = htons(8080);\n\t\tsocksize = sizeof(addr_in6);\n\t\ts = socket(AF_INET6, SOCK_STREAM, 0);\n\t} else {\n\t\taddr_in.sin_family = AF_INET;\n\t\taddr_in.sin_addr.s_addr = htonl(INADDR_ANY);\n\t\taddr_in.sin_port = htons(8080);\n\t\tsocksize = sizeof(addr_in);\n\t\ts = socket(AF_INET, SOCK_STREAM, 0);\n\t}\n\tint b = bind(s, &addr, socksize);\n\tint l = listen(s, SOMAXCONN);\n\n\tpollfd p[128];\n\tp[0].fd = s;\n\tp[0].events = POLLIN;\n\tp[1].fd = dvbFd;\n\tp[1].events = POLLIN;\n\tint nfds = 2;\n\n\twhile(true) {\n\t\tif(poll(p, nfds, 10000) > 0) {\n\t\t\tfor(int i=2; i guard(newClientsMutex);\n\t\t\t\t\tfor(int fd: newClients) {\n\t\t\t\t\t\tp[nfds].fd = fd;\n\t\t\t\t\t\tp[nfds++].events = POLLOUT|POLLHUP;\n\t\t\t\t\t}\n\t\t\t\t\tnewClients=std::vector();\n\t\t\t\t}\n\t\t\t\tfor(int i=2; iAllow switching channels#include \"DVBInterface.h\"\n#include \"ChannelList.h\"\n#include \"Util.h\"\n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n#include \n#include \n#include \n#include \n#include \n}\n\nstd::mutex newClientsMutex;\nstd::vector newClients;\nstd::mutex newChannelMutex;\nauto newChannel = std::make_pair(nullptr, nullptr);\n\nvoid httpThread(int fd) {\n\tpollfd p;\n\tp.fd = fd;\n\tp.events = POLLIN|POLLHUP;\n\tbool isGet = false, isHead = false, isBad = false, complete = false;\n\tstd::string path;\n\twhile(!complete) {\n\t\tchar buf[1024];\n\t\tif(poll(&p, 1, 10000)>0) {\n\t\t\tif(p.revents & POLLHUP) {\n\t\t\t\tclose(fd);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tssize_t count = recv(fd, buf, 1024, 0);\n\t\t\tbuf[count]=0;\n\t\t\tfor(int i=0; i(buf), count);\n\n\t\t\tchar *tmp;\n\t\t\tcomplete = ((count>=2) && buf[count-2]=='\\n' && buf[count-1]=='\\n') || ((count == 1) && buf[0] == '\\n');\n\t\t\tchar *line = strtok_r(buf, \"\\n\", &tmp);\n\t\t\twhile(line) {\n\t\t\t\tUtil::hexdump(reinterpret_cast(line), strlen(line));\n\t\t\t\tbool curHead = !strncasecmp(line, \"HEAD \", 5);\n\t\t\t\tbool curGet = !strncasecmp(line, \"GET \", 4);\n\t\t\t\tif(curHead || curGet) {\n\t\t\t\t\tisHead = curHead;\n\t\t\t\t\tisGet = curGet;\n\t\t\t\t\tchar *tmp1;\n\t\t\t\t\tchar *s = strtok_r(line, \" \", &tmp1);\n\t\t\t\t\t\/\/ Skip over \"HEAD \/\" or \"GET \/\" -- we've already seen that\n\t\t\t\t\ts = strtok_r(nullptr, \" \", &tmp1);\n\t\t\t\t\tfor(int i=1; i= '0' && s[i+1] <= '9') || (s[i+1] >= 'a' && s[i+1] <= 'f') || (s[i+1] >= 'A' && s[i+1] <= 'F')) &&\n\t\t\t\t\t\t\t\t((s[i+2] >= '0' && s[i+2] <= '9') || (s[i+2] >= 'a' && s[i+2] <= 'f') || (s[i+2] >= 'A' && s[i+2] <= 'F'))) {\n\t\t\t\t\t\t\tchar code[3] = {s[i+1], s[i+2], 0};\n\t\t\t\t\t\t\tpath.push_back(strtoul(code, nullptr, 16));\n\t\t\t\t\t\t\ti+=2;\n\t\t\t\t\t\t} else if(s[i] == '+')\n\t\t\t\t\t\t\tpath.push_back(' ');\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tpath.push_back(s[i]);\n\t\t\t\t\t}\n\t\t\t\t\ts=strtok_r(nullptr, \"\", &tmp1);\n\t\t\t\t\tif(!s || !strncmp(s, \"HTTP\/0\", 6)) { \/\/ HTTP before 1.0 -- no extras expected\n\t\t\t\t\t\tcomplete = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if(!isHead && !isGet) {\n\t\t\t\t\tisBad = true; complete = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tline = strtok_r(nullptr, \"\\n\", &tmp);\n\t\t\t}\n\t\t} else {\n\t\t\tclose(fd);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(complete) {\n\t\tstd::cerr << \"Got request for \" << path << std::endl;\n\t\tChannelList channels(\"channels.dvb\");\n\t\tauto channel = channels.find(path);\n\t\tif(!channel.first)\n\t\t\tstd::cerr << \"No such channel!\" << std::endl;\n\t\tif(isGet || isHead) {\n\t\t\tsend(fd, \"HTTP\/1.1 200 OK\\r\\n\", 17, 0);\n\t\t\tsend(fd, \"Cache-Control: no-store, no-cache\\r\\n\", 35, 0);\n\t\t\tsend(fd, \"Content-Type: video\/mp2t\\r\\n\", 26, 0);\n\t\t\tsend(fd, \"\\r\\n\", 2, 0);\n\t\t\tif(isGet) {\n\t\t\t\t\/\/ FIXME don't allow switching the channel if we're already\n\t\t\t\t\/\/ streaming to someone else...\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard channelGuard(newChannelMutex);\n\t\t\t\t\tnewChannel = channel;\n\t\t\t\t}\n\t\t\t\t\/\/ Start sending the stream...\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard guard(newClientsMutex);\n\t\t\t\t\tnewClients.push_back(fd);\n\t\t\t\t}\n\t\t\t\tstd::cerr << \"Client added\" << std::endl;\n\t\t\t} else {\n\t\t\t\tclose(fd);\n\t\t\t}\n\t\t} else {\n\t\t\tsend(fd, \"HTTP\/1.1 400 Bad Request\\r\\n\", 26, 0);\n\t\t\tsend(fd, \"Content-Type: text\/plain\\r\\n\", 26, 0);\n\t\t\tsend(fd, \"\\r\\n\", 2, 0);\n\t\t\tsend(fd, \"Send HEAD or GET\\r\\n\", 18, 0);\n\t\t\tclose(fd);\n\t\t}\n\t}\n}\n\nint main(int argc, char **argv) {\n\tbool useIPv6 = argc>1 && !strcmp(argv[1], \"-6\");\n\tsignal(SIGPIPE, SIG_IGN);\n\n\tDVBInterfaces cards = DVBInterfaces::all();\n\tif(!cards.size()) {\n\t\tstd::cerr << \"No DVB interfaces found\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tChannelList channels(\"channels.dvb\");\n\tif(!channels.size()) {\n\t\tstd::cerr << \"No channel list - run \\\"scan >channels.dvb\\\"\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tauto channel = channels.find(\"Das Erste HD\");\n\tstd::cerr << \"Tuning...\" << std::endl;\n\tcards[0].tune(channel.first);\n\tstd::cerr << \"Setting up channel...\" << std::endl;\n\tcards[0].setup(*channel.second);\n\tstd::cerr << \"Accepting connections\" << std::endl;\n\n\tint dvbFd = open(\"\/dev\/dvb\/adapter0\/dvr0\", O_RDONLY|O_NONBLOCK);\n\tchar dvbbuf[188];\n\n\tint socksize;\n\tint s;\n\tunion {\n\t\tsockaddr addr;\n\t\tsockaddr_in addr_in;\n\t\tsockaddr_in6 addr_in6;\n\t};\n\tunion {\n\t\tsockaddr dest;\n\t\tsockaddr_in dest_in;\n\t\tsockaddr_in6 dest_in6;\n\t};\n\tmemset(&addr, 0, sizeof(addr_in));\n\tif(useIPv6) {\n\t\taddr_in6.sin6_family = AF_INET6;\n\t\taddr_in6.sin6_addr = in6addr_any;\n\t\taddr_in6.sin6_port = htons(8080);\n\t\tsocksize = sizeof(addr_in6);\n\t\ts = socket(AF_INET6, SOCK_STREAM, 0);\n\t} else {\n\t\taddr_in.sin_family = AF_INET;\n\t\taddr_in.sin_addr.s_addr = htonl(INADDR_ANY);\n\t\taddr_in.sin_port = htons(8080);\n\t\tsocksize = sizeof(addr_in);\n\t\ts = socket(AF_INET, SOCK_STREAM, 0);\n\t}\n\tint b = bind(s, &addr, socksize);\n\tint l = listen(s, SOMAXCONN);\n\n\tpollfd p[128];\n\tp[0].fd = s;\n\tp[0].events = POLLIN;\n\tp[1].fd = dvbFd;\n\tp[1].events = POLLIN;\n\tint nfds = 2;\n\n\twhile(true) {\n\t\tif(poll(p, nfds, 10000) > 0) {\n\t\t\tfor(int i=2; i channelGuard(newChannelMutex);\n\t\t\t\tif(newChannel.first) {\n\t\t\t\t\tclose(dvbFd);\n\t\t\t\t\tcards[0].tune(newChannel.first);\n\t\t\t\t\tcards[0].setup(*newChannel.second);\n\t\t\t\t\tnewChannel=std::make_pair(nullptr, nullptr);\n\t\t\t\t\tdvbFd = open(\"\/dev\/dvb\/adapter0\/dvr0\", O_RDONLY|O_NONBLOCK);\n\t\t\t\t\tp[1].fd = dvbFd;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(p[1].revents & POLLIN) {\n\t\t\t\tsize_t bytes = read(dvbFd, dvbbuf, 188);\n\t\t\t\tif(bytes>0)\n\t\t\t\t{\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::lock_guard guard(newClientsMutex);\n\t\t\t\t\t\tfor(int fd: newClients) {\n\t\t\t\t\t\t\tp[nfds].fd = fd;\n\t\t\t\t\t\t\tp[nfds++].events = POLLOUT|POLLHUP;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnewClients=std::vector();\n\t\t\t\t\t}\n\t\t\t\t\tfor(int i=2; i"} {"text":"#include \"builders\/buildings\/roofs\/FlatRoofBuilder.hpp\"\n#include \"builders\/buildings\/facades\/FlatFacadeBuilder.hpp\"\n#include \"builders\/misc\/BarrierBuilder.hpp\"\n#include \"clipper\/clipper.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"utils\/ElementUtils.hpp\"\n#include \"utils\/GeoUtils.hpp\"\n\nusing namespace ClipperLib;\nusing namespace utymap::builders;\nusing namespace utymap::entities;\nusing namespace utymap::mapcss;\nusing namespace utymap::meshing;\nusing namespace utymap::utils;\n\nnamespace {\n const double Scale = 1E7;\n const std::string HeightKey = \"height\";\n const std::string MinHeightKey = \"min-height\";\n const std::string OffsetKey = \"offset\";\n const std::string MeshNamePrefix = \"barrier\";\n}\n\nvoid BarrierBuilder::visitWay(const Way& way)\n{\n Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);\n\n ClipperOffset offset;\n Path path;\n path.reserve(way.coordinates.size());\n\n for (const auto& coord : way.coordinates) {\n path.push_back(IntPoint(coord.longitude * Scale, coord.latitude * Scale));\n }\n\n offset.AddPath(path, JoinType::jtMiter, EndType::etOpenSquare);\n\n Paths solution;\n double offsetInMeters = style.getValue(OffsetKey, way.tags);\n double offsetInGrads = GeoUtils::getOffset(way.coordinates[0], offsetInMeters);\n offset.Execute(solution, offsetInGrads * Scale);\n\n \/\/ get polygon\n Polygon polygon(solution.size(), 0);\n std::vector vertices;\n vertices.reserve(solution[0].size());\n for (const auto& p : solution[0]) {\n vertices.push_back(Vector2(p.X \/ Scale, p.Y \/ Scale));\n }\n polygon.addContour(vertices);\n\n buildFromPolygon(way, style, polygon);\n}\n\nvoid BarrierBuilder::buildFromPolygon(const Way& way, const Style& style, Polygon& polygon)\n{\n double height = style.getValue(HeightKey, way.tags);\n double minHeight = style.getValue(MinHeightKey, way.tags);\n double elevation = context_.eleProvider.getElevation(way.coordinates[0]) + minHeight;\n\n Mesh mesh(utymap::utils::getMeshName(MeshNamePrefix, way));\n MeshContext meshContext(mesh, style);\n\n \/\/ NOTE: Reuse building builders.\n\n FlatRoofBuilder roofBuilder(context_, meshContext);\n roofBuilder.setHeight(0);\n roofBuilder.setMinHeight(elevation + height);\n roofBuilder.build(polygon);\n\n FlatFacadeBuilder facadeBuilder(context_, meshContext);\n facadeBuilder.setHeight(height);\n facadeBuilder.setMinHeight(elevation);\n facadeBuilder.build(polygon);\n\n context_.meshCallback(mesh);\n}core: fix barrier mesh name#include \"builders\/buildings\/roofs\/FlatRoofBuilder.hpp\"\n#include \"builders\/buildings\/facades\/FlatFacadeBuilder.hpp\"\n#include \"builders\/misc\/BarrierBuilder.hpp\"\n#include \"clipper\/clipper.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"utils\/ElementUtils.hpp\"\n#include \"utils\/GeoUtils.hpp\"\n\nusing namespace ClipperLib;\nusing namespace utymap::builders;\nusing namespace utymap::entities;\nusing namespace utymap::mapcss;\nusing namespace utymap::meshing;\nusing namespace utymap::utils;\n\nnamespace {\n const double Scale = 1E7;\n const std::string HeightKey = \"height\";\n const std::string MinHeightKey = \"min-height\";\n const std::string OffsetKey = \"offset\";\n const std::string MeshNamePrefix = \"barrier:\";\n}\n\nvoid BarrierBuilder::visitWay(const Way& way)\n{\n Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);\n\n ClipperOffset offset;\n Path path;\n path.reserve(way.coordinates.size());\n\n for (const auto& coord : way.coordinates) {\n path.push_back(IntPoint(coord.longitude * Scale, coord.latitude * Scale));\n }\n\n offset.AddPath(path, JoinType::jtMiter, EndType::etOpenSquare);\n\n Paths solution;\n double offsetInMeters = style.getValue(OffsetKey, way.tags);\n double offsetInGrads = GeoUtils::getOffset(way.coordinates[0], offsetInMeters);\n offset.Execute(solution, offsetInGrads * Scale);\n\n \/\/ get polygon\n Polygon polygon(solution.size(), 0);\n std::vector vertices;\n vertices.reserve(solution[0].size());\n for (const auto& p : solution[0]) {\n vertices.push_back(Vector2(p.X \/ Scale, p.Y \/ Scale));\n }\n polygon.addContour(vertices);\n\n buildFromPolygon(way, style, polygon);\n}\n\nvoid BarrierBuilder::buildFromPolygon(const Way& way, const Style& style, Polygon& polygon)\n{\n double height = style.getValue(HeightKey, way.tags);\n double minHeight = style.getValue(MinHeightKey, way.tags);\n double elevation = context_.eleProvider.getElevation(way.coordinates[0]) + minHeight;\n\n Mesh mesh(utymap::utils::getMeshName(MeshNamePrefix, way));\n MeshContext meshContext(mesh, style);\n\n \/\/ NOTE: Reuse building builders.\n\n FlatRoofBuilder roofBuilder(context_, meshContext);\n roofBuilder.setHeight(0);\n roofBuilder.setMinHeight(elevation + height);\n roofBuilder.build(polygon);\n\n FlatFacadeBuilder facadeBuilder(context_, meshContext);\n facadeBuilder.setHeight(height);\n facadeBuilder.setMinHeight(elevation);\n facadeBuilder.build(polygon);\n\n context_.meshCallback(mesh);\n}<|endoftext|>"} {"text":"#include \"Symbol.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace escale9\n{\n\nSymbol::Symbol()\n{\n\tstatic int id = 0;\n\tm_name = ee::SymbolFile::Instance()->Tag(s2::SYM_SCALE9) + gum::StringHelper::ToString(id++);\n}\n\nvoid Symbol::LoadResources()\n{\n\tee::SpriteLoader spr_loader;\n\tgum::Scale9SymLoader loader(this, &spr_loader);\n\tloader.LoadJson(m_filepath);\n}\n\n}[FIXED] scale9 cut edge#include \"Symbol.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace escale9\n{\n\nSymbol::Symbol()\n{\n\tstatic int id = 0;\n\tm_name = ee::SymbolFile::Instance()->Tag(s2::SYM_SCALE9) + gum::StringHelper::ToString(id++);\n}\n\nvoid Symbol::LoadResources()\n{\n\tee::SettingData& setting = ee::Config::Instance()->GetSettings();\n\tsetting.open_image_edge_clip = false;\n\n\tee::SpriteLoader spr_loader;\n\tgum::Scale9SymLoader loader(this, &spr_loader);\n\tloader.LoadJson(m_filepath);\n\n\tsetting.open_image_edge_clip = true;\n}\n\n}<|endoftext|>"} {"text":"#include \n#include \"type\/type.h\"\n#include \"ratimake\/adjustit_connector.h\"\n\n#include \n\n#include \"type\/message.h\"\n#include \n#include \"utils\/exception.h\"\n#include \"config.h\"\n#include \n\nnamespace nt = navitia::type;\nnamespace po = boost::program_options;\nnamespace pt = boost::posix_time;\n\npo::variables_map load_config(int argc, const char** argv){\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Affiche l'aide\")\n (\"date,d\", po::value(), \"Date considéré comme maintenant\")\n (\"version,v\", \"Affiche la version\")\n (\"config-file\", po::value()->default_value(argv[0] + std::string(\".ini\")), \"chemin vers le fichier de configuration\")\n (\"log4cplus-config-file\", po::value()->default_value(\"log4cplus.ini\"), \"chemin vers le fichier de configuration de log4cplus\")\n (\"connect-string\", po::value(), \"parametres de connection à la base de données : DRIVER=FreeTDS;SERVER=;UID=;PWD=;DATABASE=;TDS_Version=8.0;Port=1433;ClientCharset=UTF-8\")\n (\"media-lang\", po::value()->default_value(\"FR\"), \"filename\")\n (\"media-media\", po::value()->default_value(\"INTERNET\"), \"filename\")\n (\"destination\", po::value(), \"nom du fichier généré par ratimake\");\n\n po::variables_map vm;\n\n po::store(po::parse_command_line(argc, argv, desc), vm);\n\n if(vm.count(\"help\")){\n std::cout << desc << \"\\n\";\n return 0;\n }\n\n if(vm.count(\"config-file\")){\n std::ifstream stream;\n stream.open(vm[\"config-file\"].as());\n if(!stream.is_open()){\n throw navitia::exception(\"loading config file failed\");\n }else{\n po::store(po::parse_config_file(stream, desc), vm);\n }\n }\n po::notify(vm);\n\n return vm;\n}\n\nvoid generate(const po::variables_map& params, const pt::ptime& now){\n log4cplus::Logger logger = log4cplus::Logger::getInstance(\"log\");\n navitia::ratimake::AtLoader loader;\n std::map> messages;\n\n messages = loader.load(params, now);\n\n nt::MessageHolder holder;\n holder.messages = messages;\n holder.generation_date = pt::second_clock::universal_time();\n\n LOG4CPLUS_DEBUG(logger, boost::format(\"nb objects impactés: %s\") % messages.size());\n holder.save(params[\"destination\"].as());\n}\n\nint main(int argc, char const* argv[]){\n init_logger();\n\n po::variables_map params;\n\n try{\n params = load_config(argc, argv);\/\/@TODO: config\n }catch(const std::exception& e){\n std::cerr << e.what() << std::endl;\n return 1;\n }\n\n if(params.count(\"version\")){\n std::cout << argv[0] << \" V\" << NAVITIA_VERSION << \" \" << NAVITIA_BUILD_TYPE << std::endl;\n return 0;\n }\n\n pt::ptime now;\n if(params.count(\"date\")){\n now = pt::time_from_string(params[\"date\"].as());\n }else{\n now = pt::second_clock::local_time();\n }\n\n\n if(params.count(\"log4cplus-config-file\")){\n init_logger(params[\"log4cplus-config-file\"].as());\n }\n log4cplus::Logger logger = log4cplus::Logger::getInstance(\"log\");\n\n if(!params.count(\"connect-string\") || params[\"connect-string\"].as().empty()){\n LOG4CPLUS_FATAL(logger, \"chaine de connection à la base non défini\");\n return 2;\n }\n\n try{\n generate(params, now);\n }catch(const std::exception& e){\n LOG4CPLUS_FATAL(logger, e.what());\n return 3;\n }\n\n return 0;\n}\nhelp sur ratimake#include \n#include \"type\/type.h\"\n#include \"ratimake\/adjustit_connector.h\"\n\n#include \n\n#include \"type\/message.h\"\n#include \n#include \"utils\/exception.h\"\n#include \"config.h\"\n#include \n\nnamespace nt = navitia::type;\nnamespace po = boost::program_options;\nnamespace pt = boost::posix_time;\n\npo::variables_map load_config(int argc, const char** argv){\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Affiche l'aide\")\n (\"date,d\", po::value(), \"Date considéré comme maintenant\")\n (\"version,v\", \"Affiche la version\")\n (\"config-file\", po::value()->default_value(argv[0] + std::string(\".ini\")), \"chemin vers le fichier de configuration\")\n (\"log4cplus-config-file\", po::value()->default_value(\"log4cplus.ini\"), \"chemin vers le fichier de configuration de log4cplus\")\n (\"connect-string\", po::value(), \"parametres de connection à la base de données : DRIVER=FreeTDS;SERVER=;UID=;PWD=;DATABASE=;TDS_Version=8.0;Port=1433;ClientCharset=UTF-8\")\n (\"media-lang\", po::value()->default_value(\"FR\"), \"langue du media à charger\")\n (\"media-media\", po::value()->default_value(\"INTERNET\"), \"media à cahrger\")\n (\"destination\", po::value()->default_value(\"at.rt.lz4\"), \"nom du fichier généré par ratimake\");\n\n po::variables_map vm;\n\n po::store(po::parse_command_line(argc, argv, desc), vm);\n\n if(vm.count(\"help\")){\n std::cout << desc << \"\\n\";\n return 0;\n }\n\n if(vm.count(\"config-file\")){\n std::ifstream stream;\n stream.open(vm[\"config-file\"].as());\n if(!stream.is_open()){\n throw navitia::exception(\"loading config file failed\");\n }else{\n po::store(po::parse_config_file(stream, desc), vm);\n }\n }\n po::notify(vm);\n\n return vm;\n}\n\nvoid generate(const po::variables_map& params, const pt::ptime& now){\n log4cplus::Logger logger = log4cplus::Logger::getInstance(\"log\");\n navitia::ratimake::AtLoader loader;\n std::map> messages;\n\n messages = loader.load(params, now);\n\n nt::MessageHolder holder;\n holder.messages = messages;\n holder.generation_date = pt::second_clock::universal_time();\n\n LOG4CPLUS_DEBUG(logger, boost::format(\"nb objects impactés: %s\") % messages.size());\n holder.save(params[\"destination\"].as());\n}\n\nint main(int argc, char const* argv[]){\n init_logger();\n\n po::variables_map params;\n\n try{\n params = load_config(argc, argv);\/\/@TODO: config\n }catch(const std::exception& e){\n std::cerr << e.what() << std::endl;\n return 1;\n }\n\n if(params.count(\"version\")){\n std::cout << argv[0] << \" V\" << NAVITIA_VERSION << \" \" << NAVITIA_BUILD_TYPE << std::endl;\n return 0;\n }\n\n pt::ptime now;\n if(params.count(\"date\")){\n now = pt::time_from_string(params[\"date\"].as());\n }else{\n now = pt::second_clock::local_time();\n }\n\n\n if(params.count(\"log4cplus-config-file\")){\n init_logger(params[\"log4cplus-config-file\"].as());\n }\n log4cplus::Logger logger = log4cplus::Logger::getInstance(\"log\");\n\n if(!params.count(\"connect-string\") || params[\"connect-string\"].as().empty()){\n LOG4CPLUS_FATAL(logger, \"chaine de connection à la base non défini\");\n return 2;\n }\n\n try{\n generate(params, now);\n }catch(const std::exception& e){\n LOG4CPLUS_FATAL(logger, e.what());\n return 3;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"Arduino.h\"\n#include \"main.hpp\"\n#include \"dht.h\"\n#include \n#include \n\n#ifdef RH_PLATFORM_NANO\n# include \nSoftwareSerial Serial1(10, 11); \/\/ RX, TX\n#endif\n\n#define DHT11_PIN 5\n#define LDR_PIN 4\n\n\/\/ Sensores\ndht DHTSensor;\nldr LDRSensor = ldr(LDR_PIN);\n\n\/\/ Variáveis de Ambiente\nuint16_t TemperatureHumidity[4];\n\n\nvoid setup(){\n Serial.begin(115200);\n \/\/ Por enquanto\n Serial.println(\"DHT TEST PROGRAM \");\n Serial.print(\"LIBRARY VERSION: \");\n Serial.println(DHT_LIB_VERSION);\n Serial.println();\n Serial.println(\"Type,\\tstatus,\\tHumidity (%),\\tTemperature (C)\");\n\n #ifdef RH_PLATFORM_MEGA\n Serial1.begin(115200);\n #endif\n}\n\nvoid loop(){\n dhtDebug(DHTSensor, DHT11_PIN);\n TemperatureHumidity[0] = DHTSensor.read11(DHT11_PIN);\n TemperatureHumidity[1] = DHTSensor.temperature;\n TemperatureHumidity[2] = DHTSensor.humidity;\n TemperatureHumidity[3] = LDRSensor.check();\n\n\n delay(2000);\n} \/\/ loop\nTravis CI#include \"Arduino.h\"\n#include \"main.hpp\"\n#include \"dht.h\"\n#include \n#include <..\/lib\/MQ-Sensor\/src\/MQSensor.hpp>\n#include <..\/lib\/PrintManager\/src\/PrintManager.hpp>\n\n#ifdef RH_PLATFORM_NANO\n# include \nSoftwareSerial Serial1(10, 11); \/\/ RX, TX\n#endif\n\n#define DHT11_PIN 5\n#define LDR_PIN 4\n\n\/\/ Sensores\ndht DHTSensor;\nldr LDRSensor = ldr(LDR_PIN);\nMQSensor Dummy = MQSensor::NewMQSensor(1, MQ_SENSOR_DUMMY);\nPrintManager BT_Serial = PrintManager(&Serial1); \/\/ Explicit ti pointer conversion\n\n\/* MONTAGEM\n * LDR\/pot pino 4\n * DHT pino 5\n * VAZIO pino 1\n * BLUETOOTH Serial1\n *\n * \/\/*\/\n\n\/\/ Variáveis de Ambiente\nuint16_t TemperatureHumidity[10];\n\n\/\/ Build ffffffffffffffffffffffffffffsadsedfeasrfwerawewtaerg\nvoid setup(){\n Serial.begin(115200);\n \/\/ Por enquanto\n Serial.println(\"DHT TEST PROGRAM \");\n Serial.print(\"LIBRARY VERSION: \");\n Serial.println(DHT_LIB_VERSION);\n Serial.println();\n Serial.println(\"Type,\\tstatus,\\tHumidity (%),\\tTemperature (C)\");\n\n \/\/ #ifdef RH_PLATFORM_MEGA\n Serial1.begin(115200);\n \/\/ #endif\n}\n\nvoid loop(){\n dhtDebug(DHTSensor, DHT11_PIN);\n TemperatureHumidity[0] = DHTSensor.read11(DHT11_PIN);\n TemperatureHumidity[1] = DHTSensor.temperature;\n TemperatureHumidity[2] = DHTSensor.humidity;\n TemperatureHumidity[3] = LDRSensor.check();\n\n BT_Serial.addValue(\"th\", DHTSensor.temperature, DHTSensor.humidity);\n\n TemperatureHumidity[5] = Dummy.check();\n BT_Serial.addValue(\"M\", TemperatureHumidity[5]);\n\n BT_Serial.sendData();\n\n delay(2000);\n} \/\/ loop\n<|endoftext|>"} {"text":"\/* Copyright © 2001-2016, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"type\/geographical_coord.h\"\n#include \"utils\/exception.h\"\n#include \"isochrone.h\"\n#include \"raptor.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace navitia { namespace routing {\n\nIsochroneException::~IsochroneException() noexcept = default;\n\ntype::GeographicalCoord project_in_direction(const type::GeographicalCoord& center,\n const double& direction,\n const double& radius){\n using navitia::type::GeographicalCoord;\n assert(radius > 0);\n double alpha = radius \/ GeographicalCoord::EARTH_RADIUS_IN_METERS;\n double direction_rad = fmod(direction, 360) * GeographicalCoord::N_DEG_TO_RAD;\n if (direction < 0) {\n direction_rad = 2 * M_PI - direction_rad;\n }\n double center_lat_deg = center.lat();\n double center_lon_deg = center.lon();\n type::GeographicalCoord center_right_interval = type::GeographicalCoord(center_lon_deg, center_lat_deg);\n double center_lat_rad = center_right_interval.lat() * GeographicalCoord::N_DEG_TO_RAD;\n double center_lon_rad = center_right_interval.lon() * GeographicalCoord::N_DEG_TO_RAD;\n double lat;\n double lon;\n \/\/ To avoid rounding error we use ° instread of rad.\n if (fabs(center_right_interval.lat()) == 90) {\n lon = direction_rad - M_PI;\n lat = M_PI_2 - alpha;\n } else {\n double delta_lat;\n double delta_lon;\n if (fmod(direction, 180) == 0) {\n delta_lat = pow(-1, fmod(direction \/ 180, 2)) * alpha;\n lat = center_lat_rad + delta_lat;\n lon = center_lon_rad;\n } else {\n \/\/ asin and acos give results in rad.\n double projection = asin(sin(alpha) * sin(direction_rad));\n delta_lat = acos(cos(alpha) \/ cos(projection));\n if (direction_rad > M_PI_2 && direction_rad < 3 * M_PI_2) {\n delta_lat = -1 * delta_lat;\n }\n lat = center_lat_rad + delta_lat;\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wfloat-equal\"\n if (lat == M_PI_2) {\n delta_lon = (direction == 90 ? 1 : - 1) * alpha;\n#pragma GCC diagnostic pop\n } else {\n double b = (cos(alpha) - sin(lat) * sin(center_lat_rad)) \/ (cos(lat) * cos(center_lat_rad));\n if (fabs(b) > 1) {\n b = (std::signbit(b) ? fmod(b - 1, 2) + 1 : fmod(b + 1, 2) - 1);\n }\n delta_lon = acos(b);\n if (direction_rad > M_PI) {\n delta_lon = -1 * delta_lon;\n }\n }\n lon = center_lon_rad + delta_lon;\n }\n }\n \/\/ Lon and lat are in °\n double lon_deg = lon * N_RAD_TO_DEG;\n double lat_deg = lat * N_RAD_TO_DEG;\n return type::GeographicalCoord(lon_deg, lat_deg);\n}\n\nstatic type::GeographicalCoord build_sym (const type::GeographicalCoord& point,\n const type::GeographicalCoord& center,\n const unsigned int& i) {\n if (i % 180 == 0) {\n return type::GeographicalCoord(2*center.lon() - point.lon(), point.lat());\n } else {\n return type::GeographicalCoord(point.lon(), 2*center.lat() - point.lat());\n }\n}\n\ntype::Polygon circle(const type::GeographicalCoord& center,\n const double& radius) {\n type::Polygon points;\n auto& points_out = points.outer();\n points_out.reserve(180);\n for (unsigned int i = 0; i <= 90; i += 2) {\n points_out.push_back(project_in_direction(center, i, radius));\n }\n for (unsigned int j = 90; j <= 270; j += 90) {\n for (unsigned int k = 1; k <= 45; k++) {\n type::GeographicalCoord point;\n point = points_out[j \/ 2 - k];\n points_out.push_back(build_sym(point, center, j));\n }\n }\n points_out.push_back(project_in_direction(center, 0, radius));\n return points;\n}\n\nstatic type::MultiPolygon merge_poly(const type::MultiPolygon& multi_poly,\n const type::Polygon& poly) {\n type::MultiPolygon poly_union;\n try {\n boost::geometry::union_(poly, multi_poly, poly_union);\n } catch (const boost::geometry::exception& e) {\n \/\/We don't merge the polygons\n log4cplus::Logger logger = log4cplus::Logger::getInstance(\"logger\");\n LOG4CPLUS_WARN(logger, \"impossible to merge polygon: \" << e.what());\n }\n return poly_union;\n}\n\nstruct InfoCircle {\n type::GeographicalCoord center;\n double distance;\n int duration_left;\n InfoCircle(const type::GeographicalCoord& center,\n const double& distance,\n const int& duration_left): center(center),\n distance(distance),\n duration_left(duration_left) {}\n};\n\nstatic bool within_info_circle(const InfoCircle& circle,\n const std::vector& multi_poly,\n const double speed) {\n auto begin = multi_poly.begin();\n const auto end = multi_poly.end();\n double circle_radius = circle.duration_left * speed;\n double coslat = cos(circle.center.lat() * type::GeographicalCoord::N_DEG_TO_RAD);\n return any_of(begin, end, [=](const InfoCircle& it) {\n double it_radius = it.duration_left * speed;\n return sqrt(circle.center.approx_sqr_distance(it.center, coslat)) + circle_radius < it_radius;\n });\n}\n\nstatic std::vector delete_useless_circle(std::vector circles,\n const double speed) {\n std::vector useful_circles;\n boost::sort(circles,\n [](const InfoCircle& a, const InfoCircle& b) {return a.duration_left > b.duration_left;});\n auto it = circles.begin();\n const auto end = circles.end();\n for (; it != end; ++it) {\n if (!within_info_circle(*it, useful_circles, speed)) {\n useful_circles.push_back(std::move(*it));\n }\n }\n return useful_circles;\n}\n\ntemplate\nstatic bool in_bound(const T & begin, const T & end, bool clockwise) {\n return (clockwise && begin < end) ||\n (!clockwise && begin > end);\n}\n\ntype::MultiPolygon build_single_isochrone(RAPTOR& raptor,\n const std::vector& stop_points,\n const bool clockwise,\n const type::GeographicalCoord& coord_origin,\n const DateTime& bound,\n const map_stop_point_duration& origin,\n const double& speed,\n const int& duration) {\n std::vector circles_classed;\n type::MultiPolygon circles;\n InfoCircle to_add = InfoCircle(coord_origin, 0, duration);\n circles_classed.push_back(to_add);\n const auto& data_departure = raptor.data.pt_data->stop_points;\n for (auto it = origin.begin(); it != origin.end(); ++it){\n if (it->second.total_seconds() < duration) {\n int duration_left = duration - int(it->second.total_seconds());\n if (duration_left * speed < MIN_RADIUS) {continue;}\n const auto& center = data_departure[it->first.val]->coord;\n InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);\n circles_classed.push_back(to_add);\n }\n }\n for(const type::StopPoint* sp: stop_points) {\n SpIdx sp_idx(*sp);\n const auto best_lbl = raptor.best_labels_pts[sp_idx];\n if (in_bound(best_lbl, bound, clockwise)) {\n uint duration_left = abs(int(best_lbl) - int(bound));\n if (duration_left * speed < MIN_RADIUS) {continue;}\n const auto& center = sp->coord;\n InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);\n circles_classed.push_back(to_add);\n }\n }\n std::vector circles_check = delete_useless_circle(std::move(circles_classed), speed);\n\n for (const auto& c: circles_check) {\n type::Polygon circle_to_add = circle(c.center, c.duration_left * speed);\n circles = merge_poly(circles, circle_to_add);\n }\n return circles;\n}\n\ntype::MultiPolygon build_isochrones(RAPTOR& raptor,\n const bool clockwise,\n const type::GeographicalCoord& coord_origin,\n const DateTime& bound_max,\n const DateTime& bound_min,\n const map_stop_point_duration& origin,\n const double& speed,\n const int& max_duration,\n const int& min_duration) {\n type::MultiPolygon isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,\n clockwise, coord_origin, bound_max, origin,\n speed, max_duration);\n if (min_duration > 0) {\n type::MultiPolygon output;\n type::MultiPolygon min_isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,\n clockwise, coord_origin, bound_min, origin,\n speed, min_duration);\n boost::geometry::difference(isochrone, min_isochrone, output);\n isochrone = output;\n }\n return isochrone;\n}\n\n}} \/\/namespace navitia::routing\nCorrection\/* Copyright © 2001-2016, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"type\/geographical_coord.h\"\n#include \"utils\/exception.h\"\n#include \"isochrone.h\"\n#include \"raptor.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace navitia { namespace routing {\n\nIsochroneException::~IsochroneException() noexcept = default;\n\ntype::GeographicalCoord project_in_direction(const type::GeographicalCoord& center,\n const double& direction,\n const double& radius){\n using navitia::type::GeographicalCoord;\n assert(radius > 0);\n double alpha = radius \/ GeographicalCoord::EARTH_RADIUS_IN_METERS;\n double direction_rad = fmod(direction, 360) * GeographicalCoord::N_DEG_TO_RAD;\n if (direction < 0) {\n direction_rad = 2 * M_PI - direction_rad;\n }\n double center_lat_deg = center.lat();\n double center_lon_deg = center.lon();\n type::GeographicalCoord center_right_interval = type::GeographicalCoord(center_lon_deg, center_lat_deg);\n double center_lat_rad = center_right_interval.lat() * GeographicalCoord::N_DEG_TO_RAD;\n double center_lon_rad = center_right_interval.lon() * GeographicalCoord::N_DEG_TO_RAD;\n double lat;\n double lon;\n \/\/ To avoid rounding error we use ° instread of rad.\n if (fabs(center_right_interval.lat()) == 90) {\n lon = direction_rad - M_PI;\n lat = M_PI_2 - alpha;\n } else {\n double delta_lat;\n double delta_lon;\n if (fmod(direction, 180) == 0) {\n delta_lat = pow(-1, fmod(direction \/ 180, 2)) * alpha;\n lat = center_lat_rad + delta_lat;\n lon = center_lon_rad;\n } else {\n \/\/ asin and acos give results in rad.\n double projection = asin(sin(alpha) * sin(direction_rad));\n delta_lat = acos(cos(alpha) \/ cos(projection));\n if (direction_rad > M_PI_2 && direction_rad < 3 * M_PI_2) {\n delta_lat = -1 * delta_lat;\n }\n lat = center_lat_rad + delta_lat;\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wfloat-equal\"\n if (lat == M_PI_2) {\n delta_lon = (direction == 90 ? 1 : - 1) * alpha;\n#pragma GCC diagnostic pop\n } else {\n double b = (cos(alpha) - sin(lat) * sin(center_lat_rad)) \/ (cos(lat) * cos(center_lat_rad));\n if (fabs(b) > 1) {\n b = (std::signbit(b) ? fmod(b - 1, 2) + 1 : fmod(b + 1, 2) - 1);\n }\n delta_lon = acos(b);\n if (direction_rad > M_PI) {\n delta_lon = -1 * delta_lon;\n }\n }\n lon = center_lon_rad + delta_lon;\n }\n }\n \/\/ Lon and lat are in °\n double lon_deg = lon * N_RAD_TO_DEG;\n double lat_deg = lat * N_RAD_TO_DEG;\n return type::GeographicalCoord(lon_deg, lat_deg);\n}\n\nstatic type::GeographicalCoord build_sym (const type::GeographicalCoord& point,\n const type::GeographicalCoord& center,\n const unsigned int& i) {\n if (i % 180 == 0) {\n return type::GeographicalCoord(2*center.lon() - point.lon(), point.lat());\n } else {\n return type::GeographicalCoord(point.lon(), 2*center.lat() - point.lat());\n }\n}\n\ntype::Polygon circle(const type::GeographicalCoord& center,\n const double& radius) {\n type::Polygon points;\n auto& points_out = points.outer();\n points_out.reserve(180);\n for (unsigned int i = 0; i <= 90; i += 2) {\n points_out.push_back(project_in_direction(center, i, radius));\n }\n for (unsigned int j = 90; j <= 270; j += 90) {\n for (unsigned int k = 1; k <= 45; k++) {\n type::GeographicalCoord point;\n point = points_out[j \/ 2 - k];\n points_out.push_back(build_sym(point, center, j));\n }\n }\n points_out.push_back(project_in_direction(center, 0, radius));\n return points;\n}\n\nstatic type::MultiPolygon merge_poly(const type::MultiPolygon& multi_poly,\n const type::Polygon& poly) {\n type::MultiPolygon poly_union;\n try {\n boost::geometry::union_(poly, multi_poly, poly_union);\n } catch (const boost::geometry::exception& e) {\n \/\/We don't merge the polygons\n log4cplus::Logger logger = log4cplus::Logger::getInstance(\"logger\");\n LOG4CPLUS_WARN(logger, \"impossible to merge polygon: \" << e.what());\n }\n return poly_union;\n}\n\nstruct InfoCircle {\n type::GeographicalCoord center;\n double distance;\n int duration_left;\n InfoCircle(const type::GeographicalCoord& center,\n const double& distance,\n const int& duration_left): center(center),\n distance(distance),\n duration_left(duration_left) {}\n};\n\nstatic bool within_info_circle(const InfoCircle& circle,\n const std::vector& multi_poly,\n const double speed) {\n auto begin = multi_poly.begin();\n const auto end = multi_poly.end();\n double circle_radius = circle.duration_left * speed;\n double coslat = cos(circle.center.lat() * type::GeographicalCoord::N_DEG_TO_RAD);\n return any_of(begin, end, [&](const InfoCircle& it) {\n double it_radius = it.duration_left * speed;\n return sqrt(circle.center.approx_sqr_distance(it.center, coslat)) + circle_radius < it_radius;\n });\n}\n\nstatic std::vector delete_useless_circle(std::vector circles,\n const double speed) {\n std::vector useful_circles;\n boost::sort(circles,\n [](const InfoCircle& a, const InfoCircle& b) {return a.duration_left > b.duration_left;});\n for (auto& circle: circles) {\n if (!within_info_circle(circle, useful_circles, speed)) {\n useful_circles.push_back(std::move(circle));\n }\n }\n return useful_circles;\n}\n\ntemplate\nstatic bool in_bound(const T & begin, const T & end, bool clockwise) {\n return (clockwise && begin < end) ||\n (!clockwise && begin > end);\n}\n\ntype::MultiPolygon build_single_isochrone(RAPTOR& raptor,\n const std::vector& stop_points,\n const bool clockwise,\n const type::GeographicalCoord& coord_origin,\n const DateTime& bound,\n const map_stop_point_duration& origin,\n const double& speed,\n const int& duration) {\n std::vector circles_classed;\n type::MultiPolygon circles;\n InfoCircle to_add = InfoCircle(coord_origin, 0, duration);\n circles_classed.push_back(to_add);\n const auto& data_departure = raptor.data.pt_data->stop_points;\n for (auto it = origin.begin(); it != origin.end(); ++it){\n if (it->second.total_seconds() < duration) {\n int duration_left = duration - int(it->second.total_seconds());\n if (duration_left * speed < MIN_RADIUS) {continue;}\n const auto& center = data_departure[it->first.val]->coord;\n InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);\n circles_classed.push_back(to_add);\n }\n }\n for(const type::StopPoint* sp: stop_points) {\n SpIdx sp_idx(*sp);\n const auto best_lbl = raptor.best_labels_pts[sp_idx];\n if (in_bound(best_lbl, bound, clockwise)) {\n uint duration_left = abs(int(best_lbl) - int(bound));\n if (duration_left * speed < MIN_RADIUS) {continue;}\n const auto& center = sp->coord;\n InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);\n circles_classed.push_back(to_add);\n }\n }\n std::vector circles_check = delete_useless_circle(std::move(circles_classed), speed);\n\n for (const auto& c: circles_check) {\n type::Polygon circle_to_add = circle(c.center, c.duration_left * speed);\n circles = merge_poly(circles, circle_to_add);\n }\n return circles;\n}\n\ntype::MultiPolygon build_isochrones(RAPTOR& raptor,\n const bool clockwise,\n const type::GeographicalCoord& coord_origin,\n const DateTime& bound_max,\n const DateTime& bound_min,\n const map_stop_point_duration& origin,\n const double& speed,\n const int& max_duration,\n const int& min_duration) {\n type::MultiPolygon isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,\n clockwise, coord_origin, bound_max, origin,\n speed, max_duration);\n if (min_duration > 0) {\n type::MultiPolygon output;\n type::MultiPolygon min_isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,\n clockwise, coord_origin, bound_min, origin,\n speed, min_duration);\n boost::geometry::difference(isochrone, min_isochrone, output);\n isochrone = output;\n }\n return isochrone;\n}\n\n}} \/\/namespace navitia::routing\n<|endoftext|>"} {"text":"\/*\nCopyright 2016 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include \"OpenGLFunctions.h\"\n#include \"OpenGLTexture.h\"\n#include \"aeongames\/ResourceCache.h\"\n#include \"Uniform.h\"\n#include \n\nnamespace AeonGames\n{\n static_assert ( sizeof ( std::shared_ptr ) <= ( sizeof ( float ) * 4 ), \"Size of shared pointer is bigger than a vec4\" );\n Uniform::Uniform ( const std::string& aName, float aX ) :\n mName ( aName ),\n mType ( GL_FLOAT )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = 0;\n ( reinterpret_cast ( mData ) ) [2] = 0;\n ( reinterpret_cast ( mData ) ) [3] = 0;\n }\n Uniform::Uniform ( const std::string& aName, float aX, float aY ) :\n mName ( aName ),\n mType ( GL_FLOAT_VEC2 )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = aY;\n ( reinterpret_cast ( mData ) ) [2] = 0;\n ( reinterpret_cast ( mData ) ) [3] = 0;\n }\n Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ ) :\n mName ( aName ),\n mType ( GL_FLOAT_VEC3 )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = aY;\n ( reinterpret_cast ( mData ) ) [2] = aZ;\n ( reinterpret_cast ( mData ) ) [3] = 0;\n }\n Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ, float aW ) :\n mName ( aName ),\n mType ( GL_FLOAT_VEC4 )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = aY;\n ( reinterpret_cast ( mData ) ) [2] = aZ;\n ( reinterpret_cast ( mData ) ) [3] = aW;\n }\n Uniform::Uniform ( const std::string & aName, const std::string & aFilename ) :\n mName ( aName ),\n mType ( GL_SAMPLER_2D )\n {\n * ( new ( mData ) std::shared_ptr ( Get ( aFilename ) ) );\n }\n Uniform::~Uniform()\n {\n switch ( mType )\n {\n case GL_SAMPLER_2D:\n reinterpret_cast*> ( mData )->~shared_ptr();\n break;\n default:\n break;\n }\n }\n void Uniform::SetOffset ( const uint32_t aOffset )\n {\n mOffset = aOffset;\n }\n uint32_t Uniform::Offset() const\n {\n return mOffset;\n }\n const std::string Uniform::GetDeclaration() const\n {\n std::string declaration;\n switch ( mType )\n {\n case GL_FLOAT:\n declaration = \"float \" + mName + \";\\n\";\n break;\n case GL_FLOAT_VEC2:\n declaration = \"vec2 \" + mName + \";\\n\";\n break;\n case GL_FLOAT_VEC3:\n declaration = \"vec3 \" + mName + \";\\n\";\n break;\n case GL_FLOAT_VEC4:\n declaration = \"vec4 \" + mName + \";\\n\";\n break;\n case GL_SAMPLER_2D:\n declaration = \"sampler2D \" + mName + \";\\n\";\n break;\n }\n return declaration;\n }\n const std::string & Uniform::GetName() const\n {\n return mName;\n }\n void Uniform::CopyTo ( uint8_t * aMemory ) const\n {\n switch ( mType )\n {\n case GL_FLOAT:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) );\n break;\n case GL_FLOAT_VEC2:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 2 );\n break;\n case GL_FLOAT_VEC3:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 3 );\n break;\n case GL_FLOAT_VEC4:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 4 );\n break;\n case GL_SAMPLER_2D:\n * ( reinterpret_cast ( aMemory + mOffset ) ) =\n reinterpret_cast*> ( mData )->get()->GetHandle();\n break;\n }\n }\n}\nRemoved unecesary dereference in Uniform.cpp.\/*\nCopyright 2016 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include \"OpenGLFunctions.h\"\n#include \"OpenGLTexture.h\"\n#include \"aeongames\/ResourceCache.h\"\n#include \"Uniform.h\"\n#include \n\nnamespace AeonGames\n{\n static_assert ( sizeof ( std::shared_ptr ) <= ( sizeof ( float ) * 4 ), \"Size of shared pointer is bigger than a vec4\" );\n Uniform::Uniform ( const std::string& aName, float aX ) :\n mName ( aName ),\n mType ( GL_FLOAT )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = 0;\n ( reinterpret_cast ( mData ) ) [2] = 0;\n ( reinterpret_cast ( mData ) ) [3] = 0;\n }\n Uniform::Uniform ( const std::string& aName, float aX, float aY ) :\n mName ( aName ),\n mType ( GL_FLOAT_VEC2 )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = aY;\n ( reinterpret_cast ( mData ) ) [2] = 0;\n ( reinterpret_cast ( mData ) ) [3] = 0;\n }\n Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ ) :\n mName ( aName ),\n mType ( GL_FLOAT_VEC3 )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = aY;\n ( reinterpret_cast ( mData ) ) [2] = aZ;\n ( reinterpret_cast ( mData ) ) [3] = 0;\n }\n Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ, float aW ) :\n mName ( aName ),\n mType ( GL_FLOAT_VEC4 )\n {\n ( reinterpret_cast ( mData ) ) [0] = aX;\n ( reinterpret_cast ( mData ) ) [1] = aY;\n ( reinterpret_cast ( mData ) ) [2] = aZ;\n ( reinterpret_cast ( mData ) ) [3] = aW;\n }\n Uniform::Uniform ( const std::string & aName, const std::string & aFilename ) :\n mName ( aName ),\n mType ( GL_SAMPLER_2D )\n {\n new ( mData ) std::shared_ptr ( Get ( aFilename ) );\n }\n Uniform::~Uniform()\n {\n switch ( mType )\n {\n case GL_SAMPLER_2D:\n reinterpret_cast*> ( mData )->~shared_ptr();\n break;\n default:\n break;\n }\n }\n void Uniform::SetOffset ( const uint32_t aOffset )\n {\n mOffset = aOffset;\n }\n uint32_t Uniform::Offset() const\n {\n return mOffset;\n }\n const std::string Uniform::GetDeclaration() const\n {\n std::string declaration;\n switch ( mType )\n {\n case GL_FLOAT:\n declaration = \"float \" + mName + \";\\n\";\n break;\n case GL_FLOAT_VEC2:\n declaration = \"vec2 \" + mName + \";\\n\";\n break;\n case GL_FLOAT_VEC3:\n declaration = \"vec3 \" + mName + \";\\n\";\n break;\n case GL_FLOAT_VEC4:\n declaration = \"vec4 \" + mName + \";\\n\";\n break;\n case GL_SAMPLER_2D:\n declaration = \"sampler2D \" + mName + \";\\n\";\n break;\n }\n return declaration;\n }\n const std::string & Uniform::GetName() const\n {\n return mName;\n }\n void Uniform::CopyTo ( uint8_t * aMemory ) const\n {\n switch ( mType )\n {\n case GL_FLOAT:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) );\n break;\n case GL_FLOAT_VEC2:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 2 );\n break;\n case GL_FLOAT_VEC3:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 3 );\n break;\n case GL_FLOAT_VEC4:\n memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 4 );\n break;\n case GL_SAMPLER_2D:\n ( * ( reinterpret_cast ( aMemory + mOffset ) ) ) =\n reinterpret_cast*> ( mData )->get()->GetHandle();\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \n#include \n\n#include \"basebox_api.h\"\n#include \"netlink\/nbi_impl.hpp\"\n#include \"netlink\/tap_manager.hpp\"\n#include \"of-dpa\/controller.hpp\"\n\nstatic volatile sig_atomic_t got_SIGINT = 0;\nApiServer grpcConnector;\n\nstatic bool validate_port(const char *flagname, gflags::int32 value) {\n if (value > 0 && value < 32768) \/\/ value is ok\n return true;\n return false;\n}\n\nDEFINE_int32(port, 6654, \"Listening port\");\n\n\nint main(int argc, char **argv) {\n if (!gflags::RegisterFlagValidator(&FLAGS_port, &validate_port)) {\n std::cerr << \"Failed to register port validator\" << std::endl;\n exit(1);\n }\n\n gflags::SetUsageMessage(\"\");\n gflags::SetVersionString(PACKAGE_VERSION);\n\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n\n rofl::openflow::cofhello_elem_versionbitmap versionbitmap;\n versionbitmap.add_ofp_version(rofl::openflow13::OFP_VERSION);\n LOG(INFO) << \"using OpenFlow version-bitmap:\" << std::endl << versionbitmap;\n\n basebox::nbi_impl *nbi = new basebox::nbi_impl();\n std::unique_ptr box(\n new basebox::controller(nbi, versionbitmap));\n\n rofl::csockaddr baddr(AF_INET, std::string(\"0.0.0.0\"), FLAGS_port);\n box->dpt_sock_listen(baddr);\n\n grpcConnector.runGRPCServer();\n\n delete nbi;\n\n LOG(INFO) << \"bye\";\n return EXIT_SUCCESS;\n}\nremoved additional files<|endoftext|>"} {"text":"Fix uninitialized flag<|endoftext|>"} {"text":"\/*\n * Copyright 2013 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set\n\/\/ up the widths of wxComboBox and wxTextCtrl and wxButton (in various\n\/\/ controls in which these feature), where they are\n\/\/ supposed to be the same height, they actually turn out to be slightly\n\/\/ different heights. However even if I manually set them all to the same\n\/\/ hard-coded height number, they still seem to come out different heights\n\/\/ on KDE. It doesn't make a lot of sense.\n\n\/\/ TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.\n\n\/\/\/ TODO MEDIUM PRIORITY The database file should perhaps have a checksum to\n\/\/ guard against its contents changing other than via the application.\n\n\/\/ TODO HIGH PRIORITY Facilitate automatic checking for updates from user's\n\/\/ machine, or at least provide an easy process for installing updates\n\/\/ via NSIS. It appears that the default configuration of CPack\/NSIS is\n\/\/ such that updates will not overwrite existing files. Some manual NSIS\n\/\/ scripting may be required to enable this. Also take into account that\n\/\/ the user may have to restart their computer in the event that they have\n\/\/ files open while the installer (or \"updater\") is running (although I\n\/\/ \\e think that the default configuration under CPack does this\n\/\/ automatically).\n\n\/\/ TODO HIGH PRIORITY Create a decent icon for the application. We want this\n\/\/ in both .ico form (for Windows executable icon) and .xpm\n\/\/ form (for icon for Frame). Note, when I exported my\n\/\/ \"token icon\" using GIMP to .ico format, and later used this\n\/\/ to create a double-clickable icon in Windows, only the text\n\/\/ on the icon appeared, and the background image became\n\/\/ transparent for some reason. Furthermore, when set as the\n\/\/ large in-windows icon in the CPack\/NSIS installer, the icon\n\/\/ wasn't showing at all. Once decent icon is created, also make sure it is\n\/\/ pulled into the wxBitmap in SetupWizard.\n\n\/\/ TODO HIGH PRIORITY Create a better name for the application.\n\n\/\/ TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen\n\/\/ i.e. laptop.\n\n\/\/ TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when\n\/\/ compiled in Release mode.\n\n\/\/ TODO MEDIUM PRIORITY Give user the option to export to CSV.\n\n\/\/ TODO LOW PRIORITY Allow export\/import to\/from .qif (?) format.\n\n\/\/ TODO HIGH PRIORITY On Windows, at least on Windows 7, at least on some\n\/\/ machines, tab traversal is not working properly in SetupWizard, and you\n\/\/ can't traverse out of a wxComboBox using tab, for some reason.\n\n#include \"app.hpp\"\n#include \n\nwxIMPLEMENT_APP(phatbooks::App);\nAdded some more TODOs.\/*\n * Copyright 2013 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set\n\/\/ up the widths of wxComboBox and wxTextCtrl and wxButton (in various\n\/\/ controls in which these feature), where they are\n\/\/ supposed to be the same height, they actually turn out to be slightly\n\/\/ different heights. However even if I manually set them all to the same\n\/\/ hard-coded height number, they still seem to come out different heights\n\/\/ on KDE. It doesn't make a lot of sense.\n\n\/\/ TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.\n\n\/\/\/ TODO MEDIUM PRIORITY The database file should perhaps have a checksum to\n\/\/ guard against its contents changing other than via the application.\n\n\/\/ TODO HIGH PRIORITY Facilitate automatic checking for updates from user's\n\/\/ machine, or at least provide an easy process for installing updates\n\/\/ via NSIS. It appears that the default configuration of CPack\/NSIS is\n\/\/ such that updates will not overwrite existing files. Some manual NSIS\n\/\/ scripting may be required to enable this. Also take into account that\n\/\/ the user may have to restart their computer in the event that they have\n\/\/ files open while the installer (or \"updater\") is running (although I\n\/\/ \\e think that the default configuration under CPack does this\n\/\/ automatically).\n\n\/\/ TODO HIGH PRIORITY Create a decent icon for the application. We want this\n\/\/ in both .ico form (for Windows executable icon) and .xpm\n\/\/ form (for icon for Frame). Note, when I exported my\n\/\/ \"token icon\" using GIMP to .ico format, and later used this\n\/\/ to create a double-clickable icon in Windows, only the text\n\/\/ on the icon appeared, and the background image became\n\/\/ transparent for some reason. Furthermore, when set as the\n\/\/ large in-windows icon in the CPack\/NSIS installer, the icon\n\/\/ wasn't showing at all. Once decent icon is created, also make sure it is\n\/\/ pulled into the wxBitmap in SetupWizard.\n\n\/\/ TODO HIGH PRIORITY Create a better name for the application.\n\n\/\/ TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen\n\/\/ i.e. laptop.\n\n\/\/ TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when\n\/\/ compiled in Release mode.\n\n\/\/ TODO MEDIUM PRIORITY Give user the option to export to CSV.\n\n\/\/ TODO LOW PRIORITY Allow export\/import to\/from .qif (?) format.\n\n\/\/ TODO HIGH PRIORITY On Windows, at least on Windows 7, at least on some\n\/\/ machines, tab traversal is not working properly in SetupWizard, and you\n\/\/ can't traverse out of a wxComboBox using tab, for some reason.\n\n\/\/ TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially\n\/\/ for DraftJournalListCtrl. This make it easier for users on laptops.\n\n#include \"app.hpp\"\n#include \n\nwxIMPLEMENT_APP(phatbooks::App);\n<|endoftext|>"} {"text":"\/\/ Problem 5 from Project Euler\n\/\/ http:\/\/projecteuler.net\/problem=5\n\n#include \n#include \n#include \n\nint main()\n{\n bool is_multiple;\n\n while (!is_multiple)\n {\n for (unsigned int n = 0; n < std::numeric_limits::max(); n += 80)\n {\n is_multiple = true;\n\n if (n == 0)\n {\n continue;\n }\n\n for (unsigned int i = 2; i <= 20; i++)\n {\n if (n % i != 0)\n {\n is_multiple = false;\n break;\n }\n }\n if (is_multiple)\n {\n std::cout << \"The answer is \" << n << std::endl;\n exit(0);\n }\n }\n }\n}\nRemoved unnecessary include\/\/ Problem 5 from Project Euler\n\/\/ http:\/\/projecteuler.net\/problem=5\n\n#include \n#include \n\nint main()\n{\n bool is_multiple;\n\n while (!is_multiple)\n {\n for (unsigned int n = 0; n < std::numeric_limits::max(); n += 80)\n {\n is_multiple = true;\n\n if (n == 0)\n {\n continue;\n }\n\n for (unsigned int i = 2; i <= 20; i++)\n {\n if (n % i != 0)\n {\n is_multiple = false;\n break;\n }\n }\n if (is_multiple)\n {\n std::cout << \"The answer is \" << n << std::endl;\n exit(0);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: mtftools.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2005-04-18 10:00:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_RENDERER_MTFTOOLS_HXX\n#define _CPPCANVAS_RENDERER_MTFTOOLS_HXX\n\n#include \n#include \n\n\nclass VirtualDevice;\nclass Point;\nclass Size;\n\nnamespace basegfx\n{\n class B2DVector;\n class B2DPoint;\n}\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n struct RenderState;\n} } } }\n\n\nnamespace cppcanvas\n{\n namespace internal\n {\n struct OutDevState;\n }\n\n namespace tools\n {\n \/** Init render state from OutDevState\n\n This method initializes the given render state object,\n sets up the transformation and the clip from the\n OutDevState.\n *\/\n void initRenderState( ::com::sun::star::rendering::RenderState& renderState,\n const ::cppcanvas::internal::OutDevState& outdevState );\n\n \/** Calc output offset relative to baseline\n\n The XCanvas API always renders text relative to its\n baseline. This method calculates an offset in logical\n coordinates, depending on the OutDevState's\n textReferencePoint and the font currently set, to offset\n the text from the baseline.\n\n @param outdevState\n State to take textReferencePoint from\n\n @param rVDev\n VDev to obtain font metrics from.\n *\/\n ::Size getBaselineOffset( const ::cppcanvas::internal::OutDevState& outdevState,\n const VirtualDevice& rVDev );\n\n \/** Construct a matrix that converts from logical to pixel\n coordinate system.\n\n This method calculates a matrix that approximates the\n VirtualDevice's LogicToPixel conversion (disregarding any\n offset components, thus the 'linear' in the method name -\n the returned matrix is guaranteed to be linear).\n\n @param o_rMatrix\n This matrix will receive the calculated transform, and is\n also returned from this method.\n\n @return the calculated transformation matrix.\n *\/\n ::basegfx::B2DHomMatrix& calcLogic2PixelLinearTransform( ::basegfx::B2DHomMatrix& o_rMatrix,\n const VirtualDevice& rVDev );\n\n \/** This method modifies the clip, to cancel the given\n transformation.\n\n As the clip is relative to the render state\n transformation, offsetting or scaling the render state\n must modify the clip, to keep it at the same position\n relative to the primitive at hand\n\n @param o_rRenderState\n Render state to change the clip in\n\n @param rOutdevState\n Input state. Is used to retrieve the original clip from\n\n @param rOffset\n The clip is offsetted by the negative of this value.\n\n @param pScaling\n The clip is inversely scaled by this value (if given)\n\n @return true, if the clip has changed, false if not\n *\/\n bool modifyClip( ::com::sun::star::rendering::RenderState& o_rRenderState,\n const struct ::cppcanvas::internal::OutDevState& rOutdevState,\n const CanvasSharedPtr& rCanvas,\n const ::Point& rOffset,\n const ::basegfx::B2DVector* pScaling );\n\n \/** This method modifies the clip, to cancel the given\n transformation.\n\n As the clip is relative to the render state\n transformation, offsetting or scaling the render state\n must modify the clip, to keep it at the same position\n relative to the primitive at hand\n\n @param o_rRenderState\n Render state to change the clip in\n\n @param rOutdevState\n Input state. Is used to retrieve the original clip from\n\n @param rOffset\n The clip is offsetted by the negative of this value.\n\n @param pScaling\n The clip is inversely scaled by this value (if given)\n\n @return true, if the clip has changed, false if not\n *\/\n bool modifyClip( ::com::sun::star::rendering::RenderState& o_rRenderState,\n const struct ::cppcanvas::internal::OutDevState& rOutdevState,\n const CanvasSharedPtr& rCanvas,\n const ::basegfx::B2DPoint& rOffset,\n const ::basegfx::B2DVector* pScaling );\n\n \/** This method modifies the clip, to cancel the given\n transformation.\n\n As the clip is relative to the render state\n transformation, transforming the render state further must\n modify the clip, to keep it at the same position relative\n to the primitive at hand\n\n @param o_rRenderState\n Render state to change the clip in\n\n @param rOutdevState\n Input state. Is used to retrieve the original clip from\n\n @param rTransform\n The clip is transformed by the inverse of this value.\n\n @return true, if the clip has changed, false if not\n *\/\n bool modifyClip( ::com::sun::star::rendering::RenderState& o_rRenderState,\n const struct ::cppcanvas::internal::OutDevState& rOutdevState,\n const CanvasSharedPtr& rCanvas,\n const ::basegfx::B2DHomMatrix& rTransform );\n\n struct TextLineInfo\n {\n TextLineInfo( const double& rLineHeight,\n const double& rUnderlineOffset,\n const double& rStrikeoutOffset,\n sal_Int8 nUnderlineStyle,\n sal_Int8 nStrikeoutStyle ) :\n mnLineHeight( rLineHeight ),\n mnUnderlineOffset( rUnderlineOffset ),\n mnStrikeoutOffset( rStrikeoutOffset ),\n mnUnderlineStyle( nUnderlineStyle ),\n mnStrikeoutStyle( nStrikeoutStyle )\n {\n }\n\n double mnLineHeight;\n double mnUnderlineOffset;\n double mnStrikeoutOffset;\n sal_Int8 mnUnderlineStyle;\n sal_Int8 mnStrikeoutStyle;\n };\n\n \/** Transform given bounds to device coordinate system.\n *\/\n ::basegfx::B2DRange calcDevicePixelBounds( const ::basegfx::B2DRange& rBounds,\n const ::com::sun::star::rendering::ViewState& viewState,\n const ::com::sun::star::rendering::RenderState& renderState );\n\n \/** Generate text underline\/strikeout info struct from OutDev\n state.\n *\/\n TextLineInfo createTextLineInfo( const ::VirtualDevice& rVDev,\n const ::cppcanvas::internal::OutDevState& rState );\n\n \/** Create a poly-polygon representing the given combination\n of strikeout and underline.\n\n @param rStartOffset\n Offset in X direction, where the underline starts\n\n @param rLineWidth\n Width of the line of text to underline\/strikeout\n\n @param rTextLineInfo\n Common info needed for strikeout\/underline generation\n *\/\n ::basegfx::B2DPolyPolygon createTextLinesPolyPolygon( const double& rStartOffset,\n const double& rLineWidth,\n const TextLineInfo& rTextLineInfo );\n\n ::basegfx::B2DPolyPolygon createTextLinesPolyPolygon( const ::basegfx::B2DPoint rStartPos,\n const double& rLineWidth,\n const TextLineInfo& rTextLineInfo );\n }\n}\n\n#endif \/* _CPPCANVAS_RENDERER_MTFTOOLS_HXX *\/\nINTEGRATION: CWS ooo19126 (1.5.14); FILE MERGED 2005\/09\/05 18:40:59 rt 1.5.14.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mtftools.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 08:20:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_RENDERER_MTFTOOLS_HXX\n#define _CPPCANVAS_RENDERER_MTFTOOLS_HXX\n\n#include \n#include \n\n\nclass VirtualDevice;\nclass Point;\nclass Size;\n\nnamespace basegfx\n{\n class B2DVector;\n class B2DPoint;\n}\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n struct RenderState;\n} } } }\n\n\nnamespace cppcanvas\n{\n namespace internal\n {\n struct OutDevState;\n }\n\n namespace tools\n {\n \/** Init render state from OutDevState\n\n This method initializes the given render state object,\n sets up the transformation and the clip from the\n OutDevState.\n *\/\n void initRenderState( ::com::sun::star::rendering::RenderState& renderState,\n const ::cppcanvas::internal::OutDevState& outdevState );\n\n \/** Calc output offset relative to baseline\n\n The XCanvas API always renders text relative to its\n baseline. This method calculates an offset in logical\n coordinates, depending on the OutDevState's\n textReferencePoint and the font currently set, to offset\n the text from the baseline.\n\n @param outdevState\n State to take textReferencePoint from\n\n @param rVDev\n VDev to obtain font metrics from.\n *\/\n ::Size getBaselineOffset( const ::cppcanvas::internal::OutDevState& outdevState,\n const VirtualDevice& rVDev );\n\n \/** Construct a matrix that converts from logical to pixel\n coordinate system.\n\n This method calculates a matrix that approximates the\n VirtualDevice's LogicToPixel conversion (disregarding any\n offset components, thus the 'linear' in the method name -\n the returned matrix is guaranteed to be linear).\n\n @param o_rMatrix\n This matrix will receive the calculated transform, and is\n also returned from this method.\n\n @return the calculated transformation matrix.\n *\/\n ::basegfx::B2DHomMatrix& calcLogic2PixelLinearTransform( ::basegfx::B2DHomMatrix& o_rMatrix,\n const VirtualDevice& rVDev );\n\n \/** This method modifies the clip, to cancel the given\n transformation.\n\n As the clip is relative to the render state\n transformation, offsetting or scaling the render state\n must modify the clip, to keep it at the same position\n relative to the primitive at hand\n\n @param o_rRenderState\n Render state to change the clip in\n\n @param rOutdevState\n Input state. Is used to retrieve the original clip from\n\n @param rOffset\n The clip is offsetted by the negative of this value.\n\n @param pScaling\n The clip is inversely scaled by this value (if given)\n\n @return true, if the clip has changed, false if not\n *\/\n bool modifyClip( ::com::sun::star::rendering::RenderState& o_rRenderState,\n const struct ::cppcanvas::internal::OutDevState& rOutdevState,\n const CanvasSharedPtr& rCanvas,\n const ::Point& rOffset,\n const ::basegfx::B2DVector* pScaling );\n\n \/** This method modifies the clip, to cancel the given\n transformation.\n\n As the clip is relative to the render state\n transformation, offsetting or scaling the render state\n must modify the clip, to keep it at the same position\n relative to the primitive at hand\n\n @param o_rRenderState\n Render state to change the clip in\n\n @param rOutdevState\n Input state. Is used to retrieve the original clip from\n\n @param rOffset\n The clip is offsetted by the negative of this value.\n\n @param pScaling\n The clip is inversely scaled by this value (if given)\n\n @return true, if the clip has changed, false if not\n *\/\n bool modifyClip( ::com::sun::star::rendering::RenderState& o_rRenderState,\n const struct ::cppcanvas::internal::OutDevState& rOutdevState,\n const CanvasSharedPtr& rCanvas,\n const ::basegfx::B2DPoint& rOffset,\n const ::basegfx::B2DVector* pScaling );\n\n \/** This method modifies the clip, to cancel the given\n transformation.\n\n As the clip is relative to the render state\n transformation, transforming the render state further must\n modify the clip, to keep it at the same position relative\n to the primitive at hand\n\n @param o_rRenderState\n Render state to change the clip in\n\n @param rOutdevState\n Input state. Is used to retrieve the original clip from\n\n @param rTransform\n The clip is transformed by the inverse of this value.\n\n @return true, if the clip has changed, false if not\n *\/\n bool modifyClip( ::com::sun::star::rendering::RenderState& o_rRenderState,\n const struct ::cppcanvas::internal::OutDevState& rOutdevState,\n const CanvasSharedPtr& rCanvas,\n const ::basegfx::B2DHomMatrix& rTransform );\n\n struct TextLineInfo\n {\n TextLineInfo( const double& rLineHeight,\n const double& rUnderlineOffset,\n const double& rStrikeoutOffset,\n sal_Int8 nUnderlineStyle,\n sal_Int8 nStrikeoutStyle ) :\n mnLineHeight( rLineHeight ),\n mnUnderlineOffset( rUnderlineOffset ),\n mnStrikeoutOffset( rStrikeoutOffset ),\n mnUnderlineStyle( nUnderlineStyle ),\n mnStrikeoutStyle( nStrikeoutStyle )\n {\n }\n\n double mnLineHeight;\n double mnUnderlineOffset;\n double mnStrikeoutOffset;\n sal_Int8 mnUnderlineStyle;\n sal_Int8 mnStrikeoutStyle;\n };\n\n \/** Transform given bounds to device coordinate system.\n *\/\n ::basegfx::B2DRange calcDevicePixelBounds( const ::basegfx::B2DRange& rBounds,\n const ::com::sun::star::rendering::ViewState& viewState,\n const ::com::sun::star::rendering::RenderState& renderState );\n\n \/** Generate text underline\/strikeout info struct from OutDev\n state.\n *\/\n TextLineInfo createTextLineInfo( const ::VirtualDevice& rVDev,\n const ::cppcanvas::internal::OutDevState& rState );\n\n \/** Create a poly-polygon representing the given combination\n of strikeout and underline.\n\n @param rStartOffset\n Offset in X direction, where the underline starts\n\n @param rLineWidth\n Width of the line of text to underline\/strikeout\n\n @param rTextLineInfo\n Common info needed for strikeout\/underline generation\n *\/\n ::basegfx::B2DPolyPolygon createTextLinesPolyPolygon( const double& rStartOffset,\n const double& rLineWidth,\n const TextLineInfo& rTextLineInfo );\n\n ::basegfx::B2DPolyPolygon createTextLinesPolyPolygon( const ::basegfx::B2DPoint rStartPos,\n const double& rLineWidth,\n const TextLineInfo& rTextLineInfo );\n }\n}\n\n#endif \/* _CPPCANVAS_RENDERER_MTFTOOLS_HXX *\/\n<|endoftext|>"} {"text":"#include \"alib.h\"\n#include \"atype.h\"\n#include \"ssl_fn.h\"\n#include \"log.h\"\n#include \"lzma2_wrapper.h\"\n\n#include \n#include \n#include \n#include \n\n\/* Test if ssl_fn.c create_sha1sum is working correctly\n *\n *\/\nvoid sha1_test()\n{\n unsigned char *tmp = NULL;\n tmp = create_sha1sum(\"\/home\/gator\/Downloads\/Torrent\/tmp.txt\");\n if(tmp != NULL) {\n for (int i = 0; i < 20; i++) {\n printf(\"%02x\",tmp[i]);\n }\n printf(\"\\n\");\n free(tmp);\n }\n}\n\n\/* Test if log.c log_msg is working correctly\n *\n *\/\nvoid log_test()\n{\n log_msg(\"fewf %s\\n\", \"wfean\");\n}\n\nvoid chain_test()\n{\n chain *ch = newChain();\n uint32_t size = 1000;\n\n for (uint32_t i = 0; i < size; i++) {\n uint64_t key = 0xFFFF0000FFFF0000 + i;\n uint32_t len = 4;\n pack **packs = (pack **)malloc(sizeof(pack *) * len);\n if (packs == NULL)\n break;\n for (uint32_t j = 0; j < len; j++) {\n packs[j] = newPack((char *)\"dn:testtesttesttesttesttesttesttest\",\n 4*1024*1024,\n (char *)\"xt:testtesttesttesttesttesttesttest\",\n (char *)\"tr:testtesttesttesttesttesttesttest\");\n }\n\n if (!insertBlock(newBlock(key, len, packs), ch))\n break;\n }\n printBlock(ch->head[0]);\n printBlock(ch->head[size - 1]);\n\n printf(\"Free'd %d bytes\\n\", deleteChain(ch) + sizeof(chain));\n\n free(ch);\n\n std::cout.imbue(std::locale());\n}\n\nvoid compression_test()\n{\n compress_file(\"\/home\/gator\/Downloads\/Tc\/temp.file\",\n \"\/home\/gator\/Downloads\/Tc\/temp.file.7z\");\n}\n\nint main()\n{\n\/* sha1_test();\n log_test();\n chain_test();\n*\/\n compression_test();\n \/*\n char *args[] = {(char *)\"7z\", (char *)\"e\", (char *)\"t2\", (char *)\"t2.7z\", (char *)\"-mt4\", NULL};\n wrap7z(4, (const char **)args);\n *\/\n return 0;\n}\n\ntesting on home pc#include \"alib.h\"\n#include \"atype.h\"\n#include \"ssl_fn.h\"\n#include \"log.h\"\n#include \"lzma2_wrapper.h\"\n\n#include \n#include \n#include \n#include \n\n\/* Test if ssl_fn.c create_sha1sum is working correctly\n *\n *\/\nvoid sha1_test()\n{\n unsigned char *tmp = NULL;\n tmp = create_sha1sum(\"\/home\/gator\/Downloads\/Torrent\/tmp.txt\");\n if(tmp != NULL) {\n for (int i = 0; i < 20; i++) {\n printf(\"%02x\",tmp[i]);\n }\n printf(\"\\n\");\n free(tmp);\n }\n}\n\n\/* Test if log.c log_msg is working correctly\n *\n *\/\nvoid log_test()\n{\n log_msg(\"fewf %s\\n\", \"wfean\");\n}\n\nvoid chain_test()\n{\n chain *ch = newChain();\n uint32_t size = 1000;\n\n for (uint32_t i = 0; i < size; i++) {\n uint64_t key = 0xFFFF0000FFFF0000 + i;\n uint32_t len = 4;\n pack **packs = (pack **)malloc(sizeof(pack *) * len);\n if (packs == NULL)\n break;\n for (uint32_t j = 0; j < len; j++) {\n packs[j] = newPack((char *)\"dn:testtesttesttesttesttesttesttest\",\n 4*1024*1024,\n (char *)\"xt:testtesttesttesttesttesttesttest\",\n (char *)\"tr:testtesttesttesttesttesttesttest\");\n }\n\n if (!insertBlock(newBlock(key, len, packs), ch))\n break;\n }\n printBlock(ch->head[0]);\n printBlock(ch->head[size - 1]);\n\n printf(\"Free'd %d bytes\\n\", deleteChain(ch) + sizeof(chain));\n\n free(ch);\n\n std::cout.imbue(std::locale());\n}\n\nvoid compression_test()\n{\n compress_file(\"\/home\/gi\/multimedia\/projects\/Torrent\/temp.file\",\n \"\/home\/gi\/multimedia\/projects\/Torrent\/temp.file.7z\");\n}\n\nint main()\n{\n\/* sha1_test();\n log_test();\n chain_test();\n*\/\n compression_test();\n \/*\n char *args[] = {(char *)\"7z\", (char *)\"e\", (char *)\"t2\", (char *)\"t2.7z\", (char *)\"-mt4\", NULL};\n wrap7z(4, (const char **)args);\n *\/\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \"Parkautomat.h\"\n\nstatic const int TIMEOUT_WARNING_THRESHOLD = 1;\n\nbool Parkautomat::counterIsTimedOut()\n{\n return _shield.sevenSeg.number() == 0;\n}\n\nbool Parkautomat::shieldIsOccupied()\n{\n return _shield.getBrightness() <= 1000;\n}\n\nvoid Parkautomat::update(void)\n{\n switch(state)\n {\n case OFF: updateStateOff();\n break;\n case UNPAYED: updateStateUnpayed();\n break;\n case PAYED: updateStatePayed();\n break;\n case PAYED_TIMEOUT_WARNING: updateStatePayedTimeoutWarning();\n break;\n\n default: break;\n }\n}\n\nvoid Parkautomat::ledsOff()\n{\n _shield.setLed(ParkingShield::GREEN_LED, false);\n _shield.setLed(ParkingShield::YELLOW_LED, false);\n _shield.setLed(ParkingShield::RED_LED, false);\n}\n\nvoid Parkautomat::enterStateOff()\n{\n state = OFF;\n ledsOff();\n _shield.sevenSeg.clear();\n}\n\nvoid Parkautomat::updateStateOff()\n{\n if( shieldIsOccupied() )\n {\n enterStateUnpayed();\n }\n}\n\nvoid Parkautomat::enterStateUnpayed()\n{\n state = UNPAYED;\n ledsOff();\n _shield.sevenSeg.showNumber(0);\n _shield.setLed(ParkingShield::RED_LED, true);\n}\n\nvoid Parkautomat::updateStateUnpayed()\n{\n if( _shield.buttonS1Pressed() )\n {\n enterStatePayed();\n _shield.sevenSeg.showNumber(0);\n _shield.sevenSeg++;\n }\n \n if( !shieldIsOccupied() )\n {\n enterStateOff();\n }\n}\n\nvoid Parkautomat::enterStatePayed()\n{\n state = PAYED;\n ledsOff();\n _shield.setLed(ParkingShield::GREEN_LED, true);\n _shield.countdownStart(2000);\n}\n\nvoid Parkautomat::updateStatePayed()\n{\n if( _shield.buttonS1Pressed() )\n _shield.sevenSeg++;\n else\n {\n \/\/_shield.sevenSeg--;\n }\n \n if( TIMEOUT_WARNING_THRESHOLD == _shield.sevenSeg.number() )\n {\n enterStatePayedTimeoutWarning();\n }\n \n if( !shieldIsOccupied() )\n {\n _shield.sevenSeg.clear();\n enterStateOff();\n }\n}\n\nvoid Parkautomat::enterStatePayedTimeoutWarning()\n{\n state = PAYED_TIMEOUT_WARNING;\n ledsOff();\n _shield.setLed(ParkingShield::YELLOW_LED, true);\n}\n\nvoid Parkautomat::updateStatePayedTimeoutWarning()\n{\n if( _shield.buttonS1Pressed() )\n {\n _shield.sevenSeg++;\n }\n else\n {\n \/\/_shield.sevenSeg--;\n }\n \n if( TIMEOUT_WARNING_THRESHOLD < _shield.sevenSeg.number() )\n {\n enterStatePayed();\n }\n \n if( counterIsTimedOut() )\n {\n enterStateUnpayed();\n }\n \n if( !shieldIsOccupied() )\n {\n enterStateOff();\n }\n}\n\n\nin parkautomat make case statement more readable.#include \n#include \"Parkautomat.h\"\n\nstatic const int TIMEOUT_WARNING_THRESHOLD = 1;\n\nbool Parkautomat::counterIsTimedOut()\n{\n return _shield.sevenSeg.number() == 0;\n}\n\nbool Parkautomat::shieldIsOccupied()\n{\n return _shield.getBrightness() <= 1000;\n}\n\nvoid Parkautomat::update(void)\n{\n switch(state)\n {\n case OFF:\n updateStateOff();\n break;\n case UNPAYED:\n updateStateUnpayed();\n break;\n case PAYED:\n updateStatePayed();\n break;\n case PAYED_TIMEOUT_WARNING:\n updateStatePayedTimeoutWarning();\n break;\n default:\n break;\n }\n}\n\nvoid Parkautomat::ledsOff()\n{\n _shield.setLed(ParkingShield::GREEN_LED, false);\n _shield.setLed(ParkingShield::YELLOW_LED, false);\n _shield.setLed(ParkingShield::RED_LED, false);\n}\n\nvoid Parkautomat::enterStateOff()\n{\n state = OFF;\n ledsOff();\n _shield.sevenSeg.clear();\n}\n\nvoid Parkautomat::updateStateOff()\n{\n if( shieldIsOccupied() )\n {\n enterStateUnpayed();\n }\n}\n\nvoid Parkautomat::enterStateUnpayed()\n{\n state = UNPAYED;\n ledsOff();\n _shield.sevenSeg.showNumber(0);\n _shield.setLed(ParkingShield::RED_LED, true);\n}\n\nvoid Parkautomat::updateStateUnpayed()\n{\n if( _shield.buttonS1Pressed() )\n {\n enterStatePayed();\n _shield.sevenSeg.showNumber(0);\n _shield.sevenSeg++;\n }\n \n if( !shieldIsOccupied() )\n {\n enterStateOff();\n }\n}\n\nvoid Parkautomat::enterStatePayed()\n{\n state = PAYED;\n ledsOff();\n _shield.setLed(ParkingShield::GREEN_LED, true);\n _shield.countdownStart(2000);\n}\n\nvoid Parkautomat::updateStatePayed()\n{\n if( _shield.buttonS1Pressed() )\n _shield.sevenSeg++;\n else\n {\n \/\/_shield.sevenSeg--;\n }\n \n if( TIMEOUT_WARNING_THRESHOLD == _shield.sevenSeg.number() )\n {\n enterStatePayedTimeoutWarning();\n }\n \n if( !shieldIsOccupied() )\n {\n _shield.sevenSeg.clear();\n enterStateOff();\n }\n}\n\nvoid Parkautomat::enterStatePayedTimeoutWarning()\n{\n state = PAYED_TIMEOUT_WARNING;\n ledsOff();\n _shield.setLed(ParkingShield::YELLOW_LED, true);\n}\n\nvoid Parkautomat::updateStatePayedTimeoutWarning()\n{\n if( _shield.buttonS1Pressed() )\n {\n _shield.sevenSeg++;\n }\n else\n {\n \/\/_shield.sevenSeg--;\n }\n \n if( TIMEOUT_WARNING_THRESHOLD < _shield.sevenSeg.number() )\n {\n enterStatePayed();\n }\n \n if( counterIsTimedOut() )\n {\n enterStateUnpayed();\n }\n \n if( !shieldIsOccupied() )\n {\n enterStateOff();\n }\n}\n\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"engine_wrapper.h\"\n#include \"executors.h\"\n#include \"utilities.h\"\n#include \n#include \n#include \n#include \n#include \n\nvoid dcp_open_executor(Cookie& cookie) {\n using cb::mcbp::request::DcpOpenPayload;\n\n auto& request = cookie.getHeader().getRequest();\n auto ext = request.getExtdata();\n const auto* payload = reinterpret_cast(ext.data());\n const uint32_t flags = payload->getFlags();\n\n auto ret = cookie.swapAiostat(ENGINE_SUCCESS);\n\n auto& connection = cookie.getConnection();\n connection.enableDatatype(cb::mcbp::Feature::JSON);\n\n const bool dcpNotifier =\n (flags & DcpOpenPayload::Notifier) == DcpOpenPayload::Notifier;\n\n if (ret == ENGINE_SUCCESS) {\n cb::rbac::Privilege privilege = cb::rbac::Privilege::DcpProducer;\n if (dcpNotifier) {\n privilege = cb::rbac::Privilege::DcpConsumer;\n }\n\n ret = mcbp::checkPrivilege(cookie, privilege);\n\n if (ret == ENGINE_SUCCESS) {\n auto key = request.getKey();\n auto value = request.getValue();\n\n ret = dcpOpen(\n cookie,\n request.getOpaque(),\n payload->getSeqno(),\n flags,\n {reinterpret_cast(key.data()), key.size()},\n {reinterpret_cast(value.data()),\n value.size()});\n }\n }\n\n ret = connection.remapErrorCode(ret);\n switch (ret) {\n case ENGINE_SUCCESS: {\n const bool dcpXattrAware =\n (flags & DcpOpenPayload::IncludeXattrs) != 0 &&\n connection.selectedBucketIsXattrEnabled();\n const bool dcpDeletedUserXattr =\n (flags & DcpOpenPayload::IncludeDeletedUserXattrs) != 0 &&\n connection.selectedBucketIsXattrEnabled();\n const bool dcpNoValue = (flags & DcpOpenPayload::NoValue) != 0;\n const bool dcpDeleteTimes =\n (flags & DcpOpenPayload::IncludeDeleteTimes) != 0;\n connection.setDcpXattrAware(dcpXattrAware);\n connection.setDcpDeletedUserXattr(dcpDeletedUserXattr);\n connection.setDcpNoValue(dcpNoValue);\n connection.setDcpDeleteTimeEnabled(dcpDeleteTimes);\n connection.setDCP(true);\n connection.disableSaslAuth();\n\n \/\/ String buffer with max length = total length of all possible contents\n std::string logBuffer;\n\n const bool dcpProducer =\n (flags & DcpOpenPayload::Producer) == DcpOpenPayload::Producer;\n if (dcpProducer) {\n logBuffer.append(\"PRODUCER, \");\n }\n if (dcpNotifier) {\n logBuffer.append(\"NOTIFIER, \");\n }\n if (dcpXattrAware) {\n logBuffer.append(\"INCLUDE_XATTRS, \");\n }\n if (dcpNoValue) {\n logBuffer.append(\"NO_VALUE, \");\n }\n if (dcpDeleteTimes) {\n logBuffer.append(\"DELETE_TIMES, \");\n }\n\n \/\/ Remove trailing whitespace and comma\n if (!logBuffer.empty()) {\n logBuffer.resize(logBuffer.size() - 2);\n }\n\n LOG_INFO(\"{}: DCP connection opened successfully. {} {}\",\n connection.getId(),\n logBuffer,\n connection.getDescription().c_str());\n\n audit_dcp_open(connection);\n cookie.sendResponse(cb::mcbp::Status::Success);\n break;\n }\n\n case ENGINE_DISCONNECT:\n connection.setState(StateMachine::State::closing);\n break;\n\n case ENGINE_EWOULDBLOCK:\n cookie.setEwouldblock(true);\n break;\n\n default:\n cookie.sendResponse(cb::engine_errc(ret));\n }\n}\nMB-37374: Log IncludeDeletedUserXattrs enabled at dcp_open_executor\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"engine_wrapper.h\"\n#include \"executors.h\"\n#include \"utilities.h\"\n#include \n#include \n#include \n#include \n#include \n\nvoid dcp_open_executor(Cookie& cookie) {\n using cb::mcbp::request::DcpOpenPayload;\n\n auto& request = cookie.getHeader().getRequest();\n auto ext = request.getExtdata();\n const auto* payload = reinterpret_cast(ext.data());\n const uint32_t flags = payload->getFlags();\n\n auto ret = cookie.swapAiostat(ENGINE_SUCCESS);\n\n auto& connection = cookie.getConnection();\n connection.enableDatatype(cb::mcbp::Feature::JSON);\n\n const bool dcpNotifier =\n (flags & DcpOpenPayload::Notifier) == DcpOpenPayload::Notifier;\n\n if (ret == ENGINE_SUCCESS) {\n cb::rbac::Privilege privilege = cb::rbac::Privilege::DcpProducer;\n if (dcpNotifier) {\n privilege = cb::rbac::Privilege::DcpConsumer;\n }\n\n ret = mcbp::checkPrivilege(cookie, privilege);\n\n if (ret == ENGINE_SUCCESS) {\n auto key = request.getKey();\n auto value = request.getValue();\n\n ret = dcpOpen(\n cookie,\n request.getOpaque(),\n payload->getSeqno(),\n flags,\n {reinterpret_cast(key.data()), key.size()},\n {reinterpret_cast(value.data()),\n value.size()});\n }\n }\n\n ret = connection.remapErrorCode(ret);\n switch (ret) {\n case ENGINE_SUCCESS: {\n const bool dcpXattrAware =\n (flags & DcpOpenPayload::IncludeXattrs) != 0 &&\n connection.selectedBucketIsXattrEnabled();\n const bool dcpDeletedUserXattr =\n (flags & DcpOpenPayload::IncludeDeletedUserXattrs) != 0 &&\n connection.selectedBucketIsXattrEnabled();\n const bool dcpNoValue = (flags & DcpOpenPayload::NoValue) != 0;\n const bool dcpDeleteTimes =\n (flags & DcpOpenPayload::IncludeDeleteTimes) != 0;\n connection.setDcpXattrAware(dcpXattrAware);\n connection.setDcpDeletedUserXattr(dcpDeletedUserXattr);\n connection.setDcpNoValue(dcpNoValue);\n connection.setDcpDeleteTimeEnabled(dcpDeleteTimes);\n connection.setDCP(true);\n connection.disableSaslAuth();\n\n \/\/ String buffer with max length = total length of all possible contents\n std::string logBuffer;\n\n const bool dcpProducer =\n (flags & DcpOpenPayload::Producer) == DcpOpenPayload::Producer;\n if (dcpProducer) {\n logBuffer.append(\"PRODUCER, \");\n }\n if (dcpNotifier) {\n logBuffer.append(\"NOTIFIER, \");\n }\n if (dcpXattrAware) {\n logBuffer.append(\"INCLUDE_XATTRS, \");\n }\n if (dcpNoValue) {\n logBuffer.append(\"NO_VALUE, \");\n }\n if (dcpDeleteTimes) {\n logBuffer.append(\"DELETE_TIMES, \");\n }\n if (connection.isDcpDeletedUserXattr()) {\n logBuffer.append(\"INCLUDE_DELETED_USER_XATTRS, \");\n }\n\n \/\/ Remove trailing whitespace and comma\n if (!logBuffer.empty()) {\n logBuffer.resize(logBuffer.size() - 2);\n }\n\n LOG_INFO(\"{}: DCP connection opened successfully. {} {}\",\n connection.getId(),\n logBuffer,\n connection.getDescription().c_str());\n\n audit_dcp_open(connection);\n cookie.sendResponse(cb::mcbp::Status::Success);\n break;\n }\n\n case ENGINE_DISCONNECT:\n connection.setState(StateMachine::State::closing);\n break;\n\n case ENGINE_EWOULDBLOCK:\n cookie.setEwouldblock(true);\n break;\n\n default:\n cookie.sendResponse(cb::engine_errc(ret));\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define BUFFER_SIZE 1024\n#define INFD 1e8\nusing std::min;\nusing std::max;\nusing std::make_pair;\n\ntypedef std::vector Vector;\ntypedef std::vector Matrix;\ntypedef std::pair Edge;\n\nvoid printVector(const Vector &v) {\n for (auto x : v)\n printf(\"%.4lf\\t\", x);\n printf(\"\\n\");\n}\n\ndouble norm(const Vector &v) {\n double t = 0;\n for (auto x : v) t += x * x;\n return sqrt(t);\n}\n\nVector crossProduct(const Vector &a, const Vector &b) {\n assert(a.size() == 3 && b.size() == 3);\n Vector c(3);\n c[0] = a[1] * b[2] - a[2] * b[1];\n c[1] = a[2] * b[0] - a[0] * b[2];\n c[2] = a[0] * b[1] - a[1] * b[0];\n return c;\n}\n\ndouble innerProduct(const Vector &a, const Vector &b) {\n assert(a.size() == b.size());\n double c = 0;\n for (int i = 0; i < a.size(); i++)\n c += a[i] * b[i];\n return c;\n}\n\nMatrix outerProduct(const Vector &a, const Vector &b) {\n Matrix c(a.size(), Vector(b.size(), 0));\n for (int i = 0; i < a.size(); i++)\n for (int j = 0; j < b.size(); j++)\n c[i][j] = a[i] * b[j];\n return c;\n}\n\nVector innerProduct(const Vector &a, const Matrix &b) {\n assert(a.size() == b.size());\n if (a.size() == 0) return Vector();\n Vector c(b[0].size(), 0);\n for (int i = 0; i < b.size(); i++)\n for (int j = 0; j < b[0].size(); j++)\n c[j] += a[i] * b[i][j];\n return c;\n}\n\nVector operator + (const Vector &a, const Vector &b) {\n assert(a.size() == b.size());\n Vector c(a.size());\n for (int i = 0; i < a.size(); i++)\n c[i] = a[i] + b[i];\n return c;\n}\n\nVector operator - (const Vector &a, const Vector &b) {\n assert(a.size() == b.size());\n Vector c(a.size());\n for (int i = 0; i < a.size(); i++)\n c[i] = a[i] - b[i];\n return c;\n}\n\nVector operator \/ (const Vector &a, const double &b) {\n assert(b != 0);\n Vector c(a.size());\n for (int i = 0; i < a.size(); i++)\n c[i] = a[i] \/ b;\n return c;\n}\n\n\n\n\nclass Model {\n std::vector< Vector > vertex;\n std::vector removed;\n std::vector< std::set > face;\n std::set edge;\n int faceN;\n\n double edgeLen(Edge e) {\n return norm(vertex[e.first] - vertex[e.second]);\n }\n\npublic:\n void clear() {\n vertex.clear();\n removed.clear();\n face.clear();\n edge.clear();\n faceN = 0;\n }\n\n int getEdgeN() {\n return edge.size();\n }\n\n int getVertexN() {\n return vertex.size();\n }\n\n int getFaceN() {\n return faceN;\n }\n\n void selfCheck() {\n std::set ss;\n\n int vertexN = getVertexN();\n for (int i = 0; i < vertexN; i++) {\n if (removed[i]) {\n assert(face[i].size() == 0);\n } else {\n for (const auto &x : face[i]) {\n assert(!removed[x.first] && !removed[x.second]);\n assert(face[x.first].find(make_pair(x.second, i)) != face[x.first].end());\n assert(face[x.second].find(make_pair(i, x.first)) != face[x.second].end());\n ss.insert(make_pair(min(x.first, x.second), max(x.first, x.second)));\n }\n }\n }\n\n for (const auto &x : ss)\n assert(edge.find(x) != edge.end());\n for (const auto &x : edge)\n assert(ss.find(x) != ss.end());\n }\n\n void loadFromFile(std::string filename) {\n clear();\n\n\n char buffer[BUFFER_SIZE];\n FILE *file = fopen(filename.c_str(), \"r\");\n std::vector vertexIn;\n std::vector faceIn;\n while (fgets(buffer, BUFFER_SIZE, file) != NULL) {\n int ptr = 0;\n while (buffer[ptr] != 0 && buffer[ptr] != 'v' && buffer[ptr] != 'f' && buffer[ptr] != '#') ptr++;\n if (buffer[ptr] == 'v') vertexIn.push_back(std::string(buffer));\n if (buffer[ptr] == 'f') faceIn.push_back(std::string(buffer));\n }\n fclose(file);\n\n\n int vertexN = vertexIn.size();\n vertex.resize(vertexN, Vector(3, 0));\n removed.resize(vertexN, false);\n face.resize(vertexN);\n faceN = faceIn.size();\n\n for (int i = 0; i < vertexN; i++) {\n sscanf(vertexIn[i].c_str(), \"%*s%lf%lf%lf\", &vertex[i][0], &vertex[i][1], &vertex[i][2]);\n }\n\n\n for (const auto &f : faceIn) {\n int v[3];\n sscanf(f.c_str(), \"%*s%d%d%d\", v, v + 1, v + 2);\n v[0] --; v[1] --; v[2] --;\n face[v[0]].insert(make_pair(v[1], v[2]));\n face[v[1]].insert(make_pair(v[2], v[0]));\n face[v[2]].insert(make_pair(v[0], v[1]));\n std::sort(v, v + 3);\n assert(0 <= v[0] && v[0] < v[1] && v[1] < v[2] && v[2] < vertexN);\n edge.insert(make_pair(v[0], v[1]));\n edge.insert(make_pair(v[1], v[2]));\n edge.insert(make_pair(v[0], v[2]));\n }\n }\n\n void saveToFile(std::string filename) {\n FILE *file = fopen(filename.c_str(), \"w\");\n int vertexN = vertex.size();\n std::vector vertexID(vertexN, 0);\n int vertexReal = 0;\n\n for (int i = 0; i < vertexN; i++) {\n if (removed[i]) continue;\n vertexID[i] = ++vertexReal;\n fprintf(file, \"v %.8lf %.8lf %.8lf\\n\", vertex[i][0], vertex[i][1], vertex[i][2]);\n }\n\n for (int i = 0; i < vertexN; i++) {\n if (removed[i]) continue;\n for (const auto &f : face[i]) {\n assert(!removed[f.first] && !removed[f.second]);\n assert(vertexID[f.first] && vertexID[f.second] && vertexID[i]);\n if (i < f.first && i < f.second) {\n fprintf(file, \"f %d %d %d\\n\", vertexID[i], vertexID[f.first], vertexID[f.second]);\n }\n }\n }\n }\n\n double getCost(int vid, Vector vpos) {\n auto v = vertex[vid] - vpos;\n \/\/ printVector(v);\n double cost = 0;\n for (const auto &f : face[vid]) {\n auto n = crossProduct(vertex[f.first] - vertex[vid], vertex[f.second] - vertex[vid]);\n n = n \/ norm(n);\n \/\/ printVector(n);\n cost += innerProduct(v, n) * innerProduct(v, n);\n }\n \/\/ printf(\"%.4lf\\n\", cost);\n return cost;\n }\n\n Edge selectEdge(double threshold) {\n Edge idx = make_pair(-1, -1);\n double best = INFD;\n for (const auto &e : edge) {\n if (edgeLen(e) > threshold) continue;\n auto v = (vertex[e.first] + vertex[e.second]) \/ 2.0;\n double c = getCost(e.first, v) + getCost(e.second, v);\n \/\/ printf(\"%.4lf\\n\", c);\n if (c < best) {\n best = c;\n idx = e;\n }\n }\n assert(idx != make_pair(-1, -1));\n printf(\"%lf %d %d\", best, idx.first, idx.second);\n return idx;\n }\n\n void removeEdge(Edge e) {\n auto v = (vertex[e.first] + vertex[e.second]) \/ 2.0;\n edge.erase(e);\n vertex[e.first] = v;\n vertex[e.second].clear();\n removed[e.second] = true;\n\n for (const auto &f : face[e.second]) {\n assert(face[f.second].find(make_pair(e.second, f.first)) != face[f.second].end());\n face[f.second].erase(make_pair(e.second, f.first));\n if (f.first != e.first && f.second != e.first) {\n face[f.second].insert(make_pair(e.first, f.first));\n }\n\n assert(face[f.first].find(make_pair(f.second, e.second)) != face[f.first].end());\n face[f.first].erase(make_pair(f.second, e.second));\n if (f.first != e.first && f.second != e.first) {\n face[f.first].insert(make_pair(f.second, e.first));\n }\n\n if (f.first == e.first || f.second == e.first)\n faceN--;\n else\n face[e.first].insert(f);\n\n auto tmp = make_pair(min(e.second, f.first), max(e.second, f.first));\n if (edge.find(tmp) != edge.end())\n edge.erase(tmp);\n tmp = make_pair(min(e.second, f.second), max(e.second, f.second));\n if (edge.find(tmp) != edge.end())\n edge.erase(tmp);\n if (f.first != e.first && f.second != e.first) {\n edge.insert(make_pair(min(e.first, f.first), max(e.first, f.first)));\n edge.insert(make_pair(min(e.first, f.second), max(e.first, f.second)));\n }\n }\n face[e.second].clear();\n }\n\n void simplify(int target, double threshold) {\n while (faceN > target) {\n printf(\"%c%d\\t\", 13, faceN);\n auto e = selectEdge(threshold);\n removeEdge(e);\n selfCheck();\n fflush(stdout);\n }\n }\n\n} model;\n\nint main(int argc, char **argv) {\n if (argc < 4) {\n printf(\"Usage:\\n .\/main [Input Object] [Output Object] [Simplify Rate] [Threshold Value]\");\n return 0;\n }\n std::string inputModelFileName(argv[1]);\n std::string outputModelFileName(argv[2]);\n double simplifyRate = atof(argv[3]);\n double threshold;\n if (argc == 5) {\n threshold = atof(argv[4]);\n } else {\n printf(\"Warning: use threshold = INF (default)\\n\");\n threshold = INFD;\n }\n\n printf(\"inputModelFileName: %s\\n\", inputModelFileName.c_str());\n printf(\"outputModelFileName: %s\\n\", outputModelFileName.c_str());\n printf(\"simplifyRate: %.4lf\\n\", simplifyRate);\n printf(\"threshold: %.4lf\\n\", threshold);\n printf(\"------------------------------------\\n\");\n\n model.loadFromFile(inputModelFileName);\n\n int all = model.getFaceN();\n int simple = all * simplifyRate;\n\n printf(\"vertex: %d\\n\", model.getVertexN());\n printf(\"edge: %d\\n\", model.getEdgeN());\n printf(\"simple \/ all = %d \/ %d\\n\", simple, all);\n model.simplify(simple, threshold);\n\n model.saveToFile(outputModelFileName);\n model.selfCheck();\n return 0;\n}\nuse partial to calc minimum cost#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define BUFFER_SIZE 1024\n#define INFD 1e8\n#define EPS 1e-8\nusing std::min;\nusing std::max;\nusing std::make_pair;\n\ntypedef std::vector Vector;\ntypedef std::vector Matrix;\ntypedef std::pair Edge;\n\nvoid printVector(const Vector &v) {\n for (auto x : v)\n printf(\"%.4lf\\t\", x);\n printf(\"\\n\");\n}\n\nvoid printMatrx(const Matrix &m) {\n for (auto v : m)\n printVector(v);\n}\n\ndouble norm(const Vector &v) {\n double t = 0;\n for (auto x : v) t += x * x;\n return sqrt(t);\n}\n\nVector crossProduct(const Vector &a, const Vector &b) {\n assert(a.size() == 3 && b.size() == 3);\n Vector c(3);\n c[0] = a[1] * b[2] - a[2] * b[1];\n c[1] = a[2] * b[0] - a[0] * b[2];\n c[2] = a[0] * b[1] - a[1] * b[0];\n return c;\n}\n\ndouble innerProduct(const Vector &a, const Vector &b) {\n assert(a.size() == b.size());\n double c = 0;\n for (int i = 0; i < a.size(); i++)\n c += a[i] * b[i];\n return c;\n}\n\nMatrix outerProduct(const Vector &a, const Vector &b) {\n Matrix c(a.size(), Vector(b.size(), 0));\n for (int i = 0; i < a.size(); i++)\n for (int j = 0; j < b.size(); j++)\n c[i][j] = a[i] * b[j];\n return c;\n}\n\nVector innerProduct(const Vector &a, const Matrix &b) {\n assert(a.size() == b.size());\n if (a.size() == 0) return Vector();\n Vector c(b[0].size(), 0);\n for (int i = 0; i < b.size(); i++)\n for (int j = 0; j < b[0].size(); j++)\n c[j] += a[i] * b[i][j];\n return c;\n}\n\nVector operator + (const Vector &a, const Vector &b) {\n assert(a.size() == b.size());\n Vector c(a.size());\n for (int i = 0; i < a.size(); i++)\n c[i] = a[i] + b[i];\n return c;\n}\n\nMatrix operator + (const Matrix &a, const Matrix &b) {\n assert(a.size() == b.size());\n Matrix c(a.size());\n for (int i = 0; i < a.size(); i++)\n c[i] = a[i] + b[i];\n return c;\n}\n\nVector operator - (const Vector &a, const Vector &b) {\n assert(a.size() == b.size());\n Vector c(a.size());\n for (int i = 0; i < a.size(); i++)\n c[i] = a[i] - b[i];\n return c;\n}\n\nVector operator * (const double &a, const Vector &b) {\n Vector c(b.size());\n for (int i = 0; i < b.size(); i++)\n c[i] = a * b[i];\n return c;\n}\n\nVector operator \/ (const Vector &a, const double &b) {\n assert(b != 0);\n Vector c(a.size());\n for (int i = 0; i < a.size(); i++)\n c[i] = a[i] \/ b;\n return c;\n}\n\nVector solveEquation(Matrix m, int n) {\n Matrix bak = m;\n assert(m.size() >= n);\n if (m.size() == 0) return Vector();\n assert(m[0].size() > n);\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++)\n if (fabs(m[i][i]) < fabs(m[j][i])) m[i].swap(m[j]);\n if (fabs(m[i][i]) < EPS) throw 200;\n m[i] = m[i] \/ m[i][i];\n for (int j = i + 1; j < n; j++)\n m[j] = m[j] - m[j][i] * m[i];\n }\n Vector v(n);\n for (int i = n - 1; i >= 0; i--) {\n assert(fabs(m[i][i] - 1) < EPS);\n v[i] = -m[i][n];\n for (int j = i + 1; j < n; j++) {\n v[i] -= m[i][j] * v[j];\n }\n }\n\n for (int i = 0; i < n; i++) {\n double tmp = 0;\n for (int j = 0; j < n; j++)\n tmp += bak[i][j] * v[j];\n assert(fabs(tmp + bak[i][n]) < EPS);\n }\n return v;\n}\n\n\nclass Model {\n std::vector< Vector > vertex;\n std::vector removed;\n std::vector< std::set > face;\n std::set edge;\n int faceN;\n\n double edgeLen(Edge e) {\n return norm(vertex[e.first] - vertex[e.second]);\n }\n\npublic:\n void clear() {\n vertex.clear();\n removed.clear();\n face.clear();\n edge.clear();\n faceN = 0;\n }\n\n int getEdgeN() {\n return edge.size();\n }\n\n int getVertexN() {\n return vertex.size();\n }\n\n int getFaceN() {\n return faceN;\n }\n\n void selfCheck() {\n std::set ss;\n\n int vertexN = getVertexN();\n for (int i = 0; i < vertexN; i++) {\n if (removed[i]) {\n assert(face[i].size() == 0);\n } else {\n for (const auto &x : face[i]) {\n assert(!removed[x.first] && !removed[x.second]);\n assert(face[x.first].find(make_pair(x.second, i)) != face[x.first].end());\n assert(face[x.second].find(make_pair(i, x.first)) != face[x.second].end());\n ss.insert(make_pair(min(x.first, x.second), max(x.first, x.second)));\n }\n }\n }\n\n for (const auto &x : ss)\n assert(edge.find(x) != edge.end());\n for (const auto &x : edge)\n assert(ss.find(x) != ss.end());\n }\n\n void loadFromFile(std::string filename) {\n clear();\n\n\n char buffer[BUFFER_SIZE];\n FILE *file = fopen(filename.c_str(), \"r\");\n std::vector vertexIn;\n std::vector faceIn;\n while (fgets(buffer, BUFFER_SIZE, file) != NULL) {\n int ptr = 0;\n while (buffer[ptr] != 0 && buffer[ptr] != 'v' && buffer[ptr] != 'f' && buffer[ptr] != '#') ptr++;\n if (buffer[ptr] == 'v') vertexIn.push_back(std::string(buffer));\n if (buffer[ptr] == 'f') faceIn.push_back(std::string(buffer));\n }\n fclose(file);\n\n\n int vertexN = vertexIn.size();\n vertex.resize(vertexN, Vector(3, 0));\n removed.resize(vertexN, false);\n face.resize(vertexN);\n faceN = faceIn.size();\n\n for (int i = 0; i < vertexN; i++) {\n sscanf(vertexIn[i].c_str(), \"%*s%lf%lf%lf\", &vertex[i][0], &vertex[i][1], &vertex[i][2]);\n }\n\n\n for (const auto &f : faceIn) {\n int v[3];\n sscanf(f.c_str(), \"%*s%d%d%d\", v, v + 1, v + 2);\n v[0] --; v[1] --; v[2] --;\n face[v[0]].insert(make_pair(v[1], v[2]));\n face[v[1]].insert(make_pair(v[2], v[0]));\n face[v[2]].insert(make_pair(v[0], v[1]));\n std::sort(v, v + 3);\n assert(0 <= v[0] && v[0] < v[1] && v[1] < v[2] && v[2] < vertexN);\n edge.insert(make_pair(v[0], v[1]));\n edge.insert(make_pair(v[1], v[2]));\n edge.insert(make_pair(v[0], v[2]));\n }\n }\n\n void saveToFile(std::string filename) {\n FILE *file = fopen(filename.c_str(), \"w\");\n int vertexN = vertex.size();\n std::vector vertexID(vertexN, 0);\n int vertexReal = 0;\n\n for (int i = 0; i < vertexN; i++) {\n if (removed[i]) continue;\n vertexID[i] = ++vertexReal;\n fprintf(file, \"v %.8lf %.8lf %.8lf\\n\", vertex[i][0], vertex[i][1], vertex[i][2]);\n }\n\n for (int i = 0; i < vertexN; i++) {\n if (removed[i]) continue;\n for (const auto &f : face[i]) {\n assert(!removed[f.first] && !removed[f.second]);\n assert(vertexID[f.first] && vertexID[f.second] && vertexID[i]);\n if (i < f.first && i < f.second) {\n fprintf(file, \"f %d %d %d\\n\", vertexID[i], vertexID[f.first], vertexID[f.second]);\n }\n }\n }\n }\n\n std::pair getPosition(Edge e) {\n Matrix q(4, Vector(4, 0));\n for (const auto &f : face[e.first]) {\n auto n = crossProduct(vertex[f.first] - vertex[e.first], vertex[f.second] - vertex[e.first]);\n n = n \/ norm(n);\n n.push_back(-innerProduct(vertex[e.first], n));\n q = q + outerProduct(n, n);\n }\n for (const auto &f : face[e.second]) {\n auto n = crossProduct(vertex[f.first] - vertex[e.second], vertex[f.second] - vertex[e.second]);\n n = n \/ norm(n);\n n.push_back(-innerProduct(vertex[e.second], n));\n q = q + outerProduct(n, n);\n }\n\n Vector v;\n try {\n v = solveEquation(q, 3);\n } catch(...) {\n v = (vertex[e.first] + vertex[e.second]) \/ 2;\n }\n v.push_back(1);\n double cost = innerProduct(innerProduct(v, q), v);\n assert(cost > -EPS);\n v.pop_back();\n return make_pair(v, cost);\n }\n\n std::pair selectEdge(double threshold) {\n Edge idx = make_pair(-1, -1);\n Vector pos;\n double best = INFD;\n for (const auto &e : edge) {\n if (edgeLen(e) > threshold) continue;\n auto v = getPosition(e);\n if (v.second < best) {\n best = v.second;\n idx = e;\n pos = v.first;\n }\n }\n if (idx == make_pair(-1, -1)) {\n printf(\"%cERROR: No enough edges under threshold\\n\", 13);\n }\n printf(\"%lf %d %d\", best, idx.first, idx.second);\n return std::make_pair(idx, pos);\n }\n\n void removeEdge(Edge e, Vector v) {\n edge.erase(e);\n vertex[e.first] = v;\n vertex[e.second].clear();\n removed[e.second] = true;\n\n for (const auto &f : face[e.second]) {\n assert(face[f.second].find(make_pair(e.second, f.first)) != face[f.second].end());\n face[f.second].erase(make_pair(e.second, f.first));\n if (f.first != e.first && f.second != e.first) {\n face[f.second].insert(make_pair(e.first, f.first));\n }\n\n assert(face[f.first].find(make_pair(f.second, e.second)) != face[f.first].end());\n face[f.first].erase(make_pair(f.second, e.second));\n if (f.first != e.first && f.second != e.first) {\n face[f.first].insert(make_pair(f.second, e.first));\n }\n\n if (f.first == e.first || f.second == e.first)\n faceN--;\n else\n face[e.first].insert(f);\n\n auto tmp = make_pair(min(e.second, f.first), max(e.second, f.first));\n if (edge.find(tmp) != edge.end())\n edge.erase(tmp);\n tmp = make_pair(min(e.second, f.second), max(e.second, f.second));\n if (edge.find(tmp) != edge.end())\n edge.erase(tmp);\n if (f.first != e.first && f.second != e.first) {\n edge.insert(make_pair(min(e.first, f.first), max(e.first, f.first)));\n edge.insert(make_pair(min(e.first, f.second), max(e.first, f.second)));\n }\n }\n face[e.second].clear();\n }\n\n void simplify(int target, double threshold) {\n while (faceN > target) {\n printf(\"%c%d\\t\", 13, faceN);\n auto e = selectEdge(threshold);\n removeEdge(e.first, e.second);\n selfCheck();\n fflush(stdout);\n }\n }\n\n} model;\n\nint main(int argc, char **argv) {\n if (argc < 4) {\n printf(\"Usage:\\n .\/main [Input Object] [Output Object] [Simplify Rate] [Threshold Value]\");\n return 0;\n }\n std::string inputModelFileName(argv[1]);\n std::string outputModelFileName(argv[2]);\n double simplifyRate = atof(argv[3]);\n double threshold;\n if (argc == 5) {\n threshold = atof(argv[4]);\n } else {\n printf(\"Warning: use threshold = INF (default)\\n\");\n threshold = INFD;\n }\n\n printf(\"inputModelFileName: %s\\n\", inputModelFileName.c_str());\n printf(\"outputModelFileName: %s\\n\", outputModelFileName.c_str());\n printf(\"simplifyRate: %.4lf\\n\", simplifyRate);\n printf(\"threshold: %.4lf\\n\", threshold);\n printf(\"------------------------------------\\n\");\n\n model.loadFromFile(inputModelFileName);\n\n int all = model.getFaceN();\n int simple = all * simplifyRate;\n\n printf(\"vertex: %d\\n\", model.getVertexN());\n printf(\"edge: %d\\n\", model.getEdgeN());\n printf(\"simple \/ all = %d \/ %d\\n\", simple, all);\n model.simplify(simple, threshold);\n\n model.saveToFile(outputModelFileName);\n model.selfCheck();\n return 0;\n}\n<|endoftext|>"} {"text":"#line 2 \"sxc:main.cxx\"\n\/\/ LICENSE\/*{{{*\/\n\/*\n sxc - Simple Xmpp Client\n Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n Permission to use, copy, modify, and\/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\/*}}}*\/\n\n\n\/\/ INCLUDE\/*{{{*\/\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*}}}*\/\n\n\/**\n * @mainpage sxc Documentation\n *\n * @section contents Contents\n * @ref desc_sec\n *\n * @section desc_sec Description\n * sxc (pronounced \"sexy) is for jabber what ii (irc it \/ irc improved) is for\n * IRC: A minimalistic file-based jabber client which runs in the background\n * and can be controlled with basic command line tools to read from \/ write\n * into the files\/FIFOs sxc creates.\n *\/\n\n#include \n\n\/**\n * @brief The starting point of sxc.\n *\/\nint main(int argc, char *argv[])\/*{{{*\/\n{\n libsxc::Option::Parser parser;\n libsxc::Option::Option defHelp(\n &parser, 'h', \"help\", \"Show help and exit\");\n libsxc::Option::Option defVersion(\n &parser, 'V', \"version\", \"Show version and exit\");\n libsxc::Option::OptionPort port(\n &parser, 'p', \"port\", \"port\", \"0 - 65535, -1 for default\");\n libsxc::Option::Option name(\n &parser, ' ', \"iqname\", \"name\",\n std::string(\"Name to announce (default: \") + PACKAGE + \")\", PACKAGE);\n libsxc::Option::Option version(\n &parser, ' ', \"iqversion\", \"version\",\n std::string(\"Version to announce (default: \") + VERSION + \")\", VERSION);\n const std::string defaultResource =\n std::string(PACKAGE) + \"@\" + libsxc::getHostName();\n libsxc::Option::Option jidRaw(\n &parser, ' ', \"\", \"jid\",\n \"user@domain[\/resource] (resource default: \" + defaultResource + \")\");\n\n try {\n parser.parse(argv);\n } catch (libsxc::Exception::Exception &e) {\n std::cerr << e.what() << std::endl;\n return e.getExitCode();\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n return libsxc::Exit::General;\n } catch (...) {\n std::cerr << \"Unexpected error parsing options.\" << std::endl;\n return libsxc::Exit::General;\n }\n\n if (parser.doShowHelp()) {\n std::cerr << PACKAGE \" \" VERSION \" (C) \" COPYRIGHT << std::endl;\n\n std::vector usage = parser.getUsage();\n for(\n std::vector::iterator it = usage.begin();\n usage.end() != it;\n ++it) {\n std::cerr << *it << std::endl;\n }\n return libsxc::Exit::NoError;\n }\n\n if (parser.doShowVersion()) {\n std::cerr << VERSION << std::endl;\n return libsxc::Exit::NoError;\n }\n\n gloox::JID jid = jidRaw.getValue();\n if (\"\" == jid.resource())\n jid.setResource(defaultResource);\n\n \/\/ Fill in the passphrase later.\n gloox::Client client(jid, \"\", port.getValue());\n setupClient(client, name.getValue(), version.getValue());\n\n File::createDir(jid.bare());\n Account::File::Output out(jid.bare());\n Account::File::Info nfo(jid.bare());\n\n \/\/ Signal waiter as to be created before running any thread. Else signals\n \/\/ directed to them would not get handled by the registered handlers.\n libsxc::Signal::Waiter waiter;\n Error::Handler handler(waiter, out);\n waiter.reg(SIGINT, handler);\n waiter.reg(SIGTERM, handler);\n waiter.run(); \/\/ From this moment on signals are handled. Not blocking.\n\n try {\n Account::Roster roster(client, out, handler);\n Account::Account account(client, roster,out, nfo, handler);\n account.run();\n\n KeepAlive ka(client\/*, interval=120, timeout=120*\/);\n ka.run();\n\n waiter.join(); \/\/ Blocking. Wait until execution stop is requested.\n } catch (libsxc::Exception::Exception &e) {\n handler.printCritical(e.what());\n return e.getExitCode();\n }\n\n return handler.getExitCode();\n}\/*}}}*\/\n\n\/\/ Use no tabs at all; two spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker\nChange pinging interval to 60 seconds#line 2 \"sxc:main.cxx\"\n\/\/ LICENSE\/*{{{*\/\n\/*\n sxc - Simple Xmpp Client\n Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n Permission to use, copy, modify, and\/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\/*}}}*\/\n\n\n\/\/ INCLUDE\/*{{{*\/\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*}}}*\/\n\n\/**\n * @mainpage sxc Documentation\n *\n * @section contents Contents\n * @ref desc_sec\n *\n * @section desc_sec Description\n * sxc (pronounced \"sexy) is for jabber what ii (irc it \/ irc improved) is for\n * IRC: A minimalistic file-based jabber client which runs in the background\n * and can be controlled with basic command line tools to read from \/ write\n * into the files\/FIFOs sxc creates.\n *\/\n\n#include \n\n\/**\n * @brief The starting point of sxc.\n *\/\nint main(int argc, char *argv[])\/*{{{*\/\n{\n libsxc::Option::Parser parser;\n libsxc::Option::Option defHelp(\n &parser, 'h', \"help\", \"Show help and exit\");\n libsxc::Option::Option defVersion(\n &parser, 'V', \"version\", \"Show version and exit\");\n libsxc::Option::OptionPort port(\n &parser, 'p', \"port\", \"port\", \"0 - 65535, -1 for default\");\n libsxc::Option::Option name(\n &parser, ' ', \"iqname\", \"name\",\n std::string(\"Name to announce (default: \") + PACKAGE + \")\", PACKAGE);\n libsxc::Option::Option version(\n &parser, ' ', \"iqversion\", \"version\",\n std::string(\"Version to announce (default: \") + VERSION + \")\", VERSION);\n const std::string defaultResource =\n std::string(PACKAGE) + \"@\" + libsxc::getHostName();\n libsxc::Option::Option jidRaw(\n &parser, ' ', \"\", \"jid\",\n \"user@domain[\/resource] (resource default: \" + defaultResource + \")\");\n\n try {\n parser.parse(argv);\n } catch (libsxc::Exception::Exception &e) {\n std::cerr << e.what() << std::endl;\n return e.getExitCode();\n } catch (std::exception &e) {\n std::cerr << e.what() << std::endl;\n return libsxc::Exit::General;\n } catch (...) {\n std::cerr << \"Unexpected error parsing options.\" << std::endl;\n return libsxc::Exit::General;\n }\n\n if (parser.doShowHelp()) {\n std::cerr << PACKAGE \" \" VERSION \" (C) \" COPYRIGHT << std::endl;\n\n std::vector usage = parser.getUsage();\n for(\n std::vector::iterator it = usage.begin();\n usage.end() != it;\n ++it) {\n std::cerr << *it << std::endl;\n }\n return libsxc::Exit::NoError;\n }\n\n if (parser.doShowVersion()) {\n std::cerr << VERSION << std::endl;\n return libsxc::Exit::NoError;\n }\n\n gloox::JID jid = jidRaw.getValue();\n if (\"\" == jid.resource())\n jid.setResource(defaultResource);\n\n \/\/ Fill in the passphrase later.\n gloox::Client client(jid, \"\", port.getValue());\n setupClient(client, name.getValue(), version.getValue());\n\n File::createDir(jid.bare());\n Account::File::Output out(jid.bare());\n Account::File::Info nfo(jid.bare());\n\n \/\/ Signal waiter as to be created before running any thread. Else signals\n \/\/ directed to them would not get handled by the registered handlers.\n libsxc::Signal::Waiter waiter;\n Error::Handler handler(waiter, out);\n waiter.reg(SIGINT, handler);\n waiter.reg(SIGTERM, handler);\n waiter.run(); \/\/ From this moment on signals are handled. Not blocking.\n\n try {\n Account::Roster roster(client, out, handler);\n Account::Account account(client, roster,out, nfo, handler);\n account.run();\n\n KeepAlive ka(client, 60, 120);\n ka.run();\n\n waiter.join(); \/\/ Blocking. Wait until execution stop is requested.\n } catch (libsxc::Exception::Exception &e) {\n handler.printCritical(e.what());\n return e.getExitCode();\n }\n\n return handler.getExitCode();\n}\/*}}}*\/\n\n\/\/ Use no tabs at all; two spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"Constants.h\"\n#include \"MathUtils.h\"\n\n#include \"components\/debug\/Debug.h\"\n\ndouble MathUtils::almostZero(double value)\n{\n\treturn std::abs(value) < Constants::Epsilon;\n}\n\ndouble MathUtils::almostEqual(double a, double b)\n{\n\treturn MathUtils::almostZero(a - b);\n}\n\ndouble MathUtils::getRealIndex(int bufferSize, double percent)\n{\n\tconst double bufferSizeReal = static_cast(bufferSize);\n\n\t\/\/ Keep the real index in the same array bounds (i.e. if bufferSize is 5, the max is 4.999...).\n\tconst double maxRealIndex = std::max(0.0, bufferSizeReal - Constants::Epsilon);\n\treturn std::clamp(bufferSizeReal * percent, 0.0, maxRealIndex);\n}\n\nint MathUtils::getWrappedIndex(int bufferSize, int index)\n{\n\twhile (index >= bufferSize)\n\t{\n\t\tindex -= bufferSize;\n\t}\n\n\twhile (index < 0)\n\t{\n\t\tindex += bufferSize;\n\t}\n\n\treturn index;\n}\n\nRadians MathUtils::fullAtan2(double y, double x)\n{\n\tconst Radians angle = std::atan2(y, x);\n\treturn (angle >= 0.0) ? angle : (Constants::TwoPi + angle);\n}\n\nRadians MathUtils::fullAtan2(const NewDouble2 &v)\n{\n\t\/\/ Flip +X south\/+Y west to +X east\/+Y north.\n\treturn MathUtils::fullAtan2(-v.x, -v.y);\n}\n\ndouble MathUtils::verticalFovToZoom(Degrees fovY)\n{\n\treturn 1.0 \/ std::tan((fovY * 0.5) * Constants::DegToRad);\n}\n\nDegrees MathUtils::verticalFovToHorizontalFov(Degrees fovY, double aspectRatio)\n{\n\tDebugAssert(fovY > 0.0);\n\tDebugAssert(fovY < 180.0);\n\tDebugAssert(aspectRatio > 0.0);\n\n\tconst double halfDim = aspectRatio * std::tan((fovY * 0.50) * Constants::DegToRad);\n\treturn (2.0 * std::atan(halfDim)) * Constants::RadToDeg;\n}\n\nbool MathUtils::isPointInHalfSpace(const Double2 &point, const Double2 ÷rPoint,\n\tconst Double2 &normal)\n{\n\treturn (point - dividerPoint).normalized().dot(normal) >= 0.0;\n}\n\nbool MathUtils::triangleCircleIntersection(const Double2 &triangleP0, const Double2 &triangleP1,\n\tconst Double2 &triangleP2, const Double2 &circlePoint, double circleRadius)\n{\n\tconst double circleRadiusSqr = circleRadius * circleRadius;\n\tconst Double2 p0p1 = triangleP1 - triangleP0;\n\tconst Double2 p1p2 = triangleP2 - triangleP1;\n\tconst Double2 p2p0 = triangleP0 - triangleP2;\n\n\t\/\/ Check if the circle center is inside the triangle.\n\tconst bool circleCenterInTriangle = [&triangleP0, &triangleP1, &triangleP2, &circlePoint,\n\t\t&p0p1, &p1p2, &p2p0]()\n\t{\n\t\tconst Double2 p0p1Inner = p0p1.leftPerp().normalized();\n\t\tconst Double2 p1p2Inner = p1p2.leftPerp().normalized();\n\t\tconst Double2 p2p0Inner = p2p0.leftPerp().normalized();\n\n\t\treturn MathUtils::isPointInHalfSpace(circlePoint, triangleP0, p0p1Inner) &&\n\t\t\tMathUtils::isPointInHalfSpace(circlePoint, triangleP1, p1p2Inner) &&\n\t\t\tMathUtils::isPointInHalfSpace(circlePoint, triangleP2, p2p0Inner);\n\t}();\n\n\tif (circleCenterInTriangle)\n\t{\n\t\treturn true;\n\t}\n\n\t\/\/ Check if any of the triangle vertices are in the circle.\n\tconst bool anyTriangleVertexInCircle = [&triangleP0, &triangleP1, &triangleP2,\n\t\t&circlePoint, circleRadiusSqr]()\n\t{\n\t\tauto isVertexInCircle = [&circlePoint, circleRadiusSqr](const Double2 &vertex)\n\t\t{\n\t\t\treturn (vertex - circlePoint).lengthSquared() <= circleRadiusSqr;\n\t\t};\n\n\t\treturn isVertexInCircle(triangleP0) || isVertexInCircle(triangleP1) ||\n\t\t\tisVertexInCircle(triangleP2);\n\t}();\n\n\tif (anyTriangleVertexInCircle)\n\t{\n\t\treturn true;\n\t}\n\n\t\/\/ Check if the circle intersects any of the triangle edges.\n\tconst bool anyEdgeCircleIntersection = [&triangleP0, &triangleP1, &triangleP2,\n\t\t&p0p1, &p1p2, &p2p0, &circlePoint, circleRadiusSqr]()\n\t{\n\t\tauto isEdgeIntersectingCircle = [&circlePoint, circleRadiusSqr](\n\t\t\tconst Double2 &vStart, const Double2 &vEnd, const Double2 &vDiff)\n\t\t{\n\t\t\t\/\/ Vector projection, heavily simplified. Project circle point onto edge.\n\t\t\tconst Double2 vals = (circlePoint - vStart) * vDiff;\n\t\t\tconst double t = (vals.x + vals.y) \/ vDiff.lengthSquared();\n\t\t\tif ((t >= 0.0) && (t <= 1.0))\n\t\t\t{\n\t\t\t\t\/\/ Projection is inside the line segment. Check distance from circle center.\n\t\t\t\tconst Double2 edgePoint = vStart + (vDiff * t);\n\t\t\t\treturn (edgePoint - circlePoint).lengthSquared() <= circleRadiusSqr;\n\t\t\t}\n\n\t\t\t\/\/ Projection is outside the line segment.\n\t\t\treturn false;\n\t\t};\n\n\t\treturn isEdgeIntersectingCircle(triangleP0, triangleP1, p0p1) ||\n\t\t\tisEdgeIntersectingCircle(triangleP1, triangleP2, p1p2) ||\n\t\t\tisEdgeIntersectingCircle(triangleP2, triangleP0, p2p0);\n\t}();\n\n\tif (anyEdgeCircleIntersection)\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool MathUtils::rayPlaneIntersection(const Double3 &rayStart, const Double3 &rayDirection,\n\tconst Double3 &planeOrigin, const Double3 &planeNormal, Double3 *outPoint)\n{\n\tDebugAssert(rayDirection.isNormalized());\n\tDebugAssert(planeNormal.isNormalized());\n\n\tconst double denominator = rayDirection.dot(planeNormal);\n\tif (!MathUtils::almostZero(denominator))\n\t{\n\t\tconst Double3 projection = planeOrigin - rayStart;\n\t\tconst double t = projection.dot(planeNormal) \/ denominator;\n\t\tif (t >= 0.0)\n\t\t{\n\t\t\t\/\/ An intersection exists. Find it.\n\t\t\t*outPoint = rayStart + (rayDirection * t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool MathUtils::rayQuadIntersection(const Double3 &rayStart, const Double3 &rayDirection,\n\tconst Double3 &v0, const Double3 &v1, const Double3 &v2, Double3 *outPoint)\n{\n\tconst Double3 v3 = v0 + (v2 - v1);\n\n\t\/\/ Calculate the normal of the plane which contains the quad.\n\tconst Double3 normal = (v2 - v0).cross(v1 - v0).normalized();\n\n\t\/\/ Get the intersection of the ray and the plane that contains the quad.\n\tDouble3 hitPoint;\n\tif (MathUtils::rayPlaneIntersection(rayStart, rayDirection, v0, normal, &hitPoint))\n\t{\n\t\t\/\/ The plane intersection is a point co-planar with the quad. Check if the point is\n\t\t\/\/ within the bounds of the quad.\n\t\tconst Double3 a = (v1 - v0).cross(hitPoint - v0);\n\t\tconst Double3 b = (v2 - v1).cross(hitPoint - v1);\n\t\tconst Double3 c = (v3 - v2).cross(hitPoint - v2);\n\t\tconst Double3 d = (v0 - v3).cross(hitPoint - v3);\n\n\t\tconst double ab = a.dot(b);\n\t\tconst double bc = b.dot(c);\n\t\tconst double cd = c.dot(d);\n\n\t\tif (((ab * bc) >= 0.0) && ((bc * cd) >= 0.0))\n\t\t{\n\t\t\t*outPoint = hitPoint;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\ndouble MathUtils::distanceBetweenLineSegments(const Double3 &p0, const Double3 &p1,\n\tconst Double3 &q0, const Double3 &q1, double &s, double &t)\n{\n\tconst Double3 u = p1 - p0;\n\tconst Double3 v = q1 - q0;\n\n\t\/\/ These values are needed for the calculation of values s and t.\n\tconst Double3 p0q0 = p0 - q0;\n\tconst double a = u.dot(u);\n\tconst double b = u.dot(v);\n\tconst double c = v.dot(v);\n\tconst double d = u.dot(p0q0);\n\tconst double e = v.dot(p0q0);\n\n\tconst double be = b * e;\n\tconst double cd = c * d;\n\tconst double ac = a * c;\n\tconst double ae = a * e;\n\tconst double bd = b * d;\n\tconst double bb = b * b;\n\n\t\/\/ Calculate s and t. These are the points along u and v from p0 and q0 respectively that\n\t\/\/ are the closest to each other. The values are limited to the interval [0, 1] because\n\t\/\/ outside of that range is along the line that the segment exists on, but outside the bounds\n\t\/\/ of the segment.\n\ts = std::clamp((be - cd) \/ (ac - bb), 0.0, 1.0);\n\tt = std::clamp((ae - bd) \/ (ac - bb), 0.0, 1.0);\n\n\t\/\/ Calculate Psc and Qtc. These are the points on their respective segments that are closest\n\t\/\/ to each other.\n\tconst Double3 Psc = p0 + (u * s);\n\tconst Double3 Qtc = p0 + (v * t);\n\n\t\/\/ The distance between these two points is the shortest distance between the line segments.\n\treturn (Psc - Qtc).length();\n}\n\nstd::vector MathUtils::bresenhamLine(const Int2 &p1, const Int2 &p2)\n{\n\tconst int dx = std::abs(p2.x - p1.x);\n\tconst int dy = std::abs(p2.y - p1.y);\n\tconst int dirX = (p1.x < p2.x) ? 1 : -1;\n\tconst int dirY = (p1.y < p2.y) ? 1 : -1;\n\n\tint pointX = p1.x;\n\tint pointY = p1.y;\n\tint error = ((dx > dy) ? dx : -dy) \/ 2;\n\tconst int endX = p2.x;\n\tconst int endY = p2.y;\n\tstd::vector points;\n\n\twhile (true)\n\t{\n\t\tpoints.push_back(Int2(pointX, pointY));\n\n\t\tif ((pointX == endX) && (pointY == endY))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tconst int innerError = error;\n\n\t\tif (innerError > -dx)\n\t\t{\n\t\t\terror -= dy;\n\t\t\tpointX += dirX;\n\t\t}\n\n\t\tif (innerError < dy)\n\t\t{\n\t\t\terror += dx;\n\t\t\tpointY += dirY;\n\t\t}\n\t}\n\n\treturn points;\n}\nAdded bufferSize checks to some MathUtils functions.#include \n#include \n\n#include \"Constants.h\"\n#include \"MathUtils.h\"\n\n#include \"components\/debug\/Debug.h\"\n\ndouble MathUtils::almostZero(double value)\n{\n\treturn std::abs(value) < Constants::Epsilon;\n}\n\ndouble MathUtils::almostEqual(double a, double b)\n{\n\treturn MathUtils::almostZero(a - b);\n}\n\ndouble MathUtils::getRealIndex(int bufferSize, double percent)\n{\n\tDebugAssert(bufferSize > 0);\n\tconst double bufferSizeReal = static_cast(bufferSize);\n\n\t\/\/ Keep the real index in the same array bounds (i.e. if bufferSize is 5, the max is 4.999...).\n\tconst double maxRealIndex = std::max(0.0, bufferSizeReal - Constants::Epsilon);\n\treturn std::clamp(bufferSizeReal * percent, 0.0, maxRealIndex);\n}\n\nint MathUtils::getWrappedIndex(int bufferSize, int index)\n{\n\tDebugAssert(bufferSize > 0);\n\n\twhile (index >= bufferSize)\n\t{\n\t\tindex -= bufferSize;\n\t}\n\n\twhile (index < 0)\n\t{\n\t\tindex += bufferSize;\n\t}\n\n\treturn index;\n}\n\nRadians MathUtils::fullAtan2(double y, double x)\n{\n\tconst Radians angle = std::atan2(y, x);\n\treturn (angle >= 0.0) ? angle : (Constants::TwoPi + angle);\n}\n\nRadians MathUtils::fullAtan2(const NewDouble2 &v)\n{\n\t\/\/ Flip +X south\/+Y west to +X east\/+Y north.\n\treturn MathUtils::fullAtan2(-v.x, -v.y);\n}\n\ndouble MathUtils::verticalFovToZoom(Degrees fovY)\n{\n\treturn 1.0 \/ std::tan((fovY * 0.5) * Constants::DegToRad);\n}\n\nDegrees MathUtils::verticalFovToHorizontalFov(Degrees fovY, double aspectRatio)\n{\n\tDebugAssert(fovY > 0.0);\n\tDebugAssert(fovY < 180.0);\n\tDebugAssert(aspectRatio > 0.0);\n\n\tconst double halfDim = aspectRatio * std::tan((fovY * 0.50) * Constants::DegToRad);\n\treturn (2.0 * std::atan(halfDim)) * Constants::RadToDeg;\n}\n\nbool MathUtils::isPointInHalfSpace(const Double2 &point, const Double2 ÷rPoint,\n\tconst Double2 &normal)\n{\n\treturn (point - dividerPoint).normalized().dot(normal) >= 0.0;\n}\n\nbool MathUtils::triangleCircleIntersection(const Double2 &triangleP0, const Double2 &triangleP1,\n\tconst Double2 &triangleP2, const Double2 &circlePoint, double circleRadius)\n{\n\tconst double circleRadiusSqr = circleRadius * circleRadius;\n\tconst Double2 p0p1 = triangleP1 - triangleP0;\n\tconst Double2 p1p2 = triangleP2 - triangleP1;\n\tconst Double2 p2p0 = triangleP0 - triangleP2;\n\n\t\/\/ Check if the circle center is inside the triangle.\n\tconst bool circleCenterInTriangle = [&triangleP0, &triangleP1, &triangleP2, &circlePoint,\n\t\t&p0p1, &p1p2, &p2p0]()\n\t{\n\t\tconst Double2 p0p1Inner = p0p1.leftPerp().normalized();\n\t\tconst Double2 p1p2Inner = p1p2.leftPerp().normalized();\n\t\tconst Double2 p2p0Inner = p2p0.leftPerp().normalized();\n\n\t\treturn MathUtils::isPointInHalfSpace(circlePoint, triangleP0, p0p1Inner) &&\n\t\t\tMathUtils::isPointInHalfSpace(circlePoint, triangleP1, p1p2Inner) &&\n\t\t\tMathUtils::isPointInHalfSpace(circlePoint, triangleP2, p2p0Inner);\n\t}();\n\n\tif (circleCenterInTriangle)\n\t{\n\t\treturn true;\n\t}\n\n\t\/\/ Check if any of the triangle vertices are in the circle.\n\tconst bool anyTriangleVertexInCircle = [&triangleP0, &triangleP1, &triangleP2,\n\t\t&circlePoint, circleRadiusSqr]()\n\t{\n\t\tauto isVertexInCircle = [&circlePoint, circleRadiusSqr](const Double2 &vertex)\n\t\t{\n\t\t\treturn (vertex - circlePoint).lengthSquared() <= circleRadiusSqr;\n\t\t};\n\n\t\treturn isVertexInCircle(triangleP0) || isVertexInCircle(triangleP1) ||\n\t\t\tisVertexInCircle(triangleP2);\n\t}();\n\n\tif (anyTriangleVertexInCircle)\n\t{\n\t\treturn true;\n\t}\n\n\t\/\/ Check if the circle intersects any of the triangle edges.\n\tconst bool anyEdgeCircleIntersection = [&triangleP0, &triangleP1, &triangleP2,\n\t\t&p0p1, &p1p2, &p2p0, &circlePoint, circleRadiusSqr]()\n\t{\n\t\tauto isEdgeIntersectingCircle = [&circlePoint, circleRadiusSqr](\n\t\t\tconst Double2 &vStart, const Double2 &vEnd, const Double2 &vDiff)\n\t\t{\n\t\t\t\/\/ Vector projection, heavily simplified. Project circle point onto edge.\n\t\t\tconst Double2 vals = (circlePoint - vStart) * vDiff;\n\t\t\tconst double t = (vals.x + vals.y) \/ vDiff.lengthSquared();\n\t\t\tif ((t >= 0.0) && (t <= 1.0))\n\t\t\t{\n\t\t\t\t\/\/ Projection is inside the line segment. Check distance from circle center.\n\t\t\t\tconst Double2 edgePoint = vStart + (vDiff * t);\n\t\t\t\treturn (edgePoint - circlePoint).lengthSquared() <= circleRadiusSqr;\n\t\t\t}\n\n\t\t\t\/\/ Projection is outside the line segment.\n\t\t\treturn false;\n\t\t};\n\n\t\treturn isEdgeIntersectingCircle(triangleP0, triangleP1, p0p1) ||\n\t\t\tisEdgeIntersectingCircle(triangleP1, triangleP2, p1p2) ||\n\t\t\tisEdgeIntersectingCircle(triangleP2, triangleP0, p2p0);\n\t}();\n\n\tif (anyEdgeCircleIntersection)\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool MathUtils::rayPlaneIntersection(const Double3 &rayStart, const Double3 &rayDirection,\n\tconst Double3 &planeOrigin, const Double3 &planeNormal, Double3 *outPoint)\n{\n\tDebugAssert(rayDirection.isNormalized());\n\tDebugAssert(planeNormal.isNormalized());\n\n\tconst double denominator = rayDirection.dot(planeNormal);\n\tif (!MathUtils::almostZero(denominator))\n\t{\n\t\tconst Double3 projection = planeOrigin - rayStart;\n\t\tconst double t = projection.dot(planeNormal) \/ denominator;\n\t\tif (t >= 0.0)\n\t\t{\n\t\t\t\/\/ An intersection exists. Find it.\n\t\t\t*outPoint = rayStart + (rayDirection * t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool MathUtils::rayQuadIntersection(const Double3 &rayStart, const Double3 &rayDirection,\n\tconst Double3 &v0, const Double3 &v1, const Double3 &v2, Double3 *outPoint)\n{\n\tconst Double3 v3 = v0 + (v2 - v1);\n\n\t\/\/ Calculate the normal of the plane which contains the quad.\n\tconst Double3 normal = (v2 - v0).cross(v1 - v0).normalized();\n\n\t\/\/ Get the intersection of the ray and the plane that contains the quad.\n\tDouble3 hitPoint;\n\tif (MathUtils::rayPlaneIntersection(rayStart, rayDirection, v0, normal, &hitPoint))\n\t{\n\t\t\/\/ The plane intersection is a point co-planar with the quad. Check if the point is\n\t\t\/\/ within the bounds of the quad.\n\t\tconst Double3 a = (v1 - v0).cross(hitPoint - v0);\n\t\tconst Double3 b = (v2 - v1).cross(hitPoint - v1);\n\t\tconst Double3 c = (v3 - v2).cross(hitPoint - v2);\n\t\tconst Double3 d = (v0 - v3).cross(hitPoint - v3);\n\n\t\tconst double ab = a.dot(b);\n\t\tconst double bc = b.dot(c);\n\t\tconst double cd = c.dot(d);\n\n\t\tif (((ab * bc) >= 0.0) && ((bc * cd) >= 0.0))\n\t\t{\n\t\t\t*outPoint = hitPoint;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\ndouble MathUtils::distanceBetweenLineSegments(const Double3 &p0, const Double3 &p1,\n\tconst Double3 &q0, const Double3 &q1, double &s, double &t)\n{\n\tconst Double3 u = p1 - p0;\n\tconst Double3 v = q1 - q0;\n\n\t\/\/ These values are needed for the calculation of values s and t.\n\tconst Double3 p0q0 = p0 - q0;\n\tconst double a = u.dot(u);\n\tconst double b = u.dot(v);\n\tconst double c = v.dot(v);\n\tconst double d = u.dot(p0q0);\n\tconst double e = v.dot(p0q0);\n\n\tconst double be = b * e;\n\tconst double cd = c * d;\n\tconst double ac = a * c;\n\tconst double ae = a * e;\n\tconst double bd = b * d;\n\tconst double bb = b * b;\n\n\t\/\/ Calculate s and t. These are the points along u and v from p0 and q0 respectively that\n\t\/\/ are the closest to each other. The values are limited to the interval [0, 1] because\n\t\/\/ outside of that range is along the line that the segment exists on, but outside the bounds\n\t\/\/ of the segment.\n\ts = std::clamp((be - cd) \/ (ac - bb), 0.0, 1.0);\n\tt = std::clamp((ae - bd) \/ (ac - bb), 0.0, 1.0);\n\n\t\/\/ Calculate Psc and Qtc. These are the points on their respective segments that are closest\n\t\/\/ to each other.\n\tconst Double3 Psc = p0 + (u * s);\n\tconst Double3 Qtc = p0 + (v * t);\n\n\t\/\/ The distance between these two points is the shortest distance between the line segments.\n\treturn (Psc - Qtc).length();\n}\n\nstd::vector MathUtils::bresenhamLine(const Int2 &p1, const Int2 &p2)\n{\n\tconst int dx = std::abs(p2.x - p1.x);\n\tconst int dy = std::abs(p2.y - p1.y);\n\tconst int dirX = (p1.x < p2.x) ? 1 : -1;\n\tconst int dirY = (p1.y < p2.y) ? 1 : -1;\n\n\tint pointX = p1.x;\n\tint pointY = p1.y;\n\tint error = ((dx > dy) ? dx : -dy) \/ 2;\n\tconst int endX = p2.x;\n\tconst int endY = p2.y;\n\tstd::vector points;\n\n\twhile (true)\n\t{\n\t\tpoints.push_back(Int2(pointX, pointY));\n\n\t\tif ((pointX == endX) && (pointY == endY))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tconst int innerError = error;\n\n\t\tif (innerError > -dx)\n\t\t{\n\t\t\terror -= dy;\n\t\t\tpointX += dirX;\n\t\t}\n\n\t\tif (innerError < dy)\n\t\t{\n\t\t\terror += dx;\n\t\t\tpointY += dirY;\n\t\t}\n\t}\n\n\treturn points;\n}\n<|endoftext|>"} {"text":"better pid mappings<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: PrmMagnify.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n Copyright 2005 Sandia Corporation. Under the terms of Contract\n DE-AC04-94AL85000, there is a non-exclusive license for use of this work by\n or on behalf of the U.S. Government. Redistribution and use in source and\n binary forms, with or without modification, are permitted provided that this\n Notice and any statement of authorship are reproduced on all copies.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkActor.h\"\n#include \"vtkCellData.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkDummyController.h\"\n#include \"vtkIdFilter.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkParallelRenderManager.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSphereSource.h\"\n\n#include \"vtkSmartPointer.h\"\n\n#define VTK_CREATE(type, var) \\\n vtkSmartPointer var = vtkSmartPointer::New()\n\n\/\/-----------------------------------------------------------------------------\n\nclass vtkTestMagnifyRenderManager : public vtkParallelRenderManager\n{\npublic:\n vtkTypeRevisionMacro(vtkTestMagnifyRenderManager, vtkParallelRenderManager);\n static vtkTestMagnifyRenderManager *New();\n\nprotected:\n vtkTestMagnifyRenderManager() { }\n ~vtkTestMagnifyRenderManager() { }\n\n virtual void PreRenderProcessing();\n virtual void PostRenderProcessing();\n};\n\nvtkCxxRevisionMacro(vtkTestMagnifyRenderManager, \"1.1\");\nvtkStandardNewMacro(vtkTestMagnifyRenderManager);\n\nvoid vtkTestMagnifyRenderManager::PreRenderProcessing()\n{\n this->RenderWindow->SwapBuffersOff();\n}\n\nvoid vtkTestMagnifyRenderManager::PostRenderProcessing()\n{\n this->FullImage->SetNumberOfComponents(4);\n this->FullImage->SetNumberOfTuples(this->FullImageSize[0]*this->FullImageSize[1]);\n\n int fullImageViewport[4], reducedImageViewport[4];\n\n \/\/ Read in image as RGBA.\n this->UseRGBA = 1;\n this->ReadReducedImage();\n\n fullImageViewport[0] = 0; fullImageViewport[1] = 0;\n fullImageViewport[2] = this->FullImageSize[0]\/2;\n fullImageViewport[3] = this->FullImageSize[1]\/2;\n reducedImageViewport[0] = 0; reducedImageViewport[1] = 0;\n reducedImageViewport[2] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[3] = this->ReducedImageSize[1]\/2;\n this->MagnifyImageNearest(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n fullImageViewport[0] = this->FullImageSize[0]\/2;\n fullImageViewport[1] = 0;\n fullImageViewport[2] = this->FullImageSize[0];\n fullImageViewport[3] = this->FullImageSize[1]\/2;\n reducedImageViewport[0] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[1] = 0;\n reducedImageViewport[2] = this->ReducedImageSize[0];\n reducedImageViewport[3] = this->ReducedImageSize[1]\/2;\n this->MagnifyImageLinear(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n \/\/ Read in image as RGB.\n this->UseRGBA = 0;\n this->ReducedImageUpToDate = 0;\n this->ReadReducedImage();\n\n fullImageViewport[0] = 0;\n fullImageViewport[1] = this->FullImageSize[1]\/2;\n fullImageViewport[2] = this->FullImageSize[0]\/2;\n fullImageViewport[3] = this->FullImageSize[1];\n reducedImageViewport[0] = 0;\n reducedImageViewport[1] = this->ReducedImageSize[1]\/2;\n reducedImageViewport[2] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[3] = this->ReducedImageSize[1];\n this->MagnifyImageNearest(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n fullImageViewport[0] = this->FullImageSize[0]\/2;\n fullImageViewport[1] = this->FullImageSize[1]\/2;\n fullImageViewport[2] = this->FullImageSize[0];\n fullImageViewport[3] = this->FullImageSize[1];\n reducedImageViewport[0] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[1] = this->ReducedImageSize[1]\/2;\n reducedImageViewport[2] = this->ReducedImageSize[0];\n reducedImageViewport[3] = this->ReducedImageSize[1];\n this->MagnifyImageLinear(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n this->FullImageUpToDate = 1;\n\n this->WriteFullImage();\n\n this->RenderWindow->SwapBuffersOn();\n this->RenderWindow->Frame();\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n VTK_CREATE(vtkDummyController, controller);\n controller->Initialize(&argc, &argv);\n\n VTK_CREATE(vtkTestMagnifyRenderManager, prm);\n prm->SetController(controller);\n\n VTK_CREATE(vtkSphereSource, sphere);\n sphere->SetEndPhi(90.0);\n sphere->SetPhiResolution(4);\n\n VTK_CREATE(vtkIdFilter, colors);\n colors->SetInputConnection(sphere->GetOutputPort());\n colors->PointIdsOff();\n colors->CellIdsOn();\n colors->FieldDataOff();\n colors->Update();\n\n VTK_CREATE(vtkPolyDataMapper, mapper);\n mapper->SetInputConnection(colors->GetOutputPort());\n mapper->UseLookupTableScalarRangeOff();\n mapper->SetScalarRange(colors->GetOutput()->GetCellData()\n ->GetScalars()->GetRange());\n\n VTK_CREATE(vtkActor, actor);\n actor->SetMapper(mapper);\n\n vtkSmartPointer renderer = prm->MakeRenderer();\n renderer->Delete(); \/\/ Remove duplicate reference.\n renderer->AddActor(actor);\n\n vtkSmartPointer renwin = prm->MakeRenderWindow();\n renwin->Delete(); \/\/ Remove duplicate reference.\n renwin->SetSize(299, 299);\n renwin->AddRenderer(renderer);\n prm->SetRenderWindow(renwin);\n\n prm->ResetAllCameras();\n prm->SetImageReductionFactor(8);\n\n \/\/ Run the regression test.\n renwin->Render();\n int retVal = vtkRegressionTestImage(renwin);\n if (retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n VTK_CREATE(vtkRenderWindowInteractor, iren);\n iren->SetRenderWindow(renwin);\n renwin->Render();\n iren->Start();\n retVal = vtkRegressionTester::PASSED;\n }\n\n controller->Finalize();\n\n return !retVal;\n}\nCOMP: Fix warnings about default constructors\/copy operators.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: PrmMagnify.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n Copyright 2005 Sandia Corporation. Under the terms of Contract\n DE-AC04-94AL85000, there is a non-exclusive license for use of this work by\n or on behalf of the U.S. Government. Redistribution and use in source and\n binary forms, with or without modification, are permitted provided that this\n Notice and any statement of authorship are reproduced on all copies.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkActor.h\"\n#include \"vtkCellData.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkDummyController.h\"\n#include \"vtkIdFilter.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkParallelRenderManager.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSphereSource.h\"\n\n#include \"vtkSmartPointer.h\"\n\n#define VTK_CREATE(type, var) \\\n vtkSmartPointer var = vtkSmartPointer::New()\n\n\/\/-----------------------------------------------------------------------------\n\nclass vtkTestMagnifyRenderManager : public vtkParallelRenderManager\n{\npublic:\n vtkTypeRevisionMacro(vtkTestMagnifyRenderManager, vtkParallelRenderManager);\n static vtkTestMagnifyRenderManager *New();\n\nprotected:\n vtkTestMagnifyRenderManager() { }\n ~vtkTestMagnifyRenderManager() { }\n\n virtual void PreRenderProcessing();\n virtual void PostRenderProcessing();\n\nprivate:\n vtkTestMagnifyRenderManager(const vtkTestMagnifyRenderManager &); \/\/ Not implemented.\n void operator=(const vtkTestMagnifyRenderManager &); \/\/ Not implemented.\n};\n\nvtkCxxRevisionMacro(vtkTestMagnifyRenderManager, \"1.2\");\nvtkStandardNewMacro(vtkTestMagnifyRenderManager);\n\nvoid vtkTestMagnifyRenderManager::PreRenderProcessing()\n{\n this->RenderWindow->SwapBuffersOff();\n}\n\nvoid vtkTestMagnifyRenderManager::PostRenderProcessing()\n{\n this->FullImage->SetNumberOfComponents(4);\n this->FullImage->SetNumberOfTuples(this->FullImageSize[0]*this->FullImageSize[1]);\n\n int fullImageViewport[4], reducedImageViewport[4];\n\n \/\/ Read in image as RGBA.\n this->UseRGBA = 1;\n this->ReadReducedImage();\n\n fullImageViewport[0] = 0; fullImageViewport[1] = 0;\n fullImageViewport[2] = this->FullImageSize[0]\/2;\n fullImageViewport[3] = this->FullImageSize[1]\/2;\n reducedImageViewport[0] = 0; reducedImageViewport[1] = 0;\n reducedImageViewport[2] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[3] = this->ReducedImageSize[1]\/2;\n this->MagnifyImageNearest(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n fullImageViewport[0] = this->FullImageSize[0]\/2;\n fullImageViewport[1] = 0;\n fullImageViewport[2] = this->FullImageSize[0];\n fullImageViewport[3] = this->FullImageSize[1]\/2;\n reducedImageViewport[0] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[1] = 0;\n reducedImageViewport[2] = this->ReducedImageSize[0];\n reducedImageViewport[3] = this->ReducedImageSize[1]\/2;\n this->MagnifyImageLinear(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n \/\/ Read in image as RGB.\n this->UseRGBA = 0;\n this->ReducedImageUpToDate = 0;\n this->ReadReducedImage();\n\n fullImageViewport[0] = 0;\n fullImageViewport[1] = this->FullImageSize[1]\/2;\n fullImageViewport[2] = this->FullImageSize[0]\/2;\n fullImageViewport[3] = this->FullImageSize[1];\n reducedImageViewport[0] = 0;\n reducedImageViewport[1] = this->ReducedImageSize[1]\/2;\n reducedImageViewport[2] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[3] = this->ReducedImageSize[1];\n this->MagnifyImageNearest(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n fullImageViewport[0] = this->FullImageSize[0]\/2;\n fullImageViewport[1] = this->FullImageSize[1]\/2;\n fullImageViewport[2] = this->FullImageSize[0];\n fullImageViewport[3] = this->FullImageSize[1];\n reducedImageViewport[0] = this->ReducedImageSize[0]\/2;\n reducedImageViewport[1] = this->ReducedImageSize[1]\/2;\n reducedImageViewport[2] = this->ReducedImageSize[0];\n reducedImageViewport[3] = this->ReducedImageSize[1];\n this->MagnifyImageLinear(this->FullImage, this->FullImageSize,\n this->ReducedImage, this->ReducedImageSize,\n fullImageViewport, reducedImageViewport);\n\n this->FullImageUpToDate = 1;\n\n this->WriteFullImage();\n\n this->RenderWindow->SwapBuffersOn();\n this->RenderWindow->Frame();\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n VTK_CREATE(vtkDummyController, controller);\n controller->Initialize(&argc, &argv);\n\n VTK_CREATE(vtkTestMagnifyRenderManager, prm);\n prm->SetController(controller);\n\n VTK_CREATE(vtkSphereSource, sphere);\n sphere->SetEndPhi(90.0);\n sphere->SetPhiResolution(4);\n\n VTK_CREATE(vtkIdFilter, colors);\n colors->SetInputConnection(sphere->GetOutputPort());\n colors->PointIdsOff();\n colors->CellIdsOn();\n colors->FieldDataOff();\n colors->Update();\n\n VTK_CREATE(vtkPolyDataMapper, mapper);\n mapper->SetInputConnection(colors->GetOutputPort());\n mapper->UseLookupTableScalarRangeOff();\n mapper->SetScalarRange(colors->GetOutput()->GetCellData()\n ->GetScalars()->GetRange());\n\n VTK_CREATE(vtkActor, actor);\n actor->SetMapper(mapper);\n\n vtkSmartPointer renderer = prm->MakeRenderer();\n renderer->Delete(); \/\/ Remove duplicate reference.\n renderer->AddActor(actor);\n\n vtkSmartPointer renwin = prm->MakeRenderWindow();\n renwin->Delete(); \/\/ Remove duplicate reference.\n renwin->SetSize(299, 299);\n renwin->AddRenderer(renderer);\n prm->SetRenderWindow(renwin);\n\n prm->ResetAllCameras();\n prm->SetImageReductionFactor(8);\n\n \/\/ Run the regression test.\n renwin->Render();\n int retVal = vtkRegressionTestImage(renwin);\n if (retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n VTK_CREATE(vtkRenderWindowInteractor, iren);\n iren->SetRenderWindow(renwin);\n renwin->Render();\n iren->Start();\n retVal = vtkRegressionTester::PASSED;\n }\n\n controller->Finalize();\n\n return !retVal;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#include \"gslib.hpp\"\n\n#ifdef MFEM_USE_GSLIB\n\nnamespace mfem\n{\n\n#ifndef __GNUC__\n\n#include \"gslib.h\"\n\n#else \/\/ Ignore warnings from the gslib header (GCC version)\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#include \"gslib.h\"\n#pragma GCC diagnostic pop\n\n#endif \/\/ GCC\n\nFindPointsGSLib::FindPointsGSLib()\n : mesh(NULL), gsl_mesh(), fdata2D(NULL), fdata3D(NULL), dim(-1)\n{\n gsl_comm = new comm;\n#ifdef MFEM_USE_MPI\n MPI_Init(NULL, NULL);\n MPI_Comm comm = MPI_COMM_WORLD;;\n comm_init(gsl_comm, comm);\n#else\n comm_init(gsl_comm, 0);\n#endif\n}\n\nFindPointsGSLib::~FindPointsGSLib()\n{\n delete gsl_comm;\n}\n\n#ifdef MFEM_USE_MPI\nFindPointsGSLib::FindPointsGSLib(MPI_Comm _comm)\n : mesh(NULL), gsl_mesh(), fdata2D(NULL), fdata3D(NULL), dim(-1)\n{\n gsl_comm = new comm;\n comm_init(gsl_comm, _comm);\n}\n#endif\n\nvoid FindPointsGSLib::Setup(Mesh &m, double bb_t, double newt_tol, int npt_max)\n{\n MFEM_VERIFY(m.GetNodes() != NULL, \"Mesh nodes are required.\");\n\n mesh = &m;\n const GridFunction *nodes = mesh->GetNodes();\n const FiniteElementSpace *fes = nodes->FESpace();\n\n dim = mesh->Dimension();\n const int NE = mesh->GetNE(),\n dof_cnt = fes->GetFE(0)->GetDof(),\n pts_cnt = NE * dof_cnt;\n gsl_mesh.SetSize(dim * pts_cnt);\n\n const TensorBasisElement *tbe =\n dynamic_cast(fes->GetFE(0));\n const Array &dof_map = tbe->GetDofMap();\n\n DenseMatrix pos(dof_cnt, dim);\n Vector posV(pos.Data(), dof_cnt * dim);\n Array xdofs(dof_cnt * dim);\n\n int pt_id = 0;\n for (int i = 0; i < NE; i++)\n {\n fes->GetElementVDofs(i, xdofs);\n nodes->GetSubVector(xdofs, posV);\n for (int j = 0; j < dof_cnt; j++)\n {\n for (int d = 0; d < dim; d++)\n {\n gsl_mesh(pts_cnt * d + pt_id) = pos(dof_map[j], d);\n }\n pt_id++;\n }\n }\n\n const unsigned dof1D = fes->GetFE(0)->GetOrder() + 1;\n if (dim == 2)\n {\n unsigned nr[2] = {dof1D, dof1D};\n unsigned mr[2] = {2*dof1D, 2*dof1D};\n double * const elx[2] = { &gsl_mesh(0), &gsl_mesh(pts_cnt) };\n fdata2D = findpts_setup_2(gsl_comm, elx, nr, NE, mr, bb_t,\n pts_cnt, pts_cnt, npt_max, newt_tol);\n }\n else\n {\n unsigned nr[3] = {dof1D, dof1D, dof1D};\n unsigned mr[3] = {2*dof1D, 2*dof1D, 2*dof1D};\n double * const elx[3] =\n { &gsl_mesh(0), &gsl_mesh(pts_cnt), &gsl_mesh(2*pts_cnt) };\n fdata3D = findpts_setup_3(gsl_comm, elx, nr, NE, mr, bb_t,\n pts_cnt, pts_cnt, npt_max, newt_tol);\n }\n}\n\nvoid FindPointsGSLib::FindPoints(Vector &point_pos, Array &codes,\n Array &proc_ids, Array &elem_ids,\n Vector &ref_pos, Vector &dist)\n{\n const int points_cnt = point_pos.Size() \/ dim;\n if (dim == 2)\n {\n const double *xv_base[2];\n xv_base[0] = point_pos.GetData();\n xv_base[1] = point_pos.GetData() + points_cnt;\n unsigned xv_stride[2];\n xv_stride[0] = sizeof(double);\n xv_stride[1] = sizeof(double);\n findpts_2(codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n dist.GetData(), sizeof(double),\n xv_base, xv_stride, points_cnt, fdata2D);\n }\n else\n {\n const double *xv_base[3];\n xv_base[0] = point_pos.GetData();\n xv_base[1] = point_pos.GetData() + points_cnt;\n xv_base[2] = point_pos.GetData() + 2*points_cnt;\n unsigned xv_stride[3];\n xv_stride[0] = sizeof(double);\n xv_stride[1] = sizeof(double);\n xv_stride[2] = sizeof(double);\n findpts_3(codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n dist.GetData(), sizeof(double),\n xv_base, xv_stride, points_cnt, fdata3D);\n }\n}\n\nvoid FindPointsGSLib::Interpolate(Array &codes, Array &proc_ids,\n Array &elem_ids, Vector &ref_pos,\n const GridFunction &field_in,\n Vector &field_out)\n{\n Vector node_vals;\n GetNodeValues(field_in, node_vals);\n\n const int points_cnt = ref_pos.Size() \/ dim;\n if (dim==2)\n {\n findpts_eval_2(field_out.GetData(), sizeof(double),\n codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n points_cnt, node_vals.GetData(), fdata2D);\n }\n else\n {\n findpts_eval_3(field_out.GetData(), sizeof(double),\n codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n points_cnt, node_vals.GetData(), fdata3D);\n }\n}\n\nvoid FindPointsGSLib::FreeData()\n{\n (dim == 2) ? findpts_free_2(fdata2D) : findpts_free_3(fdata3D);\n}\n\nvoid FindPointsGSLib::GetNodeValues(const GridFunction &gf_in,\n Vector &node_vals)\n{\n MFEM_ASSERT(gf_in.FESpace()->GetVDim() == 1, \"Scalar function expected.\");\n\n const GridFunction *nodes = mesh->GetNodes();\n const FiniteElementSpace *fes = nodes->FESpace();\n const IntegrationRule &ir = fes->GetFE(0)->GetNodes();\n\n const int NE = mesh->GetNE(), dof_cnt = ir.GetNPoints();\n node_vals.SetSize(NE * dof_cnt);\n\n const TensorBasisElement *tbe =\n dynamic_cast(fes->GetFE(0));\n const Array &dof_map = tbe->GetDofMap();\n\n int pt_id = 0;\n Vector vals_el;\n for (int i = 0; i < NE; i++)\n {\n gf_in.GetValues(i, ir, vals_el);\n for (int j = 0; j < dof_cnt; j++)\n {\n node_vals(pt_id++) = vals_el(dof_map[j]);\n }\n }\n}\n\n} \/\/ namespace mfem\n\n#endif \/\/ MFEM_USE_GSLIB\nAdjusted the #pragma to ignore warnings from gslib.h.\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#include \"gslib.hpp\"\n\n#ifdef MFEM_USE_GSLIB\n\nnamespace mfem\n{\n\n#ifdef __GNUC__\n\/\/ Ignore warnings from the gslib header (GCC version)\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#endif \/\/ __GNUC__\n\n#include \"gslib.h\"\n\n\nFindPointsGSLib::FindPointsGSLib()\n : mesh(NULL), gsl_mesh(), fdata2D(NULL), fdata3D(NULL), dim(-1)\n{\n gsl_comm = new comm;\n#ifdef MFEM_USE_MPI\n MPI_Init(NULL, NULL);\n MPI_Comm comm = MPI_COMM_WORLD;;\n comm_init(gsl_comm, comm);\n#else\n comm_init(gsl_comm, 0);\n#endif\n}\n\nFindPointsGSLib::~FindPointsGSLib()\n{\n delete gsl_comm;\n}\n\n#ifdef MFEM_USE_MPI\nFindPointsGSLib::FindPointsGSLib(MPI_Comm _comm)\n : mesh(NULL), gsl_mesh(), fdata2D(NULL), fdata3D(NULL), dim(-1)\n{\n gsl_comm = new comm;\n comm_init(gsl_comm, _comm);\n}\n#endif\n\nvoid FindPointsGSLib::Setup(Mesh &m, double bb_t, double newt_tol, int npt_max)\n{\n MFEM_VERIFY(m.GetNodes() != NULL, \"Mesh nodes are required.\");\n\n mesh = &m;\n const GridFunction *nodes = mesh->GetNodes();\n const FiniteElementSpace *fes = nodes->FESpace();\n\n dim = mesh->Dimension();\n const int NE = mesh->GetNE(),\n dof_cnt = fes->GetFE(0)->GetDof(),\n pts_cnt = NE * dof_cnt;\n gsl_mesh.SetSize(dim * pts_cnt);\n\n const TensorBasisElement *tbe =\n dynamic_cast(fes->GetFE(0));\n const Array &dof_map = tbe->GetDofMap();\n\n DenseMatrix pos(dof_cnt, dim);\n Vector posV(pos.Data(), dof_cnt * dim);\n Array xdofs(dof_cnt * dim);\n\n int pt_id = 0;\n for (int i = 0; i < NE; i++)\n {\n fes->GetElementVDofs(i, xdofs);\n nodes->GetSubVector(xdofs, posV);\n for (int j = 0; j < dof_cnt; j++)\n {\n for (int d = 0; d < dim; d++)\n {\n gsl_mesh(pts_cnt * d + pt_id) = pos(dof_map[j], d);\n }\n pt_id++;\n }\n }\n\n const unsigned dof1D = fes->GetFE(0)->GetOrder() + 1;\n if (dim == 2)\n {\n unsigned nr[2] = {dof1D, dof1D};\n unsigned mr[2] = {2*dof1D, 2*dof1D};\n double * const elx[2] = { &gsl_mesh(0), &gsl_mesh(pts_cnt) };\n fdata2D = findpts_setup_2(gsl_comm, elx, nr, NE, mr, bb_t,\n pts_cnt, pts_cnt, npt_max, newt_tol);\n }\n else\n {\n unsigned nr[3] = {dof1D, dof1D, dof1D};\n unsigned mr[3] = {2*dof1D, 2*dof1D, 2*dof1D};\n double * const elx[3] =\n { &gsl_mesh(0), &gsl_mesh(pts_cnt), &gsl_mesh(2*pts_cnt) };\n fdata3D = findpts_setup_3(gsl_comm, elx, nr, NE, mr, bb_t,\n pts_cnt, pts_cnt, npt_max, newt_tol);\n }\n}\n\nvoid FindPointsGSLib::FindPoints(Vector &point_pos, Array &codes,\n Array &proc_ids, Array &elem_ids,\n Vector &ref_pos, Vector &dist)\n{\n const int points_cnt = point_pos.Size() \/ dim;\n if (dim == 2)\n {\n const double *xv_base[2];\n xv_base[0] = point_pos.GetData();\n xv_base[1] = point_pos.GetData() + points_cnt;\n unsigned xv_stride[2];\n xv_stride[0] = sizeof(double);\n xv_stride[1] = sizeof(double);\n findpts_2(codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n dist.GetData(), sizeof(double),\n xv_base, xv_stride, points_cnt, fdata2D);\n }\n else\n {\n const double *xv_base[3];\n xv_base[0] = point_pos.GetData();\n xv_base[1] = point_pos.GetData() + points_cnt;\n xv_base[2] = point_pos.GetData() + 2*points_cnt;\n unsigned xv_stride[3];\n xv_stride[0] = sizeof(double);\n xv_stride[1] = sizeof(double);\n xv_stride[2] = sizeof(double);\n findpts_3(codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n dist.GetData(), sizeof(double),\n xv_base, xv_stride, points_cnt, fdata3D);\n }\n}\n\nvoid FindPointsGSLib::Interpolate(Array &codes, Array &proc_ids,\n Array &elem_ids, Vector &ref_pos,\n const GridFunction &field_in,\n Vector &field_out)\n{\n Vector node_vals;\n GetNodeValues(field_in, node_vals);\n\n const int points_cnt = ref_pos.Size() \/ dim;\n if (dim==2)\n {\n findpts_eval_2(field_out.GetData(), sizeof(double),\n codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n points_cnt, node_vals.GetData(), fdata2D);\n }\n else\n {\n findpts_eval_3(field_out.GetData(), sizeof(double),\n codes.GetData(), sizeof(uint),\n proc_ids.GetData(), sizeof(uint),\n elem_ids.GetData(), sizeof(uint),\n ref_pos.GetData(), sizeof(double) * dim,\n points_cnt, node_vals.GetData(), fdata3D);\n }\n}\n\nvoid FindPointsGSLib::FreeData()\n{\n (dim == 2) ? findpts_free_2(fdata2D) : findpts_free_3(fdata3D);\n}\n\nvoid FindPointsGSLib::GetNodeValues(const GridFunction &gf_in,\n Vector &node_vals)\n{\n MFEM_ASSERT(gf_in.FESpace()->GetVDim() == 1, \"Scalar function expected.\");\n\n const GridFunction *nodes = mesh->GetNodes();\n const FiniteElementSpace *fes = nodes->FESpace();\n const IntegrationRule &ir = fes->GetFE(0)->GetNodes();\n\n const int NE = mesh->GetNE(), dof_cnt = ir.GetNPoints();\n node_vals.SetSize(NE * dof_cnt);\n\n const TensorBasisElement *tbe =\n dynamic_cast(fes->GetFE(0));\n const Array &dof_map = tbe->GetDofMap();\n\n int pt_id = 0;\n Vector vals_el;\n for (int i = 0; i < NE; i++)\n {\n gf_in.GetValues(i, ir, vals_el);\n for (int j = 0; j < dof_cnt; j++)\n {\n node_vals(pt_id++) = vals_el(dof_map[j]);\n }\n }\n}\n\n} \/\/ namespace mfem\n\n#endif \/\/ MFEM_USE_GSLIB\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace odesolver\n{\n\nusing namespace core::componentmodel::behavior;\nusing namespace sofa::defaulttype;\n\nvoid RungeKutta4Solver::solve(double dt)\n{\n \/\/std::cout << \"RK4 Init\\n\";\n \/\/objectmodel::BaseContext* group = getContext();\n OdeSolver* group = this;\n MultiVector pos(group, VecId::position());\n MultiVector vel(group, VecId::velocity());\n MultiVector k1a(group, VecId::V_DERIV);\n MultiVector k2a(group, VecId::V_DERIV);\n MultiVector k3a(group, VecId::V_DERIV);\n MultiVector k4a(group, VecId::V_DERIV);\n MultiVector k1v(group, VecId::V_DERIV);\n MultiVector k2v(group, VecId::V_DERIV);\n MultiVector k3v(group, VecId::V_DERIV);\n MultiVector k4v(group, VecId::V_DERIV);\n MultiVector newX(group, VecId::V_COORD);\n MultiVector newV(group, VecId::V_DERIV);\n\n double stepBy2 = double(dt \/ 2.0);\n double stepBy3 = double(dt \/ 3.0);\n double stepBy6 = double(dt \/ 6.0);\n\n double startTime = group->getTime();\n\n \/\/First step\n \/\/std::cout << \"RK4 Step 1\\n\";\n k1v = vel;\n group->computeAcc (startTime, k1a, pos, vel);\n\n \/\/Step 2\n \/\/std::cout << \"RK4 Step 2\\n\";\n newX = pos;\n newV = vel;\n\n newX.peq(k1v, stepBy2);\n newV.peq(k1a, stepBy2);\n\n k2v = newV;\n group->computeAcc ( startTime+stepBy2, k2a, newX, newV);\n\n \/\/ step 3\n \/\/std::cout << \"RK4 Step 3\\n\";\n newX = pos;\n newV = vel;\n\n newX.peq(k2v, stepBy2);\n newV.peq(k2a, stepBy2);\n\n k3v = newV;\n group->computeAcc ( startTime+stepBy2, k3a, newX, newV);\n\n \/\/ step 4\n \/\/std::cout << \"RK4 Step 4\\n\";\n newX = pos;\n newV = vel;\n newX.peq(k3v, dt);\n newV.peq(k3a, dt);\n\n k4v = newV;\n group->computeAcc( startTime+dt, k4a, newX, newV);\n\n \/\/std::cout << \"RK4 Final\\n\";\n pos.peq(k1v,stepBy6);\n vel.peq(k1a,stepBy6);\n pos.peq(k2v,stepBy3);\n vel.peq(k2a,stepBy3);\n pos.peq(k3v,stepBy3);\n vel.peq(k3a,stepBy3);\n pos.peq(k4v,stepBy6);\n vel.peq(k4a,stepBy6);\n}\n\nint RungeKutta4SolverClass = core::RegisterObject(\"A popular explicit time integrator\")\n .add< RungeKutta4Solver >();\n\nSOFA_DECL_CLASS(RungeKutta4)\n\n\n} \/\/ namespace odesolver\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\nr875\/sofa-dev : FIX RungeKutta4 registration (port of r852 from 1.0 branch)#include \n#include \n#include \n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace odesolver\n{\n\nusing namespace core::componentmodel::behavior;\nusing namespace sofa::defaulttype;\n\nvoid RungeKutta4Solver::solve(double dt)\n{\n \/\/std::cout << \"RK4 Init\\n\";\n \/\/objectmodel::BaseContext* group = getContext();\n OdeSolver* group = this;\n MultiVector pos(group, VecId::position());\n MultiVector vel(group, VecId::velocity());\n MultiVector k1a(group, VecId::V_DERIV);\n MultiVector k2a(group, VecId::V_DERIV);\n MultiVector k3a(group, VecId::V_DERIV);\n MultiVector k4a(group, VecId::V_DERIV);\n MultiVector k1v(group, VecId::V_DERIV);\n MultiVector k2v(group, VecId::V_DERIV);\n MultiVector k3v(group, VecId::V_DERIV);\n MultiVector k4v(group, VecId::V_DERIV);\n MultiVector newX(group, VecId::V_COORD);\n MultiVector newV(group, VecId::V_DERIV);\n\n double stepBy2 = double(dt \/ 2.0);\n double stepBy3 = double(dt \/ 3.0);\n double stepBy6 = double(dt \/ 6.0);\n\n double startTime = group->getTime();\n\n \/\/First step\n \/\/std::cout << \"RK4 Step 1\\n\";\n k1v = vel;\n group->computeAcc (startTime, k1a, pos, vel);\n\n \/\/Step 2\n \/\/std::cout << \"RK4 Step 2\\n\";\n newX = pos;\n newV = vel;\n\n newX.peq(k1v, stepBy2);\n newV.peq(k1a, stepBy2);\n\n k2v = newV;\n group->computeAcc ( startTime+stepBy2, k2a, newX, newV);\n\n \/\/ step 3\n \/\/std::cout << \"RK4 Step 3\\n\";\n newX = pos;\n newV = vel;\n\n newX.peq(k2v, stepBy2);\n newV.peq(k2a, stepBy2);\n\n k3v = newV;\n group->computeAcc ( startTime+stepBy2, k3a, newX, newV);\n\n \/\/ step 4\n \/\/std::cout << \"RK4 Step 4\\n\";\n newX = pos;\n newV = vel;\n newX.peq(k3v, dt);\n newV.peq(k3a, dt);\n\n k4v = newV;\n group->computeAcc( startTime+dt, k4a, newX, newV);\n\n \/\/std::cout << \"RK4 Final\\n\";\n pos.peq(k1v,stepBy6);\n vel.peq(k1a,stepBy6);\n pos.peq(k2v,stepBy3);\n vel.peq(k2a,stepBy3);\n pos.peq(k3v,stepBy3);\n vel.peq(k3a,stepBy3);\n pos.peq(k4v,stepBy6);\n vel.peq(k4a,stepBy6);\n}\n\nint RungeKutta4SolverClass = core::RegisterObject(\"A popular explicit time integrator\")\n .add< RungeKutta4Solver >()\n .addAlias(\"RungeKutta4\")\n ;\n\nSOFA_DECL_CLASS(RungeKutta4)\n\n\n} \/\/ namespace odesolver\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<|endoftext|>"} {"text":"\/*\n * LocalDegreeGTest.cpp\n *\n * Created on: 26.07.2014\n * Author: Gerd Lindner\n *\/\n\n#ifndef NOGTEST\n\n#include \"LocalDegreeGTest.h\"\n#include \"..\/LocalDegreeScore.h\"\n#include \n\nnamespace NetworKit {\n\nTEST_F(LocalDegreeGTest, testAttributeSimple) {\n\tGraph g(22);\n\tg.addEdge(0, 1);\n\tg.addEdge(0, 2);\n\tg.addEdge(2, 3);\n\tg.addEdge(3, 4);\n\tg.addEdge(2, 4);\n\tg.addEdge(2, 5);\n\tg.addEdge(2, 6);\n\tg.addEdge(2, 7);\n\tg.addEdge(4, 7);\n\tg.addEdge(5, 8);\n\tg.addEdge(5, 9);\n\tg.addEdge(5, 10);\n\tg.addEdge(5, 11);\n\tg.addEdge(5, 12);\n\tg.addEdge(6, 13);\n\tg.addEdge(6, 14);\n\tg.addEdge(6, 15);\n\tg.addEdge(6, 16);\n\tg.addEdge(7, 17);\n\tg.addEdge(7, 18);\n\tg.addEdge(7, 19);\n\tg.addEdge(3, 20);\n\tg.addEdge(3, 21);\n\tg.indexEdges();\n\n\tLocalDegreeScore localDegree(g);\n\tstd::vector scores = localDegree.scores();\n\n\tEXPECT_DOUBLE_EQ(LocalDegreeGTest::getScore(g, 0, 1, 1, 2), scores[g.edgeId(0, 1)]);\n\tEXPECT_DOUBLE_EQ(LocalDegreeGTest::getScore(g, 2, 4, 1, 4), scores[g.edgeId(2, 4)]);\n\tEXPECT_DOUBLE_EQ(LocalDegreeGTest::getScore(g, 4, 7, 2, 2), scores[g.edgeId(4, 7)]);\n}\n\n\/***\nCalculates the LD score for an edge.\n@param g the graph\n@param x first node\n@param y second node\n@param rankX rank of y in the neighborhood of y (1-based)\n@param rankY rank of y in the neighborhood of x (1-based)\n**\/\ndouble LocalDegreeGTest::getScore(const Graph& g, node x, node y, count rankX, count rankY) {\n\t\/\/Special case: degree one\n\tif (g.degree(x) == 1 || g.degree(y) == 1)\n\t\treturn 1;\n\n\t\/\/Use only the edge that leads to the higher-degree-node!\n\tif (g.degree(x) > g.degree(y))\n\t\treturn 1 - log(rankX) \/ log(g.degree(y));\n\n\tif (g.degree(x) < g.degree(y))\n\t\treturn 1 - log(rankY) \/ log(g.degree(x));\n\n\treturn -1;\n}\n\n}\n\/* namespace NetworKit *\/\n\n#endif \/*NOGTEST *\/\nMissing run call added\/*\n * LocalDegreeGTest.cpp\n *\n * Created on: 26.07.2014\n * Author: Gerd Lindner\n *\/\n\n#ifndef NOGTEST\n\n#include \"LocalDegreeGTest.h\"\n#include \"..\/LocalDegreeScore.h\"\n#include \n\nnamespace NetworKit {\n\nTEST_F(LocalDegreeGTest, testAttributeSimple) {\n\tGraph g(22);\n\tg.addEdge(0, 1);\n\tg.addEdge(0, 2);\n\tg.addEdge(2, 3);\n\tg.addEdge(3, 4);\n\tg.addEdge(2, 4);\n\tg.addEdge(2, 5);\n\tg.addEdge(2, 6);\n\tg.addEdge(2, 7);\n\tg.addEdge(4, 7);\n\tg.addEdge(5, 8);\n\tg.addEdge(5, 9);\n\tg.addEdge(5, 10);\n\tg.addEdge(5, 11);\n\tg.addEdge(5, 12);\n\tg.addEdge(6, 13);\n\tg.addEdge(6, 14);\n\tg.addEdge(6, 15);\n\tg.addEdge(6, 16);\n\tg.addEdge(7, 17);\n\tg.addEdge(7, 18);\n\tg.addEdge(7, 19);\n\tg.addEdge(3, 20);\n\tg.addEdge(3, 21);\n\tg.indexEdges();\n\n\tLocalDegreeScore localDegree(g);\n\tlocalDegree.run();\n\tstd::vector scores = localDegree.scores();\n\n\tEXPECT_DOUBLE_EQ(LocalDegreeGTest::getScore(g, 0, 1, 1, 2), scores[g.edgeId(0, 1)]);\n\tEXPECT_DOUBLE_EQ(LocalDegreeGTest::getScore(g, 2, 4, 1, 4), scores[g.edgeId(2, 4)]);\n\tEXPECT_DOUBLE_EQ(LocalDegreeGTest::getScore(g, 4, 7, 2, 2), scores[g.edgeId(4, 7)]);\n}\n\n\/***\nCalculates the LD score for an edge.\n@param g the graph\n@param x first node\n@param y second node\n@param rankX rank of y in the neighborhood of y (1-based)\n@param rankY rank of y in the neighborhood of x (1-based)\n**\/\ndouble LocalDegreeGTest::getScore(const Graph& g, node x, node y, count rankX, count rankY) {\n\t\/\/Special case: degree one\n\tif (g.degree(x) == 1 || g.degree(y) == 1)\n\t\treturn 1;\n\n\t\/\/Use only the edge that leads to the higher-degree-node!\n\tif (g.degree(x) > g.degree(y))\n\t\treturn 1 - log(rankX) \/ log(g.degree(y));\n\n\tif (g.degree(x) < g.degree(y))\n\t\treturn 1 - log(rankY) \/ log(g.degree(x));\n\n\treturn -1;\n}\n\n}\n\/* namespace NetworKit *\/\n\n#endif \/*NOGTEST *\/\n<|endoftext|>"} {"text":"\/*\n * Skaffari - a mail account administration web interface based on Cutelyst\n * Copyright (C) 2017-2018 Matthias Fehring \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"myaccount.h\"\n#include \"objects\/adminaccount.h\"\n#include \"objects\/skaffarierror.h\"\n#include \"utils\/language.h\"\n#include \"utils\/skaffariconfig.h\"\n#include \"objects\/helpentry.h\"\n\n#include \/\/ includes the main validator\n#include \/\/ includes the validator result\n#include \n#include \n#include \n#ifdef CUTELYST_VALIDATOR_WITH_PWQUALITY\n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n\nMyAccount::MyAccount(QObject *parent) : Controller(parent)\n{\n\n}\n\nMyAccount::~MyAccount()\n{\n\n}\n\nvoid MyAccount::index(Context *c)\n{\n AuthenticationUser user = Authentication::user(c);\n SkaffariError e(c);\n AdminAccount aac = AdminAccount::get(c, e, user.id().value());\n if (aac.isValid()) {\n\n static const QStringList tzIds = ([]() -> QStringList {\n QStringList lst;\n const QList availableTzIds = QTimeZone::availableTimeZoneIds();\n lst.reserve(availableTzIds.size());\n for (const QByteArray &tz : availableTzIds) {\n lst << QString::fromLatin1(tz);\n }\n return lst;\n }());\n\n auto req = c->req();\n if (req->isPost()) {\n c->setStash(QStringLiteral(\"userName\"), aac.username());\n\n static Validator v({\n new ValidatorConfirmed(QStringLiteral(\"password\")),\n #ifdef CUTELYST_VALIDATOR_WITH_PWQUALITY\n new ValidatorPwQuality(QStringLiteral(\"password\"), SkaffariConfig::admPwThreshold(), SkaffariConfig::admPwSettingsFile(), QStringLiteral(\"userName\"), QStringLiteral(\"oldpassword\")),\n #else\n new ValidatorMin(QStringLiteral(\"password\"), QMetaType::QString, SkaffariConfig::admPwMinlength()),\n #endif\n new ValidatorBetween(QStringLiteral(\"maxdisplay\"), QMetaType::UChar, 15, 255),\n new ValidatorBetween(QStringLiteral(\"warnlevel\"), QMetaType::UChar, 0, 100),\n new ValidatorIn(QStringLiteral(\"lang\"), Language::supportedLangsList()),\n new ValidatorIn(QStringLiteral(\"tz\"), tzIds)\n });\n\n ValidatorResult vr = v.validate(c, Validator::FillStashOnError|Validator::BodyParamsOnly);\n if (vr) {\n vr.addValue(QStringLiteral(\"oldpassword\"), req->bodyParam(QStringLiteral(\"oldpassword\")));\n SkaffariError e(c);\n if (aac.updateOwn(c, e, vr.values())) {\n \/\/ TODO: this is a bit hacky unless cutelyst does not support updating the authenticated user, currently the check for an old password will\n \/\/ fail after changing the password as the previous password is still in the session\n if (vr.value(QStringLiteral(\"password\")).toString().isEmpty()) {\n c->setStash(QStringLiteral(\"status_msg\"), c->translate(\"MyAccount\", \"Your account has been updated.\"));\n } else {\n c->setStash(QStringLiteral(\"status_msg\"), c->translate(\"MyAccount\", \"Your account and password have been updated. Please logout and use your new password to login again.\"));\n }\n } else {\n c->setStash(QStringLiteral(\"error_msg\"), e.errorText());\n }\n }\n }\n\n HelpHash help;\n help.reserve(8);\n help.insert(QStringLiteral(\"created\"), HelpEntry(c->translate(\"MyAccount\", \"Created\"), c->translate(\"MyAccount\", \"Date and time your account was created.\")));\n help.insert(QStringLiteral(\"updated\"), HelpEntry(c->translate(\"MyAccount\", \"Updated\"), c->translate(\"MyAccount\", \"Date and time your account was last updated.\")));\n help.insert(QStringLiteral(\"oldpassword\"), HelpEntry(c->translate(\"MyAccount\", \"Current password\"), c->translate(\"MyAccount\", \"Please enter your current password if you want to change your password.\")));\n help.insert(QStringLiteral(\"password\"), HelpEntry(c->translate(\"MyAccount\", \"New password\"), c->translate(\"MyAccount\", \"Enter a new password with a minimum length of %n character(s) or leave the field blank to avoid changing the password.\", \"\", SkaffariConfig::accPwMinlength())));\n help.insert(QStringLiteral(\"password_confirmation\"), HelpEntry(c->translate(\"MyAccount\", \"Confirm new password\"), c->translate(\"MyAccount\", \"Confirm your new password by entering it again.\")));\n help.insert(QStringLiteral(\"maxdisplay\"), HelpEntry(c->translate(\"MyAccount\", \"Max display\"), c->translate(\"MyAccount\", \"Set the number of results you want to load in paginated lists like the account list (minimum 15, maximum 255)\")));\n help.insert(QStringLiteral(\"warnlevel\"), HelpEntry(c->translate(\"MyAccount\", \"Warn level\"), c->translate(\"MyAccount\", \"Set the percentage limit that will show warnings on number of accounts and quota usage.\")));\n help.insert(QStringLiteral(\"lang\"), HelpEntry(c->translate(\"MyAccount\", \"Language\"), c->translate(\"MyAccount\", \"Select one of the supported languages.\")));\n help.insert(QStringLiteral(\"tz\"), HelpEntry(c->translate(\"MyAccount\", \"Time zone\"), c->translate(\"MyAccount\", \"Select your time zone to enter and display date and time values appropriately.\")));\n\n c->stash({\n {QStringLiteral(\"template\"), QStringLiteral(\"myaccount\/index.html\")},\n {QStringLiteral(\"site_title\"), c->translate(\"MyAccount\", \"My account\")},\n {QStringLiteral(\"adminaccount\"), QVariant::fromValue(aac)},\n {QStringLiteral(\"langs\"), QVariant::fromValue>(Language::supportedLangs(c))},\n {QStringLiteral(\"timezones\"), QVariant::fromValue(tzIds)},\n {QStringLiteral(\"help\"), QVariant::fromValue(help)}\n });\n\n } else {\n c->setStash(QStringLiteral(\"not_found_text\"), c->translate(\"MyAccount\", \"There is no administrator account with database ID %1.\").arg(user.id().toString()));\n c->setStash(QStringLiteral(\"template\"), QStringLiteral(\"404.html\"));\n c->res()->setStatus(404);\n }\n}\n\n#include \"moc_myaccount.cpp\"\nSmall cleanups\/*\n * Skaffari - a mail account administration web interface based on Cutelyst\n * Copyright (C) 2017-2018 Matthias Fehring \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"myaccount.h\"\n#include \"objects\/adminaccount.h\"\n#include \"objects\/skaffarierror.h\"\n#include \"utils\/language.h\"\n#include \"utils\/skaffariconfig.h\"\n#include \"objects\/helpentry.h\"\n\n#include \/\/ includes the main validator\n#include \/\/ includes the validator result\n#include \n#include \n#include \n#ifdef CUTELYST_VALIDATOR_WITH_PWQUALITY\n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n\nMyAccount::MyAccount(QObject *parent) : Controller(parent)\n{\n\n}\n\nMyAccount::~MyAccount()\n{\n\n}\n\nvoid MyAccount::index(Context *c)\n{\n AuthenticationUser user = Authentication::user(c);\n SkaffariError e(c);\n AdminAccount aac = AdminAccount::get(c, e, user.id().value());\n if (aac.isValid()) {\n\n static const QStringList tzIds = ([]() -> QStringList {\n QStringList lst;\n const QList availableTzIds = QTimeZone::availableTimeZoneIds();\n lst.reserve(availableTzIds.size());\n for (const QByteArray &tz : availableTzIds) {\n lst << QString::fromLatin1(tz);\n }\n return lst;\n }());\n\n auto req = c->req();\n if (req->isPost()) {\n static Validator v({\n new ValidatorConfirmed(QStringLiteral(\"password\")),\n #ifdef CUTELYST_VALIDATOR_WITH_PWQUALITY\n new ValidatorPwQuality(QStringLiteral(\"password\"), SkaffariConfig::admPwThreshold(), SkaffariConfig::admPwSettingsFile(), QStringLiteral(\"userName\"), QStringLiteral(\"oldpassword\")),\n #else\n new ValidatorMin(QStringLiteral(\"password\"), QMetaType::QString, SkaffariConfig::admPwMinlength()),\n #endif\n new ValidatorBetween(QStringLiteral(\"maxdisplay\"), QMetaType::UChar, 15, 255),\n new ValidatorBetween(QStringLiteral(\"warnlevel\"), QMetaType::UChar, 0, 100),\n new ValidatorIn(QStringLiteral(\"lang\"), Language::supportedLangsList()),\n new ValidatorIn(QStringLiteral(\"tz\"), tzIds)\n });\n\n ValidatorResult vr = v.validate(c, Validator::FillStashOnError|Validator::BodyParamsOnly);\n if (vr) {\n vr.addValue(QStringLiteral(\"oldpassword\"), req->bodyParam(QStringLiteral(\"oldpassword\")));\n SkaffariError e(c);\n if (aac.updateOwn(c, e, vr.values())) {\n \/\/ TODO: this is a bit hacky unless cutelyst does not support updating the authenticated user, currently the check for an old password will\n \/\/ fail after changing the password as the previous password is still in the session\n if (vr.value(QStringLiteral(\"password\")).toString().isEmpty()) {\n c->setStash(QStringLiteral(\"status_msg\"), c->translate(\"MyAccount\", \"Your account has been updated.\"));\n } else {\n c->setStash(QStringLiteral(\"status_msg\"), c->translate(\"MyAccount\", \"Your account and password have been updated. Please logout and use your new password to login again.\"));\n }\n } else {\n c->setStash(QStringLiteral(\"error_msg\"), e.errorText());\n }\n }\n }\n\n HelpHash help;\n help.reserve(8);\n help.insert(QStringLiteral(\"created\"), HelpEntry(c->translate(\"MyAccount\", \"Created\"), c->translate(\"MyAccount\", \"Date and time your account was created.\")));\n help.insert(QStringLiteral(\"updated\"), HelpEntry(c->translate(\"MyAccount\", \"Updated\"), c->translate(\"MyAccount\", \"Date and time your account was last updated.\")));\n help.insert(QStringLiteral(\"oldpassword\"), HelpEntry(c->translate(\"MyAccount\", \"Current password\"), c->translate(\"MyAccount\", \"Please enter your current password if you want to change your password.\")));\n help.insert(QStringLiteral(\"password\"), HelpEntry(c->translate(\"MyAccount\", \"New password\"), c->translate(\"MyAccount\", \"Enter a new password with a minimum length of %n character(s) or leave the field blank to avoid changing the password.\", \"\", SkaffariConfig::accPwMinlength())));\n help.insert(QStringLiteral(\"password_confirmation\"), HelpEntry(c->translate(\"MyAccount\", \"Confirm new password\"), c->translate(\"MyAccount\", \"Confirm your new password by entering it again.\")));\n help.insert(QStringLiteral(\"maxdisplay\"), HelpEntry(c->translate(\"MyAccount\", \"Max display\"), c->translate(\"MyAccount\", \"Set the number of results you want to load in paginated lists like the account list (minimum 15, maximum 255)\")));\n help.insert(QStringLiteral(\"warnlevel\"), HelpEntry(c->translate(\"MyAccount\", \"Warn level\"), c->translate(\"MyAccount\", \"Set the percentage limit that will show warnings on number of accounts and quota usage.\")));\n help.insert(QStringLiteral(\"lang\"), HelpEntry(c->translate(\"MyAccount\", \"Language\"), c->translate(\"MyAccount\", \"Select one of the supported languages.\")));\n help.insert(QStringLiteral(\"tz\"), HelpEntry(c->translate(\"MyAccount\", \"Time zone\"), c->translate(\"MyAccount\", \"Select your time zone to enter and display date and time values appropriately.\")));\n\n c->stash({\n {QStringLiteral(\"template\"), QStringLiteral(\"myaccount\/index.html\")},\n {QStringLiteral(\"site_title\"), c->translate(\"MyAccount\", \"My account\")},\n {QStringLiteral(\"adminaccount\"), QVariant::fromValue(aac)},\n {QStringLiteral(\"langs\"), QVariant::fromValue>(Language::supportedLangs(c))},\n {QStringLiteral(\"timezones\"), QVariant::fromValue(tzIds)},\n {QStringLiteral(\"help\"), QVariant::fromValue(help)}\n });\n\n } else {\n c->setStash(QStringLiteral(\"not_found_text\"), c->translate(\"MyAccount\", \"There is no administrator account with database ID %1.\").arg(user.id().toString()));\n c->setStash(QStringLiteral(\"template\"), QStringLiteral(\"404.html\"));\n c->res()->setStatus(404);\n }\n}\n\n#include \"moc_myaccount.cpp\"\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 Jon Taylor\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"functions\/functions.h\"\n#include \n\n\/*\n {\"record\":{\"time\":\"1497069518\",\"name:\":\"\",\"typ\":\"0\",\"amt\":0,\"fee\":0,\"sndkey\":\"026321261876CFB360F94A7FDF3F2D4F6F9FC0CEDADF15AC3D30E182A82AF5D81E\",\"rcvkey\":\"\",\"sig\":\"DF9721B14253E380F9E6EF00A5DBF1DB74751BF7F7EBBF104E04FE462CBA27255144B900251E061ED16CAC9B572088B446B42B448E0A6A64D92E697FC5142960\"}}\n\n{\"block\":{\"number\":1\",\"time\":\"\",\"hash\":\"\",\"records\":{\n{\"record\":{\"time\":\"1497071981\",\"name:\":\"\",\"typ\":\"1\",\"amt\":1,\"fee\":-1.0367648569192718e-155,\"sndkey\":\"\",\"rcvkey\":\"026321261876CFB360F94A7FDF3F2D4F6F9FC0CEDADF15AC3D30E182A82AF5D81E\",\"sig\":\"A1BBB5C4B1FD3081EBE276627DE088B76B4932650CF6A3EA9D31EFE5B03F106AD5D8C32A38537F9D09B72220D4FF54106F30BF17C8068995AF221D1FAB5EE183\"}}\n}}}\n\n*\/\n\n\/**\n* tokenClose\n*\n* Description: Find closing token for a structure in a string.\n*\/\nint CFunctions::tokenClose(std::string content, std::string open, std::string close, int start){\n\tstd::size_t start_i = content.find(open);\n std::size_t end_i = content.find(close);\n if (start_i!=std::string::npos && end_i!=std::string::npos){\n std::string section = content.substr (start_i + 1, end_i - start_i -1);\n\n\t}\t\n\n\treturn 0;\n}\n\n\/**\n* recordJSON \n*\n*\n*\/\nstd::string CFunctions::recordJSON(record_structure record){\n\tstd::string json = \"{\\\"record\\\":{\\\"time\\\":\\\"\" + record.time + \"\\\",\" +\n \"\\\"name:\\\":\\\"\" + record.name + \"\\\",\" +\n \"\\\"typ\\\":\\\"\" + boost::lexical_cast(record.transaction_type) + \"\\\",\" +\n \"\\\"amt\\\":\" + boost::lexical_cast(record.amount) + \",\" +\n \"\\\"fee\\\":\" + boost::lexical_cast(record.fee) + \",\" +\n \"\\\"sndkey\\\":\\\"\" + record.sender_public_key + \"\\\",\" +\n \"\\\"rcvkey\\\":\\\"\" + record.recipient_public_key + \"\\\",\" +\n \"\\\"sig\\\":\\\"\" + record.message_signature + \"\\\"\" +\n \"}}\\n\";\n\treturn json;\n}\n\n\/**\n * addToQueue\n *\n * Description: Add queue record to file. Data access object function.\n * @param time:\n * @param transaction_type: [add_user, issue_currency, transfer] designates action of this record.\n * @param amount: double amount of currency to be sent.\n * @param\n *\/\nint CFunctions::addToQueue(record_structure record){\n std::ofstream outfile;\n outfile.open(\"queue.dat\", std::ios_base::app);\n outfile << recordJSON(record);\n outfile.close();\n return 1;\n}\n\n\n\/**\n* parseRecordJson\n*\n* Description: \n*\/\nCFunctions::record_structure parseRecordJson(std::string json){\n\tCFunctions::record_structure record;\n\n\tstd::size_t start = json.find(\"time\\\":\\\"\");\n std::size_t end = json.find(\"]\");\n if (start!=std::string::npos && end!=std::string::npos){\n std::string time = json.substr (start + 1, end-start -1);\n record.time = time;\n std::cout << \" Time: \" << time << \" \" << std::endl;\n\n start = json.find(\"[\", end);\n end = json.find(\"]\", end + 1);\n std::string type = json.substr (start + 1, end-start - 1);\n std::cout << \" type: \" << type << \" \" << std::endl;\n\n\n }\n\n\treturn record;\n}\n\n\/**\n * parseQueueRecords\n *\n * Description: Read queued records from file into a vector of structures.\n * @return vector or record_structures\n *\/\nstd::vector CFunctions::parseQueueRecords(){\n std::vector records;\n std::ifstream infile(\"queue.dat\");\n std::string line;\n while (std::getline(infile, line))\n {\n std::istringstream iss(line);\n CFunctions::record_structure record;\n \n \n std::size_t start = line.find(\"[\");\n std::size_t end = line.find(\"]\");\n if (start!=std::string::npos && end!=std::string::npos){\n std::string time = line.substr (start + 1, end-start -1);\n record.time = time;\n std::cout << \" Time: \" << time << \" \" << std::endl;\n \n start = line.find(\"[\", end);\n end = line.find(\"]\", end + 1);\n std::string type = line.substr (start + 1, end-start - 1);\n std::cout << \" type: \" << type << \" \" << std::endl;\n\n \n }\n \n \/\/int a, b;\n \/\/if (!(iss >> a >> b)) { break; } \/\/ error\n \n std::cout << \" Line: \" << line << \" \" << std::endl;\n \/\/ process pair (a,b)\n \n \n \/\/record.time = \"2017\/06\/02\";\n \n \n records.push_back (record);\n \n \n }\n \n \n return records;\n}\n\nint CFunctions::existsInQueue(record_structure record){\n \n \n \n return 0;\n}\n\n\nint CFunctions::getRecordsInQueue( int limit ){\n \n \n}\n\n\n\/**\n * validateRecord\n *\n * Description: validate record is formatted, the hashes match and balances are sufficient.\n *\/\nint CFunctions::validateRecord(record_structure record){\n \/\/\n \/\/ Read block\n \n return 0;\n}\n\n\/**\n *\n *\n *\/\nint CFunctions::generateBlock(std::vector records, std::string time ){\n \n}\n\n\nint CFunctions::addToBlockFile( CFunctions::block_structure block ){\n \n time_t t = time(0); \/\/ get time now\n struct tm * now = localtime( & t );\n int year = (now->tm_year + 1900);\n \n std::stringstream ss;\n ss << \"block_\" << year << \".dat\";\n std::string file_path = ss.str();\n \n std::ofstream outfile;\n outfile.open(file_path, std::ios_base::app);\n outfile << \"{\\\"block\\\":{\" <<\n\t\"\\\"number\\\":\" << block.number << \"\\\",\" <<\n\t\"\\\"time\\\":\\\"\" << block.time << \"\\\",\" << \n\t\"\\\"hash\\\":\\\"\" << block.block_hash << \"\\\",\" <<\n\t\/\/\"[\" << block.transaction_type << \"]\" << \n\t\"\\\"records\\\":{\\n\";\n\n \/\/ Loop though block records\n for(int i = 0; i < block.records.size(); i++ ){\n\tCFunctions::record_structure record = block.records.at(i);\n\toutfile << recordJSON(record);\n }\n\n outfile << \"}}}\\n\";\n\n outfile.close();\n \n return 0;\n}\n\nint CFunctions::parseBlockFile(){\n time_t t = time(0); \/\/ get time now\n struct tm * now = localtime( & t );\n int year = (now->tm_year + 1900);\n\n std::stringstream ss;\n ss << \"block_\" << year << \".dat\";\n std::string file_path = ss.str();\n\n \/\/CFunctions::block_structure block;\n\n std::vector records;\n std::ifstream infile(file_path);\n std::string line;\n while (std::getline(infile, line))\n {\n std::istringstream iss(line);\n \/\/CFunctions::record_structure record;\n\n\tstd::cout << \" PARSE BLOCKCHAIN: \" << line << \" \" << std::endl;\n\n std::size_t start = line.find(\"[\");\n std::size_t end = line.find(\"]\");\n\n }\n\n\n \n return 0;\n}\nUpdate block parse.\/\/ Copyright (c) 2016 Jon Taylor\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"functions\/functions.h\"\n#include \n\n\/*\n {\"record\":{\"time\":\"1497069518\",\"name:\":\"\",\"typ\":\"0\",\"amt\":0,\"fee\":0,\"sndkey\":\"026321261876CFB360F94A7FDF3F2D4F6F9FC0CEDADF15AC3D30E182A82AF5D81E\",\"rcvkey\":\"\",\"sig\":\"DF9721B14253E380F9E6EF00A5DBF1DB74751BF7F7EBBF104E04FE462CBA27255144B900251E061ED16CAC9B572088B446B42B448E0A6A64D92E697FC5142960\"}}\n\n{\"block\":{\"number\":1\",\"time\":\"\",\"hash\":\"\",\"records\":{\n{\"record\":{\"time\":\"1497071981\",\"name:\":\"\",\"typ\":\"1\",\"amt\":1,\"fee\":-1.0367648569192718e-155,\"sndkey\":\"\",\"rcvkey\":\"026321261876CFB360F94A7FDF3F2D4F6F9FC0CEDADF15AC3D30E182A82AF5D81E\",\"sig\":\"A1BBB5C4B1FD3081EBE276627DE088B76B4932650CF6A3EA9D31EFE5B03F106AD5D8C32A38537F9D09B72220D4FF54106F30BF17C8068995AF221D1FAB5EE183\"}}\n}}}\n*\/\n\n\/**\n* tokenClose\n*\n* Description: Find closing token for a structure in a string.\n*\/\nint CFunctions::tokenClose(std::string content, std::string open, std::string close, int start){\n\tstd::size_t start_i = content.find(open);\n std::size_t end_i = content.find(close);\n if (start_i!=std::string::npos && end_i!=std::string::npos){\n std::string section = content.substr (start_i + 1, end_i - start_i -1);\n\n\t}\t\n\n\treturn 0;\n}\n\n\/**\n* recordJSON \n*\n*\n*\/\nstd::string CFunctions::recordJSON(record_structure record){\n\tstd::string json = \"{\\\"record\\\":{\\\"time\\\":\\\"\" + record.time + \"\\\",\" +\n \"\\\"name:\\\":\\\"\" + record.name + \"\\\",\" +\n \"\\\"typ\\\":\\\"\" + boost::lexical_cast(record.transaction_type) + \"\\\",\" +\n \"\\\"amt\\\":\" + boost::lexical_cast(record.amount) + \",\" +\n \"\\\"fee\\\":\" + boost::lexical_cast(record.fee) + \",\" +\n \"\\\"sndkey\\\":\\\"\" + record.sender_public_key + \"\\\",\" +\n \"\\\"rcvkey\\\":\\\"\" + record.recipient_public_key + \"\\\",\" +\n \"\\\"sig\\\":\\\"\" + record.message_signature + \"\\\"\" +\n \"}}\\n\";\n\treturn json;\n}\n\n\/**\n * addToQueue\n *\n * Description: Add queue record to file. Data access object function.\n * @param time:\n * @param transaction_type: [add_user, issue_currency, transfer] designates action of this record.\n * @param amount: double amount of currency to be sent.\n * @param\n *\/\nint CFunctions::addToQueue(record_structure record){\n std::ofstream outfile;\n outfile.open(\"queue.dat\", std::ios_base::app);\n outfile << recordJSON(record);\n outfile.close();\n return 1;\n}\n\n\n\/**\n* parseRecordJson\n*\n* Description: \n*\/\nCFunctions::record_structure parseRecordJson(std::string json){\n\tCFunctions::record_structure record;\n\n\tstd::size_t start = json.find(\"time\\\":\\\"\");\n std::size_t end = json.find(\"]\");\n if (start!=std::string::npos && end!=std::string::npos){\n std::string time = json.substr (start + 1, end-start -1);\n record.time = time;\n std::cout << \" Time: \" << time << \" \" << std::endl;\n\n start = json.find(\"[\", end);\n end = json.find(\"]\", end + 1);\n std::string type = json.substr (start + 1, end-start - 1);\n std::cout << \" type: \" << type << \" \" << std::endl;\n\n\n }\n\n\treturn record;\n}\n\n\/**\n * parseQueueRecords\n *\n * Description: Read queued records from file into a vector of structures.\n * @return vector or record_structures\n *\/\nstd::vector CFunctions::parseQueueRecords(){\n std::vector records;\n std::ifstream infile(\"queue.dat\");\n std::string line;\n while (std::getline(infile, line))\n {\n std::istringstream iss(line);\n CFunctions::record_structure record;\n \n \n std::size_t start = line.find(\"[\");\n std::size_t end = line.find(\"]\");\n if (start!=std::string::npos && end!=std::string::npos){\n std::string time = line.substr (start + 1, end-start -1);\n record.time = time;\n std::cout << \" Time: \" << time << \" \" << std::endl;\n \n start = line.find(\"[\", end);\n end = line.find(\"]\", end + 1);\n std::string type = line.substr (start + 1, end-start - 1);\n std::cout << \" type: \" << type << \" \" << std::endl;\n\n \n }\n \n \/\/int a, b;\n \/\/if (!(iss >> a >> b)) { break; } \/\/ error\n \n std::cout << \" Line: \" << line << \" \" << std::endl;\n \/\/ process pair (a,b)\n \n \n \/\/record.time = \"2017\/06\/02\";\n \n \n records.push_back (record);\n \n \n }\n \n \n return records;\n}\n\nint CFunctions::existsInQueue(record_structure record){\n \n \n \n return 0;\n}\n\n\nint CFunctions::getRecordsInQueue( int limit ){\n \n \n}\n\n\n\/**\n * validateRecord\n *\n * Description: validate record is formatted, the hashes match and balances are sufficient.\n *\/\nint CFunctions::validateRecord(record_structure record){\n \/\/\n \/\/ Read block\n \n return 0;\n}\n\n\/**\n *\n *\n *\/\nint CFunctions::generateBlock(std::vector records, std::string time ){\n \n}\n\n\nint CFunctions::addToBlockFile( CFunctions::block_structure block ){\n \n time_t t = time(0); \/\/ get time now\n struct tm * now = localtime( & t );\n int year = (now->tm_year + 1900);\n \n std::stringstream ss;\n ss << \"block_\" << year << \".dat\";\n std::string file_path = ss.str();\n \n std::ofstream outfile;\n outfile.open(file_path, std::ios_base::app);\n outfile << \"{\\\"block\\\":{\" <<\n\t\"\\\"number\\\":\" << block.number << \"\\\",\" <<\n\t\"\\\"time\\\":\\\"\" << block.time << \"\\\",\" << \n\t\"\\\"hash\\\":\\\"\" << block.block_hash << \"\\\",\" <<\n\t\/\/\"[\" << block.transaction_type << \"]\" << \n\t\"\\\"records\\\":{\\n\";\n\n \/\/ Loop though block records\n for(int i = 0; i < block.records.size(); i++ ){\n\tCFunctions::record_structure record = block.records.at(i);\n\toutfile << recordJSON(record);\n }\n\n outfile << \"}}}\\n\";\n\n outfile.close();\n \n return 0;\n}\n\n\n\/**\n* parseBlockFile\n*\n* Description: Read the block file into in memory data structure. \n*\/\nint CFunctions::parseBlockFile(){\n time_t t = time(0); \/\/ get time now\n struct tm * now = localtime( & t );\n int year = (now->tm_year + 1900);\n\n std::stringstream ss;\n ss << \"block_\" << year << \".dat\";\n std::string file_path = ss.str();\n\n \/\/CFunctions::block_structure block;\n\n std::string content = \"\";\n\n std::vector records;\n std::ifstream infile(file_path);\n std::string line;\n while (std::getline(infile, line))\n {\n std::istringstream iss(line);\n \/\/CFunctions::record_structure record;\n\n content += line;\n\n\t\/\/std::cout << \" PARSE BLOCKCHAIN: \" << line << \" \" << std::endl;\n\n \/\/ Parse content into data structures and strip it from content string as it goes. \n\n \/\/size_t n = std::count(s.begin(), s.end(), '_');\n\n\t\/\/ Read the first block in the file.\n int parenDepth = 0;\n std::size_t start_i = content.find(\"{\");\n if (start_i!=std::string::npos){\n \/\/std::string section = content.substr (start_i + 1, end_i - start_i -1);\n \/\/parenDepth = 1; \n\n for(int i = 0; i < content.length(); i++){\n if(content[start_i + i] == '{'){\n parenDepth++;\n \/\/std::cout << \" +: \" << \" \" << i << \" d: \" << parenDepth << std::endl; \n }\n if(content[start_i + i] == '}'){ \n parenDepth--;\n \/\/std::cout << \" -: \" << \" \" << i << \" d: \" << parenDepth << std::endl; \n }\n\t\tif( parenDepth == 0){\n std::cout << \" Found end of block \" << parenDepth << std::endl; \n \n std::string section = content.substr(start_i, i + 1);\n std::cout << \" --- block \" << section << std::endl;\n\n \/\/ Populate block and its records....\n \/\/ \"number\":0\",\"time\":\"\",\"hash\":\"\",\"records\"\n \/\/ {\"record\": \n\n \n content = content.substr(start_i + i, content.length());\n }\n }\n\n }\t\t\n\n\n std::size_t start = line.find(\"[\");\n std::size_t end = line.find(\"]\");\n\n }\n\n\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * A cache for NFS files.\n *\n * author: Max Kellermann \n *\/\n\n#include \"nfs_cache.hxx\"\n#include \"nfs_stock.hxx\"\n#include \"nfs_client.hxx\"\n#include \"istream_nfs.hxx\"\n#include \"strmap.hxx\"\n#include \"pool.hxx\"\n#include \"rubber.hxx\"\n#include \"sink_rubber.hxx\"\n#include \"istream_unlock.hxx\"\n#include \"istream_rubber.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_null.hxx\"\n#include \"istream\/istream_tee.hxx\"\n#include \"AllocatorStats.hxx\"\n#include \"cache.hxx\"\n#include \"async.hxx\"\n#include \"event\/Event.hxx\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef CACHE_LOG\n#include \n#define cache_log(...) daemon_log(__VA_ARGS__)\n#else\n#define cache_log(...) do {} while (0)\n#endif\n\nstruct NfsCacheItem;\n\nstruct NfsCache {\n struct pool &pool;\n\n struct nfs_stock &stock;\n\n struct cache &cache;\n\n Rubber &rubber;\n\n \/**\n * A list of requests that are currently saving their contents to\n * the cache.\n *\/\n struct list_head requests;\n\n NfsCache(struct pool &_pool, size_t max_size, struct nfs_stock &_stock);\n\n ~NfsCache() {\n cache_close(&cache);\n rubber_free(&rubber);\n pool_unref(&pool);\n }\n};\n\nstruct NfsCacheRequest {\n struct pool &pool;\n\n NfsCache &cache;\n\n const char *key;\n const char *path;\n\n const NfsCacheHandler &handler;\n void *handler_ctx;\n struct async_operation_ref &async_ref;\n\n NfsCacheRequest(struct pool &_pool, NfsCache &_cache,\n const char *_key, const char *_path,\n const NfsCacheHandler &_handler, void *_ctx,\n struct async_operation_ref &_async_ref)\n :pool(_pool), cache(_cache),\n key(_key), path(_path),\n handler(_handler), handler_ctx(_ctx),\n async_ref(_async_ref) {}\n};\n\nstruct NfsCacheHandle {\n NfsCache &cache;\n const char *key;\n\n struct nfs_file_handle *file;\n NfsCacheItem *item;\n const struct stat &stat;\n};\n\nstruct NfsCacheStore {\n struct list_head siblings;\n\n struct pool &pool;\n\n NfsCache &cache;\n\n const char *key;\n\n struct stat stat;\n\n Event timeout_event;\n struct async_operation_ref async_ref;\n\n NfsCacheStore(struct pool &_pool, NfsCache &_cache,\n const char *_key, const struct stat &_st)\n :pool(_pool), cache(_cache),\n key(_key),\n stat(_st) {}\n\n \/**\n * Release resources held by this request.\n *\/\n void Release();\n\n \/**\n * Abort the request.\n *\/\n void Abort();\n\n void Put(unsigned rubber_id);\n};\n\nstruct NfsCacheItem {\n struct cache_item item;\n\n struct pool &pool;\n\n struct stat stat;\n\n Rubber &rubber;\n unsigned rubber_id;\n\n NfsCacheItem(struct pool &_pool, const NfsCacheStore &store,\n Rubber &_rubber, unsigned _rubber_id)\n :pool(_pool), stat(store.stat),\n rubber(_rubber), rubber_id(_rubber_id) {\n cache_item_init_relative(&item, 60, stat.st_size);\n }\n};\n\nstatic constexpr off_t cacheable_size_limit = 256 * 1024;\n\nstatic constexpr struct timeval nfs_cache_timeout = { 60, 0 };\n\nstatic const char *\nnfs_cache_key(struct pool &pool, const char *server,\n const char *_export, const char *path)\n{\n return p_strcat(&pool, server, \":\", _export, path, nullptr);\n}\n\nstatic void\nnfs_cache_request_error(GError *error, void *ctx)\n{\n NfsCacheRequest *r = (NfsCacheRequest *)ctx;\n\n r->handler.error(error, r->handler_ctx);\n}\n\nvoid\nNfsCacheStore::Release()\n{\n assert(!async_ref.IsDefined());\n\n timeout_event.Delete();\n\n list_remove(&siblings);\n pool_unref(&pool);\n}\n\nvoid\nNfsCacheStore::Abort()\n{\n assert(async_ref.IsDefined());\n\n async_ref.Abort();\n async_ref.Clear();\n Release();\n}\n\nvoid\nNfsCacheStore::Put(unsigned rubber_id)\n{\n cache_log(4, \"nfs_cache: put %s\\n\", key);\n\n struct pool *item_pool = pool_new_libc(&cache.pool, \"nfs_cache_item\");\n const auto item = NewFromPool(*item_pool, *item_pool, *this,\n cache.rubber, rubber_id);\n cache_put(&cache.cache, p_strdup(item_pool, key), &item->item);\n}\n\n\/*\n * sink_rubber_handler\n *\n *\/\n\nstatic void\nnfs_cache_rubber_done(unsigned rubber_id, gcc_unused size_t size, void *ctx)\n{\n auto &store = *(NfsCacheStore *)ctx;\n assert((off_t)size == store.stat.st_size);\n\n store.async_ref.Clear();\n\n \/* the request was successful, and all of the body data has been\n saved: add it to the cache *\/\n store.Put(rubber_id);\n\n store.Release();\n}\n\nstatic void\nnfs_cache_rubber_no_store(void *ctx)\n{\n auto &store = *(NfsCacheStore *)ctx;\n store.async_ref.Clear();\n\n cache_log(4, \"nfs_cache: nocache %s\\n\", store.key);\n store.Release();\n}\n\nstatic void\nnfs_cache_rubber_error(GError *error, void *ctx)\n{\n auto &store = *(NfsCacheStore *)ctx;\n store.async_ref.Clear();\n\n cache_log(4, \"nfs_cache: body_abort %s: %s\\n\", store.key, error->message);\n g_error_free(error);\n\n store.Release();\n}\n\nstatic const struct sink_rubber_handler nfs_cache_rubber_handler = {\n .done = nfs_cache_rubber_done,\n .out_of_memory = nfs_cache_rubber_no_store,\n .too_large = nfs_cache_rubber_no_store,\n .error = nfs_cache_rubber_error,\n};\n\n\/*\n * nfs_client_open_file_handler\n *\n *\/\n\nstatic void\nnfs_open_ready(struct nfs_file_handle *handle, const struct stat *st,\n void *ctx)\n{\n auto &r = *(NfsCacheRequest *)ctx;\n\n NfsCacheHandle handle2 = {\n .cache = r.cache,\n .key = r.key,\n .file = handle,\n .item = nullptr,\n .stat = *st,\n };\n\n r.handler.response(handle2, *st, r.handler_ctx);\n\n if (handle2.file != nullptr)\n nfs_client_close_file(handle2.file);\n}\n\nstatic const struct nfs_client_open_file_handler nfs_open_handler = {\n .ready = nfs_open_ready,\n .error = nfs_cache_request_error,\n};\n\n\/*\n * nfs_stock_get_handler\n *\n *\/\n\nstatic void\nnfs_cache_request_stock_ready(struct nfs_client *client, void *ctx)\n{\n auto &r = *(NfsCacheRequest *)ctx;\n\n nfs_client_open_file(client, &r.pool, r.path,\n &nfs_open_handler, &r, &r.async_ref);\n}\n\nstatic const struct nfs_stock_get_handler nfs_cache_request_stock_handler = {\n .ready = nfs_cache_request_stock_ready,\n .error = nfs_cache_request_error,\n};\n\n\/*\n * cache_class\n *\n *\/\n\nstatic bool\nnfs_cache_item_validate(struct cache_item *_item)\n{\n const auto &item = *(NfsCacheItem *)_item;\n\n (void)item;\n return true;\n}\n\nstatic void\nnfs_cache_item_destroy(struct cache_item *_item)\n{\n const auto &item = *(NfsCacheItem *)_item;\n\n if (item.rubber_id != 0)\n rubber_remove(&item.rubber, item.rubber_id);\n\n pool_unref(&item.pool);\n}\n\nstatic const struct cache_class nfs_cache_class = {\n .validate = nfs_cache_item_validate,\n .destroy = nfs_cache_item_destroy,\n};\n\n\/*\n * libevent callbacks\n *\n *\/\n\nstatic void\nnfs_cache_timeout_callback(gcc_unused int fd, gcc_unused short event,\n void *ctx)\n{\n auto &store = *(NfsCacheStore *)ctx;\n\n \/* reading the response has taken too long already; don't store\n this resource *\/\n cache_log(4, \"nfs_cache: timeout %s\\n\", store.key);\n store.Abort();\n}\n\n\/*\n * constructor\n *\n *\/\n\nstatic Rubber &\nNewRubberOrAbort(size_t max_size)\n{\n auto r = rubber_new(max_size);\n if (r == nullptr) {\n fprintf(stderr, \"Failed to allocate HTTP cache: %s\\n\",\n strerror(errno));\n exit(2);\n }\n\n return *r;\n}\n\ninline\nNfsCache::NfsCache(struct pool &_pool, size_t max_size,\n struct nfs_stock &_stock)\n :pool(*pool_new_libc(&_pool, \"nfs_cache\")), stock(_stock),\n cache(*cache_new(pool, &nfs_cache_class, 65521, max_size * 7 \/ 8)),\n rubber(NewRubberOrAbort(max_size)) {\n list_init(&requests);\n}\n\nNfsCache *\nnfs_cache_new(struct pool &_pool, size_t max_size,\n struct nfs_stock &stock)\n{\n return new NfsCache(_pool, max_size, stock);\n}\n\nvoid\nnfs_cache_free(NfsCache *cache)\n{\n assert(cache != nullptr);\n\n delete cache;\n}\n\nAllocatorStats\nnfs_cache_get_stats(const NfsCache &cache)\n{\n return cache_get_stats(cache.cache) + rubber_get_stats(cache.rubber);\n}\n\nvoid\nnfs_cache_fork_cow(NfsCache &cache, bool inherit)\n{\n rubber_fork_cow(&cache.rubber, inherit);\n}\n\nvoid\nnfs_cache_request(struct pool &pool, NfsCache &cache,\n const char *server, const char *_export, const char *path,\n const NfsCacheHandler &handler, void *ctx,\n struct async_operation_ref &async_ref)\n{\n const char *key = nfs_cache_key(pool, server, _export, path);\n const auto item = (NfsCacheItem *)cache_get(&cache.cache, key);\n if (item != nullptr) {\n cache_log(4, \"nfs_cache: hit %s\\n\", key);\n\n NfsCacheHandle handle2 = {\n .cache = cache,\n .key = key,\n .file = nullptr,\n .item = item,\n .stat = item->stat,\n };\n\n handler.response(handle2, item->stat, ctx);\n return;\n }\n\n cache_log(4, \"nfs_cache: miss %s\\n\", key);\n\n auto r = NewFromPool(pool, pool, cache,\n key, path,\n handler, ctx, async_ref);\n nfs_stock_get(&cache.stock, &pool, server, _export,\n &nfs_cache_request_stock_handler, r,\n &async_ref);\n}\n\nstatic struct istream *\nnfs_cache_item_open(struct pool &pool, NfsCache &cache,\n NfsCacheItem &item,\n uint64_t start, uint64_t end)\n{\n assert(start <= end);\n assert(end <= (uint64_t)item.stat.st_size);\n\n assert(item.rubber_id != 0);\n\n struct istream *istream =\n istream_rubber_new(&pool, &item.rubber, item.rubber_id,\n start, end, false);\n return istream_unlock_new(&pool, istream, &cache.cache, &item.item);\n}\n\nstatic struct istream *\nnfs_cache_file_open(struct pool &pool, NfsCache &cache,\n const char *key,\n struct nfs_file_handle &file, const struct stat &st,\n uint64_t start, uint64_t end)\n{\n assert(start <= end);\n assert(end <= (uint64_t)st.st_size);\n\n struct istream *body = istream_nfs_new(&pool, &file, start, end);\n if (st.st_size > cacheable_size_limit || start != 0 ||\n end != (uint64_t)st.st_size) {\n \/* don't cache *\/\n cache_log(4, \"nfs_cache: nocache %s\\n\", key);\n return body;\n }\n\n \/* move all this stuff to a new pool, so istream_tee's second head\n can continue to fill the cache even if our caller gave up on\n it *\/\n struct pool *pool2 = pool_new_linear(&cache.pool,\n \"nfs_cache_tee\", 1024);\n auto store = NewFromPool(*pool2, *pool2, cache,\n p_strdup(pool2, key), st);\n\n \/* tee the body: one goes to our client, and one goes into the\n cache *\/\n body = istream_tee_new(pool2, body, false, true);\n\n list_add(&store->siblings, &cache.requests);\n\n store->timeout_event.SetTimer(nfs_cache_timeout_callback, store);\n store->timeout_event.Add(nfs_cache_timeout);\n\n sink_rubber_new(pool2, istream_tee_second(body),\n &cache.rubber, cacheable_size_limit,\n &nfs_cache_rubber_handler, store,\n &store->async_ref);\n\n return body;\n}\n\nstruct istream *\nnfs_cache_handle_open(struct pool &pool, NfsCacheHandle &handle,\n uint64_t start, uint64_t end)\n{\n assert((handle.file == nullptr) != (handle.item == nullptr));\n assert(start <= end);\n assert(end <= (uint64_t)handle.stat.st_size);\n\n if (start == end)\n return istream_null_new(&pool);\n\n if (handle.item != nullptr) {\n \/* cache hit: serve cached file *\/\n cache_log(5, \"nfs_cache: serve %s\\n\", handle.key);\n return nfs_cache_item_open(pool, handle.cache, *handle.item,\n start, end);\n } else {\n \/* cache miss: load from NFS server *\/\n struct nfs_file_handle *const file = handle.file;\n handle.file = nullptr;\n\n return nfs_cache_file_open(pool, handle.cache, handle.key,\n *file, handle.stat, start, end);\n }\n}\nnfs_cache: use MakeSimpleEventCallback()\/*\n * A cache for NFS files.\n *\n * author: Max Kellermann \n *\/\n\n#include \"nfs_cache.hxx\"\n#include \"nfs_stock.hxx\"\n#include \"nfs_client.hxx\"\n#include \"istream_nfs.hxx\"\n#include \"strmap.hxx\"\n#include \"pool.hxx\"\n#include \"rubber.hxx\"\n#include \"sink_rubber.hxx\"\n#include \"istream_unlock.hxx\"\n#include \"istream_rubber.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_null.hxx\"\n#include \"istream\/istream_tee.hxx\"\n#include \"AllocatorStats.hxx\"\n#include \"cache.hxx\"\n#include \"async.hxx\"\n#include \"event\/Event.hxx\"\n#include \"event\/Callback.hxx\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef CACHE_LOG\n#include \n#define cache_log(...) daemon_log(__VA_ARGS__)\n#else\n#define cache_log(...) do {} while (0)\n#endif\n\nstruct NfsCacheItem;\n\nstruct NfsCache {\n struct pool &pool;\n\n struct nfs_stock &stock;\n\n struct cache &cache;\n\n Rubber &rubber;\n\n \/**\n * A list of requests that are currently saving their contents to\n * the cache.\n *\/\n struct list_head requests;\n\n NfsCache(struct pool &_pool, size_t max_size, struct nfs_stock &_stock);\n\n ~NfsCache() {\n cache_close(&cache);\n rubber_free(&rubber);\n pool_unref(&pool);\n }\n};\n\nstruct NfsCacheRequest {\n struct pool &pool;\n\n NfsCache &cache;\n\n const char *key;\n const char *path;\n\n const NfsCacheHandler &handler;\n void *handler_ctx;\n struct async_operation_ref &async_ref;\n\n NfsCacheRequest(struct pool &_pool, NfsCache &_cache,\n const char *_key, const char *_path,\n const NfsCacheHandler &_handler, void *_ctx,\n struct async_operation_ref &_async_ref)\n :pool(_pool), cache(_cache),\n key(_key), path(_path),\n handler(_handler), handler_ctx(_ctx),\n async_ref(_async_ref) {}\n};\n\nstruct NfsCacheHandle {\n NfsCache &cache;\n const char *key;\n\n struct nfs_file_handle *file;\n NfsCacheItem *item;\n const struct stat &stat;\n};\n\nstruct NfsCacheStore {\n struct list_head siblings;\n\n struct pool &pool;\n\n NfsCache &cache;\n\n const char *key;\n\n struct stat stat;\n\n Event timeout_event;\n struct async_operation_ref async_ref;\n\n NfsCacheStore(struct pool &_pool, NfsCache &_cache,\n const char *_key, const struct stat &_st)\n :pool(_pool), cache(_cache),\n key(_key),\n stat(_st) {}\n\n \/**\n * Release resources held by this request.\n *\/\n void Release();\n\n \/**\n * Abort the request.\n *\/\n void Abort();\n\n void Put(unsigned rubber_id);\n\n void OnTimeout() {\n \/* reading the response has taken too long already; don't store\n this resource *\/\n cache_log(4, \"nfs_cache: timeout %s\\n\", key);\n Abort();\n }\n};\n\nstruct NfsCacheItem {\n struct cache_item item;\n\n struct pool &pool;\n\n struct stat stat;\n\n Rubber &rubber;\n unsigned rubber_id;\n\n NfsCacheItem(struct pool &_pool, const NfsCacheStore &store,\n Rubber &_rubber, unsigned _rubber_id)\n :pool(_pool), stat(store.stat),\n rubber(_rubber), rubber_id(_rubber_id) {\n cache_item_init_relative(&item, 60, stat.st_size);\n }\n};\n\nstatic constexpr off_t cacheable_size_limit = 256 * 1024;\n\nstatic constexpr struct timeval nfs_cache_timeout = { 60, 0 };\n\nstatic const char *\nnfs_cache_key(struct pool &pool, const char *server,\n const char *_export, const char *path)\n{\n return p_strcat(&pool, server, \":\", _export, path, nullptr);\n}\n\nstatic void\nnfs_cache_request_error(GError *error, void *ctx)\n{\n NfsCacheRequest *r = (NfsCacheRequest *)ctx;\n\n r->handler.error(error, r->handler_ctx);\n}\n\nvoid\nNfsCacheStore::Release()\n{\n assert(!async_ref.IsDefined());\n\n timeout_event.Delete();\n\n list_remove(&siblings);\n pool_unref(&pool);\n}\n\nvoid\nNfsCacheStore::Abort()\n{\n assert(async_ref.IsDefined());\n\n async_ref.Abort();\n async_ref.Clear();\n Release();\n}\n\nvoid\nNfsCacheStore::Put(unsigned rubber_id)\n{\n cache_log(4, \"nfs_cache: put %s\\n\", key);\n\n struct pool *item_pool = pool_new_libc(&cache.pool, \"nfs_cache_item\");\n const auto item = NewFromPool(*item_pool, *item_pool, *this,\n cache.rubber, rubber_id);\n cache_put(&cache.cache, p_strdup(item_pool, key), &item->item);\n}\n\n\/*\n * sink_rubber_handler\n *\n *\/\n\nstatic void\nnfs_cache_rubber_done(unsigned rubber_id, gcc_unused size_t size, void *ctx)\n{\n auto &store = *(NfsCacheStore *)ctx;\n assert((off_t)size == store.stat.st_size);\n\n store.async_ref.Clear();\n\n \/* the request was successful, and all of the body data has been\n saved: add it to the cache *\/\n store.Put(rubber_id);\n\n store.Release();\n}\n\nstatic void\nnfs_cache_rubber_no_store(void *ctx)\n{\n auto &store = *(NfsCacheStore *)ctx;\n store.async_ref.Clear();\n\n cache_log(4, \"nfs_cache: nocache %s\\n\", store.key);\n store.Release();\n}\n\nstatic void\nnfs_cache_rubber_error(GError *error, void *ctx)\n{\n auto &store = *(NfsCacheStore *)ctx;\n store.async_ref.Clear();\n\n cache_log(4, \"nfs_cache: body_abort %s: %s\\n\", store.key, error->message);\n g_error_free(error);\n\n store.Release();\n}\n\nstatic const struct sink_rubber_handler nfs_cache_rubber_handler = {\n .done = nfs_cache_rubber_done,\n .out_of_memory = nfs_cache_rubber_no_store,\n .too_large = nfs_cache_rubber_no_store,\n .error = nfs_cache_rubber_error,\n};\n\n\/*\n * nfs_client_open_file_handler\n *\n *\/\n\nstatic void\nnfs_open_ready(struct nfs_file_handle *handle, const struct stat *st,\n void *ctx)\n{\n auto &r = *(NfsCacheRequest *)ctx;\n\n NfsCacheHandle handle2 = {\n .cache = r.cache,\n .key = r.key,\n .file = handle,\n .item = nullptr,\n .stat = *st,\n };\n\n r.handler.response(handle2, *st, r.handler_ctx);\n\n if (handle2.file != nullptr)\n nfs_client_close_file(handle2.file);\n}\n\nstatic const struct nfs_client_open_file_handler nfs_open_handler = {\n .ready = nfs_open_ready,\n .error = nfs_cache_request_error,\n};\n\n\/*\n * nfs_stock_get_handler\n *\n *\/\n\nstatic void\nnfs_cache_request_stock_ready(struct nfs_client *client, void *ctx)\n{\n auto &r = *(NfsCacheRequest *)ctx;\n\n nfs_client_open_file(client, &r.pool, r.path,\n &nfs_open_handler, &r, &r.async_ref);\n}\n\nstatic const struct nfs_stock_get_handler nfs_cache_request_stock_handler = {\n .ready = nfs_cache_request_stock_ready,\n .error = nfs_cache_request_error,\n};\n\n\/*\n * cache_class\n *\n *\/\n\nstatic bool\nnfs_cache_item_validate(struct cache_item *_item)\n{\n const auto &item = *(NfsCacheItem *)_item;\n\n (void)item;\n return true;\n}\n\nstatic void\nnfs_cache_item_destroy(struct cache_item *_item)\n{\n const auto &item = *(NfsCacheItem *)_item;\n\n if (item.rubber_id != 0)\n rubber_remove(&item.rubber, item.rubber_id);\n\n pool_unref(&item.pool);\n}\n\nstatic const struct cache_class nfs_cache_class = {\n .validate = nfs_cache_item_validate,\n .destroy = nfs_cache_item_destroy,\n};\n\n\/*\n * constructor\n *\n *\/\n\nstatic Rubber &\nNewRubberOrAbort(size_t max_size)\n{\n auto r = rubber_new(max_size);\n if (r == nullptr) {\n fprintf(stderr, \"Failed to allocate HTTP cache: %s\\n\",\n strerror(errno));\n exit(2);\n }\n\n return *r;\n}\n\ninline\nNfsCache::NfsCache(struct pool &_pool, size_t max_size,\n struct nfs_stock &_stock)\n :pool(*pool_new_libc(&_pool, \"nfs_cache\")), stock(_stock),\n cache(*cache_new(pool, &nfs_cache_class, 65521, max_size * 7 \/ 8)),\n rubber(NewRubberOrAbort(max_size)) {\n list_init(&requests);\n}\n\nNfsCache *\nnfs_cache_new(struct pool &_pool, size_t max_size,\n struct nfs_stock &stock)\n{\n return new NfsCache(_pool, max_size, stock);\n}\n\nvoid\nnfs_cache_free(NfsCache *cache)\n{\n assert(cache != nullptr);\n\n delete cache;\n}\n\nAllocatorStats\nnfs_cache_get_stats(const NfsCache &cache)\n{\n return cache_get_stats(cache.cache) + rubber_get_stats(cache.rubber);\n}\n\nvoid\nnfs_cache_fork_cow(NfsCache &cache, bool inherit)\n{\n rubber_fork_cow(&cache.rubber, inherit);\n}\n\nvoid\nnfs_cache_request(struct pool &pool, NfsCache &cache,\n const char *server, const char *_export, const char *path,\n const NfsCacheHandler &handler, void *ctx,\n struct async_operation_ref &async_ref)\n{\n const char *key = nfs_cache_key(pool, server, _export, path);\n const auto item = (NfsCacheItem *)cache_get(&cache.cache, key);\n if (item != nullptr) {\n cache_log(4, \"nfs_cache: hit %s\\n\", key);\n\n NfsCacheHandle handle2 = {\n .cache = cache,\n .key = key,\n .file = nullptr,\n .item = item,\n .stat = item->stat,\n };\n\n handler.response(handle2, item->stat, ctx);\n return;\n }\n\n cache_log(4, \"nfs_cache: miss %s\\n\", key);\n\n auto r = NewFromPool(pool, pool, cache,\n key, path,\n handler, ctx, async_ref);\n nfs_stock_get(&cache.stock, &pool, server, _export,\n &nfs_cache_request_stock_handler, r,\n &async_ref);\n}\n\nstatic struct istream *\nnfs_cache_item_open(struct pool &pool, NfsCache &cache,\n NfsCacheItem &item,\n uint64_t start, uint64_t end)\n{\n assert(start <= end);\n assert(end <= (uint64_t)item.stat.st_size);\n\n assert(item.rubber_id != 0);\n\n struct istream *istream =\n istream_rubber_new(&pool, &item.rubber, item.rubber_id,\n start, end, false);\n return istream_unlock_new(&pool, istream, &cache.cache, &item.item);\n}\n\nstatic struct istream *\nnfs_cache_file_open(struct pool &pool, NfsCache &cache,\n const char *key,\n struct nfs_file_handle &file, const struct stat &st,\n uint64_t start, uint64_t end)\n{\n assert(start <= end);\n assert(end <= (uint64_t)st.st_size);\n\n struct istream *body = istream_nfs_new(&pool, &file, start, end);\n if (st.st_size > cacheable_size_limit || start != 0 ||\n end != (uint64_t)st.st_size) {\n \/* don't cache *\/\n cache_log(4, \"nfs_cache: nocache %s\\n\", key);\n return body;\n }\n\n \/* move all this stuff to a new pool, so istream_tee's second head\n can continue to fill the cache even if our caller gave up on\n it *\/\n struct pool *pool2 = pool_new_linear(&cache.pool,\n \"nfs_cache_tee\", 1024);\n auto store = NewFromPool(*pool2, *pool2, cache,\n p_strdup(pool2, key), st);\n\n \/* tee the body: one goes to our client, and one goes into the\n cache *\/\n body = istream_tee_new(pool2, body, false, true);\n\n list_add(&store->siblings, &cache.requests);\n\n store->timeout_event.SetTimer(MakeSimpleEventCallback(NfsCacheStore,\n OnTimeout), store);\n store->timeout_event.Add(nfs_cache_timeout);\n\n sink_rubber_new(pool2, istream_tee_second(body),\n &cache.rubber, cacheable_size_limit,\n &nfs_cache_rubber_handler, store,\n &store->async_ref);\n\n return body;\n}\n\nstruct istream *\nnfs_cache_handle_open(struct pool &pool, NfsCacheHandle &handle,\n uint64_t start, uint64_t end)\n{\n assert((handle.file == nullptr) != (handle.item == nullptr));\n assert(start <= end);\n assert(end <= (uint64_t)handle.stat.st_size);\n\n if (start == end)\n return istream_null_new(&pool);\n\n if (handle.item != nullptr) {\n \/* cache hit: serve cached file *\/\n cache_log(5, \"nfs_cache: serve %s\\n\", handle.key);\n return nfs_cache_item_open(pool, handle.cache, *handle.item,\n start, end);\n } else {\n \/* cache miss: load from NFS server *\/\n struct nfs_file_handle *const file = handle.file;\n handle.file = nullptr;\n\n return nfs_cache_file_open(pool, handle.cache, handle.key,\n *file, handle.stat, start, end);\n }\n}\n<|endoftext|>"} {"text":"#include \"generator\/generator.h\"\n\n\/\/ from STL\n#include \n#include \n\n\/\/ from ROOT\n#include \"TRandom.h\"\n\n\/\/ from project\n#include \"configuration\/configuration.h\"\n\n\nnamespace cptoymc {\nnamespace generator {\n\nbool GenerateExpo(TRandom& rndm, double par_expo, double& obs, double min, double max) {\n if (par_expo != 0.) {\n obs = (-1.\/par_expo)*log(exp(-1.*max*par_expo)+rndm.Uniform()*(exp(-1.*min*par_expo)-exp(-1.*max*par_expo)));\n } else {\n obs = rndm.Uniform(min,max);\n }\n return true;\n}\n\n\nbool GenerateMassBreitWigner(TRandom& rndm, double par_mean, double par_gamma, double& obs_mass_true) {\n obs_mass_true = rndm.BreitWigner(par_mean, par_gamma);\n return true;\n}\n\nbool GenerateLognormal(TRandom& rndm, double m, double k, double min, double max,\n double& obs_sigma_t) {\n obs_sigma_t = std::exp(std::log(m) + std::log(k)*rndm.Gaus(0,1));\n\n while (obs_sigma_t > max || obs_sigma_t < min) {\n obs_sigma_t = std::exp(std::log(m) + std::log(k)*rndm.Gaus(0,1));\n }\n\n return true;\n}\n\n \nbool GenerateCPV_P2PV(TRandom& rndm, double par_prod_asym,\n double par_tau, double par_dGamma, double par_dm,\n double par_Sf, double par_Cf, double par_Df,\n double& obs_time_true, int& obs_tag_true) {\n \/\/ helper quantities\n double prob_B = (1. - par_prod_asym)\/2.;\n double gamma_min = 1.\/par_tau - std::abs(par_dGamma)\/2.;\n \n \/\/ local values of tag and time\n int val_d = 0;\n double val_t = 0.;\n \n \/\/ now hit and miss, stolen from BDecay!!!\n double val_envelope = 0.;\n double val_pdf = 0.;\n while(true) {\n \/\/ get initial flavour while taking production asymmetry into account\n val_d = (rndm.Uniform() < prob_B) ? +1 : -1;\n \n \/\/ get time\n val_t = -log(rndm.Uniform())\/gamma_min;\n \n \/\/ get pdf value and envelope value\n val_pdf = BCPV_PDF(val_t, val_d, par_tau, par_dGamma, par_dm, par_Sf, par_Cf, par_Df);\n val_envelope = BCPV_PDF_Envelope(val_t, gamma_min, par_Sf, par_Cf, par_Df);\n \n if (val_envelope < val_pdf) {\n std::cout << \"WARNING: Envelope smaller than PDF!\" << std::endl;\n }\n \n if(val_envelope*rndm.Uniform() > val_pdf) continue;\n else break;\n }\n \n obs_tag_true = val_d;\n obs_time_true = val_t;\n \n return true;\n}\n\ndouble BCPV_PDF(double t, double d, double tau, double dGamma, double dm,\n double Sf, double Cf, double Df) {\n return exp(-t\/tau)*(cosh(dGamma*t\/2.)+Df*sinh(dGamma*t\/2.)+d*Cf*cos(dm*t)-d*Sf*sin(dm*t));\n}\n \ndouble BCPV_PDF_Envelope(double t, double gamma_min, double Sf, double Cf, double Df) {\n return exp(-t*gamma_min)*(1.+std::abs(Df)+sqrt(Sf*Sf+Cf*Cf));\n}\n\nbool GenerateResolSingleGauss(TRandom& rndm, double par_bias, double par_sigma, double obs_true, double& obs_meas) {\n obs_meas = obs_true;\n obs_meas += rndm.Gaus(par_bias, par_sigma);\n \n return true;\n}\n\nbool GenerateResolSingleGaussPerEvent(TRandom& rndm, double par_bias, double par_scale, double obs_per_event_error, double obs_true, double& obs_meas) {\n obs_meas = obs_true;\n obs_meas += rndm.Gaus(par_bias, par_scale*obs_per_event_error);\n \n return true;\n}\n\n\nbool GenerateEtaFlat(TRandom& rndm, double& obs_eta) {\n return GenerateEtaFlat(rndm,0.0,0.5,obs_eta);\n}\n\nbool GenerateEtaFlat(TRandom& rndm, double obs_eta_min, double obs_eta_max, double& obs_eta) {\n obs_eta = rndm.Uniform(obs_eta_min,obs_eta_max);\n return true;\n}\n\nbool GenerateEtaGauss(TRandom& rndm, double m, double s, double obs_eta_min, double obs_eta_max, double& obs_eta) {\n \/\/ s is set to -1.0 on default; a negative Gaussian width does not make sense, thus generate a uniform distribution\n if (s < 0.0) {\n obs_eta = rndm.Uniform(obs_eta_min,obs_eta_max);\n return true;\n } else {\n obs_eta = rndm.Gaus(m,s);\n\n while (obs_eta > obs_eta_max || obs_eta < obs_eta_min) {\n obs_eta = rndm.Gaus(m,s);\n }\n\n return true;\n }\n}\n\nbool GenerateTag(TRandom& rndm, double par_omega, double par_domega,\n const int par_tag_true_B, const int par_tag_true_Bb,\n const int par_tag_B, const int par_tag_Bb,\n int obs_tag_true, int& obs_tag_meas) {\n \/\/if (par_omega > 0.5) par_omega = 0.5;\n if (par_omega < 0.0) par_omega = 0.;\n \n int correct_tag = 0;\n \n \/\/ always assume that omega_B = omega + dOmega\/2 for true B mesons\n \/\/ and that omega_Bb = omega - dOmega\/2 for true Bb mesons\n if (obs_tag_true == par_tag_true_B) {\n par_omega += par_domega\/2.; \/\/ B meson case\n correct_tag = par_tag_B;\n }\n else if (obs_tag_true == par_tag_true_Bb) {\n par_omega -= par_domega\/2.; \/\/ Bb meson case\n correct_tag = par_tag_Bb;\n } else {\n std::cout << \"Cannot interpret true tag of \" << obs_tag_true << \". Failed.\" << std::endl;\n return false;\n }\n \n if (rndm.Uniform() < par_omega) {\n obs_tag_meas = -1*correct_tag;\n } else {\n obs_tag_meas = correct_tag;\n }\n return true;\n}\n\n \nbool GenerateTag(TRandom& rndm, double par_omega, double par_domega, int obs_tag_true, int& obs_tag_meas) {\n return GenerateTag(rndm, par_omega, par_domega, +1, -1, +1, -1, obs_tag_true, obs_tag_meas);\n}\n\nbool GenerateTag(TRandom& rndm,\n std::function& func_omega,\n std::function& func_domega,\n const int par_tag_true_B, const int par_tag_true_Bb,\n const int par_tag_B, const int par_tag_Bb,\n int obs_tag_true, double obs_eta, int& obs_tag_meas) {\n return GenerateTag(rndm, func_omega(obs_eta), func_domega(obs_eta),\n par_tag_true_B, par_tag_true_Bb, par_tag_B, par_tag_Bb,\n obs_tag_true, obs_tag_meas);\n}\n \nbool GenerateRandomTag(TRandom& rndm, int& obs_tag_meas) {\n obs_tag_meas = (rndm.Uniform() < 0.5) ? +1 : -1;\n return true;\n}\n\n\n\n\nint yieldToGenerate(TRandom& rndm, double yield_exp) {\n return rndm.Poisson(yield_exp);\n}\n\n\n} \/\/ namespace cptoymc\n} \/\/ namespace generator\n\nGenerator: adding warnings for bad parameters leading to heavy hit and miss iterations for Gaussian etas#include \"generator\/generator.h\"\n\n\/\/ from STL\n#include \n#include \n\n\/\/ from ROOT\n#include \"TRandom.h\"\n\n\/\/ from project\n#include \"configuration\/configuration.h\"\n\n\nnamespace cptoymc {\nnamespace generator {\n\nbool GenerateExpo(TRandom& rndm, double par_expo, double& obs, double min, double max) {\n if (par_expo != 0.) {\n obs = (-1.\/par_expo)*log(exp(-1.*max*par_expo)+rndm.Uniform()*(exp(-1.*min*par_expo)-exp(-1.*max*par_expo)));\n } else {\n obs = rndm.Uniform(min,max);\n }\n return true;\n}\n\n\nbool GenerateMassBreitWigner(TRandom& rndm, double par_mean, double par_gamma, double& obs_mass_true) {\n obs_mass_true = rndm.BreitWigner(par_mean, par_gamma);\n return true;\n}\n\nbool GenerateLognormal(TRandom& rndm, double m, double k, double min, double max,\n double& obs_sigma_t) {\n obs_sigma_t = std::exp(std::log(m) + std::log(k)*rndm.Gaus(0,1));\n\n while (obs_sigma_t > max || obs_sigma_t < min) {\n obs_sigma_t = std::exp(std::log(m) + std::log(k)*rndm.Gaus(0,1));\n }\n\n return true;\n}\n\n \nbool GenerateCPV_P2PV(TRandom& rndm, double par_prod_asym,\n double par_tau, double par_dGamma, double par_dm,\n double par_Sf, double par_Cf, double par_Df,\n double& obs_time_true, int& obs_tag_true) {\n \/\/ helper quantities\n double prob_B = (1. - par_prod_asym)\/2.;\n double gamma_min = 1.\/par_tau - std::abs(par_dGamma)\/2.;\n \n \/\/ local values of tag and time\n int val_d = 0;\n double val_t = 0.;\n \n \/\/ now hit and miss, stolen from BDecay!!!\n double val_envelope = 0.;\n double val_pdf = 0.;\n while(true) {\n \/\/ get initial flavour while taking production asymmetry into account\n val_d = (rndm.Uniform() < prob_B) ? +1 : -1;\n \n \/\/ get time\n val_t = -log(rndm.Uniform())\/gamma_min;\n \n \/\/ get pdf value and envelope value\n val_pdf = BCPV_PDF(val_t, val_d, par_tau, par_dGamma, par_dm, par_Sf, par_Cf, par_Df);\n val_envelope = BCPV_PDF_Envelope(val_t, gamma_min, par_Sf, par_Cf, par_Df);\n \n if (val_envelope < val_pdf) {\n std::cout << \"WARNING: Envelope smaller than PDF!\" << std::endl;\n }\n \n if(val_envelope*rndm.Uniform() > val_pdf) continue;\n else break;\n }\n \n obs_tag_true = val_d;\n obs_time_true = val_t;\n \n return true;\n}\n\ndouble BCPV_PDF(double t, double d, double tau, double dGamma, double dm,\n double Sf, double Cf, double Df) {\n return exp(-t\/tau)*(cosh(dGamma*t\/2.)+Df*sinh(dGamma*t\/2.)+d*Cf*cos(dm*t)-d*Sf*sin(dm*t));\n}\n \ndouble BCPV_PDF_Envelope(double t, double gamma_min, double Sf, double Cf, double Df) {\n return exp(-t*gamma_min)*(1.+std::abs(Df)+sqrt(Sf*Sf+Cf*Cf));\n}\n\nbool GenerateResolSingleGauss(TRandom& rndm, double par_bias, double par_sigma, double obs_true, double& obs_meas) {\n obs_meas = obs_true;\n obs_meas += rndm.Gaus(par_bias, par_sigma);\n \n return true;\n}\n\nbool GenerateResolSingleGaussPerEvent(TRandom& rndm, double par_bias, double par_scale, double obs_per_event_error, double obs_true, double& obs_meas) {\n obs_meas = obs_true;\n obs_meas += rndm.Gaus(par_bias, par_scale*obs_per_event_error);\n \n return true;\n}\n\n\nbool GenerateEtaFlat(TRandom& rndm, double& obs_eta) {\n return GenerateEtaFlat(rndm,0.0,0.5,obs_eta);\n}\n\nbool GenerateEtaFlat(TRandom& rndm, double obs_eta_min, double obs_eta_max, double& obs_eta) {\n obs_eta = rndm.Uniform(obs_eta_min,obs_eta_max);\n return true;\n}\n\nbool GenerateEtaGauss(TRandom& rndm, double m, double s, double obs_eta_min, double obs_eta_max, double& obs_eta) {\n unsigned int num_samples(0);\n\n \/\/ s is set to -1.0 on default; a negative Gaussian width does not make sense, thus generate a uniform distribution\n if (s < 0.0) {\n obs_eta = rndm.Uniform(obs_eta_min,obs_eta_max);\n return true;\n } else {\n obs_eta = rndm.Gaus(m,s);\n ++num_samples;\n\n while (obs_eta > obs_eta_max || obs_eta < obs_eta_min) {\n obs_eta = rndm.Gaus(m,s);\n ++num_samples;\n\n if (num_samples % 1000 == 0) {\n std::cout << \"WARNING in cptoymc::generator::GenerateEtaGauss(rndm, m=\" << m << \", s=\" << s << \", obs_eta_min=\" << obs_eta_min << \", obs_eta_max=\" << obs_eta_max << \"): Generated \" << num_samples << \" sample values without one candidate passing. You probably want to check your parameters.\" << std::endl;\n }\n }\n\n return true;\n }\n}\n\nbool GenerateTag(TRandom& rndm, double par_omega, double par_domega,\n const int par_tag_true_B, const int par_tag_true_Bb,\n const int par_tag_B, const int par_tag_Bb,\n int obs_tag_true, int& obs_tag_meas) {\n \/\/if (par_omega > 0.5) par_omega = 0.5;\n if (par_omega < 0.0) par_omega = 0.;\n \n int correct_tag = 0;\n \n \/\/ always assume that omega_B = omega + dOmega\/2 for true B mesons\n \/\/ and that omega_Bb = omega - dOmega\/2 for true Bb mesons\n if (obs_tag_true == par_tag_true_B) {\n par_omega += par_domega\/2.; \/\/ B meson case\n correct_tag = par_tag_B;\n }\n else if (obs_tag_true == par_tag_true_Bb) {\n par_omega -= par_domega\/2.; \/\/ Bb meson case\n correct_tag = par_tag_Bb;\n } else {\n std::cout << \"Cannot interpret true tag of \" << obs_tag_true << \". Failed.\" << std::endl;\n return false;\n }\n \n if (rndm.Uniform() < par_omega) {\n obs_tag_meas = -1*correct_tag;\n } else {\n obs_tag_meas = correct_tag;\n }\n return true;\n}\n\n \nbool GenerateTag(TRandom& rndm, double par_omega, double par_domega, int obs_tag_true, int& obs_tag_meas) {\n return GenerateTag(rndm, par_omega, par_domega, +1, -1, +1, -1, obs_tag_true, obs_tag_meas);\n}\n\nbool GenerateTag(TRandom& rndm,\n std::function& func_omega,\n std::function& func_domega,\n const int par_tag_true_B, const int par_tag_true_Bb,\n const int par_tag_B, const int par_tag_Bb,\n int obs_tag_true, double obs_eta, int& obs_tag_meas) {\n return GenerateTag(rndm, func_omega(obs_eta), func_domega(obs_eta),\n par_tag_true_B, par_tag_true_Bb, par_tag_B, par_tag_Bb,\n obs_tag_true, obs_tag_meas);\n}\n \nbool GenerateRandomTag(TRandom& rndm, int& obs_tag_meas) {\n obs_tag_meas = (rndm.Uniform() < 0.5) ? +1 : -1;\n return true;\n}\n\n\n\n\nint yieldToGenerate(TRandom& rndm, double yield_exp) {\n return rndm.Poisson(yield_exp);\n}\n\n\n} \/\/ namespace cptoymc\n} \/\/ namespace generator\n\n<|endoftext|>"} {"text":"#include \"command.hh\"\n#include \"globals.hh\"\n#include \"eval.hh\"\n#include \"eval-inline.hh\"\n#include \"names.hh\"\n#include \"get-drvs.hh\"\n#include \"common-args.hh\"\n#include \"json.hh\"\n#include \"json-to-value.hh\"\n\n#include \n#include \n\nusing namespace nix;\n\nstd::string hilite(const std::string & s, const std::smatch & m)\n{\n return\n m.empty()\n ? s\n : std::string(m.prefix())\n + ANSI_RED + std::string(m.str()) + ANSI_NORMAL\n + std::string(m.suffix());\n}\n\nstruct CmdSearch : SourceExprCommand, MixJSON\n{\n std::string re;\n\n bool writeCache = true;\n bool useCache = true;\n\n CmdSearch()\n {\n expectArg(\"regex\", &re, true);\n\n mkFlag()\n .longName(\"update-cache\")\n .shortName('u')\n .description(\"update the package search cache\")\n .handler([&](Strings ss) { writeCache = true; useCache = false; });\n\n mkFlag()\n .longName(\"no-cache\")\n .description(\"do not use or update the package search cache\")\n .handler([&](Strings ss) { writeCache = false; useCache = false; });\n }\n\n std::string name() override\n {\n return \"search\";\n }\n\n std::string description() override\n {\n return \"query available packages\";\n }\n\n void run(ref store) override\n {\n settings.readOnlyMode = true;\n\n std::regex regex(re, std::regex::extended | std::regex::icase);\n\n auto state = getEvalState();\n\n bool first = true;\n\n auto jsonOut = json ? std::make_unique(std::cout, true) : nullptr;\n\n auto sToplevel = state->symbols.create(\"_toplevel\");\n auto sRecurse = state->symbols.create(\"recurseForDerivations\");\n\n bool fromCache = false;\n\n std::function doExpr;\n\n doExpr = [&](Value * v, std::string attrPath, bool toplevel, JSONObject * cache) {\n debug(\"at attribute '%s'\", attrPath);\n\n try {\n\n state->forceValue(*v);\n\n if (v->type == tLambda && toplevel) {\n Value * v2 = state->allocValue();\n state->autoCallFunction(*state->allocBindings(1), *v, *v2);\n v = v2;\n state->forceValue(*v);\n }\n\n if (state->isDerivation(*v)) {\n\n DrvInfo drv(*state, attrPath, v->attrs);\n\n DrvName parsed(drv.queryName());\n\n std::smatch attrPathMatch;\n std::regex_search(attrPath, attrPathMatch, regex);\n\n auto name = parsed.name;\n std::smatch nameMatch;\n std::regex_search(name, nameMatch, regex);\n\n std::string description = drv.queryMetaString(\"description\");\n std::replace(description.begin(), description.end(), '\\n', ' ');\n std::smatch descriptionMatch;\n std::regex_search(description, descriptionMatch, regex);\n\n if (!attrPathMatch.empty()\n || !nameMatch.empty()\n || !descriptionMatch.empty())\n {\n if (json) {\n\n auto jsonElem = jsonOut->object(attrPath);\n\n jsonElem.attr(\"pkgName\", parsed.name);\n jsonElem.attr(\"version\", parsed.version);\n jsonElem.attr(\"description\", description);\n\n } else {\n if (!first) std::cout << \"\\n\";\n first = false;\n\n std::cout << fmt(\n \"Attribute name: %s\\n\"\n \"Package name: %s\\n\"\n \"Version: %s\\n\"\n \"Description: %s\\n\",\n hilite(attrPath, attrPathMatch),\n hilite(name, nameMatch),\n parsed.version,\n hilite(description, descriptionMatch));\n }\n }\n\n if (cache) {\n cache->attr(\"type\", \"derivation\");\n cache->attr(\"name\", drv.queryName());\n cache->attr(\"system\", drv.querySystem());\n if (description != \"\") {\n auto meta(cache->object(\"meta\"));\n meta.attr(\"description\", description);\n }\n }\n }\n\n else if (v->type == tAttrs) {\n\n if (!toplevel) {\n auto attrs = v->attrs;\n Bindings::iterator j = attrs->find(sRecurse);\n if (j == attrs->end() || !state->forceBool(*j->value, *j->pos)) {\n debug(\"skip attribute '%s'\", attrPath);\n return;\n }\n }\n\n bool toplevel2 = false;\n if (!fromCache) {\n Bindings::iterator j = v->attrs->find(sToplevel);\n toplevel2 = j != v->attrs->end() && state->forceBool(*j->value, *j->pos);\n }\n\n for (auto & i : *v->attrs) {\n auto cache2 =\n cache ? std::make_unique(cache->object(i.name)) : nullptr;\n doExpr(i.value,\n attrPath == \"\" ? (std::string) i.name : attrPath + \".\" + (std::string) i.name,\n toplevel2 || fromCache, cache2 ? cache2.get() : nullptr);\n }\n }\n\n } catch (AssertionError & e) {\n } catch (Error & e) {\n if (!toplevel) {\n e.addPrefix(fmt(\"While evaluating the attribute '%s':\\n\", attrPath));\n throw;\n }\n }\n };\n\n Path jsonCacheFileName = getCacheDir() + \"\/nix\/package-search.json\";\n\n if (useCache && pathExists(jsonCacheFileName)) {\n\n warn(\"using cached results; pass '-u' to update the cache\");\n\n Value vRoot;\n parseJSON(*state, readFile(jsonCacheFileName), vRoot);\n\n fromCache = true;\n\n doExpr(&vRoot, \"\", true, nullptr);\n }\n\n else {\n Path tmpFile = fmt(\"%s.tmp.%d\", jsonCacheFileName, getpid());\n\n std::ofstream jsonCacheFile(tmpFile);\n\n auto cache = writeCache ? std::make_unique(jsonCacheFile, false) : nullptr;\n\n doExpr(getSourceExpr(*state), \"\", true, cache.get());\n\n if (rename(tmpFile.c_str(), jsonCacheFileName.c_str()) == -1)\n throw SysError(\"cannot rename '%s' to '%s'\", tmpFile, jsonCacheFileName);\n }\n }\n};\n\nstatic RegisterCommand r1(make_ref());\nnix search: Add examples#include \"command.hh\"\n#include \"globals.hh\"\n#include \"eval.hh\"\n#include \"eval-inline.hh\"\n#include \"names.hh\"\n#include \"get-drvs.hh\"\n#include \"common-args.hh\"\n#include \"json.hh\"\n#include \"json-to-value.hh\"\n\n#include \n#include \n\nusing namespace nix;\n\nstd::string hilite(const std::string & s, const std::smatch & m)\n{\n return\n m.empty()\n ? s\n : std::string(m.prefix())\n + ANSI_RED + std::string(m.str()) + ANSI_NORMAL\n + std::string(m.suffix());\n}\n\nstruct CmdSearch : SourceExprCommand, MixJSON\n{\n std::string re;\n\n bool writeCache = true;\n bool useCache = true;\n\n CmdSearch()\n {\n expectArg(\"regex\", &re, true);\n\n mkFlag()\n .longName(\"update-cache\")\n .shortName('u')\n .description(\"update the package search cache\")\n .handler([&](Strings ss) { writeCache = true; useCache = false; });\n\n mkFlag()\n .longName(\"no-cache\")\n .description(\"do not use or update the package search cache\")\n .handler([&](Strings ss) { writeCache = false; useCache = false; });\n }\n\n std::string name() override\n {\n return \"search\";\n }\n\n std::string description() override\n {\n return \"query available packages\";\n }\n\n Examples examples() override\n {\n return {\n Example{\n \"To show all available packages:\",\n \"nix search\"\n },\n Example{\n \"To show any packages containing 'blender' in its name or description:\",\n \"nix search blender\"\n },\n Example{\n \"To search for Firefox and Chromium:\",\n \"nix search 'firefox|chromium'\"\n },\n };\n }\n\n void run(ref store) override\n {\n settings.readOnlyMode = true;\n\n std::regex regex(re, std::regex::extended | std::regex::icase);\n\n auto state = getEvalState();\n\n bool first = true;\n\n auto jsonOut = json ? std::make_unique(std::cout, true) : nullptr;\n\n auto sToplevel = state->symbols.create(\"_toplevel\");\n auto sRecurse = state->symbols.create(\"recurseForDerivations\");\n\n bool fromCache = false;\n\n std::function doExpr;\n\n doExpr = [&](Value * v, std::string attrPath, bool toplevel, JSONObject * cache) {\n debug(\"at attribute '%s'\", attrPath);\n\n try {\n\n state->forceValue(*v);\n\n if (v->type == tLambda && toplevel) {\n Value * v2 = state->allocValue();\n state->autoCallFunction(*state->allocBindings(1), *v, *v2);\n v = v2;\n state->forceValue(*v);\n }\n\n if (state->isDerivation(*v)) {\n\n DrvInfo drv(*state, attrPath, v->attrs);\n\n DrvName parsed(drv.queryName());\n\n std::smatch attrPathMatch;\n std::regex_search(attrPath, attrPathMatch, regex);\n\n auto name = parsed.name;\n std::smatch nameMatch;\n std::regex_search(name, nameMatch, regex);\n\n std::string description = drv.queryMetaString(\"description\");\n std::replace(description.begin(), description.end(), '\\n', ' ');\n std::smatch descriptionMatch;\n std::regex_search(description, descriptionMatch, regex);\n\n if (!attrPathMatch.empty()\n || !nameMatch.empty()\n || !descriptionMatch.empty())\n {\n if (json) {\n\n auto jsonElem = jsonOut->object(attrPath);\n\n jsonElem.attr(\"pkgName\", parsed.name);\n jsonElem.attr(\"version\", parsed.version);\n jsonElem.attr(\"description\", description);\n\n } else {\n if (!first) std::cout << \"\\n\";\n first = false;\n\n std::cout << fmt(\n \"Attribute name: %s\\n\"\n \"Package name: %s\\n\"\n \"Version: %s\\n\"\n \"Description: %s\\n\",\n hilite(attrPath, attrPathMatch),\n hilite(name, nameMatch),\n parsed.version,\n hilite(description, descriptionMatch));\n }\n }\n\n if (cache) {\n cache->attr(\"type\", \"derivation\");\n cache->attr(\"name\", drv.queryName());\n cache->attr(\"system\", drv.querySystem());\n if (description != \"\") {\n auto meta(cache->object(\"meta\"));\n meta.attr(\"description\", description);\n }\n }\n }\n\n else if (v->type == tAttrs) {\n\n if (!toplevel) {\n auto attrs = v->attrs;\n Bindings::iterator j = attrs->find(sRecurse);\n if (j == attrs->end() || !state->forceBool(*j->value, *j->pos)) {\n debug(\"skip attribute '%s'\", attrPath);\n return;\n }\n }\n\n bool toplevel2 = false;\n if (!fromCache) {\n Bindings::iterator j = v->attrs->find(sToplevel);\n toplevel2 = j != v->attrs->end() && state->forceBool(*j->value, *j->pos);\n }\n\n for (auto & i : *v->attrs) {\n auto cache2 =\n cache ? std::make_unique(cache->object(i.name)) : nullptr;\n doExpr(i.value,\n attrPath == \"\" ? (std::string) i.name : attrPath + \".\" + (std::string) i.name,\n toplevel2 || fromCache, cache2 ? cache2.get() : nullptr);\n }\n }\n\n } catch (AssertionError & e) {\n } catch (Error & e) {\n if (!toplevel) {\n e.addPrefix(fmt(\"While evaluating the attribute '%s':\\n\", attrPath));\n throw;\n }\n }\n };\n\n Path jsonCacheFileName = getCacheDir() + \"\/nix\/package-search.json\";\n\n if (useCache && pathExists(jsonCacheFileName)) {\n\n warn(\"using cached results; pass '-u' to update the cache\");\n\n Value vRoot;\n parseJSON(*state, readFile(jsonCacheFileName), vRoot);\n\n fromCache = true;\n\n doExpr(&vRoot, \"\", true, nullptr);\n }\n\n else {\n Path tmpFile = fmt(\"%s.tmp.%d\", jsonCacheFileName, getpid());\n\n std::ofstream jsonCacheFile(tmpFile);\n\n auto cache = writeCache ? std::make_unique(jsonCacheFile, false) : nullptr;\n\n doExpr(getSourceExpr(*state), \"\", true, cache.get());\n\n if (rename(tmpFile.c_str(), jsonCacheFileName.c_str()) == -1)\n throw SysError(\"cannot rename '%s' to '%s'\", tmpFile, jsonCacheFileName);\n }\n }\n};\n\nstatic RegisterCommand r1(make_ref());\n<|endoftext|>"} {"text":"#if HAVE_CONFIG_H\n#include \n#endif\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"input-driver-test.h\"\n#include \"device-interface.h\"\n#include \"helpers.h\"\n\n#define NUM_ELEMS_MATRIX 9\n\/\/ Intuos5 maxX=44704 maxY=27940 maxZ=2047 resX=200000 resY=200000 tilt=enabled\n#define MAX_X 44704\n#define MAX_Y 27940\n\ntypedef struct Matrix {\n float elem[NUM_ELEMS_MATRIX];\n} Matrix;\n\n\/**\n * Wacom driver test class. This class takes a struct Tablet that defines\n * which device should be initialised.\n *\/\nclass WacomMatrixTest : public InputDriverTest,\n public DeviceInterface {\npublic:\n \/**\n * Initializes a standard tablet device.\n *\/\n virtual void SetUp() {\n SetDevice(\"tablets\/Wacom-Intuos5-touch-M-Pen.desc\");\n InputDriverTest::SetUp();\n }\n\n \/**\n * Sets up an xorg.conf for a single mouse CorePointer device based on\n * the evemu device.\n *\/\n virtual void SetUpConfigAndLog(const std::string ¶m) {\n server.SetOption(\"-logfile\", \"\/tmp\/Xorg-wacom-matrix-test.log\");\n server.SetOption(\"-config\", \"\/tmp\/wacom-matrix-test.conf\");\n\n config.AddDefaultScreenWithDriver();\n config.AddInputSection(\"wacom\", \"Stylus\",\n \"Option \\\"CorePointer\\\" \\\"on\\\"\\n\"\n \"Option \\\"Type\\\" \\\"stylus\\\"\\n\"\n \"Option \\\"Device\\\" \\\"\" + dev->GetDeviceNode() + \"\\\"\\n\");\n\n config.WriteConfig(\"\/tmp\/wacom-matrix-test.conf\");\n }\nprotected:\n int xrandr_event, xrandr_error;\n};\n\nTEST_F(WacomMatrixTest, DevicePresent)\n{\n SCOPED_TRACE(\"Test presence of tools as defined in the xorg.conf\");\n\n int ndevices;\n XIDeviceInfo *info;\n\n info = XIQueryDevice(Display(), XIAllDevices, &ndevices);\n\n bool found = false;\n while(ndevices--) {\n if (strcmp(info[ndevices].name, \"Stylus\") == 0) {\n ASSERT_EQ(found, false) << \"Duplicate device\" << std::endl;\n found = true;\n }\n }\n ASSERT_EQ(found, true);\n XIFreeDeviceInfo(info);\n}\n\nbool set_input_matrix (Display *dpy, int deviceid, Matrix *matrix)\n{\n Atom prop_float, prop_matrix;\n\n union {\n unsigned char *c;\n float *f;\n } data;\n int format_return;\n Atom type_return;\n unsigned long nitems;\n unsigned long bytes_after;\n int rc;\n\n prop_float = XInternAtom(dpy, \"FLOAT\", False);\n prop_matrix = XInternAtom(dpy, XI_PROP_TRANSFORM, False);\n\n if (!prop_float)\n return False;\n\n if (!prop_matrix)\n return False;\n\n rc = XIGetProperty(dpy, deviceid, prop_matrix, 0, 9, False, prop_float,\n &type_return, &format_return, &nitems, &bytes_after,\n &data.c);\n\n if (rc != Success || prop_float != type_return || format_return != 32 ||\n nitems != NUM_ELEMS_MATRIX || bytes_after != 0)\n return False;\n\n memcpy(data.f, matrix->elem, sizeof(matrix->elem));\n\n XIChangeProperty(dpy, deviceid, prop_matrix, prop_float,\n format_return, PropModeReplace, data.c, nitems);\n\n XFree(data.c);\n\n return True;\n}\n\n\/**\n * compute the input trarnsformation matrix to match the area specified\n * by the given (x,y) width x height.\n *\/\nBool compute_input_matrix (Display *dpy, int x, int y, int width, int height, Matrix *matrix)\n{\n \/\/ Reset matrix to no transformation by default\n matrix->elem[0] = 1.0f;\n matrix->elem[1] = 0.0f;\n matrix->elem[2] = 0.0f;\n matrix->elem[3] = 0.0f;\n matrix->elem[4] = 1.0f;\n matrix->elem[5] = 0.0f;\n matrix->elem[6] = 0.0f;\n matrix->elem[7] = 0.0f;\n matrix->elem[8] = 1.0f;\n\n int screen_x = 0;\n int screen_y = 0;\n int screen_width = WidthOfScreen (DefaultScreenOfDisplay (dpy));\n int screen_height = HeightOfScreen (DefaultScreenOfDisplay (dpy));\n\n if ((x < screen_x) ||\n (y < screen_y) ||\n (x + width > screen_x + screen_width) ||\n (y + height > screen_y + screen_height))\n return False;\n\n float x_scale = (float) x \/ screen_width;\n float y_scale = (float) y \/ screen_height;\n float width_scale = (float) width \/ screen_width;\n float height_scale = (float) height \/ screen_height;\n\n matrix->elem[0] = width_scale;\n matrix->elem[1] = 0.0f;\n matrix->elem[2] = x_scale;\n\n matrix->elem[3] = 0.0f;\n matrix->elem[4] = height_scale;\n matrix->elem[5] = y_scale;\n\n matrix->elem[6] = 0.0f;\n matrix->elem[7] = 0.0f;\n matrix->elem[8] = 1.0f;\n\n return True;\n}\n\n\/**\n * Moves the stylus from positon (x, y) by n steps in the\n * direction (code) ABS_X or ABS_Y.\n *\/\nvoid move_stylus (xorg::testing::evemu::Device *dev,\n int x, int y, int steps, int code)\n{\n int i;\n\n \/\/ Move to device coord (x, y)\n dev->PlayOne(EV_ABS, ABS_X, x, True);\n dev->PlayOne(EV_ABS, ABS_Y, y, True);\n dev->PlayOne(EV_ABS, ABS_DISTANCE, 0, True);\n dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 1, True);\n\n for (i = 0; i < steps; i++) {\n if (code == ABS_X)\n dev->PlayOne(EV_ABS, ABS_X, x + i, True);\n else\n dev->PlayOne(EV_ABS, ABS_Y, y + i, True);\n\n dev->PlayOne(EV_ABS, ABS_DISTANCE, i, True);\n }\n dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 0, True);\n}\n\nvoid test_area (Display *dpy, xorg::testing::evemu::Device *dev,\n int deviceid, int x, int y, int width, int height)\n{\n XEvent ev;\n\n Matrix matrix;\n compute_input_matrix (dpy, x, y, width, height, &matrix);\n ASSERT_TRUE (set_input_matrix (dpy, deviceid, &matrix));\n\n XSync(dpy, False);\n while(XPending(dpy))\n XNextEvent(dpy, &ev);\n\n \/\/ Simulate stylus movement for the entire tablet resolution\n move_stylus (dev, 0, 0, MAX_X, ABS_X);\n move_stylus (dev, MAX_X, 0, MAX_Y, ABS_Y);\n move_stylus (dev, 0, 0, MAX_Y, ABS_Y);\n move_stylus (dev, 0, MAX_Y, MAX_X, ABS_X);\n\n XSync (dpy, False);\n EXPECT_NE(XPending(dpy), 0) << \"No event received??\" << std::endl;\n\n \/\/ Capture motion events and check they remain within the mapped area\n XSync (dpy, False);\n while(XCheckMaskEvent (dpy, PointerMotionMask, &ev)) {\n EXPECT_TRUE (ev.xmotion.x_root >= x);\n EXPECT_TRUE (ev.xmotion.x_root < x + width);\n EXPECT_TRUE (ev.xmotion.y_root >= y);\n EXPECT_TRUE (ev.xmotion.y_root < y + height);\n }\n\n while(XPending(dpy))\n XNextEvent(dpy, &ev);\n}\n\nTEST_F(WacomMatrixTest, InputMatrix)\n{\n SCOPED_TRACE(\"Test input transformation matrix\");\n\n \/* the server takes a while to start up but the devices may not respond\n to events yet. Add a noop call that just delays everything long\n enough for this test to work *\/\n XInternAtom(Display(), \"foo\", True);\n XFlush(Display());\n\n int major = 2;\n int minor = 0;\n ASSERT_EQ(Success, XIQueryVersion(Display(), &major, &minor));\n\n EXPECT_TRUE(InitRandRSupport(Display(), &xrandr_event, &xrandr_error));\n\n int monitor_x, monitor_y, monitor_width, monitor_height;\n int n_monitors = GetNMonitors (Display());\n\n monitor_x = 0;\n monitor_y = 0;\n monitor_width = WidthOfScreen (DefaultScreenOfDisplay (Display()));\n monitor_height = HeightOfScreen (DefaultScreenOfDisplay (Display()));\n\n if (n_monitors > 0)\n GetMonitorGeometry (Display(), 0, &monitor_x, &monitor_y, &monitor_width, &monitor_height);\n\n int deviceid;\n FindInputDeviceByName(Display(), \"Stylus\", &deviceid);\n ASSERT_NE (deviceid, 0);\n\n XSelectInput(Display(), DefaultRootWindow(Display()), PointerMotionMask |\n ButtonMotionMask);\n XSync(Display(), False);\n\n \/\/ Check with upper right quarter\n test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y, monitor_width \/ 2, monitor_height \/ 2);\n\n \/\/ Check with upper left quarter\n test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width \/ 2, monitor_y, monitor_width \/ 2, monitor_height \/ 2);\n\n \/\/ Check with bottom right quarter\n test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y + monitor_height \/ 2, monitor_width \/ 2, monitor_height \/ 2);\n\n \/\/ Check with bottom left quarter\n test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width \/ 2, monitor_y + monitor_height \/ 2, monitor_width \/ 2, monitor_height \/ 2);\n}\ninput\/wacom: use EXPECT_GT, etc. instead of EXPECT_TRUE#if HAVE_CONFIG_H\n#include \n#endif\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"input-driver-test.h\"\n#include \"device-interface.h\"\n#include \"helpers.h\"\n\n#define NUM_ELEMS_MATRIX 9\n\/\/ Intuos5 maxX=44704 maxY=27940 maxZ=2047 resX=200000 resY=200000 tilt=enabled\n#define MAX_X 44704\n#define MAX_Y 27940\n\ntypedef struct Matrix {\n float elem[NUM_ELEMS_MATRIX];\n} Matrix;\n\n\/**\n * Wacom driver test class. This class takes a struct Tablet that defines\n * which device should be initialised.\n *\/\nclass WacomMatrixTest : public InputDriverTest,\n public DeviceInterface {\npublic:\n \/**\n * Initializes a standard tablet device.\n *\/\n virtual void SetUp() {\n SetDevice(\"tablets\/Wacom-Intuos5-touch-M-Pen.desc\");\n InputDriverTest::SetUp();\n }\n\n \/**\n * Sets up an xorg.conf for a single mouse CorePointer device based on\n * the evemu device.\n *\/\n virtual void SetUpConfigAndLog(const std::string ¶m) {\n server.SetOption(\"-logfile\", \"\/tmp\/Xorg-wacom-matrix-test.log\");\n server.SetOption(\"-config\", \"\/tmp\/wacom-matrix-test.conf\");\n\n config.AddDefaultScreenWithDriver();\n config.AddInputSection(\"wacom\", \"Stylus\",\n \"Option \\\"CorePointer\\\" \\\"on\\\"\\n\"\n \"Option \\\"Type\\\" \\\"stylus\\\"\\n\"\n \"Option \\\"Device\\\" \\\"\" + dev->GetDeviceNode() + \"\\\"\\n\");\n\n config.WriteConfig(\"\/tmp\/wacom-matrix-test.conf\");\n }\nprotected:\n int xrandr_event, xrandr_error;\n};\n\nTEST_F(WacomMatrixTest, DevicePresent)\n{\n SCOPED_TRACE(\"Test presence of tools as defined in the xorg.conf\");\n\n int ndevices;\n XIDeviceInfo *info;\n\n info = XIQueryDevice(Display(), XIAllDevices, &ndevices);\n\n bool found = false;\n while(ndevices--) {\n if (strcmp(info[ndevices].name, \"Stylus\") == 0) {\n ASSERT_EQ(found, false) << \"Duplicate device\" << std::endl;\n found = true;\n }\n }\n ASSERT_EQ(found, true);\n XIFreeDeviceInfo(info);\n}\n\nbool set_input_matrix (Display *dpy, int deviceid, Matrix *matrix)\n{\n Atom prop_float, prop_matrix;\n\n union {\n unsigned char *c;\n float *f;\n } data;\n int format_return;\n Atom type_return;\n unsigned long nitems;\n unsigned long bytes_after;\n int rc;\n\n prop_float = XInternAtom(dpy, \"FLOAT\", False);\n prop_matrix = XInternAtom(dpy, XI_PROP_TRANSFORM, False);\n\n if (!prop_float)\n return False;\n\n if (!prop_matrix)\n return False;\n\n rc = XIGetProperty(dpy, deviceid, prop_matrix, 0, 9, False, prop_float,\n &type_return, &format_return, &nitems, &bytes_after,\n &data.c);\n\n if (rc != Success || prop_float != type_return || format_return != 32 ||\n nitems != NUM_ELEMS_MATRIX || bytes_after != 0)\n return False;\n\n memcpy(data.f, matrix->elem, sizeof(matrix->elem));\n\n XIChangeProperty(dpy, deviceid, prop_matrix, prop_float,\n format_return, PropModeReplace, data.c, nitems);\n\n XFree(data.c);\n\n return True;\n}\n\n\/**\n * compute the input trarnsformation matrix to match the area specified\n * by the given (x,y) width x height.\n *\/\nBool compute_input_matrix (Display *dpy, int x, int y, int width, int height, Matrix *matrix)\n{\n \/\/ Reset matrix to no transformation by default\n matrix->elem[0] = 1.0f;\n matrix->elem[1] = 0.0f;\n matrix->elem[2] = 0.0f;\n matrix->elem[3] = 0.0f;\n matrix->elem[4] = 1.0f;\n matrix->elem[5] = 0.0f;\n matrix->elem[6] = 0.0f;\n matrix->elem[7] = 0.0f;\n matrix->elem[8] = 1.0f;\n\n int screen_x = 0;\n int screen_y = 0;\n int screen_width = WidthOfScreen (DefaultScreenOfDisplay (dpy));\n int screen_height = HeightOfScreen (DefaultScreenOfDisplay (dpy));\n\n if ((x < screen_x) ||\n (y < screen_y) ||\n (x + width > screen_x + screen_width) ||\n (y + height > screen_y + screen_height))\n return False;\n\n float x_scale = (float) x \/ screen_width;\n float y_scale = (float) y \/ screen_height;\n float width_scale = (float) width \/ screen_width;\n float height_scale = (float) height \/ screen_height;\n\n matrix->elem[0] = width_scale;\n matrix->elem[1] = 0.0f;\n matrix->elem[2] = x_scale;\n\n matrix->elem[3] = 0.0f;\n matrix->elem[4] = height_scale;\n matrix->elem[5] = y_scale;\n\n matrix->elem[6] = 0.0f;\n matrix->elem[7] = 0.0f;\n matrix->elem[8] = 1.0f;\n\n return True;\n}\n\n\/**\n * Moves the stylus from positon (x, y) by n steps in the\n * direction (code) ABS_X or ABS_Y.\n *\/\nvoid move_stylus (xorg::testing::evemu::Device *dev,\n int x, int y, int steps, int code)\n{\n int i;\n\n \/\/ Move to device coord (x, y)\n dev->PlayOne(EV_ABS, ABS_X, x, True);\n dev->PlayOne(EV_ABS, ABS_Y, y, True);\n dev->PlayOne(EV_ABS, ABS_DISTANCE, 0, True);\n dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 1, True);\n\n for (i = 0; i < steps; i++) {\n if (code == ABS_X)\n dev->PlayOne(EV_ABS, ABS_X, x + i, True);\n else\n dev->PlayOne(EV_ABS, ABS_Y, y + i, True);\n\n dev->PlayOne(EV_ABS, ABS_DISTANCE, i, True);\n }\n dev->PlayOne(EV_KEY, BTN_TOOL_PEN, 0, True);\n}\n\nvoid test_area (Display *dpy, xorg::testing::evemu::Device *dev,\n int deviceid, int x, int y, int width, int height)\n{\n XEvent ev;\n\n Matrix matrix;\n compute_input_matrix (dpy, x, y, width, height, &matrix);\n ASSERT_TRUE (set_input_matrix (dpy, deviceid, &matrix));\n\n XSync(dpy, False);\n while(XPending(dpy))\n XNextEvent(dpy, &ev);\n\n \/\/ Simulate stylus movement for the entire tablet resolution\n move_stylus (dev, 0, 0, MAX_X, ABS_X);\n move_stylus (dev, MAX_X, 0, MAX_Y, ABS_Y);\n move_stylus (dev, 0, 0, MAX_Y, ABS_Y);\n move_stylus (dev, 0, MAX_Y, MAX_X, ABS_X);\n\n XSync (dpy, False);\n EXPECT_NE(XPending(dpy), 0) << \"No event received??\" << std::endl;\n\n \/\/ Capture motion events and check they remain within the mapped area\n XSync (dpy, False);\n while(XCheckMaskEvent (dpy, PointerMotionMask, &ev)) {\n EXPECT_GE (ev.xmotion.x_root, x);\n EXPECT_LT (ev.xmotion.x_root, x + width);\n EXPECT_GE (ev.xmotion.y_root, y);\n EXPECT_LE (ev.xmotion.y_root, y + height);\n }\n\n while(XPending(dpy))\n XNextEvent(dpy, &ev);\n}\n\nTEST_F(WacomMatrixTest, InputMatrix)\n{\n SCOPED_TRACE(\"Test input transformation matrix\");\n\n \/* the server takes a while to start up but the devices may not respond\n to events yet. Add a noop call that just delays everything long\n enough for this test to work *\/\n XInternAtom(Display(), \"foo\", True);\n XFlush(Display());\n\n int major = 2;\n int minor = 0;\n ASSERT_EQ(Success, XIQueryVersion(Display(), &major, &minor));\n\n EXPECT_TRUE(InitRandRSupport(Display(), &xrandr_event, &xrandr_error));\n\n int monitor_x, monitor_y, monitor_width, monitor_height;\n int n_monitors = GetNMonitors (Display());\n\n monitor_x = 0;\n monitor_y = 0;\n monitor_width = WidthOfScreen (DefaultScreenOfDisplay (Display()));\n monitor_height = HeightOfScreen (DefaultScreenOfDisplay (Display()));\n\n if (n_monitors > 0)\n GetMonitorGeometry (Display(), 0, &monitor_x, &monitor_y, &monitor_width, &monitor_height);\n\n int deviceid;\n FindInputDeviceByName(Display(), \"Stylus\", &deviceid);\n ASSERT_NE (deviceid, 0);\n\n XSelectInput(Display(), DefaultRootWindow(Display()), PointerMotionMask |\n ButtonMotionMask);\n XSync(Display(), False);\n\n \/\/ Check with upper right quarter\n test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y, monitor_width \/ 2, monitor_height \/ 2);\n\n \/\/ Check with upper left quarter\n test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width \/ 2, monitor_y, monitor_width \/ 2, monitor_height \/ 2);\n\n \/\/ Check with bottom right quarter\n test_area (Display(), dev.get(), deviceid, monitor_x, monitor_y + monitor_height \/ 2, monitor_width \/ 2, monitor_height \/ 2);\n\n \/\/ Check with bottom left quarter\n test_area (Display(), dev.get(), deviceid, monitor_x + monitor_width \/ 2, monitor_y + monitor_height \/ 2, monitor_width \/ 2, monitor_height \/ 2);\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * VLC backend for the Phonon library *\n * Copyright (C) 2007-2008 Tanguy Krotoff *\n * Copyright (C) 2008 Lukas Durfina *\n * Copyright (C) 2009 Fathi Boudra *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 3 of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this package; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *\n *****************************************************************************\/\n\n#include \"audiooutput.h\"\n#include \"devicemanager.h\"\n#include \"backend.h\"\n\n#include \"mediaobject.h\"\n#include \"vlcmediaobject.h\"\n\n#include \"vlcloader.h\"\n\n#ifdef PHONON_PULSESUPPORT\n# include \n#endif\n\nnamespace Phonon\n{\nnamespace VLC {\n\nAudioOutput::AudioOutput(Backend *p_back, QObject * p_parent)\n : SinkNode(p_parent),\n f_volume(1.0),\n i_device(0),\n p_backend(p_back)\n{\n p_media_object = 0;\n}\n\nAudioOutput::~AudioOutput()\n{\n}\n\nqreal AudioOutput::volume() const\n{\n return f_volume;\n}\n\nvoid AudioOutput::setVolume(qreal volume)\n{\n if (vlc_current_media_player) {\n libvlc_audio_set_volume(vlc_current_media_player, (int)(f_volume * 100));\n f_volume = volume;\n emit volumeChanged(f_volume);\n }\n}\n\nint AudioOutput::outputDevice() const\n{\n return i_device;\n}\n\nbool AudioOutput::setOutputDevice(int device)\n{\n if (i_device == device)\n return true;\n\n#ifdef PHONON_PULSESUPPORT\n if (PulseSupport::getInstance()->isActive()) {\n i_device = device;\n libvlc_audio_output_set(vlc_current_media_player, \"pulse\");\n qDebug() << \"set aout \" << \"pulse\";\n return true;\n }\n#endif\n\n const QList deviceList = p_backend->deviceManager()->audioOutputDevices();\n if (device >= 0 && device < deviceList.size()) {\n\n i_device = device;\n const QByteArray deviceName = deviceList.at(device).vlcId;\n libvlc_audio_output_set(vlc_current_media_player, (char *) deviceList.at(device).vlcId.data());\n qDebug() << \"set aout \" << deviceList.at(device).vlcId.data();\n\/\/ if (deviceName == DEFAULT_ID) {\n\/\/ libvlc_audio_device_set(p_vlc_instance, DEFAULT, vlc_exception);\n\/\/ vlcExceptionRaised();\n\/\/ } else if (deviceName.startsWith(ALSA_ID)) {\n\/\/ qDebug() << \"setting ALSA \" << deviceList.at(device).hwId.data();\n\/\/ libvlc_audio_device_set(p_vlc_instance, ALSA, vlc_exception);\n\/\/ vlcExceptionRaised();\n\/\/ libvlc_audio_alsa_device_set(p_vlc_instance,\n\/\/ deviceList.at(device).hwId,\n\/\/ vlc_exception);\n\/\/ vlcExceptionRaised();\n }\n\n return true;\n}\n\n#if (PHONON_VERSION >= PHONON_VERSION_CHECK(4, 2, 0))\nbool AudioOutput::setOutputDevice(const Phonon::AudioOutputDevice & device)\n{\n return true;\n}\n#endif\n\n}\n} \/\/ Namespace Phonon::VLC\nWorkaround: Do not crash on NULL mediaplayer.\/*****************************************************************************\n * VLC backend for the Phonon library *\n * Copyright (C) 2007-2008 Tanguy Krotoff *\n * Copyright (C) 2008 Lukas Durfina *\n * Copyright (C) 2009 Fathi Boudra *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 3 of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this package; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *\n *****************************************************************************\/\n\n#include \"audiooutput.h\"\n#include \"devicemanager.h\"\n#include \"backend.h\"\n\n#include \"mediaobject.h\"\n#include \"vlcmediaobject.h\"\n\n#include \"vlcloader.h\"\n\n#ifdef PHONON_PULSESUPPORT\n# include \n#endif\n\nnamespace Phonon\n{\nnamespace VLC {\n\nAudioOutput::AudioOutput(Backend *p_back, QObject * p_parent)\n : SinkNode(p_parent),\n f_volume(1.0),\n i_device(0),\n p_backend(p_back)\n{\n p_media_object = 0;\n}\n\nAudioOutput::~AudioOutput()\n{\n}\n\nqreal AudioOutput::volume() const\n{\n return f_volume;\n}\n\nvoid AudioOutput::setVolume(qreal volume)\n{\n if (vlc_current_media_player) {\n libvlc_audio_set_volume(vlc_current_media_player, (int)(f_volume * 100));\n f_volume = volume;\n emit volumeChanged(f_volume);\n }\n}\n\nint AudioOutput::outputDevice() const\n{\n return i_device;\n}\n\nbool AudioOutput::setOutputDevice(int device)\n{\n if (i_device == device)\n return true;\n\n#ifdef PHONON_PULSESUPPORT\n if (PulseSupport::getInstance()->isActive()) {\n i_device = device;\n libvlc_audio_output_set(vlc_current_media_player, \"pulse\");\n qDebug() << \"set aout \" << \"pulse\";\n return true;\n }\n#endif\n\n const QList deviceList = p_backend->deviceManager()->audioOutputDevices();\n if (device >= 0 && device < deviceList.size()) {\n\n if (!vlc_current_media_player)\n return false;\n i_device = device;\n const QByteArray deviceName = deviceList.at(device).vlcId;\n libvlc_audio_output_set(vlc_current_media_player, (char *) deviceList.at(device).vlcId.data());\n qDebug() << \"set aout \" << deviceList.at(device).vlcId.data();\n\/\/ if (deviceName == DEFAULT_ID) {\n\/\/ libvlc_audio_device_set(p_vlc_instance, DEFAULT, vlc_exception);\n\/\/ vlcExceptionRaised();\n\/\/ } else if (deviceName.startsWith(ALSA_ID)) {\n\/\/ qDebug() << \"setting ALSA \" << deviceList.at(device).hwId.data();\n\/\/ libvlc_audio_device_set(p_vlc_instance, ALSA, vlc_exception);\n\/\/ vlcExceptionRaised();\n\/\/ libvlc_audio_alsa_device_set(p_vlc_instance,\n\/\/ deviceList.at(device).hwId,\n\/\/ vlc_exception);\n\/\/ vlcExceptionRaised();\n }\n\n return true;\n}\n\n#if (PHONON_VERSION >= PHONON_VERSION_CHECK(4, 2, 0))\nbool AudioOutput::setOutputDevice(const Phonon::AudioOutputDevice & device)\n{\n return true;\n}\n#endif\n\n}\n} \/\/ Namespace Phonon::VLC\n<|endoftext|>"} {"text":"#include \"config.h\"\n\n#include \"vm.hpp\"\n#include \"vm\/object_utils.hpp\"\n#include \"objectmemory.hpp\"\n#include \"primitives.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/integer.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/time.hpp\"\n\n#include \"ontology.hpp\"\n\n#include \"util\/time.h\"\n\n#include \n#include \n\n#include \"windows_compat.h\"\n#include \"configuration.hpp\"\n\nnamespace rubinius {\n void Time::init(STATE) {\n GO(time_class).set(ontology::new_class(state, \"Time\", G(object)));\n G(time_class)->set_object_type(state, TimeType);\n }\n\n Time* Time::now(STATE, Object* self) {\n Time* tm = state->new_object