text stringlengths 1 2.12k | source dict |
|---|---|
c++, c++17
void RunCallbacks();
private:
std::mutex mutex_;
std::string id_;
std::deque<std::shared_ptr<T const>> messages_ = {};
std::vector<std::function<void(std::shared_ptr<T const>)>> callbacks_ = {};
std::chrono::time_point<std::chrono::system_clock> prev = std::chrono::system_clock::now();
std::shared_ptr<T const> DequeueMessage();
};
template<class T>
void Queue<T>::EnqueueMessage(std::shared_ptr<T const> message) {
messages_.push_back(message);
};
template<class T>
std::shared_ptr<T const> Queue<T>::DequeueMessage() {
if (length() > 0) {
auto item = messages_.front();
messages_.pop_front();
return item;
}
return nullptr;
};
template<class T>
template<typename CallbackT>
void Queue<T>::RegisterCallback(CallbackT &&callback) {
std::scoped_lock lock(mutex_);
callbacks_.template emplace_back(std::forward<CallbackT>(callback));
}; | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
template<class T>
void Queue<T>::RunCallbacks() {
while (true) {
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(prev - now);
auto ms = 100 - milliseconds.count();
while (ms > 0) {
--ms;
}
if (callbacks_.size() > 0 && messages_.size() > 0) {
std::scoped_lock lock(mutex_);
std::shared_ptr<T const> message = DequeueMessage();
for (auto &&callback: callbacks_) {
std::thread t = std::thread([&callback, &message]() {
callback(message);
});
t.detach();
}
}
prev = std::chrono::system_clock::now();
}
}
} // namespace messaging
} // namespace tareeqav
The Broker class acts as a middle layer between the pub/sub and the stored data.
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>
#include "tareeqav/messaging/queue.h"
#include "tareeqav/messaging/proto/control_message.h"
namespace tareeqav {
namespace messaging {
enum class TopicStatus {
TOPIC_CREATED,
TOPIC_EXISTS
};
enum class MessageStatus {
QUEUED,
PENDING,
PUBLISHED,
TOPIC_NOT_FOUND
};
class Broker {
public:
template<typename T>
TopicStatus CreateTopic(std::string topicName);
template<typename T>
MessageStatus PublishMessage(std::string topicName, std::shared_ptr<T const> message); | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
template<class T, typename CallbackT>
void AddSubscription(
std::string topicName,
CallbackT &&callback);
private:
template<typename T>
std::shared_ptr<Queue<T const>> get(std::string topicName) {
auto base = queues_[topicName];
return std::dynamic_pointer_cast<Queue<T const>>(base);
}
std::vector<std::thread::id> threads_;
std::unordered_map<std::string, std::shared_ptr<QueueBase>> queues_;
};
template<typename T>
TopicStatus Broker::CreateTopic(std::string topicName) {
// check if we already have a topic with that name
if (queues_.find(topicName) == queues_.end()) {
queues_[topicName] = std::make_shared<Queue<T const>>();
return TopicStatus::TOPIC_CREATED;
}
return TopicStatus::TOPIC_EXISTS;
};
template<typename T>
MessageStatus Broker::PublishMessage(std::string topicName, std::shared_ptr<T const> message) {
if (queues_.find(topicName) != queues_.end()) {
auto queue = get<T>(topicName);
std::scoped_lock lock(queue->mutex_);
queue->EnqueueMessage(message);
return MessageStatus::QUEUED;
}
return MessageStatus::TOPIC_NOT_FOUND;
}
template<class T, typename CallbackT>
void Broker::AddSubscription(
std::string topicName,
CallbackT &&callback) {
if (queues_.find(topicName) != queues_.end()) {
auto queue = get<T>(topicName);
queue->RegisterCallback(std::forward<CallbackT>(callback));
}
}
} // namespace messaging
} // namespace tareeqav
The Subscriber class is a simple example of the management of adding subscriptions.
#pragma once | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
The Subscriber class is a simple example of the management of adding subscriptions.
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <utility>
#include "tareeqav/messaging/broker.h"
namespace tareeqav {
namespace nodes {
using tareeqav::messaging::Broker;
using tareeqav::messaging::TopicStatus;
using tareeqav::messaging::MessageStatus;
class Subscriber {
public:
Subscriber(
std::shared_ptr<Broker> broker,
std::string topicName);
template<class T, typename CallbackT>
void AddSubscription(CallbackT &&callback);
private:
const std::string topicName_;
std::shared_ptr<Broker> broker_;
};
Subscriber::Subscriber(
std::shared_ptr<Broker> broker,
std::string topicName) :
topicName_(std::move(topicName)), broker_(std::move(broker)) {
};
template<class T, class CallbackT>
void Subscriber::AddSubscription(CallbackT &&callback) {
broker_->template AddSubscription<T>(
topicName_,
std::forward<CallbackT>(callback));
}
} // namespace node
} // namespace tareeqav
The Publisher class creates messages.
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <utility>
#include "tareeqav/messaging/broker.h"
namespace tareeqav {
namespace nodes {
using tareeqav::messaging::Broker;
using tareeqav::messaging::TopicStatus;
using tareeqav::messaging::MessageStatus;
template<class T>
class Publisher {
public:
Publisher(
std::shared_ptr<Broker> broker,
std::string topicName); | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
void CreateTopic() {
TopicStatus status = broker_->template CreateTopic<T>(topicName_);
switch (status) {
case TopicStatus::TOPIC_CREATED:
std::cout << "topic created" << std::endl;
break;
case TopicStatus::TOPIC_EXISTS:
std::cout << "topic exists" << std::endl;
break;
}
}
MessageStatus PublishMessage(
std::string topicName,
std::shared_ptr<const T> message);
private:
const std::string topicName_;
std::shared_ptr<Broker> broker_;
};
template<class T>
Publisher<T>::Publisher(
std::shared_ptr<Broker> broker,
std::string topicName):
topicName_(std::move(topicName)), broker_(std::move(broker)) {
};
template<class T>
MessageStatus Publisher<T>::PublishMessage(
const std::string topicName,
std::shared_ptr<T const> message) {
std::cout << "publishing message " << message << std::endl;
broker_->template PublishMessage(std::move(topicName), std::move(message));
return MessageStatus::QUEUED;
};
} // namespace node
} // namespace tareeqav
The base pipeline class in inherited below
#pragma once
#include <memory>
#include <utility>
#include "tareeqav/messaging/broker.h"
namespace tareeqav {
using tareeqav::messaging::Broker;
class Pipeline {
public:
Pipeline() = delete;
Pipeline(std::shared_ptr<Broker> broker) : broker_(std::move(broker)) {};
protected:
std::shared_ptr<Broker> broker_ = nullptr;
};
}
This pipeline is a consumer of the test message. A pipeline can be both a consumer and producer of messsages.
#pragma once | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
#include <memory>
#include "tareeqav/pipelines/pipeline.h"
#include "tareeqav/messaging/proto/control_message.h"
#include "tareeqav/pipelines/perception/control_subscriber.h"
namespace tareeqav {
namespace perception {
using std::placeholders::_1;
class PerceptionPipeline : public Pipeline {
public:
PerceptionPipeline(const std::shared_ptr<Broker> broker) : Pipeline(std::move(broker)) {
std::string topicName = std::string("/control_message");
subscriber_ = std::make_shared<
nodes::Subscriber>(broker, topicName);
controlCallback = std::make_shared<ControlSubscriber>();
subscriber_->AddSubscription<const messaging::ControlMessage>(
[this](auto &&T) { controlCallback->MessageCallback(std::forward<decltype(T)>(T)); }
);
};
private:
std::shared_ptr<nodes::Subscriber> subscriber_ = nullptr;
std::shared_ptr<ControlSubscriber> controlCallback = nullptr;
};
} // namespace perception
} // namespace tareeqav
This pipeline publishes a message.
#pragma once
#include "tareeqav/pipelines/pipeline.h"
#include "tareeqav/node/publisher.h"
#include "tareeqav/messaging/proto/control_message.h"
namespace tareeqav {
namespace planning {
class PlanningPipeline : public Pipeline {
public:
PlanningPipeline(std::shared_ptr<Broker> broker) : Pipeline(std::move(broker)) {
std::string topicName = std::string("/control_message");
controlPublisher_ = std::make_shared<nodes::Publisher<messaging::ControlMessage>>(
broker_, topicName);
controlPublisher_->CreateTopic();
auto message = std::make_shared<messaging::ControlMessage>(.9, .1); | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
auto message = std::make_shared<messaging::ControlMessage>(.9, .1);
controlPublisher_->PublishMessage(topicName, message);
};
private:
std::shared_ptr<nodes::Publisher<messaging::ControlMessage>> controlPublisher_ = nullptr;
};
} // namespace perception
} // namespace tareeqav
The control message (which will be replaced with protobuf soon)
#pragma once
namespace tareeqav
{
namespace messaging
{
class ControlMessage
{
public:
ControlMessage(){};
ControlMessage(float a, float s): acceleration(a), steering(s){};
float acceleration;
float steering;
};
} // namespace perception
} // namespace tareeqav
This is the driver with the entry point.
#include <memory>
#include "tareeqav/messaging/broker.h"
#include "tareeqav/pipelines/planning/planning.h"
#include "tareeqav/pipelines/perception/perception.h"
using tareeqav::messaging::Broker;
using tareeqav::planning::PlanningPipeline;
using tareeqav::perception::PerceptionPipeline;
int main(int argc, char *argv[]) {
auto broker = std::make_shared<Broker>();
auto planningPipeline = std::make_shared<PlanningPipeline>(PlanningPipeline(broker));
auto perceptionPipeline = std::make_shared<PerceptionPipeline>(PerceptionPipeline(broker));
while (true) {};
return 0;
}
Answer: About code style
I attempt to use c++17 idioms where ever they are known to me;
Don't force yourself to use the latest idioms; while they have their uses, sometimes an older idiom is still better for a given context.
for example in std::scoped_lock vs std::lock_guard,
See this answer for a possible reason not to use std::scoped_lock.
One of my main struggles with C++ is the lack of clarity on which techniques are C++11 and which are more modern. | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
I think that's the wrong thing to worry about. Later versions of C++ build on top of older versions, and a lot of the "old C++" is still very much exactly what you need. I would make it a habit to keep up with the latest C++ by watching C++ conferences and browsing cppreference.com now and then, and then the knowledge you absorbed will find its way into the code you write. But again, don't force it.
Along these lines, is any aware why the Google C++ style guide prohibits the use of C++20? | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
Unless you work for Google and write code for them, you are free to ignore it. Also note that it's just a guide, not a set of commandments. In my experience, big companies are usually quite conservative in what they allow, sometimes for good reasons (for example, they need their code to compile on old systems because their customers still use those).
For your own code, consider who is going to use it, and if they are able to compile it. For example, a lot of people are using LTS versions of their favourite operating systems, which means you might want to support compilers that are a few years old.
Remove length()
While it doesn't really matter for a std::deque, make it a habit to use .empty() to check if a container is empty or not instead of using .size(), as for some containers the latter is less efficient.
But more importantly, there should not be a public member function that returns the length of the queue. The issue is that other threads can enqueue and dequeue at any moment, so the return value of length() is meaningless to anything other than another member function of Queue (and even then only if a lock is held). So at the very least make it private(), but it's better to just remove it.
Fragile locking
Apart from the fact that your code doesn't compile because queue->mutex_ is private, it is a bad idea to have public API functions in Queue that depend on the caller to do proper locking. It is easy to forget to do that, and then the code will compile and seem to work, until you do get that race condition in production and your data gets corrupted. I recommend you make all public member functions take locks if they modify member variables.
Use condition variables to wake up the callback handler | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
Use condition variables to wake up the callback handler
Despite the use of std::chrono functions, nothing in RunCallbacks() actually sleeps, and the compiler will optimize away the while(ms > 0) { --ms; }. In any case, sleeping for fixed amounts of time or busy looping is never a good choice: you will either sleep longer than necessary and/or waste CPU time. Instead, use condition variables so the callback handler can sleep until an entry is added to the queue.
Calling callback functions
First of all, the lambda you pass to std::thread() is unnecessary, you can just write:
std::thread t(callback, message);
t.detach(); | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
This also avoids the issue where message is captured by reference, but by the time the thread runs the object it points to might already have gone out of scope.
But consider what happens here: for every message that arrives, you created one or more threads that call the callback functions. Threads are not free; they use quite a bit of memory (each thread needs its own stack at the very least), and the kernel has to do bookkeeping for each thread. Also, there is now no guarantee whatsoever in which order the callbacks are actually executed. Consider that I send two messages: one to start accelerating, and another one to decelerate. The kernel can schedule threads however it likes, what would happen if those messages are handled in the opposite order they were enqueued?
Finally, detaching a thread means you lose control over it. If a thread goes into an infinite loop, it will continue to use resources, but you won't notice it for a while.
I strongly suggest that RunCallbacks() does not start any threads on its own. For callback functions that execute in very little time, this is much more efficient. If a callback function takes a long time, it can create a thread itself if necessary.
Unused member variable threads_ in Broker
I guess that originally, you had the broker create the threads to handle callbacks? But now Queue starts its own thread, so threads_ can be removed.
Think about shutting down a Queue orderly
RunCallbacks() loops indefinitely, making it impossible to destroy a Queue safely. Maybe it's not an issue (yet), but what if you want to add support for removing topics from the broker?
If a tree falls in a forest
If a message is put into a queue and there is no callback registered, should it still be dequeued?
Consider adding messages to a queue with zero callbacks, then registering a callback, and compare that to adding messages to a queue with one callback, and then registering a second one later.
Publishing a message of the wrong type causes a crash | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
Publishing a message of the wrong type causes a crash
Once you create a topic it has a type associated with it. But later on you can call PublishMessage() with a message of a different type. This causes get<T>(topicName) to return a nulltpr, but you dereference it without checking.
Use of std::shared_ptr | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
I don't use a Singleton, but rather I create a shared_ptr and std::move it across constructors.
First, in many cases you don't need singletons. Maybe you can't think of a reason why someone would want to create two brokers in the same program, but on the other hand, there is nothing that would prevent that from working correctly.
Second, I don't think you need to use std::shared_ptr at all, just pass non-owning references to objects and make sure their lifetime is correct. For example, I think you should be able to write your main() function like so:
int main() {
Broker broker;
PlanningPipeline planningPipeline(broker);
PerceptionPipeline perceptionPipeline(broker);
...
}
As for the messages, consider having Queue own the messages enqueued on it:
template<class T>
class Queue: public QueueBase {
public:
...
template<typename... Args>
void EnqueueMessage(Args&&... args);
...
private:
...
std::queue<T> messages;
};
template<typename... Args>
void Queue::EnqueueMessage(Args&&... args) {
std::lock_guard lock(mutex_);
messages.emplace(std::forward<Args>(args)...);
}
This also uses perfect forwarding to avoid having to repeat any types:
Queue<std::pair<float, std::string>> queue;
queue.EnqueueMessage(42, "The answer"); | {
"domain": "codereview.stackexchange",
"id": 43677,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
kotlin, constructor
Title: Performing complex operation before calling the primary constructor in Kotlin
Question: Semester is a simple enum class.
data class YearSemester(
val year: Int,
val semester: Semester
) {
constructor(string: String) : this(
string.split("-")[0].toInt(),
Semester.valueOf(string.split("-")[1])
)
}
The point is that I don't want to split the String string twice.
So to say:
data class YearSemester(
val year: Int,
val semester: Semester
) {
constructor(string: String){
val splitted = string.split("-")
this(splitted[0].toInt(), Semester.valueOf(splitted[1]))
}
}
However, the Kotlin syntax does not permit this code as the primary constructor must be called at the first of the secondary constructors.
Is there a more elegant way to handle situations like this?
(Performing some complex operation before calling the primary constructor from secondary constructor)
Answer: Here are two more options:
Write a factory function that has the same name as the class. They do this a lot in the standard library, although mostly for interfaces. The default lint rules warn about functions starting with capital letters, but not if the name matches the type it returns. For this reason, this maybe should be considered the conventional approach.
data class YearSemester(
val year: Int,
val semester: Semester
)
fun YearSemester(string: String): YearSemester {
val splitted = string.split("-")
return YearSemester(splitted[0].toInt(), Semester.valueOf(splitted[1]))
}
Add an invoke operator function to its companion object. Then it can be called with the same syntax as a constructor. I've seen people do this, but it seems kind of awkward to me. | {
"domain": "codereview.stackexchange",
"id": 43678,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin, constructor",
"url": null
} |
kotlin, constructor
data class YearSemester(
val year: Int,
val semester: Semester
) {
companion object {
operator fun invoke(string: String): YearSemester {
val splitted = string.split("-")
return YearSemester(splitted[0].toInt(), Semester.valueOf(splitted[1]))
}
} | {
"domain": "codereview.stackexchange",
"id": 43678,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin, constructor",
"url": null
} |
c++, design-patterns, graph
Title: C++ Refactored graph again, separated property maps from Graph type
Question: This is yet another improvement from my graph class - Link
Now property maps are no longer parts of Graph type, they are just stored in a member variable.
This seems much more reasonable for me! It is wise to combine dynamic polymorphism and static polymorphism appropriately.
#include "GraphProperties.h"
#include <memory>
#include <concepts>
template <typename T>
concept GraphConcept = T::is_graph_;
template <typename T>
concept DiGraphConcept = GraphConcept<T> && T::directed_;
template <Descriptor VertexType, typename Traits>
class Graph : private Traits::template Impl<VertexType> {
public:
using TraitBase = Traits::template Impl<VertexType>;
using vertex_type = TraitBase::vertex_type;
using edge_type = TraitBase::edge_type;
static constexpr bool directed_ = TraitBase::directed_;
static constexpr bool is_graph_ = true;
Graph() : TraitBase() {}
void add_vertex(const vertex_type &v) { TraitBase::add_vertex(v); }
void add_edge(const vertex_type &src, const vertex_type &dst) {
TraitBase::add_edge(src, dst);
}
auto adj(const vertex_type &src) { return TraitBase::adj(src); }
auto adj(const vertex_type &src) const { return TraitBase::adj(src); }
const auto &vertices() const noexcept { return TraitBase::vertices(); }
[[nodiscard]] auto size() const noexcept {
return TraitBase::vertices().size();
}
const auto &edges() const noexcept { return TraitBase::edges(); }
const auto &out_edges() const noexcept { return TraitBase::out_edges(); }
bool has_vertex(const vertex_type &src) const noexcept {
return TraitBase::has_vertex(src);
}
bool has_edge(const edge_type &edge) const noexcept {
return TraitBase::has_edge(edge);
} | {
"domain": "codereview.stackexchange",
"id": 43679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
bool has_edge(const edge_type &edge) const noexcept {
return TraitBase::has_edge(edge);
}
template <typename PropertyType>
VertexProperty<PropertyType, vertex_type> &
add_vertex_property(const GraphPropertyTag &tag) {
properties_.emplace(
tag, std::make_unique<VertexProperty<PropertyType, vertex_type>>());
return get_vertex_property<PropertyType>(tag);
}
template <typename PropertyType>
EdgeProperty<PropertyType, edge_type> &
add_edge_property(const GraphPropertyTag &tag) {
properties_.emplace(tag,
std::make_unique<EdgeProperty<PropertyType, edge_type>>());
return get_edge_property<PropertyType>(tag);
}
template <typename PropertyType>
GraphProperty<PropertyType> &add_graph_property(const GraphPropertyTag &tag) {
properties_.emplace(tag, std::make_unique<GraphProperty<PropertyType>>());
return get_graph_property<PropertyType>(tag);
}
template <typename PropertyType>
VertexProperty<PropertyType, vertex_type> &
get_vertex_property(const GraphPropertyTag &tag) {
return dynamic_cast<VertexProperty<PropertyType, vertex_type> &>(
*properties_.at(tag));
}
template <typename PropertyType>
const VertexProperty<PropertyType, vertex_type> &
get_vertex_property(const GraphPropertyTag &tag) const {
return dynamic_cast<const VertexProperty<PropertyType, vertex_type> &>(
*properties_.at(tag));
}
template <typename PropertyType>
EdgeProperty<PropertyType, edge_type> &
get_edge_property(const GraphPropertyTag &tag) {
return dynamic_cast<EdgeProperty<PropertyType, edge_type> &>(
*properties_.at(tag));
}
template <typename PropertyType>
const EdgeProperty<PropertyType, edge_type> &
get_edge_property(const GraphPropertyTag &tag) const {
return dynamic_cast<const EdgeProperty<PropertyType, edge_type> &>(
*properties_.at(tag));
} | {
"domain": "codereview.stackexchange",
"id": 43679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
template <typename PropertyType>
GraphProperty<PropertyType> &get_graph_property(const GraphPropertyTag &tag) {
return dynamic_cast<GraphProperty<PropertyType> &>(*properties_.at(tag));
}
template <typename PropertyType>
const GraphProperty<PropertyType> &
get_graph_property(const GraphPropertyTag &tag) const {
return dynamic_cast<const GraphProperty<PropertyType> &>(
*properties_.at(tag));
}
private:
std::unordered_map<GraphPropertyTag, std::unique_ptr<Property>> properties_;
};
// omit AdjList Traits
GraphProperties.h
#include <bit>
#include <functional>
#include <vector>
#include <unordered_map>
#include <type_traits>
enum class GraphPropertyTag : std::int32_t {
VertexDistance,
VertexVisited,
VertexRank,
VertexSize,
VertexParent,
VertexLink,
EdgeWeight,
GraphTopSort,
};
template<> struct std::hash<GraphPropertyTag> {
std::size_t operator()(const GraphPropertyTag &tag) const {
return std::hash<std::uint32_t>{}(std::bit_cast<std::uint32_t>(tag));
}
};
struct Property {
virtual ~Property() {}
};
enum class VisitMark {
Unvisited,
Visiting,
Visited
};
template <typename PropertyType, Descriptor VertexType>
struct VertexProperty final : public Property {
static constexpr bool int_vertex_ = std::is_integral_v<VertexType>;
PropertyType &operator()(const VertexType &vertex) {
if constexpr (int_vertex_) {
if (vertex >= std::ssize(vertex_properties_)) {
vertex_properties_.resize(vertex + 1);
}
}
return vertex_properties_[vertex];
}
const PropertyType &operator()(const VertexType &vertex) const {
return vertex_properties_.at(vertex);
}
private:
std::conditional_t<int_vertex_, std::vector<PropertyType>,
std::unordered_map<VertexType, PropertyType>>
vertex_properties_;
}; | {
"domain": "codereview.stackexchange",
"id": 43679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
template <typename PropertyType, typename EdgeType>
struct EdgeProperty final : public Property {
PropertyType &operator()(const EdgeType &edge) {
return edge_properties_[edge];
}
const PropertyType &operator()(const EdgeType &edge) const {
return edge_properties_.at(edge);
}
private:
std::unordered_map<EdgeType, PropertyType, std::hash<EdgeType>> edge_properties_;
};
template <typename PropertyType>
struct GraphProperty final : public Property {
PropertyType& operator()() {
return graph_property_;
}
const PropertyType& operator()() const {
return graph_property_;
}
private:
PropertyType graph_property_;
};
Topological sort example
template <DiGraphConcept DiGraphType>
bool topological_sort_helper(
DiGraphType &g,
VertexProperty<VisitMark, typename DiGraphType::vertex_type> &visited,
GraphProperty<std::list<typename DiGraphType::vertex_type>> &top_sort,
const typename DiGraphType::vertex_type &vertex) {
visited(vertex) = VisitMark::Visiting;
for (const auto &[_, dst] : g.adj(vertex)) {
auto status = visited(dst);
if (status == VisitMark::Unvisited) {
if (!topological_sort_helper(g, visited, top_sort, dst)) {
top_sort().clear();
return false;
}
} else if (status == VisitMark::Visiting) {
std::cerr << "Not a DAG, can't topological sort\n";
top_sort().clear();
return false;
}
}
visited(vertex) = VisitMark::Visited;
top_sort().push_back(vertex);
return true;
}
template <DiGraphConcept DiGraphType> void topological_sort(DiGraphType &g) {
using vertex_type = DiGraphType::vertex_type;
auto &visited =
g.add_vertex_property<VisitMark>(GraphPropertyTag::VertexVisited);
auto &top_sort =
g.add_graph_property<std::list<vertex_type>>(GraphPropertyTag::GraphTopSort); | {
"domain": "codereview.stackexchange",
"id": 43679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
for (const auto &vertex : g.vertices()) {
if (visited(vertex) == VisitMark::Unvisited) {
topological_sort_helper(g, visited, top_sort, vertex);
}
}
}
Union Find example
template <Descriptor V>
void make_set(VertexProperty<V, V> &parent, VertexProperty<int, V> &rank,
VertexProperty<V, V> &link, const V &vertex) {
parent(vertex) = vertex;
rank(vertex) = 0;
link(vertex) = vertex;
}
template <Descriptor V>
V find_set(UndirGraph<V> &g, VertexProperty<V, V> &parent, const V &v) {
if (parent(v) != v) {
parent(v) = find_set(g, parent, parent(v));
}
return parent(v);
}
template <Descriptor V>
void link_by_size(VertexProperty<V, V> &parent, VertexProperty<int, V> &rank,
VertexProperty<V, V> &link, const V &x, const V &y) {
auto temp = link(y);
link(y) = link(x);
link(x) = temp;
if (rank(x) > rank(y)) {
parent(y) = x;
} else {
parent(x) = y;
if (rank(x) == rank(y)) {
rank(y) += rank(x);
}
}
}
template <Descriptor V> void union_find_by_size(UndirGraph<V> &g) {
auto &parent = g.add_vertex_property<V>(GraphPropertyTag::VertexParent);
auto &rank = g.add_vertex_property<int>(GraphPropertyTag::VertexRank);
auto &link = g.add_vertex_property<V>(GraphPropertyTag::VertexLink);
for (const auto &vertex : g.vertices()) {
make_set(parent, rank, link, vertex);
}
for (const auto &v : g.vertices()) {
for (const auto &[_, u] : g.adj(v)) {
auto vr = find_set(g, parent, v);
auto ur = find_set(g, parent, u);
link_by_size(parent, rank, link, vr, ur);
}
}
}
``` | {
"domain": "codereview.stackexchange",
"id": 43679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
Answer: This is certainly an interesting way to have a generic graph class that is dynamically extensible. It's very nice to be able to write code like visited(vertex) = ....
Use more [[nodiscard]]
I see you use [[nodiscard]] for size(), but there are many more functions where [[nodiscard]] would be appropriate.
No need to overload std::hash for enums
std::hash already has specializations for all possible enum types, you don't need to specialize it for GraphPropertyTag.
Consider using operator[] instead of operator() for properties
Since a graph is like a container, I think it feels more natural to use bracket notation to access its elements. Since everything has to be accessed via properties, I would add operator[] member functions to them instead of operator(). | {
"domain": "codereview.stackexchange",
"id": 43679,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, graph",
"url": null
} |
strings, array, vba, excel, hash-map
Title: Fastest function to `Remove Duplicate Lines` per each cell
Question: The below function is used to Remove Duplicate Lines per each cell.
It works without problem, but it is slow with a range of only one column and 17k rows.
Actually, (with the same range in addition to another two column) , I am using a different excellent code by @VBasic2008 Link which perform complex tasks than my function and it takes just 1.5 second to finish.
I do not know where is the bottleneck on my code and How to optimize it.
There is no problem to totally change my codes or provide a new one.
In advance, pleased for all your help.
Option Explicit
Option Compare Text
Function RemoveDuplicateLines(ByVal Text As String, Optional delimiter As String = vbLf) As String
Dim dictionary As Object
Dim x, part
Set dictionary = CreateObject("Scripting.Dictionary")
dictionary.CompareMode = vbTextCompare
For Each x In Split(Text, delimiter)
part = Trim(x)
If part <> "" And Not dictionary.Exists(part) Then
dictionary.Add part, Nothing
End If
Next
If dictionary.Count > 0 Then
RemoveDuplicateLines = Join(dictionary.keys, delimiter)
Else
RemoveDuplicateLines = ""
End If
Set dictionary = Nothing
End Function
Sub Remove_Duplicate_Lines()
With Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
On Error GoTo Errorhandler
Dim ws As Worksheet: Set ws = sh2
Dim crg As Range
Set crg = ws.Range("O2:O" & ws.Cells(Rows.Count, "O").End(xlUp).Row) '#Column contains Combined URL
Dim arr: arr = crg.Value2
Dim i As Long
For i = LBound(arr) To UBound(arr)
arr(i, 1) = RemoveDuplicateLines(arr(i, 1))
Next i
crg.value = arr
Errorhandler:
With Application
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub | {
"domain": "codereview.stackexchange",
"id": 43680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, array, vba, excel, hash-map",
"url": null
} |
strings, array, vba, excel, hash-map
Answer: Binding
Late-binding is slower than early-binding. Add a reference to Microsoft Scripting Runtime: | {
"domain": "codereview.stackexchange",
"id": 43680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, array, vba, excel, hash-map",
"url": null
} |
strings, array, vba, excel, hash-map
then change Dim dictionary As Object to Dim dict As Dictionary
and Set dictionary = CreateObject("Scripting.Dictionary") to Set dict = New Dictionary. Note that these are not the final declarations but more on this below.
Declare variables
The line Dim x, part simply declares 2 variables of type Variant by default. Although x needs to be a Variant because it's used in a For Each... loop you should still declare it as a best practice. part however should be declared as String. Never use Variant if you already know the var type because the extra wrapping is using extra resources.
Also, a For... To... loop is slightly faster on a 1D array, compared to a For Each..., so really you don't need x to be Variant at all but rather an iterator declared as Long and an array of String() as that is returned by Split.
Efficiency
You are presuming that all values in the O column are strings. It's better to only run the RemoveDuplicateLines for strings only and not for anything else like blanks or numbers. So, use VarType to check for type.
If the number of individual lines returned by the call to Split is exactly the same as the number of keys in the dictionary (i.e. no duplicates) then there is no need to join the keys because the original string would already be satisfactory as the result. Same goes for trimming - if trim does not remove any character then we can use the original text as long as there were no duplicates either.
You could avoid a lot of string copying by changing the string by reference and not returning as a result of the function. This improves efficiency a lot.
Using a Static dictionary will remove the need to instantiate a Dictionary on each call.
Other
You should not restore the state of the application to 'On' as maybe it was intentionally off before running your macro. So, store state, turn things off and finally restore when done. | {
"domain": "codereview.stackexchange",
"id": 43680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, array, vba, excel, hash-map",
"url": null
} |
strings, array, vba, excel, hash-map
To make the main method reusable, you should pass the range from a higher level method call so that you can run your macro on other ranges as well.
No need for Option Compare Text as the Dictionary.CompareMode option takes care of text comparison for keys.
Solution
Run Main method below:
Option Explicit | {
"domain": "codereview.stackexchange",
"id": 43680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, array, vba, excel, hash-map",
"url": null
} |
strings, array, vba, excel, hash-map
Public Sub Main()
Dim rng As Range
'
On Error Resume Next
With ActiveSheet 'Or whatever worksheet
Set rng = .Range("O2:O" & .Cells(Rows.Count, "O").End(xlUp).Row) 'Or whatever range
End With
On Error GoTo 0
If rng Is Nothing Then Exit Sub 'Or display a message
'
RemoveDuplicateLinesFromRange rng
End Sub
Public Sub RemoveDuplicateLinesFromRange(ByVal rng As Range _
, Optional ByVal delimiter As String = vbLf)
If rng Is Nothing Then
Err.Raise 91, , "Range not set"
ElseIf rng.Areas.Count > 1 Then
Err.Raise 5, , "Non-contigous range"
End If
'
Dim xlCalc As XlCalculation: xlCalc = Application.Calculation
Dim displayOn As Boolean: displayOn = Application.ScreenUpdating
Dim eventsOn As Boolean: eventsOn = Application.EnableEvents
'
With Application
If xlCalc <> xlCalculationManual Then .Calculation = xlCalculationManual
If displayOn Then .ScreenUpdating = False
If eventsOn Then .EnableEvents = False
End With
'
Dim arr() As Variant
Dim i As Long
Dim j As Long
'
If rng.Count = 1 Then
ReDim arr(1 To 1, 1 To 1)
arr(1, 1) = rng.Value2
Else
arr = rng.Value2
End If
'
If UBound(arr, 1) < UBound(arr, 2) Then
For i = LBound(arr, 1) To UBound(arr, 1)
For j = LBound(arr, 2) To UBound(arr, 2)
RemoveDuplicateLines arr(i, j), delimiter
Next j
Next i
Else
For j = LBound(arr, 2) To UBound(arr, 2)
For i = LBound(arr, 1) To UBound(arr, 1)
RemoveDuplicateLines arr(i, j), delimiter
Next i
Next j
End If
rng.Value2 = arr
'
With Application
If xlCalc <> xlCalculationManual Then .Calculation = xlCalc
If displayOn Then .ScreenUpdating = True
If eventsOn Then .EnableEvents = True
End With
End Sub | {
"domain": "codereview.stackexchange",
"id": 43680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, array, vba, excel, hash-map",
"url": null
} |
strings, array, vba, excel, hash-map
Private Sub RemoveDuplicateLines(ByRef v As Variant _
, Optional ByVal delimiter As String = vbLf)
If VarType(v) <> vbString Then Exit Sub
'
Static dict As dictionary
Dim parts() As String
Dim i As Long
Dim hasChanged As Boolean
'
If dict Is Nothing Then
Set dict = New dictionary
dict.CompareMode = vbTextCompare
Else
dict.RemoveAll
End If
'
parts = Split(v, delimiter)
If LBound(parts) = UBound(parts) Then
v = Trim$(v)
Exit Sub
End If
'
For i = LBound(parts, 1) To UBound(parts, 1)
If TrimIfNeeded(parts(i)) Then hasChanged = True
dict(parts(i)) = Empty
Next
'
If hasChanged Or (UBound(parts, 1) - LBound(parts, 1) + 1 > dict.Count) Then
v = Join(dict.Keys, delimiter)
End If
End Sub
Private Function TrimIfNeeded(ByRef Text As String) As Boolean
Dim size As Long: size = Len(Text)
If size = 0 Then Exit Function
'
Text = Trim$(Text)
TrimIfNeeded = (size > Len(Text))
End Function
Final thoughts
You might want to check for formulas. When you read an entire range, you could have a combination of formulas and values so you might want to update code to exclude formula cells from the macro. | {
"domain": "codereview.stackexchange",
"id": 43680,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, array, vba, excel, hash-map",
"url": null
} |
c++, embedded
Title: Hardware abstraction in C++ on STM32F4
Question: I've recently watched a few talks on implementing easy-to-use hardware abstraction layers in C++ for use on embedded devices such as ARM Cortex-based microcontrollers such as the STM32F4 that I am targeting with this project. I would like some input into whether or not the following usage structure makes sense to the average programmer and the embedded programmer due to the amount of hardware that must be normally set up manually when interacting with memory-mapped hardware peripherals in the context of an embedded application. My full project is too big but I will try to boil down the parts I want feedback on as follows:
startup.cpp: inital processor boot entry file
#include <cstddef>
#include <cstring>
/*
* External definitions from linker for stack, BSS, data, and initialization/constructor
* functions
*/
extern "C" int __stack_top__;
extern "C" char __bss_start__;
extern "C" char __bss_end__;
extern "C" char __data_start__;
extern "C" char __data_end__;
extern "C" char __data_flash__;
extern "C" void (*__preinit_array_start[])(void);
extern "C" void (*__preinit_array_end[])(void);
extern "C" void (*__init_array_start[])(void);
extern "C" void (*__init_array_end[])(void);
// Prototype definition of main function
int boot_main();
namespace Startup {
/**
* @brief Default interrupt handler for interrupt vector table
*
*/
void Default_Handler();
/**
* @brief Goes through all startup initialization, including:
* -- Copies initialization values from flash to RAM
* -- Zeros BSS area
* -- Calls all initializers and constructors
*
*/
void Initialize();
} // namespace Startup
/**
* @brief Reset handler that exectures the initialization functions then calls main
*
*/
extern "C" void Reset_Handler() {
Startup::Initialize();
boot_main();
Startup::Default_Handler();
}
void Startup::Initialize() {
size_t count; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
void Startup::Initialize() {
size_t count;
// Copy static values from flash .data to RAM .data
count = &__data_end__ - &__data_start__;
std::memcpy(&__data_start__, &__data_flash__, count);
// Set BSS area to zero
count = &__bss_end__ - &__bss_start__;
std::memset(&__bss_start__, 0, count);
// Call all initializers & constructors
size_t i;
count = __preinit_array_end - __preinit_array_start;
for (i = 0; i < count; i++)
__preinit_array_start[i]();
count = __init_array_end - __init_array_start;
for (i = 0; i < count; i++)
__init_array_start[i]();
}
void Startup::Default_Handler() {
while (true) {
// Do nothing
}
}
// NVIC interrupt table
extern "C" void (*const vectors[])(void)
__attribute__((used, section(".vectors"))) = {(void (*)(void))(&__stack_top__),
Reset_Handler,
Startup::Default_Handler,
Startup::Default_Handler,
Startup::Default_Handler,
Startup::Default_Handler,
Startup::Default_Handler,
nullptr,
nullptr,
nullptr,
nullptr,
Startup::Default_Handler,
Startup::Default_Handler,
nullptr,
Startup::Default_Handler,
... { repeat several times } ...
Startup::Default_Handler}; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
main.cpp: main entry file
#include "hardware/GPIO.hpp"
#include "hardware/RCC.hpp"
#include <cstdint>
#include <cstring>
int boot_main() {
RCC &rcc = *new RCC();
rcc.EnableExternalSystemClock();
for (std::size_t i = 0; i < 2000000; i++) {
// Do nothing (busy wait)
}
GPIO &gpioc = *new (GPIO::GPIOC) GPIO();
gpioc.SetMode(GPIO::PIN13, GPIO::Mode::OUTPUT);
gpioc.SetType(GPIO::PIN13, GPIO::Type::PUSH_PULL);
gpioc.SetResistor(GPIO::PIN13, GPIO::PUPD::PULL_UP);
while (true) {
gpioc.EnableOutput(GPIO::PIN13);
for (std::size_t i = 0; i < 45000; i++) {
// Do nothing (busy wait)
}
gpioc.DisableOutput(GPIO::PIN13);
for (std::size_t i = 0; i < 45000; i++) {
// Do nothing (busy wait)
}
}
}
GPIO.cpp: GPIO class implementation
#include "GPIO.hpp"
#include "RCC.hpp"
GPIO::GPIO() {
// Do nothing
}
void *GPIO::operator new(std::size_t) {
// Enable GPIOA clock
RCC &rcc = *new RCC();
rcc.EnableGPIO(GPIO::GPIOA);
// Return GPIOA address
return reinterpret_cast<void *>(0x40020000);
}
void *GPIO::operator new(std::size_t, const enum gpio_selection n) {
RCC &rcc = *new RCC();
rcc.EnableGPIO(n);
// Return GPIO address
auto address = 0x40020000 + n * 0x400;
return reinterpret_cast<void *>(address);
}
void GPIO::SetMode(enum gpio_pin pin_num, GPIO::Mode mode) {
uint32_t set_moder = this->MODER.reg;
set_moder &= ~(0b11 << (2 * pin_num));
switch (mode) {
case GPIO::Mode::OUTPUT:
set_moder |= (0b01 << (2 * pin_num));
break;
case GPIO::Mode::ALTERNATE:
set_moder |= (0b10 << (2 * pin_num));
break;
case GPIO::Mode::ANALOG:
set_moder |= (0b11 << (2 * pin_num));
break;
default:
// Do nothing
break;
}
this->MODER.reg = set_moder;
}
... { several other method implementations } ... | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
GPIO.hpp: GPIO class header
#include <cstddef>
#include <cstdint>
#include <type_traits>
#pragma once
using reg32_t = volatile uint32_t;
using reg16_t = volatile uint16_t; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
class GPIO {
private:
union {
reg32_t reg;
struct {
reg32_t MODER15 : 2;
reg32_t MODER14 : 2;
reg32_t MODER13 : 2;
reg32_t MODER12 : 2;
reg32_t MODER11 : 2;
reg32_t MODER10 : 2;
reg32_t MODER9 : 2;
reg32_t MODER8 : 2;
reg32_t MODER7 : 2;
reg32_t MODER6 : 2;
reg32_t MODER5 : 2;
reg32_t MODER4 : 2;
reg32_t MODER3 : 2;
reg32_t MODER2 : 2;
reg32_t MODER1 : 2;
reg32_t MODER0 : 2;
} bits;
} MODER;
union {
reg32_t reg;
struct {
reg32_t : 16;
reg32_t OT15 : 1;
reg32_t OT14 : 1;
reg32_t OT13 : 1;
reg32_t OT12 : 1;
reg32_t OT11 : 1;
reg32_t OT10 : 1;
reg32_t OT9 : 1;
reg32_t OT8 : 1;
reg32_t OT7 : 1;
reg32_t OT6 : 1;
reg32_t OT5 : 1;
reg32_t OT4 : 1;
reg32_t OT3 : 1;
reg32_t OT2 : 1;
reg32_t OT1 : 1;
reg32_t OT0 : 1;
} bits;
} OTYPER;
union {
reg32_t reg;
struct {
reg32_t OSPEEDR15 : 2;
reg32_t OSPEEDR14 : 2;
reg32_t OSPEEDR13 : 2;
reg32_t OSPEEDR12 : 2;
reg32_t OSPEEDR11 : 2;
reg32_t OSPEEDR10 : 2;
reg32_t OSPEEDR9 : 2;
reg32_t OSPEEDR8 : 2;
reg32_t OSPEEDR7 : 2;
reg32_t OSPEEDR6 : 2;
reg32_t OSPEEDR5 : 2;
reg32_t OSPEEDR4 : 2;
reg32_t OSPEEDR3 : 2;
reg32_t OSPEEDR2 : 2;
reg32_t OSPEEDR1 : 2;
reg32_t OSPEEDR0 : 2;
} bits;
} OSPEEDR;
union {
reg32_t reg;
struct {
reg32_t PUPDR15 : 2;
reg32_t PUPDR14 : 2;
reg32_t PUPDR13 : 2; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
reg32_t PUPDR15 : 2;
reg32_t PUPDR14 : 2;
reg32_t PUPDR13 : 2;
reg32_t PUPDR12 : 2;
reg32_t PUPDR11 : 2;
reg32_t PUPDR10 : 2;
reg32_t PUPDR9 : 2;
reg32_t PUPDR8 : 2;
reg32_t PUPDR7 : 2;
reg32_t PUPDR6 : 2;
reg32_t PUPDR5 : 2;
reg32_t PUPDR4 : 2;
reg32_t PUPDR3 : 2;
reg32_t PUPDR2 : 2;
reg32_t PUPDR1 : 2;
reg32_t PUPDR0 : 2;
} bits;
} PUPDR;
union {
reg32_t reg;
struct {
reg32_t : 16;
reg32_t IDR15 : 1;
reg32_t IDR14 : 1;
reg32_t IDR13 : 1;
reg32_t IDR12 : 1;
reg32_t IDR11 : 1;
reg32_t IDR10 : 1;
reg32_t IDR9 : 1;
reg32_t IDR8 : 1;
reg32_t IDR7 : 1;
reg32_t IDR6 : 1;
reg32_t IDR5 : 1;
reg32_t IDR4 : 1;
reg32_t IDR3 : 1;
reg32_t IDR2 : 1;
reg32_t IDR1 : 1;
reg32_t IDR0 : 1;
} bits;
} IDR;
union {
reg32_t reg;
struct {
reg32_t : 16;
reg32_t ODR15 : 1;
reg32_t ODR14 : 1;
reg32_t ODR13 : 1;
reg32_t ODR12 : 1;
reg32_t ODR11 : 1;
reg32_t ODR10 : 1;
reg32_t ODR9 : 1;
reg32_t ODR8 : 1;
reg32_t ODR7 : 1;
reg32_t ODR6 : 1;
reg32_t ODR5 : 1;
reg32_t ODR4 : 1;
reg32_t ODR3 : 1;
reg32_t ODR2 : 1;
reg32_t ODR1 : 1;
reg32_t ODR0 : 1;
} bits;
} ODR;
union {
reg32_t reg;
struct {
reg32_t BR15 : 1;
reg32_t BR14 : 1;
reg32_t BR13 : 1;
reg32_t BR12 : 1;
reg32_t BR11 : 1;
reg32_t BR10 : 1;
reg32_t BR9 : 1; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
reg32_t BR11 : 1;
reg32_t BR10 : 1;
reg32_t BR9 : 1;
reg32_t BR8 : 1;
reg32_t BR7 : 1;
reg32_t BR6 : 1;
reg32_t BR5 : 1;
reg32_t BR4 : 1;
reg32_t BR3 : 1;
reg32_t BR2 : 1;
reg32_t BR1 : 1;
reg32_t BR0 : 1;
reg32_t BS15 : 1;
reg32_t BS14 : 1;
reg32_t BS13 : 1;
reg32_t BS12 : 1;
reg32_t BS11 : 1;
reg32_t BS10 : 1;
reg32_t BS9 : 1;
reg32_t BS8 : 1;
reg32_t BS7 : 1;
reg32_t BS6 : 1;
reg32_t BS5 : 1;
reg32_t BS4 : 1;
reg32_t BS3 : 1;
reg32_t BS2 : 1;
reg32_t BS1 : 1;
reg32_t BS0 : 1;
} bits;
struct {
reg16_t BR;
reg16_t BS;
} split;
} BSRR;
union {
reg32_t reg;
struct {
reg32_t : 15;
reg32_t LCKK : 1;
reg32_t LCK15 : 1;
reg32_t LCK14 : 1;
reg32_t LCK13 : 1;
reg32_t LCK12 : 1;
reg32_t LCK11 : 1;
reg32_t LCK10 : 1;
reg32_t LCK9 : 1;
reg32_t LCK8 : 1;
reg32_t LCK7 : 1;
reg32_t LCK6 : 1;
reg32_t LCK5 : 1;
reg32_t LCK4 : 1;
reg32_t LCK3 : 1;
reg32_t LCK2 : 1;
reg32_t LCK1 : 1;
reg32_t LCK0 : 1;
} bits;
} LCKR;
union {
reg32_t reg;
struct {
reg32_t AFRL7 : 4;
reg32_t AFRL6 : 4;
reg32_t AFRL5 : 4;
reg32_t AFRL4 : 4;
reg32_t AFRL3 : 4;
reg32_t AFRL2 : 4;
reg32_t AFRL1 : 4;
reg32_t AFRL0 : 4;
} bits;
} AFRL;
union {
reg32_t reg;
struct {
reg32_t AFRH15 : 4;
reg32_t AFRH14 : 4; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
struct {
reg32_t AFRH15 : 4;
reg32_t AFRH14 : 4;
reg32_t AFRH13 : 4;
reg32_t AFRH12 : 4;
reg32_t AFRH11 : 4;
reg32_t AFRH10 : 4;
reg32_t AFRH9 : 4;
reg32_t AFRH8 : 4;
} bits;
} AFRH; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
public:
enum gpio_selection { GPIOA = 0, GPIOB = 1, GPIOC = 2, GPIOD = 3, GPIOE = 4, GPIOH = 7 };
enum gpio_pin {
PIN0,
PIN1,
PIN2,
PIN3,
PIN4,
PIN5,
PIN6,
PIN7,
PIN8,
PIN9,
PIN10,
PIN11,
PIN12,
PIN13,
PIN14,
PIN15
};
enum class Mode { INPUT, OUTPUT, ALTERNATE, ANALOG };
enum class Type { PUSH_PULL, OPEN_DRAIN };
enum class PUPD { NONE, PULL_UP, PULL_DOWN };
GPIO();
void *operator new(std::size_t);
void *operator new(std::size_t, const enum gpio_selection n);
void SetMode(enum gpio_pin pin_num, GPIO::Mode mode);
GPIO::Mode GetMode(enum gpio_pin pin_num);
void SetType(enum gpio_pin pin_num, GPIO::Type type);
void SetResistor(enum gpio_pin pin_num, enum GPIO::PUPD pupd_type);
void EnableOutput(enum gpio_pin pin_num);
void DisableOutput(enum gpio_pin pin_num);
bool GetOutput(enum gpio_pin pin_num);
enum gpio_selection GetGPIO() {
return static_cast<enum gpio_selection>((reinterpret_cast<int>(this) & 0xFFFF) / 0x400);
}
};
static_assert(sizeof(GPIO) == 10 * sizeof(reg32_t), "GPIO contains padding bytes.");
static_assert(std::is_standard_layout<GPIO>::value, "GPIO isn't standard layout.");
RCC.cpp: RCC class implementation
#include "RCC.hpp"
#include "FLASH.hpp"
#include "GPIO.hpp"
#include "PWR.hpp"
RCC::RCC() {
// Do nothing
}
void *RCC::operator new(std::size_t) {
return reinterpret_cast<void *>(0x40023800);
}
void RCC::EnableExternalSystemClock() {
// Enable HSE
this->CR.bits.HSEON = 1;
while (this->CR.bits.HSERDY == 0) {
// Do nothing
}
// Enable power controller
this->APB1ENR.bits.PWREN = 1;
// Configure voltage regulator scaling
PWR &power = *new PWR();
power.SetRegulatorScale(PWR::Scale::DIV2); | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
// Enable flash prefetch & caches
FLASH &flash = *new FLASH();
flash.EnablePrefetchCache();
// Set PLL scalers
constexpr auto pll_clocks = RCC::CalculatePLLClocks(HSE_CRYSTAL_FREQ_HZ, TARGET_SYSTEM_CLOCK);
this->PLLCFGR.bits.PLLM = std::get<0>(pll_clocks);
this->PLLCFGR.bits.PLLN = std::get<1>(pll_clocks);
this->PLLCFGR.bits.PLLP = std::get<2>(pll_clocks);
// Calculate actual system clock
constexpr auto sys_clock =
RCC::CalculateSysClock(HSE_CRYSTAL_FREQ_HZ, std::get<0>(pll_clocks),
std::get<1>(pll_clocks), std::get<2>(pll_clocks));
// Set APB scalers
constexpr auto lsapb2_prescaler = RCC::CalculateLSAPB2Prescaler(sys_clock);
this->CFGR.bits.HPRE = 0b000;
this->CFGR.bits.PPRE1 = lsapb2_prescaler;
this->CFGR.bits.PPRE2 = 0b000;
// Set PLL source
this->PLLCFGR.bits.PLLSRC = 1;
// Enable PLL
this->CR.bits.PLLON = 1;
while (this->CR.bits.PLLRDY == 0) {
// Do nothing
}
// Set clock source
this->CFGR.bits.SW = 0b01;
while (this->CFGR.bits.SWS != 0b01) {
// Do nothing
}
}
RCC.hpp: RCC class header
#include "GPIO.hpp"
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <tuple>
#include <type_traits>
#pragma once
#define HSE_CRYSTAL_FREQ_HZ 25000000
#define HSI_CRYSTAL_FREQ_HZ 16000000
#define TARGET_SYSTEM_CLOCK 84000000
using reg32_t = volatile uint32_t; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
class RCC {
private:
union {
reg32_t reg;
struct {
reg32_t : 4;
reg32_t PLLI2SRDY : 1;
reg32_t PLLI2SON : 1;
reg32_t PLLRDY : 1;
reg32_t PLLON : 1;
reg32_t : 4;
reg32_t CSSON : 1;
reg32_t HSEBYP : 1;
reg32_t HSERDY : 1;
reg32_t HSEON : 1;
reg32_t HSICAL : 8;
reg32_t HSITRIM : 5;
reg32_t : 1;
reg32_t HSIRDY : 1;
reg32_t HSION : 1;
} bits;
} CR;
union {
reg32_t reg;
struct {
reg32_t : 4;
reg32_t PLLQ : 4;
reg32_t : 1;
reg32_t PLLSRC : 1;
reg32_t : 4;
reg32_t PLLP : 2;
reg32_t : 1;
reg32_t PLLN : 9;
reg32_t PLLM : 6;
} bits;
} PLLCFGR;
union {
reg32_t reg;
struct {
reg32_t MCO2 : 2;
reg32_t MCO2PRE : 3;
reg32_t MCO1PRE : 3;
reg32_t I2SSRC : 1;
reg32_t MCO1 : 2;
reg32_t RTCPRE : 5;
reg32_t PPRE2 : 3;
reg32_t PPRE1 : 3;
reg32_t : 2;
reg32_t HPRE : 4;
reg32_t SWS : 2;
reg32_t SW : 2;
} bits;
} CFGR;
reg32_t CIR;
reg32_t AHB1RSTR;
reg32_t AHB2RSTR;
reg32_t : 32;
reg32_t : 32;
reg32_t APB1RSTR;
reg32_t APB2RSTR;
reg32_t : 32;
reg32_t : 32;
union {
reg32_t reg;
struct {
reg32_t : 9;
reg32_t DMA2EN : 1;
reg32_t DMA1EN : 1;
reg32_t : 8;
reg32_t CRCEN : 1;
reg32_t : 4;
reg32_t GPIOHEN : 1;
reg32_t : 2;
reg32_t GPIOEEN : 1;
reg32_t GPIODEN : 1;
reg32_t GPIOCEN : 1;
reg32_t GPIOBEN : 1;
reg32_t GPIOAEN : 1;
} bits;
} AHB1ENR; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
reg32_t GPIOBEN : 1;
reg32_t GPIOAEN : 1;
} bits;
} AHB1ENR;
reg32_t AHB2ENR;
reg32_t : 32;
reg32_t : 32;
union {
reg32_t reg;
struct {
reg32_t : 3;
reg32_t PWREN : 1;
reg32_t : 4;
reg32_t I2C3EN : 1;
reg32_t I2C2EN : 1;
reg32_t I2C1EN : 1;
reg32_t : 3;
reg32_t USART2EN : 1;
reg32_t : 1;
reg32_t SPI3EN : 1;
reg32_t SPI2EN : 1;
reg32_t : 2;
reg32_t WWDGEN : 1;
reg32_t : 7;
reg32_t TIM5EN : 1;
reg32_t TIM4EN : 1;
reg32_t TIM3EN : 1;
reg32_t TIM2EN : 1;
} bits;
} APB1ENR;
reg32_t APB2ENR;
reg32_t : 32;
reg32_t : 32;
reg32_t AHB1LPENR;
reg32_t AHB2LPENR;
reg32_t : 32;
reg32_t : 32;
reg32_t APB1LPENR;
reg32_t APB2LPENR;
reg32_t : 32;
reg32_t : 32;
reg32_t BDCR;
reg32_t CSR;
reg32_t : 32;
reg32_t : 32;
reg32_t SSCGR;
reg32_t PLLI2SCFGR;
reg32_t : 32;
reg32_t DCKCFGR; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
public:
RCC();
void *operator new(std::size_t);
void EnableExternalSystemClock();
inline void EnableGPIO(const enum GPIO::gpio_selection selection) {
this->AHB1ENR.reg |= (1 << selection);
// switch (selection) {
// case GPIO::GPIOA:
// this->AHB1ENR.bits.GPIOAEN = 1;
// break;
// case GPIO::GPIOB:
// this->AHB1ENR.bits.GPIOBEN = 1;
// break;
// case GPIO::GPIOC:
// this->AHB1ENR.bits.GPIOCEN = 1;
// break;
// case GPIO::GPIOD:
// this->AHB1ENR.bits.GPIODEN = 1;
// break;
// case GPIO::GPIOE:
// this->AHB1ENR.bits.GPIOEEN = 1;
// break;
// case GPIO::GPIOH:
// this->AHB1ENR.bits.GPIOHEN = 1;
// break;
// default:
// break; // Do nothing
// }
}
inline void DisableGPIO(const enum GPIO::gpio_selection selection) {
this->AHB1ENR.reg &= ~(1 << selection);
}
/**
* @brief Calculate system clock frequency through PLL register values
*
* @param hs_crystal_freq HS clock signal frequency in Hz
* @param pll_m M divisor
* @param pll_n N mulitplier
* @param pll_p P divisor in register form
* @return constexpr int System clock frequency
*/
static constexpr int CalculateSysClock(uint32_t hs_crystal_freq, uint32_t pll_m, uint32_t pll_n,
uint32_t pll_p) {
return ((hs_crystal_freq / pll_m) * pll_n) / ((pll_p * 2) + 2);
} | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
/**
* @brief Returns best match for PLL M, N, and P register values for main MCU PLL
*
* @param hs_crystal_freq Input HS clock signal frequency in Hz
* @param target Target system clock frequency
* @return constexpr std::tuple<uint32_t, uint32_t, uint32_t> M, N, and P values in tuple
*/
static constexpr std::tuple<uint32_t, uint32_t, uint32_t>
CalculatePLLClocks(uint32_t hs_crystal_freq, uint32_t target) {
uint32_t pll_m = 1, optimum_pll_n = 0, optimum_pll_p = 0;
int64_t min_diff = INT64_MAX;
// Calculate PLL M value to satisfy frequency constraints
while (hs_crystal_freq / pll_m > 2100000) {
pll_m++;
}
// Iterate through all values of N and P to find closest match to target
for (uint32_t pll_n = 430; pll_n > 50; pll_n--) {
for (uint32_t pll_p = 2; pll_p <= 8; pll_p += 2) {
// Calculate system clock with crystal, M, N, and P
uint32_t clock =
RCC::CalculateSysClock(hs_crystal_freq, pll_m, pll_n, (pll_p - 2) / 2);
if ((hs_crystal_freq / pll_m) * pll_n < 432000000 && clock < 84000000) {
// Calcualte absolute difference between target and calculated clock
int64_t diff = (static_cast<int64_t>(target) - static_cast<int64_t>(clock));
diff *= ((diff < 0) ? -1 : 1);
// If it's closer than previously saved result, overwrite it
if (diff <= min_diff) {
min_diff = diff;
optimum_pll_n = pll_n;
optimum_pll_p = pll_p;
}
}
}
}
// Return closest answer in register form
return {pll_m, optimum_pll_n, (optimum_pll_p - 2) / 2};
} | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
/**
* @brief Calculate system clock frequency through target clock frequency
*
* @param hs_crystal_freq HS clock signal frequency in Hz
* @return constexpr int System clock frequency
*/
static constexpr int GetSystemClock(uint32_t hs_crystal_freq) {
auto pll_clocks = RCC::CalculatePLLClocks(hs_crystal_freq, TARGET_SYSTEM_CLOCK);
return RCC::CalculateSysClock(hs_crystal_freq, std::get<0>(pll_clocks),
std::get<1>(pll_clocks), std::get<2>(pll_clocks));
}
/**
* @brief Calcualte APB2 clock prescaler
*
* @param sys_clock Current system clock
* @return constexpr int APB2 prescaler value
*/
static constexpr int CalculateLSAPB2Prescaler(uint32_t sys_clock) {
int divisor = 1;
while (sys_clock / divisor > 42000000) {
divisor *= 2;
}
switch (divisor) {
case 1:
return 0b000;
case 2:
return 0b100;
case 4:
return 0b101;
case 8:
return 0b110;
case 16:
return 0b111;
}
}
};
static_assert(sizeof(RCC) == 36 * sizeof(reg32_t), "RCC contains padding bytes.");
static_assert(std::is_standard_layout<RCC>::value, "RCC isn't standard layout.");
What I like about my current implementation is that as long as I turn on -flto and -O2 then it pretty much inlines everything into ResetHandler which is very nice. I also use constexpr for automatic calculation of system registers at compile-time. My primary question with this implementation is: does it make sense to automatically enable the RCC registers for the appropriate GPIO peripheral when "allocating"/creating an instance of the class? Or should I leave it to the application programmer to deal with such a hardware task themselves? The class will be useless without the RCC registers enabled. | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
Answer: I like the reg32_t type alias and the good use of binary literals. The static_assert()s are also a great way to prevent accidental mistakes, especially with bit fields where it's hard to spot if you added one bit too many.
Use of placement new
The point of new is to create a new object. Placement new creates a new object at a given location. However, the hardware registers are already there, you don't have to create them. So I would rather not use placement new, but just write a static member function that returns a pointer to the right memory location:
class RCC {
...
public:
RCC() = delete;
...
static RCC *get() {
return reinterpret_cast<RCC *>(0x40023800);
// return std::launder(reinterpret_cast<RCC *>(0x40023800)); // C++17
}
}; | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
Since C++17, you should use std::launder() to tell the compiler and static analysis tools that there really is a live object at that address, so it won't treat any access to it as undefined behavior.
While overloading operator new() and calling it multiple times is fine in some cases, consider what would happen if you added constructors and destructors to your classes (for example, to ensure that the registers are in a well-defined state at startup, or to ensure all pins will be high-impedance when you stop using a hardware peripheral).
Another reason against your use of placement new is that code like FOO &f = *new FOO() looks like an instant memory leak, and might even cause some static analyzers to complain about it.
Since you are using __attribute__((section)) anyway, consider using sections to declare global instances of your classes at the right address, see this StackOverflow post.
Unnecessary use of this->
In C++ you almost never have to use this->. I would remove it wherever it is unneeded.
Don't busy wait
Busy waiting uses CPU cycles unnecessarily, using more power which drains batteries faster and generates heat. On a STM32F4, you might want to go to sleep mode in the loop in main(), which halts the CPU until an interrupt arrives. To toggle pin 13, you can set up a timer interrupt.
In some cases it is fine to busy wait if you know it's just for a few cycles, like when waiting for PLLRDY to become set.
Inconsistent enums
Some enum types are all lower-case, some start with a capital. I would use a consistent way to format type names, regardless of whether it is a struct, union, enum or enum class, and make sure it is different from how you format variables. Also, sometimes you add enum in front of an existing enum name, but that is not necessary in C++. For example, you can write:
void SetMode(gpio_pin pin_num, GPIO::Mode mode); | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
c++, embedded
Casting pointers to integers
While casting a pointer to an int might work for your use case, it is more correct to cast then to std::uintptr_t. This type is guaranteed to be large enough to fit a whole pointer.
Prefer using static constexpr for constants
In C++ it is hardly ever necessary to use macros anymore. To declare a constant, prefer static constexpr, like so:
static constexpr std::uint32_t HSE_CRYSTAL_FREQ_HZ = 25000000;
Avoid std::tuple in non-generic code
std::tuple can be very useful when writing generic code, especially in variadic templates. But they are otherwise a bit cumbersome to work with, in particular you need to use get<>() to access tuple elements, and then you have to remember the order in which elements are stored. Instead, you can just create a struct:
struct PLLClocks {
uint32_t pll_m;
uint32_t pll_n;
uint32_t pll_p;
};
And then let CalculatePLLClocks() return a PLLClocks.
Default switch cases
In SetMode(), I would change default to case GPIO::Mode::INPUT. This makes it clear that you handle the case of input pins, and by not having a default case, the compiler will be able to warn if you ever have an enum value that you didn't handle inside the switch-statement. | {
"domain": "codereview.stackexchange",
"id": 43681,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, embedded",
"url": null
} |
sql, postgresql
Title: SQL: Search for a keyword in several columns of a table
Question: I want to perform a search in several columns of a table. I use the following query:
select *
from Tabela t
inner join "TabelaPai" tp on tp."ID" = t."RefTabelaPai" and tp."RefProject" = 'projectid'
where not t."Deleted"
and (t.Col1 ~ '.*__param1__.*' or t.Col2 ~ '.*__param1__.*' or t.Col3 ~ '.*__param1__.*'
or t.Col4 ~ '.*__param1__.*' or t.Col5 ~ '.*__param1__.*' or t.Col6 ~ '.*__param1__.*'
or t.Col7 ~ '.*__param1__.*' or t.Col8 ~ '.*__param1__.*' or t.Col9 ~ '.*__param1__.*');
This will search for the keyword __param1__ in any of the columns and it's working fine.
But I don't like the way the query looks like. Any suggestion on how to refactor the query so it can look 'prettier' (without those ~ '.*__param1__.*' repetitions, for example)?
Edit: A little of context about the query:
What leads to this usage is that I can parameterize the data in the table. For example, I have a column in a table where scripts are saved. My application allows the users to parametrize the script using something like __param1__. If the user wants to rename the parameter I'll have to search for the usage of the parameter in every column that is parameterizable, and this is the query that finds where the parameter is used.
Answer: I must admit, I don't really see what's wrong with the repetition — assuming it is what you're wanting to do (and your columns aren't actually named t.Colx!). If I came across this query in a project, I'd know pretty quickly what it's doing I think: searching a bunch of columns for a single supplied value (e.g. searching name, address, phone, etc. with a single search box, perhaps).
As for the matter of storing scripts and their parameters in a database: I'd probably go for a second key-value table, something like:
scripts { id, name, body }
script_parameters { id, script_id, name, value } | {
"domain": "codereview.stackexchange",
"id": 43682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql, postgresql",
"url": null
} |
sql, postgresql
And you'd fetch the script and parameters and substitute the latter into the former in the app.
But then, I'm probably quite missing the point of what you're trying to do! :-) | {
"domain": "codereview.stackexchange",
"id": 43682,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql, postgresql",
"url": null
} |
python
Title: Process dictionary data and return variable data
Question: I'm pretty sure the script below can be refactored but I'm not sure how to go about it. Assuming I need to make use of inheritances but that's a skill I'm still working on. Any thoughts on how this script can be improved would be greatly appreciated. This is just a snippet of my project - the end goal is to retrieve data from multiple external API's, process/clean the data and export individual datasets to tables via mysqlalchemy.
import pandas as pd
import download
def parse_to_list(dic,k):
"""
Function parse_to_list takes a dictionary and nested key to return
portion of dictionary.
"""
lst = []
for x in dic['events']:
if x['type'] == 'MATCH':
for y in x['markets']:
if k in y['displayName']:
try:
lst.append(y)
except:
pass
return lst
def gamelist_parse(dic):
event_id = dic['eventId']
away_team = dic['selections'][0]['teamData']['teamAbbreviation']
home_team = dic['selections'][1]['teamData']['teamAbbreviation']
game_ref = f'{away_team}@{home_team}'
return [(event_id,game_ref)]
def runline_parse(dic):
event_id = dic['eventId']
away_team = dic['selections'][0]['teamData']['teamAbbreviation']
away_price = dic['selections'][0]['price']['a']
home_team = dic['selections'][1]['teamData']['teamAbbreviation']
home_price = dic['selections'][1]['price']['a']
away_line = dic['line'] if away_price > home_price else dic['line'] * -1
home_line = dic['line'] if away_price < home_price else dic['line'] * -1
return [(away_team,event_id,away_price,away_line),(home_team,event_id,home_price,home_line)]
class Gamelist:
display_name = 'Money Line'
df_cols = ['event_id','game_ref']
df_idx = 'event_id'
parser = gamelist_parse | {
"domain": "codereview.stackexchange",
"id": 43683,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
class Runline:
display_name = 'Run Line'
df_cols = ['team','event_id','price','line']
df_idx = 'team'
parser = runline_parse
class Parser:
def __init__(self,dic,clsdata):
self._dic = dic
self._clsdata = clsdata
self.to_list()
self.parse()
self.df = self.to_df()
def to_list(self):
self.data = parse_to_list(self._dic,self._clsdata.display_name)
def parse(self):
self.data = [self._clsdata.parser(x) for x in self.data]
self.data = [item for sublist in self.data for item in sublist]
def to_df(self):
return pd.DataFrame(self.data,columns=self._clsdata.df_cols).set_index(self._clsdata.df_idx)
#EXECUTION
games_dic = download.GamesDict('Baseball','MLB').main() #returns dictionary of data
gamelist = Parser(games_dic,Gamelist).df
runline = Parser(games_dic,Runline).df
print(gamelist)
Answer: Don't name variables x, y and k where more descriptive names are possible.
This exception-handling:
try:
lst.append(y)
except:
pass
first, shouldn't exist; but also will never actually catch any exceptions; there's nothing to fail here.
Add PEP484 type hints.
This code:
away_team = dic['selections'][0]['teamData']['teamAbbreviation']
home_team = dic['selections'][1]['teamData']['teamAbbreviation']
doesn't seem like it's going to succeed, because there are many rows for which there are no teamData dictionaries.
This:
away_line = dic['line'] if away_price > home_price else dic['line'] * -1
home_line = dic['line'] if away_price < home_price else dic['line'] * -1 | {
"domain": "codereview.stackexchange",
"id": 43683,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
can just negate -line rather than multiplying. Also, does this really do what you want in the case where the home and away prices are equal to each other? Can you assume that the home line is always the negative away line?
You may benefit from making Parser as an abstract parent of Gamelist and Runline, and varying the record generation by basic polymorphism.
You've omitted a section of your data processing, where you need to iterate over sports etc.
Suggested
from typing import Any, Iterator, Iterable
import pandas as pd
import requests
def get_data() -> list[dict[str, Any]]:
with requests.get(
url='https://www.williamhill.com/us/il/bet/api/v3/events/highlights',
params={'promotedOnly': 'false'},
headers={'Accept': 'application/json'},
) as resp:
resp.raise_for_status()
return resp.json()
def get_match_markets(dic: list[dict[str, Any]]) -> Iterator[dict[str, Any]]:
for sport in dic:
for competition in sport.get('competitions', ()):
for event in competition.get('events', ()):
if event.get('type') == 'MATCH':
yield from event.get('markets', ())
class Parser:
DISPLAY_NAME: str
DF_COLS: tuple[str]
DF_IDX: str
def to_df(self, markets: Iterable[dict[str, Any]]) -> pd.DataFrame:
df = pd.DataFrame.from_records(
self._get_records(markets), columns=self.DF_COLS, index=self.DF_IDX,
)
return df
@classmethod
def _get_records(cls, markets: Iterable[dict[str, Any]]) -> Iterator[tuple]:
for market in markets:
if market['displayName'] == cls.DISPLAY_NAME:
yield from cls._get_data(market)
@classmethod
def _get_data(cls, market: dict[str, Any]) -> tuple:
raise NotImplementedError()
class Gamelist(Parser):
DISPLAY_NAME = 'Money Line'
DF_IDX = 'event_id'
DF_COLS = (DF_IDX, 'game_ref') | {
"domain": "codereview.stackexchange",
"id": 43683,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
@staticmethod
def team_abbrev(team: dict) -> str:
return team.get('teamData', {}).get('teamAbbreviation', '')
@classmethod
def _get_data(cls, market: dict[str, Any]) -> tuple[tuple, ...]:
event_id = market['eventId']
away_team, home_team = market['selections'][:2]
game_ref = (
f'{cls.team_abbrev(away_team)}@{cls.team_abbrev(home_team)}'
)
return (event_id, game_ref),
class Runline(Parser):
DISPLAY_NAME = 'Run Line'
DF_IDX = 'team'
DF_COLS = (DF_IDX, 'event_id', 'price', 'line')
@classmethod
def _get_data(cls, market: dict[str, Any]) -> tuple[tuple, ...]:
event_id = market['eventId']
away_team, home_team = market['selections'][:2]
away_abbrev = away_team['teamData']['teamAbbreviation']
home_abbrev = home_team['teamData']['teamAbbreviation']
away_price = away_team['price']['a']
home_price = home_team['price']['a']
line = market['line']
away_line = line if away_price > home_price else -line
return (
(away_abbrev, event_id, away_price, away_line),
(home_abbrev, event_id, home_price, -away_line),
)
def main() -> None:
games_dic = get_data()
markets = tuple(get_match_markets(games_dic))
print(Gamelist().to_df(markets))
print(Runline().to_df(markets))
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43683,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
if __name__ == '__main__':
main()
Output
game_ref
event_id
ffb909b1-647e-4e55-8418-08185b91d110 CHC@STL
d4422840-d074-4285-ab8b-0e9a7efe50f4 LAD@SF
582f0d9b-68db-4c00-9cd5-a67b5e158b59 COL@SD
fb5729e1-7c18-4677-bc8e-2945138363ac OAK@LAA
64ad7ff0-c332-40ff-8b94-1ddbfd49cdbf LV@JAX
1e5e5964-a63b-4caf-9654-48535d9a61eb LV@JAX
a52257b5-ab62-4f82-bc7d-348dfc85f3e4 @
c2d17d0e-001f-4ef1-b560-6446830d91ee BUF@LAR
d3df8dc1-fc2b-48c6-9ce9-27175f0eaf5b SF@CHI
9e39445d-7c97-48c0-b976-331fdc0ad14c PHI@DET
22906ec4-07fc-4555-a0a7-fbdf0b72bb2a BAL@NYJ
cd54c138-261c-4995-8593-3dfd8b292b81 false@ATL
80df769c-227b-4d6e-95b0-0cd8063e1aa7 NE@MIA
dbe5a92b-b3d6-4540-97c5-df467df706f4 CLE@CAR
8cee45a2-8213-4897-a77e-c80f2b633346 PIT@CIN
273c7880-67ee-499f-acd7-9f3bccb96637 JAX@WAS
67653008-cb76-4276-affc-185c630f0ad4 IND@HOU
f41715b2-79e6-48bf-b950-a39294437a81 KC@ARZ
5d5e9a33-80b4-4172-9731-0022763d4d81 GB@MIN
48a31fb4-1f85-4867-9ebe-b1e7970e8080 LV@LAC
35fcb682-9e61-4066-b9b5-a834161336bc NYG@TEN
bab85113-360f-4fc4-9ff4-6df0fbc8b9e1 TB@DAL
9112dd1b-4e4f-4790-823e-8ae354ff34da DEN@SEA
7d0709c4-b547-4fa0-95a0-274513a7ee2a @
c878f903-533a-48dd-a60d-74bcc4fc1c54 @
3f54141a-fdf2-40a1-b6f1-c551f35c560e @
1b478545-1c07-4bf2-a411-da11fab5c024 @
event_id price line
team
CHC ffb909b1-647e-4e55-8418-08185b91d110 -130 1.5
STL ffb909b1-647e-4e55-8418-08185b91d110 110 -1.5
LAD d4422840-d074-4285-ab8b-0e9a7efe50f4 105 1.5
SF d4422840-d074-4285-ab8b-0e9a7efe50f4 -125 -1.5
COL 582f0d9b-68db-4c00-9cd5-a67b5e158b59 122 -1.5
SD 582f0d9b-68db-4c00-9cd5-a67b5e158b59 -145 1.5
OAK fb5729e1-7c18-4677-bc8e-2945138363ac -110 1.5
LAA fb5729e1-7c18-4677-bc8e-2945138363ac -110 -1.5 | {
"domain": "codereview.stackexchange",
"id": 43683,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python, image, ascii-art
Title: Convert image into ASCII art | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
Question: I made a python script that takes an image and converts it into an ASCII-art representation and saves it as a .txt file.
The logic is somewhat simple. It resizes the image to a manageable size, converts it to gray-scale, takes the value of each pixel and assigns it a character according to it. Then appends the characters to a string and wrap it to the number of pixels of width.
Can this be improved in any way? Does it follows conventions and best practices?
import PIL.Image
image=None
def closest(myList, myNumber):
from bisect import bisect_left
pos=bisect_left(myList, myNumber)
if pos==0:
return myList[0]
if pos==len(myList):
return myList[-1]
before=myList[pos-1]
after=myList[pos]
if after-myNumber<myNumber-before:
return after
else:
return before
def resize(image,new_width=300):
width,height=image.size
new_height=int((new_width*height/width)/2.5)
return image.resize((int(round(new_width)), int(round(new_height))))
def to_greyscale(image):
return image.convert("L")
def pixel_to_ascii(image):
pixels=image.getdata()
a=list("@$B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]) #remove the slice to get light mode
pixlist=list(pixels)
minp=min(pixlist)
maxp=max(pixlist)
vals=[]
lst=list(range(minp,maxp+1))
def chunks(lst,n):
import numpy as np
return np.array_split(lst,n)
lchunks=list(chunks(lst,len(a)))
for chunk in lchunks:
vals.append(chunk[0])
avals={vals[i]:a[i] for i in range(len(vals))}
ascii_str="";
for pixel in pixels:
ascii_str+=avals[closest(vals,pixel)];
return ascii_str
if __name__='main'
path=#drop your path here
image=PIL.Image.open(path)
name=input("enter the image name here: ")
image=resize(image);
greyscale_image=to_greyscale(image)
ascii_str=pixel_to_ascii(greyscale_image)
img_width=greyscale_image.width | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
ascii_str=pixel_to_ascii(greyscale_image)
img_width=greyscale_image.width
ascii_str_len=len(ascii_str)
ascii_img=""
for i in range(0,ascii_str_len, img_width):
ascii_img+=ascii_str[i:i+img_width]+"\n"
with open("{}.txt".format(n ame), "w") as f:
f.write(ascii_img);
print(ascii_img) | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
Answer: myList should be my_list by PEP8.
Add PEP484 type hints.
from bisect import bisect_left should be moved to the top of the file.
I think it's clearer, rather than image.getdata(), to just use the np.array() call on the image file. That way you can min and max on it without converting it to a list.
I don't see a lot of value in defining a local function chunks that you only call once and has only one line (the import not counting; that should also be moved to the top).
avals should not use a range, and should just zip over the two sub-series.
You should extract from your main code a conversion function that neither prints nor saves to a file.
Suggested
import PIL.Image
from bisect import bisect_left
import numpy as np
CHARSET = (
"@$B%8&WM#*oahkbdpqwm"
"ZO0QLCJUYXzcvunxrjft"
"/\|()1{}[]?-_+~<>i!l"
"I;:,\"^`'. "
)
def closest(my_list: list[int], my_number: int) -> int:
pos = bisect_left(my_list, my_number)
if pos == 0:
return my_list[0]
if pos == len(my_list):
return my_list[-1]
before = my_list[pos - 1]
after = my_list[pos]
if after - my_number < my_number - before:
return after
else:
return before
def resize(image: PIL.Image.Image, new_width: int = 300) -> PIL.Image.Image:
width, height = image.size
new_height = int((new_width*height/width)/2.5)
return image.resize((round(new_width), round(new_height)))
def to_greyscale(image: PIL.Image.Image) -> PIL.Image.Image:
return image.convert("L")
def pixel_to_ascii(image: PIL.Image.Image, light_mode: bool = True) -> str:
pixels = np.array(image.getdata())
direction = 1 if light_mode else -1
charset = CHARSET[::direction]
minp = pixels.min()
maxp = pixels.max()
lst = np.arange(minp, maxp+1)
lchunks = np.array_split(lst, len(charset)) | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
vals = [chunk[0] for chunk in lchunks]
avals = dict(zip(vals, charset))
ascii_str = ''.join(
avals[closest(vals, pixel)]
for pixel in pixels
)
return ascii_str
def convert(path: str) -> str:
image = PIL.Image.open(path)
image = resize(image)
greyscale_image = to_greyscale(image)
ascii_str = pixel_to_ascii(greyscale_image)
img_width = greyscale_image.width
ascii_str_len = len(ascii_str)
ascii_img = ""
for i in range(0, ascii_str_len, img_width):
ascii_img += ascii_str[i:i+img_width] + "\n"
return ascii_img
def main() -> None:
ascii_img = convert('archived/image2l.png')
name = input("enter the image name here: ")
with open("{}.txt".format(name), "w") as f:
f.write(ascii_img)
print(ascii_img)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
Output
IxL00QOqW%Q)I... . . .``',~tCd****#MW&%%%%&*d0c/?~<i!I;;:,""^`'``'....'...'''````^`'... ....'' .'`'.
ln0ZOQ0wMBO\!'`` . ..`:~(vma**o*#W8%%%BB%MdUr([-+>!I;;I;:,"""^'''```````^^^^"^`'`'''''.'' .'''.
;xQZOCQm#8Zti'`' .'^^;+\Uq*M##*#MW8%BBB8*pUf([_<!I::,,,,,^```^"^^^^`^^^^^``''''''..'` .....
IrQqwQ0wMBwj>',". `"^^:~|cZk##*ooM&8BBBB8#pUt}?+<il;:;I;:"^"","^^"^^^^````'``''. '` .''.
. ,\UqpO0m#Bqri."". ....'`^``,<(vmoWWM##W8%BB$$8bCr([_<illI;:"^^^^^^","^^^`````````. '''... .'''.
")XdkmZq#8dc+'""'. .'^^,<(Xqa####M&8%BB$%MdUj1-<>>!I,^```^^^"^^`''.''.'''. `^`'.. ....''. | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
.. . ^{cpkmmqo#mn<',,. .. .^,,,;~(u0kM&WMMWW8%BB8a0u|}-<!lI;:,,"^`^^````. .'..`^`' .''.....'. .. . ...
.... ...... ^1cqdOOwkaOx<`,". . .. .`"I!Il</Qa%8M*o#M&%B%8Ma0v\[+<ilI;:"",,"^""`'..'''..`^. .... .``'.... .... ..
.. '_xmpQ0w*&qu+^;: ..''. `,;li]fO&%&8888WW8%%BB%8owv([_~>!;"""``^^^``^^`'`^'.....'. .''.. ....''..`^,;l>+{|frxnnuvr\{_l"""^`.
11{{1)))1}]?---__-___-_1uZ**pqbW$#mzft\(1}[[[})|/rcCOJj?"`' `;-fLaaaWB$$B%%%%8W&%BB*qUx\[++?}1|/tfjxuvvvvxjf\}_<iI:"```,l<-]]-<;^"I+1fvYJLQ0QLQQCUXzzzzUQO0LX\+:`'. ..
bbbbdddddpppppppdbkaahhaoo**oaa#&W#abbdddddbkkkbbkk#$#C|;,,' I|L*ada#MWB$$$$%8&&W&%B8MkZCOpqwZ0CYczYcxvYUC0wkbmX|{1\xcJOZQLQLJLOmwqqZ0CXuxxf/|)1{}[]][][\vmakOx(1{{]+!:^'''.. .
bbbbdppppdbbbdbkbppqpddpqwmmwZOmqqwwwqqqqwqqwwZOOZmdobL\:^^. .. . I\O8MbbkbkoM%$$$$B%&W&8$$$&hq0Yurt|))))1{{{11)|xYmbhbwwm0Jznt//|(fzZbkqzf/|){}}}{{[[[[[[???)rUZqq0LCL00Q00CXr(]>:^..''......... | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
00QLLQ000OOZO0000QQLLLQQQQ00OOOOO00OOOOZZOZmZO00OZwdhbOf!::`. !jm&Waaakka#B@@$%88B$$8#bOYnt|(()1{}}}{}}{11{{|uQbkqCnf\||()}[{{1}}(/jf)}{}}[[[[[[]]???]]]][[{1111{{{1)\/jcC0ZZJj}!:,"^```'.....''......
mZZOOZZmmmwwwmmwqqqpddbbkkkkhhahkbbkhbddppqwZZZmmwmqbdZfI,:`. ijw%Wao#&8&Wokq0COd##qJvj/()}]??]]]]]]]][[]--1fzYcr|1}[][}{{[]]][[][[[]--][[[]]]]][[[]???]]]][}}[]]???--][]?])uCwC/_;^```^`..``^`'''... ...
#######MMMMM####MWWWMM#*********oaao**#W%B8#bmqdpqmmppZt,`"' !fm%8M%BWk0XnjfnYwkOzt()))11}[}}}[[[[[[}{}]???]]]??]][]?][[]???][]]]]]]??]]]]]???]]]]??------???????--????]]?-+)zQ0u}i,^^^^.'^"^``..`````''''.... . . .. .
pppqwwwwwwwmmmwwwqqwmmZZZZZZOZZmmZZmmmqb*%B8awqpqmZmdp0/,^,` !fw$@@8oLuf\\||cmmLx|()1{{}]]]}}[]]][]]]]]]]??????]]]]????[}]]?]]??]]]]]][[]???]]]?-------???????????-?]]]?-]?__?tC0Ct~I:"^`````''..'''''''............................ .....
zzXXzzzXXXzccczXYUJJCCJUUUJJCCLLLLQ0OOZqhW8&hwqqwOQ0mqZjI,:`. . ixp$@&pUx/|){{(tj/(1{11}}}[?][[]]]??]]]]][[11[?????????-??]]]?-__--???]?]]??---?????----?]]]]?????]]]??????---]?~?\YqOc1lllI:"`'...''```````'''````'..'''''''.''''..'''..................... ... ....
czzzzccczzzzzXXXXXYUJJCCCJJJCCLLQ0000Zwpa&8&apqqZ0LLOmZf:":^. .,>}jXZ*BWpXff/)}[[}}[]???-?[]?][[]???][[]]?????]]?---------?]]?-??--_--??]]]??-------??]]]???]]]]]???]]]]?]]]]--]}}}}[[\cwokwOQCXx\}+!I::,,,,,""^^```^^''''''''''''..''''''''''``'''''''.'........... | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
YYXXXzvccXXXzXXXYUUYYUJCCJJJCCLLLQ00OZwdo&%8aqqqmOQQQZZj;,;"'. .. `l?jXUUXux0#kLj1))1{}[[]]???--?[}]]]]]]]??]]]?--????????????????--?????--??????]]]]]???---???]]]?--????--?]]]????????][[]]]][)/jxrxzJ0wqOYj1~!lI,"^^"^`^^^````'''`''`^'..'```''````""^`^``''''....''.'''.
UYXzzzzczXYYYXXzXUUYYUUUYUCLLLLLLLQ0OZmpa&%8aqqqwOCJLZwx!;I"'. ."-fJmLzj|11|cZJr([}{}[]]]]??]???]]]?]]]]]]???]]?--??????????????-------????]]]??-????-----------???----???--?]????]]]]??]]??----?]]]?_-}(fcLZZJn1~l;:::"^""^^""^^^^^^`^^`'```^"^```'`^^^``'''...........''....... .
JJYYXXYYUUJJUUYYYUYXYYUUUUJJJCLLLLLQ0Omqa&%8hmmmZ0CJQwpxI,:"'. `?nLZUr)[{{[]]}1}]][[[]?_-]?--?--]]??????]]?--?]??---????????????-------??---????---???-----------????---?]?????????][[]]]]]]?--?[}]??][[[[[?]|nJOOLct?>!I:;I;:,"^^^^^^^^^`''''`^^'````^""^`'''..... ....''......... ......
JJJUYYYUJJUUUUUYYXXYYYUUJJJJJCCLLLCLQ0Zwh&%&hmZmZ0CJLZmj;,;"'. I|YwLx([}}]][[?][[[[[??][[]]??????[]??]]?????--???-__---??????--------------__----??]]]????????????????--?]]]???]]]?-?]?-___-----?][]???][}[??]??](nCqmX\~!!ll:,::,","^""""^````^"^```''^^^``'''..'.. ....''''''...........
JJJJUJJJUYXYYYYYXXXYYUYYUJLLLCCLQLCLLQOwa8%WhwwmZOQLQZmj:^,^'. ^<jqpJx()1{}??[[?][[[[[??][[]--?--??]?]??-_-???---??-__----???-------------??-__-------?????-------????--_--?----???-----__--??-___?]]?----??][}{{}?_+{rJwz]>!lI;:;:,,:,"","^^```^""^^^^``^^''''`''''.....'.''''''''''...........
CCCJJCLCUYYUUUJJJJUYUUYYYJLLCCCLQLCLLQOwh8%WappqZ0QQOwqr;`^'. ';}nm*Mmx/|()){[]][}[?????-----_-?]?-????]]?-------_----__-------------_______---------___-???-______--???-_________-----???------_____------??-?]\vC0Xx/|/Ya0(+i;:::;:,,""^"""^``'`^^^^^^`'`^^``^^`''``'''''''''``````'''''''''```` | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
LLCCUJJJUJJJCCCCCLCJJCUYUUJJJCLQQLLQ0Omqa88MhpqmZ0QLQZZf,'^. .. 'l|vzUOqpU\)(1[[[]???]]???????]??---???-_--------_____---------___-------___+__------___+____--??--_-???-?????--__+____--?-___-----------_+-?-------+-/XmpCcnQWm)<lII;;II;:,"^"""""^```""""^``^"""""^`'`""^```````^"""""^^^""^^`^^^^^^
CLLLCCCCCCCCCCCCCJJJCCCJUUCCCLQ00QQQ0Ompo8&obqwmZ0LL0ZOt"'`. .+fUCx/\/t([}{[]]??????????????????-???????---_-??------------?-_++___--------___------_____----?????]]]??-?????--------_________---------___---?--?[]-+]x0baddbX}+<!IllI;:,""",,,,,,"",,,"^``^,,,,""""","^```^,,"""""""^^^",,,"^"",:::
QQQQLLCCCCLLLLCCCJCLLLLLLLQLCLQ000Q0OZwpo%8*bqwmOQL0wmL('."`. `ijJvt({[?--?[[?-]]??????-?]]??-?????????????-_-?]?-----?????????-___--------_____-------__---?????????]]]??]?----------______---------________--?--?[[[_+?/Qa&bu1+~_<!I;;;:,,,,,::::::::;;;:,,,,:,,:;I;;;,"""^";II;,"^"""^^":;I;:::::::
QQQQQQLLLLLLLLCJJJCLLCCLQQQLCLQQQ00Zmmqd*B%*kpwmmZLOdpC1 .,' `-rYUt}{1}[}]??]]??]]]????-??]]?-?????????????----??-------????????]]]]]]????-____---???-------?]???????-??]]]?---???????----___---??????----??-__??-?]]]]]+-|XhhCt+<+ill!I;;;:::::;;;;;:::;;::::::,,:;;;IlI;;:::III;;;;II;;;;III;;;I;;;;
00QQQLLLLCCCLLCJUUJCCCCCQQQLLQ000OOmmwqb#$8adwmZZ0COapX[ ',' :[vOUj)}))}[]]]]]-_-?????]??????????--???--__????-__-----------------????]]]]?????????]???------???--???---??]?-____---???????-__--?]]]]]]?????--??????-???-??_(YpoQ1+<!l!!II;;;;;;;;;;IIII;::,",:::,,:I;:;lIIIl!!III;:;l!!lllII;,,":;:,,,
OO000QLLQLLLLLLLCJJCLLLQQQLQ00OOOOZZmmqkM$&hdpwZZ0CmMpr~.'"' >jUCj[}11{]?]]]]]?-----??]]?????????---??--_--???-_+_---____-------__-----------__?]?]????--------__-?]]]]?]]??--------????]]]]????]]]]]]?-------------?????]]])rZB8qz\[+~<!lllII;::::;;;;:::::;;;;;:;;;::;Il!!!lI::;;:::IIII:,,,"",,:;;;; | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
OOZOO0Q00O0QLLLLCCCLLLQQQQQ0OO000OZZmZwkM@%obpwmZOCwMw/i..'. `{YUu|]{1[?-??][]]??????]]]]]]]]]?---_-????????--__++_------_____----_----??---__+__-_____--???--____-??]]]]]???------??--?????][]]???????--__----???????]]]]?--](UW$8bJt[_~il!llI;;;;;;:,:::;;;;I;::;I;,:IIII;;;::::;;II;II;:,,,,,,,:;IIII
ZO0OOOO00QLLQ00QLQQQLLLLQ000Q00OOOZmmmqbM$%obqwZ0QLqWq\i' .:/ZJt)}11]----?]?-__-??]??]]??????-----?????????----____-???--____-?-----??????????---------?????-_+_____--------__---??????????]???---????----?????]]]]][[[]]??}\U*&*aqj+~<!llIIIII;;::::I!!llIIIIIIIII:,::;;;;;;;;;IllI;;I;;::::::::;Illl
ZZOOOOOOO0QLQ000QQQ0QQLLQ000000OZZZmwwqd*$%*kqmO0QCwWpf+^ `(0Ln|[[[?-___---__--???---------______-----??????]]]?-----???----------????????]]]----------__________________--___-------?--????-----????-------------??????]?1jCbakobx~<<>i!llIII;;;IIl!!!llIll!!!lll;;Ill!!!llIII;;;;:;;;::::::,,,::;;;
ZZZZO0QOZZOQLQQ0QLQ00O000OOOO0OZmZZmwqpdo%8#kqmZZ0UZMpr+' -zCYf}}}]-___----????????---------????????----------??------?]]?--_----______---??-_--------??????---_______-------______--?????--------??------------??????]?-?1\fYmdmti><>i!!lll!!llllll;IIIIll!!lllllIIIll!!llI;;;;;;;;;::,,:::,,,,:;;;
ZZZZZO00000QQ000QLQOZZOOOOOO00OZmmmmwqpda88MkwmmmOJmWdr~ . . itYLx1)(}]??]][]?---?-??????-----???]]]]??--________-??------?????-????--______---___-----____------___________________---------_____--????---------????????]]]-~_{zbqY)!!!IIIllI;;;;;;;;;;IlI;;;;;,,:;!l;;;;II;;::;;;IIllI;:,:;;;;;;II;;;
ZZZZmZZZOO00000QQQQ0OOOOZZZZZOOZZmmwqqpdo&8WkmmmmOCw&bx_'.`. I)Ywc))1[????][[[]????----______----?????-----_____--?------------????-----___--?----????---____-____________________--??--____--_-__-----_--------??--??---???-+1vqWO\->iii!lI;::;;;;II;IllII;;;:,"",:;;IIIIlIIII;IIllllIII;::;;;;IIlIIII | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
OOOOOZmZZ0QQ00000O00OOOOOOOOOOOZZZmwqqpb*8%&hwmmZ0CZMdn?^.'. "_vwz(1{[?---?][{[]??_______----?????????]]]??-____--___--------___--_++++++++__--------_____________--__-??--?--_____----__++-[?------____-?--__-???-----__?}1)(zhowx_<<i!!l;::;;;;;;;IIIII;;;Il!!lIII::I;:l>ii>>>i!!!lII;IlI;IIIIIII;:::
ZZmmZZZO00QQQLQ0OO0Q0OOOOZZZZZOZmwwqqqqdo8%8aqwwZ0Lmoqu?. ... ;1Xwc1[]??--???][]?----????????????????]]]??-__+______-----------______+++_---____--_+++++__-______+______--__----___++______+-]?_______----------???-------[\zOb*#Of[<<~illlIIl!ii!lllllIll!lllliiiiii!i>!I!>>i!!l!ii>i!!lIII;:;I;:;IIIII
ZZmmmZOOOOOZO000OZO0OZZOOZZZZZZZZwqppppdaW%B*qwwmOCZopu?. . `1CQYf{{{[?---???]]?-_----------------___--___++++__---??-______-?---?-___--?????-________--------_______________---__+++__--___---------__---??---???---??---(UphZr{~<~>lI;;;;Il!llIIIl!!i>>>i!!>~+~<>>><~<<>><~<>!iii!ii>>>ii!I;II;Il!!!!
ZZZZOOZZZOOOZZO0OZO0OZZZZmmmmmmmmwqpddddhM%$*qqqmOJOapc]..^' ^+udC\)111[??--?]]?]]?-??????----------____--_____-?????---______--???--__---__-???-+++_----_______--__-_______+__----_____---____-?-__-]1||1[-?]?-???----????-(JZJtl,!!!!lII;;IIl!!!!!iii!i<<>i!!i<<<<<<<<~+_++~<>ii!!!ii>>>>>>i!!!!!ii!lll
qqwmZZZZZZOZOOOOZZZOZZZZZmZmmmmmwqppppdbaM%B*qwwwZLZapz[..^' >nL0n[}1}?]]]]?][]?????]]]]]?]????------__--???------?-___--------___---???--___--??__----------__-------______+__??-__-????-------?-_---\CCu/}]]?????----??-?|zb*qJrtt////tft//ttffrncYCLQ0OO0QCCCLQZmqqmZZmmZOO0CJJYzvxf\(()1{}{{{{}[[[]]]
qqwwmmmmZOOOZZZOOOOOOZZmmmmmmmmwwqpqqqpbaM%B*qqqmZ0mkdC(^`"' -LOXj{[[?-]]?--?]?????]]]]]?????---?-??-_+__----____---__------??--_---]]]?-_+_--])tnx1?-_+_-____++------_-?---???][{1)}]?????????--____+|L0zf1[[?-?]]]?]]?]1j0hohpph*W&&#ahhbdpddbkkbkkkkbbkkkao*#MM*oabpwwwqqqkoaaoM%%&*hddkahaoooooaaaaaa | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
mmwwwmZZZZZZmmmmZOO0OZmmmmmmmmmmwqpppqpdh#%$#pppwmOmkkZfI"^' ]O0x|{}[-_??----?----?]]]]??????----???-_++______+___--______________++_---_++__+_)vaaj??--][{1}]--_--_-)jcXf1[???[tzUXf1{}]?]]]?_--??+-|vmQr([][???]]]]-_[/YpMMqCXzJZhMMdO00LCCCCLLLCJUUUYYYYXYJCL0O0QLCCCJCCCCLCJYYJObM%@@$%Makbbbbbbbdppp
mwqqqwZZZmmwmZZmZZOOOOZmmwwmmmwwwqpqqwqdh#%@#ppqwm0wahZj!:,' .)pwx|}}[?-??--??----?]]]????????????------?????---------______-----__------??-?]++|X*oj-_?1xJCXf)1}--}\nUQJu|[}]_[/UdZz/}}}[[][[]?---}/vQ0Ux)}}]--?---]1tzOk#Mkw0Q0QJOkoaOYJCCJUUUUJJJJCCCLLLCCCCLQQQ0QLLLLLLLQ0QQCJJUYJ0kWMhwQLLLCJCQOOQLLL
mwwwwmZZZmwwwmZZZmmZOOOZmwwwmmmwwqpqqqpbh#%@#qwmmOLZabJ(,^"' .(bm/1{[?--??????----?]]]???????????----_+_____+++__------_____-----__-???----___]|YqbOt}1jJwpUt1]?]{tU0OYf)]?-_-[j0pwu[?]]???]?-__-1rUOOYx({}[]-__?1\rUp*8&opO0QQLCUYZohmYuXJJJUUUUJCCLLLQQQLLLLLQ0QQ00QLLLLLLQ000LCCCCJCp#aqQJQQLQQQQQQ0000
wwmmZZZZZmmmmZZZOOZZZZmmmmmmmmwwqppqqqpbh#%@MdwZZOQmodX1:,:` .(kwt)1]-__??--??----?]]]????????????-----??]???--_____---__++_----______+___+~+[x0bdz/1/YmkOn|})\fvOqmYt){}[?_+1u0dLf}+?[-_-?}{)fcQqdwUnt|()(\juXUQqh#MMadwOQQ00QLJUJw#amJzJCUUYYYYJCLLLCCLLQLLLCLLLLLQQQQLCJCLQOO0QQLCCQd*hqO0OOQQ0QLLLQQQQ
ZZZZOOOOZZZZZZZO00OOZmmmZZZZZZmwqppqqpdbh*8@WkqZZZOqapY(I,,' ^/opf1}1)[???----?---?]]]]???????----???????----_+++++_--__+++__---_++_-_+~~_{fUd*#bZLQp*&#dLzYLOmdqLv/{--?-]1tYmahOzjnzvnnuzUCJULZb*M#kpppqqqpdhooabpmOQQ000QQQQQQLLLq*odOCLQLLLCJJJCLLLCCLLLLCCCLLQQLCCLQQLCCLQQQLLLLCL0dapOLLOOQLQLLCCCLLL
ZmmmZO0OOZmmZOOOOOZZmmmmmmZOOZmwqqqqqqpbh*%@&adwqwmqapY(;``. .}mwc\[}{}]]]?--???????]][]]??----?]?---__++++______+__---_--??----_-----[|xJ0O0CYzccunucYYXU0bMMawJr/fjxvzUL0Zwm0CUUUJJYcvnrt\)[+>?/UqbbwZZOQQQLLLLCCCLQQQQQLLLLLLLCCmhbw0CCCCCCCCCJCLLLCCLLCCCLLLLLCCCLLLLLLLLLLLLQQQQQOdap0CJLLLLQQQ0QLCCC | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
wmmZZOOZZmmmZZZZO0OZmwqwmZ000OZwwwwqqqpdh*8@&hqmqqZqadC|;""`. <uCUj}}1{}[]]]]]????]]]]][]??---????-_______________---____-??-__+~+-[\cQZ0Xj1+!lllI;::;I;;I!+}|fnzUJUYzcnj\1-<!llllllllIIIIIIIII;:;~(z0ZOCJCJUCQLCCCCCLLLLLCCCCCCLCUQpdpOCJCCCCCCCJJCCCJJLLLCCCLLLQQLLLLLQQQQ0000OO0QQQOk#dQCCLQQQLLLQQLLLL
wwwwmZZZZmmmmZZZZZZmmmwwmmZOOZZwqwwqqppdko8@8odqppmqabQ/l,:^``. 'l1r/[[[]?-??]]???????---???-__-????]?--__----__------??----?]----[\nYJXr)-<ii!lllI;IIllII;;IIIIIl!>>i!lllII;;;;;;:::;;;;;;;;;;;;;;:,:<)zOpwLJUJLLLQQLCUJLLLLLCUUJCJYLqhhZJJCCCCCCJJJCCCJJCCCLLLLLLQQ00QLCQ00QQQQ000QQQQZaWdQLLQ00QQQQQLLQQQ
wwwwwwwmZZZmmwwmZZZmmwwwwmmZOZmwqwwqqqpdbaWB8#kppqmpabL/l::`.. ^</Xr[?]???????]]]]??------__---??]]????_--------????---????]]_+?tU0Lu(_illllI;:::;;::;;;Il!!lIIIIIII;;;;;;;IIIIIIIIIII;;;;;;;;;::;;II:;</QqmQYXXJLLLLCJLQQLCJCLCCCJYQphhOUJCCCLLLLLLLLCJJJCCLLQQQ000QQQQQ0O0QQLCCLQ0000ZhMqCJCLQ00QQQLLQ0QQ
mmwwwwwmZZZZmwwwmZZOmwwwZZZZZZmmwqqqqqqdbhMB8#bwqqZwkdQ\;,;^' ,]fct_?}}}[]???]]]??----?]?-???---??---------------??----?]?+_[tUQJj-il!!I;IlI;:,,::::;;;;:;;II;;;;;;II;;:::;;III;::;;IllllII;;;IlIIlll;,l[uwwQYcYCCCCCLLLLCUUJCCJJUYQphk0YJCCCLLCLLLQLLCCCCLLQ0000000Q000000000QQQ00QQLQd*qCCCQ000QQQQQQQQQ
qwmmmmmmmmmmmmmmmZZOZmmmZZmZZZmmwqpqqwqdbb*%%WbZwwZmbpL(``;,`' ,?fXr}{))1}[[[[]]?????????]]??????--------___--------?--?]__-|YQCr?i!!i!llI;;;;;;;;;::::;;:::::,,;;:;III;:::::;;;::::;;;IIIII;;;IllIlllII:,+fCqOJUUJJJJJJUUUUUYYUUYYYLwkh0zJLCCLCJJJCCCCLLLLLCLLLLLLLLQQLLLLQQ0000QLCCCLOb*dOLL0O00QQQQQLLLL
mwwmZZZwwwmmmwwmmZZZZZmmZZO0OOZmwqqwwwqdbk*&%&kmqqOZdqJ(^'"`. "_jJu)11[]??]]]??---??-__--??----__-?]]]----____________-?_}rY0z}>l!i!IIII;;;;;;::;;;;:::::::::::;;::;III;;:;;;:,::::::;;;;;;;;;IIIIIlII;:::I)XZqLXYUUUUUUUYYYUUYYUYXU0pbQzUCCCCCCJUUUJCCCLLCJJJCCLLLLLCLLQQQQQQQLQLCCCLObodOQQ00QLJCLLLLCCC | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
wwwmZmwwqwwwwmmmZZZmZZmZZO00OZmmwqqwwqppdkoM%8bOwqZwkpC(^^;` .:(Jc|{]+~_-?----__----__------------???--___---__++++_-++?/Q0j[il!!lI;;;;;;;;;:::;;;;;;:::::::;;;;::;;;;;;;;;::,,::::::::::::::::::::::;Il;:I-vqqZJXXXUJUUYYYXXzzzXXCZqqCcXUJCCCCCJUUJJCCCCCCJCCLQQQLCCCLLLQQQQLLLLLCCLOpbZCJCLLCJJLQQLLCCC
pqwmZZwwwwmmmZZZZmmmmmZZZO0OZZmmwwwwqpppdbaM%%bOwwZmdqC)`"l^ .. .-cJXf1{}[]]]?---??]]]]]??---------???-__-----_____+++++]tzLz]!iii!l;;;I;;;::;;;;::::::;;;;;;;::::;;:::;;;;;:::::;;;;;;;;;;;;;;;:;I;:::;;;Il;;]j0pLXccXYYYYUUYXYYXXYQpdwCzYUUUJJJJJJJJJCCJJJCLLCLLLLLLLLCCCLQQQLCLLCCCLOdhmLLLLLCCCCCCCCCCC
ppqmZZmqpqwmZZZZZmmmmZmmmZOOZZmwwqqwwqpddbh#&8kmwwOZpwL|"^:^.. ;1Xmc()1[???---???????---??????--_------_______________{XQc\<l>ilI;;;III;;;;;;;;;:::::;;;;;;;::::;;::::;;;::::;;;;;;;;;;;;;;;;;:;;I;:;II;I!l;;<umZQXczXYYYYYYYUUUXcCqdqLXUCUUJJJJCCJUUUJUJJCCCJJJJJJCLLCCCCCLLQQQQCJJLOdhmJJCCCCJJUYJCCCJJ
wwwmOOZwqwmZZmmZmmmmZZmmwmZZZZmwqqwwwqpdbbh*&8kZmwqdhkO/,";"'. "\LXf{-][?-----?---_-_--?]]]]?-___----______+___---_-[tmpt~>iil;;;;;IIII;;;;;;;;;::::;;;;;;;:::;;;;::::::::::;;:::::::::::::::::;l!I;IIIIII;:l|zOZYczXXXzXXXXXXXzzLqpwJcYJUUUUUJJJJUUUUJJJCCJUYYYYYUUUUUUUJJCLQQLJUUCOdk0XXYJJUUUYUJLCCCC
mmmmZZmmwmmmmmZZZmwwmZmmwmZZmmwwwwwmwqppdbh*8BhZmwwphkmt,";,`'. ~fULr1)1}]?-??????-??????]]???--____++______-_--___?{fwdf+<i!lllIII;;;;III;;;;;;;;;;:::::::;;;;;;;;;:,,,::;;;:::::::::::::::;I;:;II;;;;;III:;>)JmCYzzzzzXXXXzzcvcJmwZUcXUUUUUJJJJUUUYUJJYYYYUYYYYYYXXXYYUUUUUUUUXXYC0dhZUYYUUYYYYUJCCCCC
wwZZZZmZZZZmmZZZZmwqwmmZZZZZmwqqqwmmmwqppdh*%$hZwqwpbbwt^^;"'. ^+XpX\(1[?---????-_-????----------_________----___~+[tOm|>i!lI;;I;;;;;;;;:::::;;;:::::::;II;:::;;:::::::;;:::::::;I;;:;;;;;I;;:::::;;;;;;;;;;;_uQ0LXczXYcvczccvvvCwqOUvXYYYXXYYYUUUUYXYYYXXXYYXzzXYUUYUJJUUUYYXXXYUJLqhmJYYXXYXXXYUUUUUU | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
pqmZZmmmZZZZZZZmmmmmmmmZZZZZmmwwwwwmmwppdbh#B$*pppppdbpj,";^.. . `t0Lv\{}[?------__-??-______--??-?_+++__+++~~~++_~~}jOZ\<>ii!lI;;::::::::::::::;;;::::;IIII;::;;:::::::;;:::::::;I;;::;;:;I;:::::::;;;;;;;;I,itY0LvuvccvvccvvvvuJqqZUvzYYXzzzXXXXXXzzXYXXXXXXXXXXXXzcXUUXYYUUYYYYUYYOpQzcvczXXXXXYYYYYY
qwmZZZZZOOOOOOZmmmmZZZZZZZmZZZmmmwwwwqpdbka#B$oqppqqpdqr:";^'. )XJc|}1{]-__-___-?]]?-____--??--__---___________~+1xmw\<i!!lIII;::::::::::::::;;::,,:::;;;;::;::::::::;;::::::::::::::::;;;:::::;;;;;;;;;II:>fUZLnxvunuvvvvccvuUmwOYuczccccczzXzzzcczzzXYYYXzzzXXzzzXYUUYYXXXXXzzXUOwCvnnuczzzXXXYXzzz
wwmmZZZZZO000OZmmmZOOZZZZZZZZZmmmmmwwqpdbho#%Bhmqpqpkhdn!;I"'. .. . .?rYz|[}[-__---?]][[[]?-____----__________--__+~~<+[fZw\>>i>!;II;::::::::::::::::::,,,,,::::::::::;:::::::::::::::::::::;;;::::::;;;;;;;;;II;~rJQXttxxxxnuvccvvcJmqZYnczcvvvvczzzzccvuvccczzccvvuvvvuvvcXzzcczzcvuvX0wCcvczXXzcvvvczXXX
mmZZOOOOO0QQ0OZZZZZZZZZZZZZOOZmmZmmmwwqpbka#%$hZwpwpboac>II,`'. .l1XJ/[]?-------?]]?---______---??-__-----_+~~~~~<<_|Opr?+<>l;;;;::::::::::::::;:::::::::;;:;:::::;;:::::::;;::;:::;;;;;I;;::::;;;;;;;;;;;II;~xJUcffnxxnnnuvvuuvJZZLzxucccvuuuvccccccvvcccvvuuuuvccvvuvvvvvvcczzcvvcQwCvuuvcccvuvczzccc
ZZZZOOOOO00Q0ZZZOOZZZZZZZZO0OZwmZmmmmmwpdka*%$amwwwwqa#Xi:;^.. `~zQf}]][[[?_++__---------____---???---_++++++++~~<}Cwr]iIIIl;::;;;;;;;;;;;;;:,,,,:::::::::::::::;;:::::::;;;;;:,:;II;;II;;:::;;;;;;;;;;;Ill-cQYutfxxrxnnuuvuuvCqmCznuvvvvvvvzzzcvccvvuvcccvuvcccvvcvuuvvvvvccccvcYOpLvnxuvcvuvvzXXzzz
wmmZZZZmmZOOOOOOOOOOOOOOOZZZZwqqwmmmmmwqdkho8$hZmwwZOkWU>::^'.... . "xLn\{[{}]?????-__?]?????--------?---_______++~~++[zQz/~lii!lI;:::::;;;;;I;I;;;;;;;;I;;;IIII;;:;III;;;;;III;;;;;;;;;;;II;I;;;;;;;;;;;;;;Ili}zLXujjxuuuuuuccvuvCqmLXuvvccvczzcccvvczcvvvccvvvvvuvczzzcvvvcvvvvvvccz0pQzunvvuuvvvvvzXzz | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
wmZZZZZmmZZOOOZZZZZZZZZZZZmmmmwwmmmwwwqpbkao%$hZwqwZQb&C~:,"`'... . `|zzx1[1[-_--????-----------------_______---___+++]jUOY[i>ilII;;;;;;;;;;;II;l?|rj)]_~ilIl!lI;;I;;;;;;I;::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;I!+)XLvrjrxnnnnnuvvnnvJZOLzuczcvuvzcvczvvczcvuuvvvvcccvvccvvccccvvuuvvcczXOdQzuuvcvvvvuuuuuuu
wmZOOOOZZZZZZmmZZZZZZZZZZZZZZmmmmmwwqpddka*MB$hZwqwZLd&Q]I"""'... .~/CU)-]?-----?---______-----------___++__------_+-1nbp/+>i!lII;;;;;IIIIIII;l>]/rruzzv\?<i!lIIll;;II;;;;;;;:::::;;;;;;;;;:,,::;;;IIIIIII;![jQ0ujxnunnnnxnvvunnYZOJvxuccvvvzcvccvuczccczzzcczzccvvvvvvccccvvvvvvvcY0wCvuuuuvvuvvvuvvvv
ZZOOZZmmmmZZOOOOOZZZZZOOOOOOOZZZZZZmwwqdko#W$$awqqm0QdWO(!^""'. ^-UQt11}]-__-??--??-------_____-]]?-__++______-?_++\dhv{ili!lIIIIIIIIIIIIIIIII;Ili~(xvuxf/)+!ll!!lI;;;II;;::;;;;;;;;;;;;:,,::;;IIIIIIII,I)cmmurvvuuuvvunnuuunYO0CcnvzzzcvvvvvvcczzccczzXXXXzcvvccccvccvuunuvcvvXLmqJvcccczzcczzzcccc
mmZZZZZmmZZOOOOZZZZZZZZZZOOOOOOOOZZmmwqpko#&B$*pqwZ0QdMZt<`^"' IxQQv{__-?-_?]????????------__?[]?-__+_______-?_+<1LqJtiIi!lIIII;;II;;;;;;;II;:,,":l+{\rzcf1~!lII;;;;;::;;;;;;;;IIIIIIIIII;;;;;;;;;;;;"I/JZ0urvvnnuuuuuvvvuuUZm0zrucccvvvvcvuvcccccvccccvvunnnuvvvvccvvuvvvcvnX0wwJvvcvvcccccvvczzz
wwmZZZZZZZOOOOOOOOOOOOOOO0QQQQ000OZmmwqpbh*MB$#dqwmOCq#wx~''^. 'i/OL/}[]?-__---??---????????????-______------_++<[vQLx>I!lI;III;;;;;;:::::,:;;::::::::;i}xvrt|)}_>!III::;I;IIIIIIIIIIIIIII;;;;;;;;;;I:>xQ0JurnuunnnnunnnunxYZmQcrnvuunnuvvvvvvvunnuuuunuuunnnuunuvccvuuvvvvunYmwOYnuvvvvvcvvcczzzz
ZZZZmmZZZmmmZZOZO0ZmwmZOOmdkhahdqwwwwmwpka*#B@owOOwZQq#qu-`",' IfYCn{?]??--__--??]?---???--??]]?-____-?--?-_-_>-uQOv~I!lII;;IIIIIIII;;;;;;;;;IllllIII:I~}\rzJCj]<!lIIIllI;:IlI;IllI;IlII;:;;;;;;;Ill_zwLcrjnxxrxxnnnnxxrxYmm0XnuvvvunnuvcccvuunnnuuuuuuuvvvvunuvvvuuvvccvvuUZZLznucczzzcvcczzXXX | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
wwmmmZZZZZZZZZZZZZmmZO0Zk#88&%B&odmwwwwpbho*8BMahoWMbh#dY{",:`.. 'Itw0j1??]?-----???--__---____-?----_-??-___-_+~-tUpC}<<!IIIIIIIIIIIII;;;IlIIIllII;;;;;;;;::I]tnccvvr(]~>ilI!i!!lIllIII;;;;::;;;;III![CbLvxrnuunxnuxrxxnnvJww0zxucczzcvuuuvvvuunnuvcvuuuuuvvvvnuccvuuuvczzcvY0Z0XuvzzzXzcvvczXXXX
qwmmZZZZZZZOOZZOOZZZZwph8B#bmbW&#dZmwmwpkaooW%BB$$@$8%%aC1":I^'. !tvcf{1)}]__???]]?---??-___--___--_+_------??-])vbO(+>lIIlllllllllIIIII!!I;IIllII;;IIIII!!lIl_1|tnXCXf}<i>!!!!ll!!!lIIIII;::;Il!ll>1QbJnuvvvvunvvuuvcvucLqmCcnzXvuccvvvczzzvuvcczXzcvvvvvczcuuvvvvvcccccvvJwwOUcXYXXYYYXXXYXXXX
mZZZZZmmwmmZZZZO00Ommwb*$%bmOp*WWbZmwmwpko*#&%$@$$$@@@@#0/>i!,`'. .I\Ju)}]?-__-????-----?-__---?-_--__-----????--}xbZ\_i!llllllllllllllll!!IIIl!lIIIllIIl!!iii!l;:""i|ncj?>illl!!!!!!lIIlIIllIIIIl!~)vp*wCUYzcvvvvccvcvnuzLmOJzvXYcvzXzzzzXXzccczzzXzcvvvvcczcvvcccccczzzzzcJmwZJzYUYXYYUYXXYXXXX
mmZZZZmmwwwmZZZmZZZmmwkM$8pOOqhW&b0Ommwdh*#M8$$$$$$@@@@#Zj_<>:^'. . [YYx)_?[?????]]????][]]]?-???-]}{{}]-?[]?-_+-1vkm|+>!!!!!!lllllllll!!lIl!!!l!i<~__-?--?-??]?---__?/ULUzuxf([_<i!ll!i>i!!llI;i?/zZh*awQCYcuuuvvcczzzvvzQbqQznvzczYYXXXXXzzXYYXXXzzzzzzzXXzzzzXXXXXYUUUUYY0dbwLYUJUUJUYYXYYYYYY
qwwmZZZZZmmmmZZZZOZZOmkM$%bmZwh&BhZZZZmdho*M8$$$$B$$$@@Mmx]+>;"`. itYLf-[{[?---?]???][[[[[]-?])fcJQ00Cvf)[]???{fUkO)~>i>>>ii!!llllllll!lIl!!<}jJmkaaooaaooao*######o*W&8%BB8#kmLXuf)?_+<>i+1tuYLOmpbkd0CLQQLCCCUXYYYYXzz0hhwXxzUzzXXXYJJUXzYUUYXzccXXXXYYXzzXXXXXYYUUUUUYY0dpmCYUJUUUUUUUYYUJJJ
ZZmmZZZZmmmmmmmZZOOOOZd*B8pOZqk&@aZZmZwph*M&%@$B8W#M%$@*0/>i!:^'.. . ,?vOn{}}[]__-][[]]]]]]]]??}\XZQz|(uCmZQ0Omwwpk*WoZ0ZO0OZO000QLJJUYXcvxf/trUpW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$&qu|}}(nQa%$BW**WB$@$$B$@@@B8#hZQ0QJYX0khdJvYJYzzXXXXXXzcczXzzccccXUUUXzzzXzzzzYYYXYYYYYQqw0YcYJUYJUYYXYUUJJJ | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
mmmmmmZmmmZZOZZZZ00QL0p*$8qQ0mb&@aZZmZmpko#WB@@$BB%88$@aJ(lII"'. ,f0Xt)[[]?---?---?]]?-_-]|uwhY(+l!-/LW$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$B%%$@@@@@@$B&*bqm00mdho#M&W*abpppppdbhM%$@@&hm0wh&$@@@@@@@@@@@@@@@@@@@@$Wp00QUXXCmppCczXzzczzzcccczXXzzzzzzccczXXXXXcczzXYYzzXXzzX0dpOUcXYYYUUUYXYUUUUU
mmmmmmmmmmmZZZZmmO0QQ0p*$8qQ0ZdW@ammmmmqba*M%@@@@@@@@@$aC/+>!:^' -nJJf{{[-_---????]]]?-1jQ*B%J\|/xf{/Up#*aaadwZ00QQCUC00Zqdkao#MMMMMMW8%8%B$@@$8aJj)-!l<xZ0z/{1\nYCLCzr\{_[j08@@@@@@@@@$WhZLJLOmOXnrjjuLkB@$&amLLCYXYLmddLvczXzcvvvvczcvcczXXXzcvvczzcczccczXXXXcczXcccQddZJcXUUYYYUUYYYYYYY
OZZZOOOOZZZZZmmZZOOO0Zp*$8pOZwb&@omwqwqbh*M&%@@$@$$8#MMwn];;;^. ^~u0ct({{}}[]][[]]]-?}nqW@Baz()xmOr1[fCZwp0j[+>iiil;;;;I!><~~++___+<~]]-|Xb$@$hJ)~_<:":1zQ0v|~;:i}jYQOLz/)fL8@@@@@@@@@8dX(-?|uXv],,"`I1C8@$Md0JUYXXYCmbkLvucXXcvvvvzzcvvczXzzccvczzzvvvcccczXXzcvvvccc0kbmCXYUUUUUUYYUCUYYY
OZZZOOOOZZZZZZmZZZZZZmd*$%dZwqk&@aZmwwqbho#M%@@$@@$&dh&pn]:;;^. .[nUYt)()1[?????]]?{f08@@hJt(xJq0/-!<])()]>llI;;l!!llllIIII;;;IllIIIllI?rq@@Bpc1~~<i;"^:[rJ0Ux[i;"",i}fz0d*B@@8*dwa8@&QnfjcLwq0f?-~!>1J8@$*qQJJUYzcUOko0vvcccvvcczzzzzXYYXcccvvcczcccccczXYUYXXXXXYYX0dbqQUJJYYUJJUYJCCCCC
OOOOOOOOOO00000OOOOO0Zd*$%dmwpk&@hOZmwqbh*#M%@@@$$@&dkWqr_":;^. . ,]Cwu(}][[]???]]?-)uq$@@wx|jdoLt>!+<lII;;;IlI;Il!!lIIIIIII;;Ill!!lIlll}ud@@Bmx1_~>l;:^'`"!]tncu/}~i>+}\vqM$@@#ZufLoB%bmZJnjjYQn)-i;>(L%@$omQJJJUYXYCb#OunnuvccccvvcvvvczzccvvuvvczzzzzzzXXXXXXXXXUYY0dkbQXUJUUUJJJCCCCCCC
OOOZZZZmZZOO0QQQ00OOOZpoB%hqwqb&$kQZmZwdh*#W%@@@@@$%M8$dx];,"`. . ,vmUr1[1{?-_][]?-?)xQk#qz|(UZLn]~~>iI;;;Il!!IIllllIIIIIlllIIIIll!!lIl[up@@Bpz(_~!;::,,"^^`.,-|xunvzJCzYpM$@@oLr/Yb8BhOc/{(jcc)i!I,-vpB@$hOLCJUYXXczmhZYcvczcczcvczcccvvvvvvvczXXXXXXXXYYXXXYUJJCCJULwkh0zUCLLJUCCLLLLLLL | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
OOOOOOOZZZOO0QQ000ZmZZqaB%kwmmpMBkOmwZZwdaM8$@@@$B8W#&$dn{i;,`.. ']xLCf((1}]]][[[]?-]1umaaCf1{t\]<llilIIIIIIIII;;;;IIIIIIIIIlllIl!!lII<(0$@@%oQn|]~l:,,"^^`...`,!-)fnXLqW$$@Bdv//Yb%%p0Q0mOJx)+lllI)Q*$@%b0LLCJUYXccQdwQUYUUXXXXXXYYYYXzzczzzXXXYYUUUUUUUUUJCCCCCLLJCQqbZCCLQQCJJLQLCCLLL
OOOOO0OOOOOO00000Q00Q0whBBaqZwkM8kOZmOZqboM8B@$$$$%WaW$pj+"",'. .^?U0v/}]}[[?-??--]/XYcXCdpx[<!>]|)-<llII;;;;;;IlI;IIIIIIIIlllII;IlllI>jwM$@@@%Mokpm0LUzvxf//\|||/rYw#B$@@8hLj|/Yd%%p00Zwc[~>>i!>?u*$@%#wCJJJUYYUYX0pqZUzXYXXXXXzzXXXXXzczYYXzcXYYYXXYYYYUJJUUYUCJUUCZpZLJUJJUUJJCCJJJJJ
OO00QQQ00000000OOO00Omdo%B#dZwhWBW**adqdh*&%BBBB$$$%M&%px-,",`. ;jJLz\)1[???]??[(zpY}i>tJw0j\rCdJ(_!!!!llI;;II;;;IIII;;IIlllII;;;IllIl~/Up*&B$@@@@@@@@@@@@@@@@@@@@@@@@@BaCx(?]xZ&$Maho*qUXXzXJObM$@@&kOJCCJUYXzccQpqOcxvcccccczzXzccczzzYXzzzXYYYYYUYXYJJUJUUUUYXUQdamJYYCLJJJJJLQLCCC
OO00QQQQQ00000OOOOmqaW%B@$8Mo#8$@@@@B*hhoM&%B$$$$@@BMW&pu],,,`.. `?nwL|}1}[[}[[[\zLLj<!ii?uL00Czr{ilIllIIll;;;::;II;IIIIIIIIIIIIIlllIIIIIl+{|tjuYCQZpka*#W8%$@$$$$%WW#kZzj(]<l!1chB@@@@@@@@@@@@@@@$8*d0CJUUYYUXcczLqpmzxvcvvuvvczXYXzzXYXXXXXXXXXXYYYUUUUUYUUJUUYYJ0boZYYULLJUUUUCQLCCC
000QLLLLLQ00000000mbW$@@@$BBBB$B$$@@B*hhao#M8B$@@$B8M%@bn+`^,`. .")wmj(1{{{}-]|cpOf]!!ii!!i<<ilI;:;::::;;;:,::;II;;;;IIIIIIIIIlllI;;;;:;III;;;;Ill!iii>>><+_-__]}_<~~>!!lll!I;;</Xmko#MM*akkdqmOLYzzXXXzccczzcvvcULZZXxuuuuuczcczXXXXXYYXXXXXYYYYYYUJCCJUJCLCJUUUJLqhmJJJJJJUUUUJCCCCC
QLLCCCCCLLQQQQQQQ0mbMBBB@%addka&@@@@$8&&WWMWW&%$$B&#hM$bx+^",`. !vQCu|(()}_[rQhL[><>i!I;:::;IlII;;;;;;;::::;;;;;;;IIIIIlllI;;;;;;;IIIIIIIIl!l;IlIIII;::;IIllIIIlI;:;;;IlIIII::![uOahmUuuvunnnnnnuvccvvczzzccvvcXCqdCcccccvvccvczXYYYYYYYYYYUUUUUUJJJUUJLLCCJJUUJ0b#d0CUUJCJUUUUUCCCC | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
LLLLCCCLLLLLLLLQ0Zb#8$BB@B#ahoW%@@@$$$@@@$$$$$$$$BW*aW$dx-,,,`.. ,1YkQ\)11{]1xLbY~li!llII;;IIII;;Il;;;III;::,,:;IIIII;;IIllllI;;;IIIIIIIIIIIII;;;:::;::;IllI;II!+}(tjrxrrrrt(}-ii-fOkadOmpqm0JzzYYXzcczXYzzXXzccYQhoOXXXYXccczzXXYYXXYUUUUUUJJJJJJCCCJJCCJJJJJUYUQdop0LJUUJUUUJUJCCCC
QQQQLLQQQQQQQLQOmb#B$@@@$$$$$@@@$@@@@@@@@@$$$@@@@%#ak#%du?"",^.. .:x&ac/{1){|z0qviI<il;;IIIIII;;;;I;;;;;:,:;::::;;;;;;III;;;;IIIIIIIIIIIIIIIII;III;;;;I;;,;i?|rvcvxjf/(1{{1{[_<>!II<tOdpCcX0aMawUXYUUUUXcczzXYYXU0o&mXzzXXvcXYYYYUUXXYUJJJJUJCCCJJJCLLCCCJUJJUUYULd*pQUXYUJJJUUUYJCCC
00QQQQQQQQQQQLQZqhW$@@@@@$%B@@$@@@@@@@@@@@@$@@$B%&*hb*8bc?^",^. (kWaQx/(1tQwQr>i+>l;;IIIIIIIIIIII;;:::;III;;;I!iilIIllI;IIIIIIIIIIIII;;;IIIII;;IIlll;I>{rczr)-<!i~]1)(()[_~>i!!l:I+\zUUucwo*pYzYUUUUYYYYYYXzvcUbMwJYXXzvzUUUUUJJYYUUJJJJJJJCCCJJJJCCJJCLCCJJCJJqadOCUJCJJCCCCCCLLL
000QQLLLQQQQQL0ZqbM@@$@$$%W&B$$$$$@@@@B88B$@$%*kbbbdpo8pn+'^,`'. "|q&$#mcfjXbpn{ii~>lI;II;III;;;;IllIIIIll!~[fXOqqm0Xf}i!i!lllllIIIII;;;;;;lllllIIII;;!}uzx(<IIi}n0hM&&88&MaQn|}]-+>l;!)vOkohZJzzYYYYUCCUUUUYYXXJb#mUzczXzYJJJUUJUUUUJCCCCCLQLCJUJCLLLCJJCCCCCLCCp#hwQCLLLL000QLLQQQ
00QLCCCCCCCCCCLQmb#B@$$$$B88%B$$@$$$@@%okh#%8#bwqppqwa%dn-^,:^'. .:|Z#%BMmYXQ*p/+!!i!lIIIIIII;;;;IIIlIIIIIl>}/jf([??]]_>I;I;IIlIIIIIIIIIII;IlllIII;;:;!+|Uc[iIIli[u0pbqwZ0QQLcf)]-~<i!!lIl_|c0pq0JXXYXXXXXXUJJJUYJb#mUzzYUYUJCCLLLCLLCLLLLLQQQLLCCLLLLLLCJJCLQLCCLb#kZLJLQQQQQ0QQQQQQ
O0LCCLLLLLCCCJC0md#B$@@$$B%%B$$$@$$$@@B*hhMB8#kqqqddqo%dx_^":^' .;\ma#%BdQZpkC-I!!!lIIIIIIII;;;IIIllllllllllllI;Ii+]?+illi!!!llIIIIIIIlllllIllI;II;;;!+)uu/\\()11)(((()){]?-~<>>>ilIIIllI;;!]jJqmJYYXXYUUUJCLCJUCdomJUUJJJCCLQQLCCLLLLLLLQQQQQQQLLLLCCLQQLLLLCJJLbMpCUUCLLLQQQQQQLLL | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
00QQQQQLCCCLLLQ0md*%@@@$@$$$$$@$$$$$$@%ohaM%&*kqwwqwZh%dx+`^,^' ,\wkboWMM%Mmu?ii!!llIIIIIIIII;;;;;IIIIIIIIllI;:;i(JwwY\]~>illllI;I;;;;;;IIIIl!lIIIIIlIi_{\jrxnxxrrrrrrrnvJ00QCCQQUUUXcr/({-+?xdb0JXXYYUJJJJCJJJQh#wJUUJJJJCCLLLLQ0QQLLQQQQQQQQLLLLLCJCL00000QLLOkMbOOO00QQQQQ00QQQQ
00QLLLCCCLLQQLL0wkoM&%B$$$$B%%B$$@@@@$&hbk#B8#kpqqpwZk%dx_^^"`' .:tdhwph%@%kc|}_>!!llI;;;II;III;IIIIIIIIIIllllIII;>(nCCXUYx|?<i!lIIl!lII;IIllIIIIIIIl!ll;Illll!!l!!!i!!!i-uwdqLJOZQQOZmqddddqqkW*q0JJCCCJCCLQLCCQhMpQLLLQQQQQQQQLQQQLLLLLLQQQQQQQQ0ZOQQQQQQQLLLQOhWaqmZO0QQ0OO000000
0QLCCCJJCLQQLCC0wdbbbbhaaaaoo*#W8&&WM*abbhMB&*bqqqqmOk%qt>`^"^'. ,thowZq&$kY)~+~>i!llIIIIllIIII;;;;;;;IIIIIIIllll;I>}fnzOdw0QJXur\}]]-+~<i!!!lIIIIII;Ill;;Illl!llll!ii!!li|Uda0XXzcczXYUJCLQQLLQQ0QCCJCCCCCCCCCC0aMwCCCLQ0OOO00000000000000QQ000000O0000000000QLQbWaq0LOO000OZZZmwww
QLLLLLLCLLQQLLCLZpbbdqqqqqqqpdbkahhhkbpwqk#%WobqqwwZOk%m|>"",^'. ^\dhmmqM8bU|-_<ii!llllllIIII;;;;;;;;;IIIlIIIIIIllI;l_fJCv)>i>-\X0wm0LLCCQQJXuxxjt/|1[-+>!!!lllIIl!ii>iill?rd&wJUUJJJJCJUUUJUYYYUCCCCLLLLLQQQQQOwM8qLLQQ0OZZO000OOOOOOOOOOOOOOOZZZZOOZZZZZZZZmZOOb#hqZOZZmmwwwmZmwww
00QQQQQLCLQ00QQ0ZwmOQLCCLQQQLLQQLLLLQ00QZd#%WabpqqwmZaBZ1l^^"`. ^/kawZwa#*mf[-~i!!llllllIIII;IIII;;;IIlllllll!lIIIll;l_/vcx|1)xZC|>`'`:?XJ|+!i-{\rvJQCUzccvuvzXYvnnnnxj|}?)Q*kZJYUJCCJCCJJCLCCCCCCLLQQQ000QQQQ0moMqQ0OOOZZZO0Q00OOZZZZOOOOOOOOZZZmmmmZZmmmmmmmZZdabqmZOZmwqqwwmmwmm
O0QQQQQLCCLLQLLQLJUYYYYUJCCCCCCJUUJJCLLLOp*%Wadqwwmmwa8L-:`^"'. "f*#qwqk*%av)}_>i!!!ll!!llIIIIIII;;;;;;;;IIIll!!lIIII;:l~1fzOk&@WZu)-~_|O0-. ;rUf1}[}}}\uqbu}]?][1fcXUp**bQUCCLCCCCCCCLLLLLLLLLCQ000QQ0QQ0m*WwL0OmmmZZOOOZZZOOZZOOOOOOOOOOZmwwwwwwmwwwwmZZZb*hpmZmwwmmmmwwwmmm | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
LLLLLLLLLCCJJCCCJUUUUUCCJJJJJCCJUJJJJCCLOp*%Whpwmmmwp*&C+;:"^'. "fo*wwqpk$8Lf[~ii<>i!!!!!llllIIII;;;;;;;IIIIIIllI;;;III;;Ili~-)ruvvcczCqM#Lnf|{<I~\waY)I'. i|L0? ~upWaqmOCCLLJJCJJCLQQQLLCCCCLLQQLLQQ00QOq&BdLQ0OOO0QQ0ZmmmOOOOZZZZOOOOOZZZZmmmmmmmmmmmZOOb*#aqZZmmmmmwwqmZZZ
LLLLCJJUJJJCJJJUUUJJJJCCCCCCJCCJUCCJJCLLOq*%#bpwmZZmd#&J~;:,^'. .:j**Zmqqk%&0r]i!i>i!l;IIII;;IIIII;;;;;;;IIIIIIllllIlllIIIIl!!llIIIIl>_]}1(truzXzXLwh#WM*bwZZd*WoU/[<:"l\0bkQzXYUUUYYYUUJCCCCCLLLLCCLLLLLLLLLCCQZoMqLCLQQ00000OOZZZO00OOZOO0OOOOO0OZZZZZmmmwwwmmmdo#aw0OZZZOmqqqwmmm
LLCCCCCCCJJJJJUYYYXYUJJJJJJJCCCCCCCJUJCC0q*%#dqwwmZmd*WY>::,"'. '!uW*OZppk8&mu[<<>>ilI;;;IIIIIIIII;;;;;;IIIIll!!!!lIIIIlllllIIllIIIll!!I;;;llll!><~_-}|rYCQmd#%B$$B&*kbhW$$%&*dwmZO0QLJJCCCJJJCLLLLCCCCCLQQ00QQQOdkZLQ0OZZZ00Q00OOOO0OOZZZZZZOOOOOOZZZOOOOZZZZOOOqh##q0OOZZOZmwwwwww
LLLLCCCCCCJJJCCUUJJUUUUUJJJJJUJCLLLJJCLC0qo8#bqwwmZwb*MXi::"`'. . 'iuW*Ompwqa*kC(??+>!llI;;Il!!lIIIIII;;;;IIIllII;I;IIIIIIllIIllIIIl!lIl!!i!l!lIII;;;I;;;;Ill!>_[1(\tfxvUOkW%$@@$%&WM#obwZ0QCJJJCCLQQQCCLLLLQQLLL0mh*qQLLQQ0OOOOOOZZZZOOZZZmmmZZZZZZmwmZZZOOOOOZZOOwboowQ0OZZZmmmZZmmm
JJJJUYYUUJJJUUUUYYUUUYYYYUUJJJJCCCCUUUUULwo%#dwmwwmqb*#Xi::,^'. 'lxoaOwdqqba#qr1]+>!llIII!ii!II;II;;;;;IIIIIIIIIIII;IIIIIIIIll!lII!lll!!lll!!llIIlllI;IllIII;II:,:;;;;Il<]\nXYcr({)cbokmLCCJJJCLLQQQQQQQLLLLLCCLOh#pO00QQ00OO00000OZZZZZOZZZOOOOOZmmZZOOOOOOOOO0OOwo#q00OOOOOOZZmmmm
JJUUUJJJJJJJUYYYYYUUUUUYUYYYUJLCJCCCJUYYLwo%#bwmmmmqk*#X<Il:^'. .;jhhOwdqqkoMqf}-~i!llIll!!lII;;II;;IlllllII;IIIIIIllllllIIIllll!lIIllllll!!!lllllllllI;;III;;IIIlllllllIIII;;;Il[uw8MdOCCLCCCCCCCLLLQQQQQCCCJJJQdawQLLQ000QLLLQQ000OOOOOO0O000000OZZOOZZZOO00000Ow#8kZO00OOOOOOOOOO | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
CCCJUUUUJCCJUYYUUUJJUYYYUUYUJJUUUJCLCJUJQq*%MbqmZZZwboovl","^'. ';jaamqdddka#wt}]+>!!!!!!!lIII;;II;;l!llllII;IIIIll!!!!!!!i!IIl!!!!!!!ii>iii!!i>i!ll!!ll!!lllllllllllllll!!l!!!?rO&&bZCJCJJJJJUUUJCLLLLLLLLLLLCCQb*dOCCLQQQQLLLQQQQQQ00OOOOO00000000OOOOO0OO00QLLLOaWkm00ZZOOOO0OZZZ
JJCCJJJCLCJUUJJJJUJCCJUYUUJUUUJJJCCCCJJULmo%MhdqmZ0mdaocl"""^' . .IjhamwppdhahQ/[]+>i!llllllII;;IllIIlllllllllllllll!!!lllll!llllIIllllllllll!!!!llllllllllllll!!!!!!llll!i!llll[YdMdXcYUUUUJJJJJJJJCCCCCJJJJJJJUCb#kmLJLLLLCCCLQQQQQLQQ0000QQLQQ000Q0OZOOOOOO0QQQLQkMkwQLZZOOO0Q0000
CCLLLCCLLCCJUYUJCLLQLCCCCCJJJCQLCLLLCUUULwo%WhbqmZOmdaavl:I,`' .IjbkZwpqp**wz(]?_~>i!lll!!!lIIl!!IIIl;IIl!!i!l!!!!lllllllllllli~++_-??-+~<>>!!lIII;;IIIl!!!!!!!!iii!!ll!i!ll!l?vq8hXvzXYUUYYXXXXXXYUJJUYYYUUUYXYwhbmLUJCCCLLLLLLLLLCCLLLLCCCCCLQQQLLQQQQQQ00QLLLC0kMhwCJ00QQ0QLLLLL
LLLLLLLLCJJJJUJCCCCCCCJJJUYUJCLLCLLLLJJJ0p#BMbqwmZ0ZpaauI;!:`. .. ,-vh*hkhho%WZu(]-~>ii!llllllllIIIlIIII;;IIll!!i!l!!ii!!l!!>~-)uCwba*######hm0LYvuxj/)}?_~<>i!!lll!iiii!l!>!l!!l>{Y&#CXXYUUUUUYXXzzXYUJJJYXXXYXzczOdkpLYYYYUJJJJJJCLLCCCLLLLLLQQQQQQQLLQQQQQLLLLLLCLbodZJULQCLLLLLLLL
QLCCLCCCCCCCCJCLLCCCCCJJUYUJJJCCCLLCCJUULq*$MbpqwZ0OdaavlI!,'. ... ^i)uOb*M&8%$@@&Ou|}?+>ii>>>iiii>>illlIllllIll!!!!!!iiii!!<]tz0doW%%&#ahbqqo&&oZOdhaaooabqqwZQUcnt)1{]-+<ilI!>!liili[z&M0JJZdbpZQCUXULQ0QLCJYYYUUUUYUQmbdQYUUUJCCCJJJCCLCLQLLLQQ0000QQQLCCLLQQLCCLQQLCLdobmJYCQ0wbbdwZOO
QLCLQLCJJJJCCLLLLLCJCLLCJUJUUJCCCCCCJCJUQp#$MdqqmZ0Zk#*cl:I"'. `}cd#abqb*W&W#&aYf([+>!!i>><>ii>>iiiii!ll!!i!ll!i!l!!!<]/XwokmQQbokpqqqqqZZh#awznvvuXQhMpCXY0b&%8&##*bwOJvj/|)[-__-(Xd%*CJ0wbaokmJXX0h&8k0JUJJUYUJJYYCmM8aq0LLCJJCCCLLLLCCLLLLLCJLLLCCCLLLLLLCCCLCJUUUCpahmXcCOpko*apO00 | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
LCJCQLCJUUJCCCJJCCCJCLCJUUYYYUJJJJCCCCCJ0p#B#dqqwZQOd**cl;l"'.. .. ."~\QkakpqpbaM&M**qx){?~<>>ii>>>!!!iiii!!ll!i>>iiiii!ll_fJdkwUf_:,?LapwqqqwmOOk#*b0CLCCma%$h0UCwhM&8%&hmOZpo%$$%Madqqpa88amCOdppbkdmJXUZo8$MbOJUYXXXXzczCqW$%#q0JUJUYUUUUUUUYYUJJUYUJCJJUUUUYYYYYJCCL00LXzQpdwJYQmdkkhk0UUJ
CCCCLCJJJUUJJCCJJJJUCLJUJUXXXYYUUJCCCLCC0p#$MbpqwZQZk*avl:I".. .. . `I-/zZkkbddppddbh*&&*qXr/)[_~>iiii>>>>>iiiii!!l!!i><<>>~{vm#Wh0urr\)(rp#dwwwwmmOZa&#hqqppqoB@$#bpk&B%%B@$*pwwpa%$@$8#a*MMMW#akk*WM*##abwmpaWWM88*kpwwmwmOQQOwbho*#kOQQQQQLLLCCL0mwwmZOOZwdkhdZ00000QLQOb&8#qLZpkbmmdkhhhhbOCLQ
LLLLCJUJLCCJJCCCCCJCCLJJJUYYYUUJCLQLLCCULw*BMbpwZOQma#hu!;I"`'... . ';[vOhoohkbbddddppddpdk#WW#hbpLuf\{-~<>i!!!iiiiiiiii>>>>!~/C#@@BW#*###**#88W#okpqwZmo&M##WBB&%$@@$B%B$$BB$$@$$BB$$@@$$BB%%%%%%%BB%BB8&%B8WMW8&Moa*&%$$BBBB%8WMWW#akaW8&*bdpdpmOOmd#B&apmwdoMMW%B%&#abppdkaMB@$8#ooMMooMW&&888M*##
JJJCCJUUJUYUUJCCJUUJJUUUUYXXYYYUUJCCCLLC0pM$MbpwmOQmh*hu!Il,`'... .. `+uqWWabdddddbbdddbbdppddbbh*M&8%%&*d0Uzx\)1]_~<<<>><<<i!<{cpW$B&*hbdbbbbkho#W&888WhdoW#aqpho**okdbhookpmwdkaahhkdppqmmwqppwmmqpdbbkkpqbaMWWW#ohbddbko##aaa*W&&88W#aha*WWWWM####*#MWM#***###ohbkh*MW&&MM&8&W**#W&8&&&8%8&MabbhM%88
YYYUUUYYYYYYYUUJUUUUUUUYXXXXXYYUUUUJCCCJ0dM$#dqqwZLZh#oc!:I,`'.. ... ,1zb#okppddddddddddbbdddddpddddbbkkko##MWW#*akdqZCzxft/())tcp&B$%W*ahkkbbbbbbkbbh*W%8&%%*pCYYXzccuxxnczcvuuccczzccvuuuvvvvvvvuuvcczXUUYXYUL0O0LLCCCCCJJCJJJJJJCQQQ0QLLCJCQOwpbkbdqmOQCLOwppqZQCUYXXYJL0OmwqwmOOOO0OOQQ00QQQ00LCQO0Q
YYUUJJJJUUUUUUUJJJUUJCJUYYUUUUYYYYYJJJUYQdW@#pwwZ0J0b*av!:;^'....... .>/Zoakqqdddpddddpdddppppdbppddppddpddbbbbbkhhh*WWW&8&&WWWWWWWWWWM*akbbbbddbkdddbbbdbaM%$BMdLYYXvvvunxxnuuunuuuuuunnnnnnnuvccvuuunnnuvvvvvccXXYYYXzzzXXYYXzcccvvcccvvvvvvvvuuuvczcvuuvvvvuvczzccvvvcccvvcvvzXzXYYXXzcvzzzcczXYYYXXXYY | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
CCCCJJJUUUUJJJCCCCCCLLCJUUJCCCJJCJJCCJJJ0bW@MbqmOQCQqa*X>"^^`''`'. '^>up##bppddddddddbbddbbbbbbbddbbbbbddbkkkbbbbbbbbbddddbkkkkhahkdpbkkbbbkkbdpdbkbddbbkbdkoW88oZCJXcccvvuuuuuunnuuvuuuuuuvvuuvvccvvvvuuvvvvnnvzXYYYXzzXXYYXzzzccczzzzzccvcccccccccccvvuvvczzzcczzzzzzzXYYYYXXUOwwOCUXXXYYUYzczXXzvzXzzYU
QQQQLLCCJJJCCCLLCCCLQQQLLLQQQQLQ0000QLLLZk&@WhdqmOL0qoWJ~,^""``^`..'.^_rq#hdpdkbddbkkkkkbbbbddbbbbbbbbbbbddbbbbbbkkkkkkkkkbbkkkkbkkbdbkkkkbbdbbkkkbbkhkkbkkkbdbaM%8kZCYXzccvccccccvvvvcunuvvvccvccvvuuuuuuuuuvvuuucczzzzXXXXXzzzzzzzXXXXXYUUYXzzXYYXXXXXzzXXXXXzzczXYYYYYUUJJUUJQZdhapLUJLZpkkdwZO0000QLCJUU
LLLLCCJJJJJCCLQ0QLLQQQLLLLCLLCCLLLQ0O0LLObW@&hdqZ0LOb#&Y>:;"^^^^^'..`ixqaobppdddpdkkbbbddbbbbbbbddbbbdbbdddbbkkbbkkbbbbbbbbdbbbbbbbbbkbbdddbkkbbbbkkhhkbbddbkhhkhM&&oZQCJJUYYYXXzzccvvvuuuuuuvuuvzcvuuuuvvuuuvcvvvvvvcczXXXXzcczzXYYXXXzczzzzzzzXYYYXzcczXYYXXXXYJJJJUUUUJJUUUJLOOCLZqbkaakpZOZqbbbdbkhahbwm
LLLLLLCCCCCCLLQLCJCLLCJJJUUUJCLLLLLQQLCJQp#$WhpmZOQZkMWY<;I,^^^`''.'!(OWodpdbbddddbddddpddbdbbkbddbbddbbbbbbbkkbdddbbddbbbbbdddbkkkkkkkbdddbbkbbbbbbkkbbbddddkhkba#B&d0JUUYYXYYYXzcccvvcccvvvnnnuvuuvvuuuvcvuuuuuuuvvcccccccccvvvvzzcczzczzzzXXzXXXXzccczXUUzccXJLLCUYXYYYYUUJL0LJXXCZdbdmQJUYYUJJJUUJJCQQLL
CCCCJJJJUJCCCCCCCJCCCCCJJJJJCCLLQLLQQCCJObMBWhpmmZOmb#8J~l!I:,"..`^;{zbWhpbkbbdddddbbbbddbbbbbddddkkdddbbbkbbbdddbbbbdppddbbddbbkbdbkkbbdbbbbbbdbkkbbbbbbbbbbbkkbba88oqCYYXzccczzzXXzzzzzcczcvvuunnuvvvuvczzccccvuuuuvvvvvvvvvvvvvczzXXXzzzczXYXXXzzzXYYYYYYXzzXYYYYYYUUYYYYYYYYzzzXYUUYXzzzzzzXXXXzzcccczzz
CCCCJJUUYJJJJJJJJJJJCCCCCCCCCCCLLLLQQQQQmkW$WhdwmZOZq#$O[l:^`^^`'.`lfmo#bwpdbbddbbddddddba*M*kbdddbkbbkkbbbbbbbbkkkkbbbbkkkbbbbbkbdbbbddbkkbbbbbkkkkbbbbbbbbbbbbbbh#W&ow0JYXzczccccvuuuuuvvvvvvvvcvvvvccccccczzcvvvvcccccccczzzzcccczXXzzcccczXYYYXzccccvczzXXXXzzzzXXXXXzcczXXXXXXXXXzccczccccczzzzzzzXXXXX | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
JJCJUUUUUCLLLLLCCCCJUUYYUUUUYUJLLQQ00QLLObM$WkpwmmmZmo$q/~,^^^`''':-za*adqpdddppddbddbbbkhM%Wahkbbbbkhkkbbkkkbbbbbbkbbbkkkbbkkkkkkkbkkkbbkbdddbbkhkbbbddbbbddbkkkbka#8#pQXzcunnnrrxxxnuuunnuunnxnnxrrrxnnxjjjrxrrrxxxxxxxxxxrrnunnnnnnnnxxxnnunnnnxxxnnnxxnuuuuuuunnnuuunnnuuvvuunnuvvvuuvcccvvvvvvvvvvuuuuu
JJJUYYYYYJCCCCCCLLLCJJUUJJUUUUCLLLLCCCCC0q*%&obqwmmmma%dn-";I^. '~jw&oqpbao##*##MM*ooaaaoM%&#ohhhhhhhkkkhhkkbddddbbbbbbbbbdkkbbdbbkkkbddbbbbbddbkbbbbbbbbbka**ahhkk*8MbQvnxjft/\|||/fjft////\\\||||((|\||(((|||||\|||||\\\\\\tfjjjjjftt/tfjrrrjjjffjrrrjjrxxxrxxxrrrxrrrrxnxrrjjjrrrjjjjrrxxrjfffffjfffffff
CCJUYYYYUJCCCJJCCCCJJJJJJJJJJJJJCCCJJJJC0w*B&okpmOOOZk8hY},;I"' !\Ca**&88#dOJJJXcYC0mh*#&B8#ahhoW&WWWW&&WMMMM#*ahhkhhaahhkkkbbkhkbbddbbkkbbkbbbbbbbbbbbddh*MMakbbbo88#mXvurft/\\\\||||()1)(|()))(((((|||||\\\\/\\\\\\||\//////ttffft////tjrjjjjjfffffftfjjffjjjrrxrjjjjjjfffjjrrjft/ttfftttfftttttffffffff
JJJUYYUUUCCCJUJJJJJJJJJJJUUUJJJCLLLCJCCCQwo%WhdwZOOOObMa0|Il!,`'...'I?\v0db0f1]??_~+--|Jk8B%Moao#W%$BB$$BBBBB%8W#**M&8&M#***#MMMWM*ahkh*#M*ahhhkkkkkkkbbkbbh*W&#ahaoM%%WqYzvxft/////\()\jxnf\()(((((|||||\\\|\\/\((|\//||\/t/\\||||\\//////ttttffft/ttffffjjfffjrrxrjft///////////\\|||\\\\\\\////\\\\\/////
000QLCCJUUUUJJUYYUJJJUUUUUJJJUJCCLLCJJJCQZh&*pZQ00QQQwohZ/Ili:^^^'''. `}xJz[<?-~~~<<+|Ch8&abbaM&%88&&W&&%$$B%&M*oo#W%WoaoM8BBBBB8MoahoM&&Mo*WM#oahhaao*#*aaoW8M*o*WWodOUvnxrft///\|()\XZdmr\xJwmJx|(|\///||(((()11)|//|()))(||(((((||\\\\\||||\\\\\//ttt//tttttftttt/\\||||((|||(||()(())(|||(((((((|\/\|||
UUJJJCCJUUUUUUUYYYYXXXYYUUYYYYUJCLLCCJJL0mhWopZQO0CUJZaopr<~+I"^^^`'.. `/UJn?<]-<<~<+[jw**oa*MW&M*akkkbh*W%B%&#*aao#&BWooM8BBBBB$%W#*aoW%8Wo*&8&888888%BB%&WWMaJjtckomJcuxrffttttt//txXQmZ0JLw*BMqOLJzxt/\\||()11))(|||(){{{1)(((((((((||((()))(((((|\\\\\\\\\\|\||||||||||))(||)1)((())1)|||((()))))((((((( | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
UUUYXXXXXXXYYXXXXXXXXXXYUUUUYYUJLQQQ00Zwpb#%MkwOZ0JYUZaaqtI!!^. "vmXt-<_+~~+>_\Uo&hh#WW#akbbkkbbddh*MWM#oahhoM&W##MMM**#M&8&W##M8B%&MM88888888%$$BB%B%Mpu)\X#WZUcunrftfxvXC0Zw0JUJ0ZZQYQbdZmqhk0zr/|(())1)(((()1)))))))(((()))))))))))11)(()))(((())((((((((((||||||)(||((((()(()1)(((((((())(())))))
OOZmmmwwwwwqpddbbbbkkkkkkkkkkkkao***#W&%%8B$&admOLUYJma#aLnnunxrjfjrrxxXo80x|{[_<~_~[cp88kdkkbppdkkkbddbbbbbbbkhkkkbkkhhhkbbbkkkkhhhkkhao*****oa*M&%B%W&B$$$B#wn|tJW&ZUvnrrrjffffruczx//fjjft\/ft|11rYQOLJYzcunxxjt\|(()((||||((((((((((((|||))((((((|||(()((||||||||||(((()(|((|||())()11111)((())))())1111
#MWW&&WWW#*###*o****ahbddppqqwmwwqqqqmmZZwh&&#dOCUXXJZa&%Moaaao*###MMM&%$WQnj\)[-__+1Uh88kdbbbbbbbbbbbbbbkkbbbddbbkkkbbbbbkkkkbbkkkkbbbbddbkhkbbh*W8W#hh*&B$$oOvffY#Wp0Jzvuunnnnxxrrjjfjrffrrjt/\//\|\fnvXUUYUUYzurf//\||||||||||||((())))))))(|||(((((())1)|||||||||(()))111))((())()1{{{{11)((()))))((((((
OOOO00QQQCJCCJUUUUUUYYYUUUUYYYYYYYYYYYXXYCwo8$8M*ooo###ohqOOOQQ00QLLQOda#dn(/([??_-}jq&&#bdbbbbddbbbbbbbkbbbbbbbbbbbbbbbbbbkkkkkbkkbbbbbbbbbdpddkhhhhkkkbaWB$hCx/tUW8pQUzccvnxnunnnxrxnnuuuuxffrrfffffffft////tttt///ttft////////tttt//\\\\\\((||||((||(()))||||||((((((((||()11(()))1{1(()(((((((())1)))111
YYXXXXXXXXYYUUYYXXXXYUUUUUUUUUJJJJJUUUUUJCL0wdppppqwwZ00QQLLQ00000OOZm*8hQr||)]--_?/U#$*kbddppdbbkbbbbkbbbbbbbbbbbbbbbbbbbkkbbbbbbbkkkbkbbbbbbbbbbdbkkkbpdh&$hJj\x0%%qQCYXXXcuxxnuuunnnnnnnxrrrxxxrrxxxrrrrrjjffffjjjjjjfttt//////tffffffffjjtttt/\\\\/\\\\\///\|||\\|((((||)111)(((())))1111{{{11)))))))(((
uuunuunnxnnuvvuuuvvccczzvvccccXXzzzccvvczXzzzzzzzczcvczXXYXYYXXYYUUJLmW$qc/)){]-??)YdW&kpkkbbdbbkkbbbbbbbbbbbbbbbbbbbbbbbbbbkkkbbbbbkkkkkbbkkkkkkkbbkkkkkka&$dXjjJd%WmLLJUYYzcccccvvuuuuuunnxxxnnunnxxnnxxxxnxxxrjjrxnnxrjjjjffffffjjfffttfjjttffftttfff//////tttttfftttttftt/\\/tt/\\/\||||((((|\\\\///tfff | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
xrjjjjjffjjjjjfffjjjjjrrrrnxrxxxxrrjrrrrjjrxrrrrrrjffjrxnnxjffrnnnxxcLM$Zx/(1[-+_[/m&MobdkkkkbbkkkkkbbbbbbbbbbbbbbbbbbkkbbdbbkkkkbbbkkkkkkkkkkkkkkkbkbkkbbkWBdXrn0hWo0JJUYXzzzccccvvvvvvvvvunnnuuunxrrrxxrrrxrrrxrrxnnxrrxnuxrjjjjffjjfttffjjjfjjrjffjrxjjjjttjjffffjjrxxxxjrrrrxxrjffjfffjftttffjjfffjjjjjj
jjjjjjjfftffjfjjjjjjjjjjffft//fffjjfftttfjjjt//tfjfffjjrrjffjjrrrrxxuU*B0f\()}?-](nbB#kkkhhhkkkkkkkkbbbbbbbbbbbbbbbbbbkhkdddbkhkkbbkkkkkbbbbbkkkkbbbkhhkbbkWBdXrxOa#hQUYzvccccvuuuuunuuuvvunnnnnnnnnnnxxxnnnxrrxxnxxrjjjrxnnnnxxxxrrrrrjfjrxxrrxxxxjjrxxrjrrffjjjjjrrrxxxrjfjxxrxxxrjjrrjxxxrjjjjjjjjjjjjjjj
ffttffffffffffffjjjjjfff//tt//tfffffft////tft//ttfffffrrrjjrxxxrrnnncC#BQt(11[--[tUo$Mkhhhkbbbbkkkkkkbbkkkkkkkkkkkkkkkkkbbbbkkkkbbbkkkkkkbbbbkkkkbbbbbkkdba&$pcfrZo#kQJUXcvvunxnuunnxxxxnnxxxxxxxxnuuunnnnnnrrxnnnxxxxxxxxnnuunxnnnnxxrrrrrrrxxxxxxrrxrrrrnuuuunnnnnnnnuunrjrnnnxxnnxxxxxxxxxrrrjjjrrjjjjjjj
tt/tttftttffffffftttttff//////ttttttffffffffjjfffffffjrxnuuuuuuvvuuuUm&BQft|{]__[r0#B*bkhkkbddbkhhkkbkkkkkkkkkkkkkkkkkbbbkkkkkbbbbkkkkkkkkkkkkkkkkkbbbkkbbh&$pcjnq#MkLYYzvunnnnnuuvuunnuuuunnuuuunnuunnnnxrrrnuvvuuuvcvvuuvvuunuuvccvuuvvvvuuuuuuuuvvunxrxnuuunnnuvunxxnnnnnnuunxxxnnxrrrrrxxxrjjrxnnnnxxxxx
fttt//////ttfffjjtttjjjffjxxxrjjjjfjrrxxnunnnnuuuxjjrxnuunxnuvvvuvuvQb#az||)[--?1vqM%obbkhhkkkkkkkkkkkkkkkbbbbbbkkkkkkkkkkkkhhkkkkkkkbbbbbbbkkkkkkkkbbkkkkkW$bUnuZoWhCXzccvuvuuunnvvvunuvvuuuvuxrxuvunuunxrrrxnuuuuunnnnuvvuxrrrxnuuuuuuuuuvvvvvvvvvvvunxxxnnnnxxxxxxnnnnnnnuuunnxrxnnnxxnuunxxuvcvuuvuuuvvv
///\\\\//tffffjrrrrrjjjjrrjjrjjjrrrrrrrxxxxxxnnnxrjjxxxnnnnnnnuvuunvQkhqu|\|}?][(UaMMakhhhhhhhkkkkkkkkkkkkkbbbbbkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkbbbkkbbW$kUxrCbWoLXXzccvuuuuuuvvuuuuvvunnunrjjrxnnxxnxxxxnnnuxrrrxnnxrrrxxxxrrxnnxxrjjjrxrrxxnnuuuunxxnnnnnnnxxxxnnnxxxnnnnxnnxxnunxxxnnnrrnuuunnuuuuuuu | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
\\\/ttttt////ttffjjjftffjf//tttttfjjjjjfffjrrrftfjjrrjjrxrrxnxxrxxxv0hhZt-1)}?-]|C#W#kdkkbbkkkkkkkkkbbbkhhkkkkbbbbbkkkkkkkbbbbbbkkkkkkkkkkkkkkbbbbbbbkkkkkhW$hCnn0a8oLXXcvvunnnnnnnnxnnnnunrrnnxrrrxnnxrxrjjrjjjjjrrxxxxxrrxxxjjrxuunxxnnxrrjrrrrrrxnnnxxrxxxxnnnnnnnnuunxnunxrjrxxxnxxxrrrxnnxxxrjjrnnnnuuu
ffffffffffffftfjrrrrrxnnxrxxxrjffjxxxxnxxxnuunrfjjxrjfffjjruvxrjjxxnLkhmt-)(}]??{nmW$#kkkbbkkkkkkkbbbbbbhhhkkkkbbbbkkkkkkkkkbbbbbbkkkkkkkkkkkkkkbbbkkkkkkkh&$aQuuZaMkYvcuxnnxrrrxnnxrjjjjxnrjrjjjrjfjjjrxjttjjjjjjjrrjjfffjjrrjffrnnnnnuunxxxxxnnnnuuunxrrxxxxxnnnxxxxxxxrxxrjt/tfffjjfjjjjrrxxrjjrrxnnnnnnn
nxxrrrrxxxrjjfjxxxrxnnnxxxnxxrrrxxxxrxxnnnnnxxxxxxnnxxxrrxnuunnuunxnYwMWU|(1}[[-~]tOM8WkdkhkkkkkkkkkkkkkkkkkkkkbbkkkkhkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkhkbdkMB*mzvZa#bXvcuxnnnxxxnnxrjjjjjxxrjjrrxnxjjrxxxrjjxxxxrxxxxxxrrrrrrrxxrrrrjjjrrrrxxjfffttffjffttfffffjjjjjjfffjjrrrjttffffffffjffjrrrrjffjjjrrjjjj
xxnnuuunnnnnnunxxxnnnxxxnnnnnnvvunxxnnnnnnnxxrnnnnnnxxnnnnuxxnuvuxrjxzp*qYt)(1]-_+?/Y*$&ohkkkkkkkkkkkkkkbbkkkkkbbkkhhhhkkkkkhhhkkkkkkkkkkkkkkkkhhhhhkkhhkka&BoZvnOhMbYcXvxxnxrrjjjrjfftffjjfftfrxxrjffjjftttjjjftfffffjjjrrrrrrrrrjjjjjjjrrrrjjjffffffftttfft/////tt/\\\/ft/tt//ttt/t/////tttffffffjffffjjjj | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
On path-likes
@TamoghnaChowdhury suggests
taking path as an actual pathlib.Path instead of as a str, at least for the purposes of the type hint. Maybe even path: pathlib.Path | str to shut the type checker up (I'm not sure where you can get the type annotation PathLike from)?
You can use os.PathLike. However, if we were to abide by the protocol of the inner open() call, then a PathLike is incorrect, because it can also take a file-like:
:param fp: A filename (string), pathlib.Path object or a file object.
The file object must implement ``file.read``,
``file.seek``, and ``file.tell`` methods,
and be opened in binary mode.
But I consider all of that to be a bit much for this application, and would constrain it to PathLike for simplicity and clarity.
Simplified algorithm
I don't think you need to bisect. You can simply load the image in 'F' mode (32-bit floating-point), scale to your min and max, round to the nearest index and then index into your charset. You can take the opportunity to improve Numpy vectorisation and eliminate your loops.
from os import PathLike
from pathlib import Path
import PIL.Image
import numpy as np
CHARSET = (
"@$B%8&WM#*oahkbdpqwm"
"ZO0QLCJUYXzcvunxrjft"
"/\|()1{}[]?-_+~<>i!l"
"I;:,\"^`'. "
)
def resize(image: PIL.Image.Image, new_width: int = 300) -> PIL.Image.Image:
width, height = image.size
new_height = new_width * height / width / 2.5
return image.resize((round(new_width), round(new_height)))
def pixel_to_ascii(pixels: np.ndarray, light_mode: bool = True) -> str:
direction = 1 if light_mode else -1
charset_str = CHARSET[::direction]
charset = np.array(tuple(charset_str), dtype='U1')
minp = pixels.min()
maxp = pixels.max()
scaled = (pixels - minp) / (maxp - minp) * (len(CHARSET) - 1)
indices = np.around(scaled).astype(int)
ascii_array = charset[indices]
rows = ascii_array.view(f'U{pixels.shape[1]}')[:, 0]
return '\n'.join(rows) | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
python, image, ascii-art
def convert(path: PathLike) -> str:
greyscale_image = resize(PIL.Image.open(path).convert('F'))
return pixel_to_ascii(np.array(greyscale_image))
def main() -> None:
ascii_img = convert('archived/image2l.png')
print(ascii_img)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43684,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, image, ascii-art",
"url": null
} |
c#, design-patterns, unity3d
Title: Code to determine move position in a hex grid when the user moves the stick on the gamepad
Question: I have code that is responsible for determining move position in a hex grid when the user moves the stick on the gamepad.
cameraAdjustedMovement is a Vector3.
_xThreshold and _yThreshold are floats.
_isOdd is a bool. | {
"domain": "codereview.stackexchange",
"id": 43685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, unity3d",
"url": null
} |
c#, design-patterns, unity3d
The code is very simple. We just check input from cameraAdjustedMovement and determine where to move. The _isOdd case is basically when where we want to move is a pointy hex, so if you constantly input up, then you will go in a straight line in a hex grid, switching between left and right.
Is there a way to improve it without making it too complicated or is this code as good as it can get?
if (cameraAdjustedMovement.x < -_xThreshold)
{
if (cameraAdjustedMovement.z > _yThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.ETopLeft;
}
else if (cameraAdjustedMovement.z < -_yThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.EBottomLeft;
}
else
{
movePosition = ScenarioManager.EAdjacentPosition.ELeft;
}
}
else if (cameraAdjustedMovement.x > _xThreshold)
{
if (cameraAdjustedMovement.z > _yThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.ETopRight;
}
else if (cameraAdjustedMovement.z < -_xThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.EBottomRight;
}
else
{
movePosition = ScenarioManager.EAdjacentPosition.ERight;
}
}
else
{
if (_isOdd)
{
if (cameraAdjustedMovement.z > _yThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.ETopRight;
_isOdd = !_isOdd;
}
else if (cameraAdjustedMovement.z < -_yThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.EBottomRight;
_isOdd = !_isOdd;
}
}
else
{
if (cameraAdjustedMovement.z > _yThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.ETopLeft;
_isOdd = !_isOdd;
}
else if (cameraAdjustedMovement.z < -_yThreshold)
{
movePosition = ScenarioManager.EAdjacentPosition.EBottomLeft;
_isOdd = !_isOdd;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, unity3d",
"url": null
} |
c#, design-patterns, unity3d
Answer: My main concern with this code is its repetition: you're making the same checks over and over, and performing very similar actions over and over. This gives lots of space for bugs to hide in, and means that any fixes need to be applied in multiple places. Enigmativity appears to have found one such bug in your sample code already.
First let's look at the repeated checks. In your current code you make the check for movement up and down the grid dependant on the movement left and right in the grid. i.e.
if (moves left)
if (moves up)
move topleft
else if (moves down)
move downleft
else
move left
else if (moves right)
if(moves up)
...
But these checks don't actually depend on each other, so instead we can just make each check once. Note that I've introduces a couple of new enums to encode the possible directions.
enum HMovement { Left, Right, None }
enum VMovement { Up, Down, None }
HMovement hMovement;
if(cameraAdjustedMovement.x < -_xThreshold)
{
hMovement = HMovement.Left;
}
else if(cameraAdjustedMovement.x > _xThreshold)
{
hMovement = HMovement.Right;
}
else
{
hMovement = HMovement.None;
}
VMovement vMovement;
if(cameraAdjustedMovement.z > _yThreshold)
{
vMovement = VMovement.Up;
}
else if(cameraAdjustedMovement.z < -_yThreshold)
{
vMovement = VMovement.Down;
}
else
{
vMovement = VMovement.None;
}
This removes some of the repeated checks, but it adds in a repeated action: inside every case of the if-else tree we're assigning to the same variable. This is somewhere else we could introduce errors. Instead, let's switch to using the conditional expression syntax:
enum HMovement { Left, Right, None }
enum VMovement { Up, Down, None }
var hMovement =
cameraAdjustedMovement.x < -_xThreshold ? HMovement.Left :
cameraAdjustedMovement.x > _xThreshold ? HMovement.Right :
HMovement.None; | {
"domain": "codereview.stackexchange",
"id": 43685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, unity3d",
"url": null
} |
c#, design-patterns, unity3d
var vMovement =
cameraAdjustedMovement.z > _yThreshold ? VMovement.Up :
cameraAdjustedMovement.z < -_yThreshold ? VMovement.Down :
VMovement.None;
Now we have the two directions, we need to combine them to work out the net movement. Given that all we're doing is assigning something again, we're going to learn our lesson from the last step and use expression syntax again (this time with a switch expression).
enum Movement { Left, TopLeft, TopRight, Right, BottomRight, BottomLeft, None}
(var movePosition, isOdd) =
(hMovement, vMovement, isOdd) switch {
(HMovement.Left, VMovement.Up, _) => (Movement.TopLeft, isOdd),
(HMovement.Left, VMovement.Down, _) => (Movement.BottomLeft, isOdd),
(HMovement.Left, VMovement.None, _) => (Movement.Left, isOdd),
(HMovement.Right, VMovement.Up, _) => (Movement.TopRight, isOdd),
(HMovement.Right, VMovement.Down, _) => (Movement.BottomRight, isOdd),
(HMovement.Right, VMovement.None, _) => (Movement.Right, isOdd),
(HMovement.None, VMovement.Up, true) => (Movement.TopRight, false),
(HMovement.None, VMovement.Down, true) => (Movement.BottomRight, false),
(HMovement.None, VMovement.Up, false) => (Movement.TopLeft, true),
(HMovement.None, VMovement.Down, false) => (Movement.BottomLeft, true),
(HMovement.None, VMovement.None, _) => (Movement.None, isOdd)
}
Note here that, while in your code the case where the user does not move is implicit (you simply do not have the final else case after the if..elseif), here we have to define it. This is an expression, rather than a statement so it must always return the same kind of thing, no matter which branch it took. | {
"domain": "codereview.stackexchange",
"id": 43685,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, unity3d",
"url": null
} |
c, linked-list, queue
Title: Type-generic queue implementation using singly linked lists
Question: Simple lightweight queue implementation using data size registration and singly linked lists as the underlying type
Update #2
/*
Author: Jared Thomas
Date: Tuesday, August 2, 2022
Type-generic queue using singly linked lists
*/
#include <stdlib.h>
#include <stdio.h>
typedef struct Node {
void * data;
struct Node * next;
} Node;
typedef struct Queue {
Node * head;
size_t data_size;
} Queue;
typedef struct Person {
char const * name;
unsigned short int age;
char const * occupation;
} Person;
Queue *create_queue();
void register_new_size(Queue *, size_t data_size);
void enqueue(Queue *, void *data);
void *front(Queue *);
int length(Queue *);
int is_empty(Queue *);
void dequeue(Queue *);
Queue *copy_queue(Queue *);
void print(Queue *);
void destroy_queue(Queue *);
int is_empty(Queue *b)
{
if(b->head == NULL) { return 1; }
return 0;
}
Queue *create_queue()
{
Queue *new_queue = (Queue *)malloc(sizeof(Queue));
new_queue->head = NULL;
return new_queue;
}
void destroy_queue(Queue *b)
{
while(!is_empty(b)) {
dequeue(b);
}
free(b);
}
void enqueue(Queue *b, void *data)
{
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = malloc(b->data_size);
memcpy(new_node->data, data, b->data_size);
new_node->next = NULL;
if(is_empty(b)) {
b->head = new_node;
return;
}
Node *n = b->head;
while(n->next != NULL) {
n = n->next;
}
n->next = new_node;
}
void *front(Queue *b)
{
return (b->head)->data;
} | {
"domain": "codereview.stackexchange",
"id": 43686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, linked-list, queue",
"url": null
} |
c, linked-list, queue
void *front(Queue *b)
{
return (b->head)->data;
}
int length(Queue *b)
{
Queue *copy = create_queue();
register_new_size(copy, b->data_size);
int count = 0;
while(!is_empty(b)) {
enqueue(copy, front(b));
dequeue(b);
count++;
}
while(!is_empty(copy)) {
enqueue(b, front(copy));
dequeue(copy);
}
destroy_queue(copy);
return count;
}
void dequeue(Queue *b)
{
Node *upcoming = b->head->next;
free(b->head);
b->head = NULL;
if(upcoming != NULL) {
b->head = upcoming;
}
}
Queue *copy_queue(Queue *b)
{
Queue *copy = create_queue();
register_new_size(copy, b->data_size);
int count = length(b);
while(count > 0) {
void *d = front(b);
enqueue(copy, d);
dequeue(b);
enqueue(b, d);
count--;
}
return copy;
}
void print(Queue *b)
{
if(is_empty(b)) {
printf("[empty]\n");
return;
}
Queue *copy = copy_queue(b);
printf("[");
while(!is_empty(copy)) {
struct Person *d = (struct Person *)front(copy);
printf("%s, ", d->name);
dequeue(copy);
}
printf("]");
printf("\n");
destroy_queue(copy);
}
void register_new_size(Queue *b, size_t data_size)
{
b->data_size = data_size;
}
int main(void)
{
Queue *queue = create_queue();
Person chase = { "Chase", 49, "Banker" };
Person evan = { "Evan", 34, "Doctor" };
Person susie = { "Susie", 43, "Teacher" };
register_new_size(queue, sizeof(Person));
enqueue(queue, &chase);
enqueue(queue, &evan);
enqueue(queue, &susie);
print(queue);
dequeue(queue);
print(queue);
dequeue(queue);
print(queue);
dequeue(queue);
print(queue);
destroy_queue(queue);
return 0;
}
```
Answer:
Yes, you don't check the malloc return value. Along the same line, you should not cast it.
is_empty implementation is anti-idiomatic. It should be
return b->head == NULL; | {
"domain": "codereview.stackexchange",
"id": 43686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, linked-list, queue",
"url": null
} |
c, linked-list, queue
is_empty implementation is anti-idiomatic. It should be
return b->head == NULL;
dequeue from an empty queue dereferences NULL.
register_new_size is called uncontrollably, and has no relation to the size of the next data item to be enqueued. You'd be in much less eror prone having
typedef struct Node {
void * data;
size_t size;
Node * next;
};
and
void enqueue(Queue * b, void * data, size_t data_size);
length is scarily suboptimal. There is no need create a copy. Consider
size_t length(Queue * b)
{
size_t len = 0;
Node * cursor = b->head;
while (cursor) {
len++;
cursor = cursor->next;
}
return len;
}
Better yet, make size a member of Queue; increment it on each enqueueing, and decrement it in each dequeuing.
BTW, notice the type. int may not be wide enough.
print_queue has a very limited utility. Consider a more generic
map(Function f, Queue * q, void * args)
{
Node * cursor = q->head;
while (cursor) {
f(cursor->data, args);
}
}
where Function should be declared along the lines of
typedef void (*Function)(void *, void *);
As a side note, there are plenty of variations of the theme.
enqueue has a linear time complexity. Keeping a tail pointer is a small price to make it constant time (just enqueue at the tail, and dequeue from the head). | {
"domain": "codereview.stackexchange",
"id": 43686,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, linked-list, queue",
"url": null
} |
javascript, knockout.js
Title: Monitoring a view model for changes to display a save button | {
"domain": "codereview.stackexchange",
"id": 43687,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, knockout.js",
"url": null
} |
javascript, knockout.js
Question: I'm working with Knockout3 in a Chromium 40 environment (ES5).
I have a series of preset difficulty options, and a player has an option to switch to custom difficulty and tweak the options. When they tweak an option the save button lights up and the player cannot proceed to start the game until they save their settings. If they switch away from custom difficulty to a preset all changes are marked as saved so that they can proceed.
To track whether there has been a change I am using ko.computed, and it all looks as follows:
model.gwaioDifficultySettings = {
shuffleSpawns: ko.observable(true),
easierStart: ko.observable(false),
tougherCommanders: ko.observable(false),
factionTech: ko.observable(false),
customDifficulty: ko.observable(false),
goForKill: ko.observable(false),
microType: ko.observableArray([0, 1, 2]),
microTypeDescription: ko.observable({
0: "!LOC:No",
1: "!LOC:Basic",
2: "!LOC:Advanced",
}),
microTypeChosen: ko.observable(0),
getmicroTypeDescription: function (value) {
return loc(model.gwaioDifficultySettings.microTypeDescription()[value]);
},
mandatoryMinions: ko.observable(0).extend({
precision: 3,
}),
minionMod: ko.observable(0).extend({
precision: 3,
}),
priorityScoutMetalSpots: ko.observable(false),
useEasierSystemTemplate: ko.observable(false),
factoryBuildDelayMin: ko.observable(0).extend({
precision: 0,
}),
factoryBuildDelayMax: ko.observable(0).extend({
precision: 0,
}),
unableToExpandDelay: ko.observable(0).extend({
precision: 0,
}),
enableCommanderDangerResponses: ko.observable(false),
perExpansionDelay: ko.observable(0).extend({
precision: 0,
}),
personalityTags: ko.observableArray([
"Default",
"Tutorial",
"SlowerExpansion",
"PreventsWaste",
]),
personalityTagsDescription: ko.observable({
Default: "!LOC:Default",
Tutorial: "!LOC:Lobotomy",
SlowerExpansion: "!LOC:Slower Expansion", | {
"domain": "codereview.stackexchange",
"id": 43687,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, knockout.js",
"url": null
} |
javascript, knockout.js
Tutorial: "!LOC:Lobotomy",
SlowerExpansion: "!LOC:Slower Expansion",
PreventsWaste: "!LOC:Prevent Waste",
}),
personalityTagsChosen: ko.observableArray([]),
getpersonalityTagsDescription: function (value) {
return loc(
model.gwaioDifficultySettings.personalityTagsDescription()[value]
);
},
econBase: ko.observable(0).extend({
precision: 3,
}),
econRatePerDist: ko.observable(0).extend({
precision: 3,
}),
maxBasicFabbers: ko.observable(0).extend({
precision: 0,
}),
maxAdvancedFabbers: ko.observable(0).extend({
precision: 0,
}),
startingLocationEvaluationRadius: ko.observable(0).extend({
precision: 0,
}),
ffaChance: ko.observable(0).extend({
precision: 0,
}),
bossCommanders: ko.observable(0).extend({
precision: 0,
}),
landAnywhereChance: ko.observable(0).extend({
precision: 0,
}),
suddenDeathChance: ko.observable(0).extend({
precision: 0,
}),
bountyModeChance: ko.observable(0).extend({
precision: 0,
}),
bountyModeValue: ko.observable(0).extend({
precision: 3,
}),
unsavedChanges: ko.observable(false),
newGalaxyNeeded: ko.observable(false).extend({ notify: "always" }),
}; | {
"domain": "codereview.stackexchange",
"id": 43687,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, knockout.js",
"url": null
} |
javascript, knockout.js
ko.computed(function () {
if (model.gwaioDifficultySettings.customDifficulty()) {
model.gwaioDifficultySettings.bossCommanders();
model.gwaioDifficultySettings.bountyModeChance();
model.gwaioDifficultySettings.bountyModeValue();
model.gwaioDifficultySettings.microTypeChosen();
model.gwaioDifficultySettings.personalityTagsChosen();
model.gwaioDifficultySettings.econBase();
model.gwaioDifficultySettings.econRatePerDist();
model.gwaioDifficultySettings.enableCommanderDangerResponses();
model.gwaioDifficultySettings.factoryBuildDelayMax();
model.gwaioDifficultySettings.factoryBuildDelayMin();
model.gwaioDifficultySettings.ffaChance();
model.gwaioDifficultySettings.goForKill();
model.gwaioDifficultySettings.landAnywhereChance();
model.gwaioDifficultySettings.mandatoryMinions();
model.gwaioDifficultySettings.maxAdvancedFabbers();
model.gwaioDifficultySettings.maxBasicFabbers();
model.gwaioDifficultySettings.minionMod();
model.gwaioDifficultySettings.perExpansionDelay();
model.gwaioDifficultySettings.priorityScoutMetalSpots();
model.gwaioDifficultySettings.startingLocationEvaluationRadius();
model.gwaioDifficultySettings.suddenDeathChance();
model.gwaioDifficultySettings.unableToExpandDelay();
model.gwaioDifficultySettings.useEasierSystemTemplate();
model.gwaioDifficultySettings.unsavedChanges(true);
}
});
// Prevent simply switching to GW-CUSTOM causing unsaved changes to become true
model.gwaioDifficultySettings.customDifficulty.subscribe(function () {
model.gwaioDifficultySettings.unsavedChanges(false);
}); | {
"domain": "codereview.stackexchange",
"id": 43687,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, knockout.js",
"url": null
} |
javascript, knockout.js
This all seems to work rather well, except that switching to custom difficulty causes unsavedChanges to become true, when in reality the desired behaviour is that changes to fields like shuffleSpawns cause it to become true, but only when customDifficulty is true. I'm using a subscription to customDifficulty to workaround this, but given my inexperience with Knockout I'm wondering if there's a better way to achieve the desired result? I can replace the subscription with:
ko.computed(function () {
model.gwaioDifficultySettings.customDifficulty();
model.gwaioDifficultySettings.unsavedChanges(false);
});
This achieves the same thing, but I've no idea if that's consider better, worse, or irrelevant.
I have seen commentary on dirtyFlag extenders, and was wondering if that's the route I should have gone down, or if my current method is acceptable.
Answer: A super short review;
I would have renamed microTypeDescription to microTypeDescriptions
I like your approach better, it expresses what you want to achieve. The second approach looks more like wrangling with the library
I would have considered a custom helper/builder function for these patterns;
minionMod: ko.observable(0).extend({
precision: 3,
}),
vs
minionMod: koObservable(0,3), | {
"domain": "codereview.stackexchange",
"id": 43687,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, knockout.js",
"url": null
} |
algorithm, sorting, salesforce-apex
Title: Custom sorting algorithm in Salesforce Apex
Question: I had a scenario where I needed to sort a list of EmailTemplate, but didn't have anything to sort the list by (other than a common number in the Name property).
The email templates looked something like this:
Some email template - 1
Some other email template - 2
Another email template - 3 (with end text)
Xylophone email template - 4
Aardvark email template - 5 (with end text)
Here's the code I wrote:
public static List<EmailTemplate> OrderEmailTemplates(List<EmailTemplate> emailTemplates)
{
Integer n = emailTemplates.size();
for(Integer i = 0; i < n; i++)
{
for(Integer j = 0; j < n - i - 1; j++)
{
if(!AreTemplatesInOrder(emailTemplates[j], emailTemplates[j+1]))
{
EmailTemplate temp = emailTemplates[j];
emailTemplates[j] = emailTemplates[j+1];
emailTemplates[j+1] = temp;
}
}
}
return emailTemplates;
}
private static Boolean AreTemplatesInOrder(EmailTemplate t1, EmailTemplate t2)
{
return RetrieveNumberFromTemplateName(t1) < RetrieveNumberFromTemplateName(t2);
}
private static Integer RetrieveNumberFromTemplateName(EmailTemplate template)
{
return Integer.valueOf(template.Name.split('-')[1].replaceAll('[a-zA-Z]{1,}|\\-', '').trim());
}
It feels a little verbose considering the task. Perhaps I'm too used to using mordern manipulation/querying technologies like LINQ.
Is there a less verbose way of doing this in Apex?
Some useful syntax would be something like the following, though I'm sure it doesn't exist (ignoring the lambda, it's there for readability):
emailTemplates.OrderBy((x,y) => AreTemplatesInOrder(x,y)); | {
"domain": "codereview.stackexchange",
"id": 43688,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, sorting, salesforce-apex",
"url": null
} |
algorithm, sorting, salesforce-apex
Answer: For a less verbose way to achieve this in Apex you need to create a wrapper class for EmailTemplate that implements Comparable interface. The advantage is that elements don't need to be manually moved in the array.
public static EmailTemplate[] orderEmailTemplates(List<EmailTemplate> emailTemplates) {
EmailTemplateWrapper[] wrappers = new List<EmailTemplateWrapper>();
for(EmailTemplate template : emailTemplates) {
wrappers.add(new EmailTemplateWrapper(template));
}
wrappers.sort();
EmailTemplate[] sortedTemplates = new List<EmailTemplate>();
for(EmailTemplateWrapper wrapper : wrappers) {
sortedTemplates.add(wrapper.record);
}
return sortedTemplates;
}
class EmailTemplateWrapper implements Comparable {
public EmailTemplate record { public get; set; }
public EmailTemplateWrapper(EmailTemplate record) {
this.record = record;
}
public Integer compareTo(Object compareTo) {
if(!(compareTo instanceOf EmailTemplateWrapper)) {
return -1;
}
EmailTemplate otherRecord = ((EmailTemplateWrapper) compareTo).record;
Integer numerForThisRecord = retrieveNumberFromTemplateName(record);
Integer numerForOtherRecord = retrieveNumberFromTemplateName(otherRecord);
if(numerForThisRecord == numerForOtherRecord ) {
return 0;
} else if(numerForThisRecord < numerForOtherRecord) {
return -1;
}
return 1;
}
Integer retrieveNumberFromTemplateName(EmailTemplate template){
return Integer.valueOf(template.Name.split('-')[1].replaceAll('[a-zA-Z]{1,}|\\-', '').trim());
}
} | {
"domain": "codereview.stackexchange",
"id": 43688,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, sorting, salesforce-apex",
"url": null
} |
javascript, form
Title: Secure password generator form
Question: With the demise of passwordsgenerator.net I wrote my own generator;
Please review with an eye on correctness and maintainability;
//Inspiration; https://web.archive.org/web/20220711113233/https://passwordsgenerator.net/
button.addEventListener("click", generatePassword);
//Yes, not super, global constant..
const symbolList = ';!#$%&*+-=?^_';
function generatePassword(){
const includeSymbols = symbols.checked;
const includeNumbers = numbers.checked;
const includeLower = lower.checked;
const includeUpper = upper.checked;
const excludeHard = easy.checked;
const length = size.valueAsNumber;
const charPool = [];
let pwd;
//Users who check everything off get an all spaces password, not really secure
if(!includeSymbols && !includeNumbers && !includeLower && !includeUpper){
setPassword(' '.repeat(length));
return
}
if(includeLower){ //No i or o
charPool.push(... 'abcdefghjklmnpqrtsuvwxyz'.split(''));
}
if(includeUpper){ //No I or O
charPool.push(... 'ABCDEFGHJKLMNPQRSTUVWXYZ'.split(''));
}
if(includeNumbers){ //No 0 or 1
charPool.push(... '23456789'.split(''));
}
if(includeSymbols){ //No @ or |
charPool.push(... symbolList.split(''));
}
if(!excludeHard){
charPool.push(... ''.split('ioIo01|'));
}
const charPoolLength = charPool.length;
do {
pwd = '';
for(let i = 0; i < length; i++){
pwd += charPool[Math.floor(Math.random()*charPoolLength)];
}
}while(
(includeLower && !hasLowercase(pwd)) ||
(includeUpper && !hasUppercase(pwd)) ||
(includeNumbers && !hasNumber(pwd)) ||
(includeSymbols && !hasSymbol(pwd))
)
setPassword(pwd);
}
function hasLowercase(s) {
return s.toUpperCase() != s;
}
function hasUppercase(s) {
return s.toUpperCase() != s;
}
function hasNumber(s){
return s.split('').some(c => !!~'0123456789'.indexOf(c));
} | {
"domain": "codereview.stackexchange",
"id": 43689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, form",
"url": null
} |
javascript, form
function hasNumber(s){
return s.split('').some(c => !!~'0123456789'.indexOf(c));
}
function hasSymbol(s){
return s.split('').some(c => !!~symbolList.indexOf(c));
}
function setPassword(s){
pwd.value = s;
pwd.select();
}
/**form {text-align: center;display: block}*/
/**pair {display:block; text-align: left}*/
form {display: block; margin-left: auto; margin-right: auto; width: 75%}
pair {display:block}
<form>
<h2>Secure Password Generator</h2>
<pair>
<label for="size">Password Length</label>
<!-- Minimum 4 so that we have space for 1 upper, 1 lower, 1 symbol, 1 number -->
<!-- Maximum 42 because that's the answer -->
<input type="number" id="size" value="12" min="4" max="42">
</pair>
<pair>
<label for="symbols">Include Symbols ( e.g. @#$% )</label>
<input type="checkbox" id="symbols" checked>
</pair>
<pair>
<label for="numbers">Include Numbers:( e.g. 123456 )</label>
<input type="checkbox" id="numbers" checked>
</pair>
<pair>
<label for="lower">Include Lowercase Characters:( e.g. abcdefgh )</label>
<input type="checkbox" id="lower" checked>
</pair>
<pair>
<label for="upper">Include Uppercase Characters:( e.g. ABCDEFGH )</label>
<input type="checkbox" id="upper" checked>
</pair>
<pair>
<label for="easy">Exclude Similar & Ambiguous Characters:( e.g. oO0iI1| )</label>
<input type="checkbox" id="easy" checked>
</pair>
<br>
<button type="button" id="button">Generate</button>
<br><br>
<pair>
<label for="pwd">Generated password</label>
<input type="text" id="pwd">
</pair>
<br><br>
Inspired by <a href="https://web.archive.org/web/20220711113233/https://passwordsgenerator.net/">passwordsgenerator.net</a>
<!-- This will never generate server side, always try to use cookies, and always autoselect the pwd-->
</form> | {
"domain": "codereview.stackexchange",
"id": 43689,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, form",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.