instruction stringlengths 34 36.1k |
|---|
Python loop generator
Looks like I’m missing something with for loop generators…
I deliberately made this simple code to test what was happening when I converted my list comprehensions to generators.
It showed that the generator var can’t be used more than once:
lst = [1,2,3]
plus = (i+1 for i in lst)
for i in plus: ... |
The commonly endorsed, and considered the most reliable, way of evaluating the security of a program is through examining its source code. That is, this method is based on the fundamental assumption: "what you see is what is run".
But if the program's memory has both 'writeable' and 'executable' attributes and the prog... |
I have created a dashboard for rendering a list of clients into a DataTable. Below shown is the data model structure:
When I had a few records in the clients schema, let's say a thousand rows, the request time was fairly okay. It would take around of 4-5 seconds for the whole trip, from requesting to processing at bac... |
In my doctor's appointment booking system, I identified the following entities:
Doctor
Patient
Appointment
I also identified an aggregate, which is Doctor (aggregate root) and Appointment. It's an aggregate, as it has to hold an invariant of making sure that appointments assigned to them do not overlap. In pseudocode... |
One of the complaints about C++ is the lack of automated bounds checking, which lead to memory errors.
But the C++ STL containers provide a quite convenient .at() method for bounds checking a container access. Sure, it comes with a small performance impact, as opposed to the more popular operator[], but usually this is... |
According to the definition by Robert Martin, high level modules should not depend on low level modules, instead both should depend on abstractions.
So if I have a domain entity Invoice that uses an interface InvoiceRepository for persistence, and an infrastructure layer where this interface is implemented in a class P... |
Until this moment, I have seen a lot of variations and combinations of the Repository pattern, implementations that simply queried the required information, some used something like a mapper, some used something called Units of Work, and some used something called CQRS that separated the reads from the writes, updates ... |
If i wanted to encrypt a password on my website before its sent to the server, would i have to encrypt the password in javascript on the frontend for it to be hidden over the interent or could it be encrypted in my flask backend code over the interent somehow. Im just a little confused on what code is actually sent to ... |
I have been creating new ASP.Net web apps for my workplace intranet (it is a closed system, not accessible to customers) and also re-creating some existing Windows programs as web applications. One colleague always suggests that things work more like a Windows desktop program - things that would take extensive effort w... |
I am designing a timesheet app for logging user tasks using React for frontend and Django REST Framework for backend. The database is PostgreSQL and I have a table for recording the tasks with 4 columns: date, start_time, duration, description.
I need a way to support the updating of a task after the user had created s... |
I am a newbie to microservice. Currently I'm learning microservices by creating 2 microservices with CQRS pattern, with NO event sourcing, but each service has separate DB. Each service has separate end points for Command and Query. There is no separate Read store and write store.
The services communicate with each oth... |
I have a code-coverage requirement of of a certain percentage, and face the following tradeoff:
Should I sacrifice in-method sanity checks and error handling for ease of (unit-) testability?
Lets consider two variants of a simple method addAndSquare.
Variant A:
double addAndSquare(double a, double b ){
re... |
tl;dr - I want to stream text data from one writer process to multiple reader processes. I'm thinking of using a file to achieve this. Is it a good idea?
Using a file would avoid having to maintain client connections in the server and send data on each of those connections. The file would have a single writer which wou... |
I have a method where I fetch user input, check if certain values exist, and based on that build my own custom input object that I would use to search in a database. The code for the search method is as follows.
public SearchDocumentResult searchData(EmployeeInput employeeInput) {
EmployeeInput getEmployeeInputForS... |
There are two logical entities, Customer and Account where a Customer is associated with one or more Accounts.
How to design a system that ensures Customers can update their Accounts concurrently, but for a given Account, the requests should be processed in order based on a time attribute?
Example: Customer A has 2 Acc... |
My understanding is that it's rarely a good idea to compare two floating point numbers due to inherent inaccuracies. However, my understanding of those inaccuracies are that they are deterministic and will always show up the same way given two identical inputs and identical transformations, hardware errors notwithstand... |
The UNIX load average gives 3 numbers over 1/5/15 minute time intervals. It's supposed to be an indicator of how busy a UNIX machine is. The global load average is an exponentially decaying average of number of runnable/uninteruptable tasks.
I'm interested to implement such kind of exponential decay algorithm in my pro... |
If Pet is a class that implements the interface INameable, and dog is an instance of Pet, what is the name of the relationship between dog and INameable?
In casual conversation and while talking with other devs, I would unthinkingly call dog an instance of INameable. This is always understood but might not be technical... |
In the documentation about discriminated unions in typescript, here it says:
Discriminated unions are useful for more than just talking about
circles and squares. They’re good for representing any sort of
messaging scheme in JavaScript, like when sending messages over the
network (client/server communication), ...
Co... |
I am learning stuff and have made 2 microservices, Listener and MyApp. Listener is a jms listener (consumer of messages) and MyApp is the app sending messages to queue.
I have 2 type of events CREATE and UPDATE and I want to maintain a single queue. So, my initial solution looked like below, here the Event class repres... |
I don't work for an development company, but we have been working in partnership with one to develop an application for use internally within our business. The application is somewhat "niche", and so while we have the ability to scale it and roll it out to our other locations (we are an international company), it is u... |
I've got a large, old application with a clunky, extremely manual deployment process (essentially, tribal knowledge combined with random scripts / build jobs scattered across servers). The application is largely written in C# with a little C here and there and is source controlled in one monolithic Accurev repo about 5... |
We have an enterprise solution which consists of multiple components which are in turn comprised of micro services. We cater to both onprem and hosted models.
The challenge is to keep track of the GIT tag and version details of the components/services that are delivered to customers.
I am looking for a tool that would ... |
I run unit and integration tests on my system. These create, start, stop and delete Docker containers. I want the exact same state in my Docker environment at the end of the tests as I had at the beginning. What would be the best way to restore the original state after the tests run?
Option A: I create a class in the m... |
So I want to write this function that downloads a file and unpacks it in python using TDD.
The function will look like this approximately
import urllib.request
import tarfile
def download_and_unpack(tarball_url, destination)
datastream = urllib.request.urlopen(tarball_url)
thetarfile = tarfile.open(fileobj=dat... |
In his article RESTful Casuistry, Tim Bray claims that rebooting a server is not idempotent:
But I don’t buy it, and here’s why. If I want to update some fields in an existing resource, I’m inclined to think about PUT. But that doesn’t work because it’s supposed to be idempotent, and rebooting a server sure isn’t. Wel... |
Consider the following fictitious toy example:
There is an aggregate root DayChecklist that holds a list of Tasks planned for the day:
class DayChecklist {
String id;
DateTime today;
...
List<Task> tasks;
// lots of other business logic
}
Task itself is modeled as:
abstract class Task {
DateT... |
I want to implement a search feature in my chat application like a messenger, skype, whatsapp has done. What they have done is when we search a word then it would not only show the message with that word in the current viewable message list but also on the past messages. To see the message with matching word, they prov... |
I'm developing a Command Pattern with Undo/Redo support. The environment is Unity C# but should be mostly language-agnostic.
My initial commands comprise of adding and removing objects to and from a space, but I'm encountering commands that lose their reference to their object. Removing an object means destroying it, s... |
This doubt is about Switch Statements from Chapter 3: Functions of the book named Clean Code
Here we have a function:
public Money calculatePay(Employee e)
throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateH... |
I would like to find the best way to solve the following problem:
I need a database for a software. The software needs to use the data to populate the UI and allow the user to interact with them (edit, add, delete etc). There are multiple instances of that software (desktop, mobile, another desktop etc) all linked to t... |
I was reading articles about TDD and I found the following one. https://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Architecture.html
In order to answer this question I think someone should read the full article, but in any case I'll quote the part I'm not able to grasp or to picture in my head.
The right side... |
I've seen a couple of talks on Hexagonal architecture where they illustrate problems with N-tier architecture. Specifically, they show a spaghetti of service layer dependencies as the software grows. For example, the image below is from the Hexagonal Architecture with Grails talk: https://www.infoq.com/presentations/he... |
as the title, how to know? is task manager the best way as my friend told me?
I code in python..
I'm new here sorry if my question was in the wrong place.
|
on design stage , after finding my main objects ,
I am always find my self writing "manager" or "controllers" classes in order to handle the connection between them. some of the logic is in those classes.
i know it is an antipattern
Anemic Domain Model
and that each class should have its own behavior.
my problem is t... |
I am thinking of creating two applications, one of which (App 1) will be in Django (DRF) and other (App 2)might be Django but might be another more lightweight framework (maybe Flask or plain Django or maybe different language altoghether depending of how efficient will be the script in Python). Anyway the idea is that... |
I have question on how to design an order management microservice. An order has different workflow based on the previous state or based on the business needs. I'm guessing at some point cannot keep on adding if/else/switch because it would be very difficult manage workflows and this will also leads to more bugs.
Order ... |
I hope this is the right place to ask.
I'm an experienced developer, and have used MVC for much time.
This question is in the context of iOS/macOS development for the most part, (SwiftUI).
Using MVC in iOS I always found the paradigm and architecture simple.
Views contained view related code (layout and reactive code)... |
In this post, Uncle Bob writes:
Entities encapsulate Enterprise wide business rules. An entity can be an object with methods, or it can be a set of data structures and functions. It doesn’t matter so long as the entities could be used by many different applications in the enterprise.
If I understood correctly, entiti... |
My develper team includes Android, iOS, PHP, Web Front, .Net developers, but every type of developer only 1 person, and they don't know other's programming languages very well.
We have setup Jenkins with some static analysis tools such as Sonarqube, but it's not enough to find out some logic mistakes.
Is there any sugg... |
I want a database table that can hold all of the group chat messages from all of the group chats.
The max amount of users per group chat would be 20.
The max amount of group chats per user would 25-30.
Using Python3 Flask as my backend. (Clarifying for speed expectations when looping on the second option)
The colum... |
i'm trying to design a game program, but when thinking about which objects to introduce there seems to be far too many.
For example for main object "Player" there are a lot of peripheral classes that should exist for e.g:
PlayerRenderer - renders the player
PlayerMovementHandler - moves the player
So on and so forth..... |
LocalDTO term refers to Fowler's article.
Say I have a domain entity Person:
public class Person {
private String id;
private String name;
private int age;
}
This entity has its own semantics in the domain & application layer and has its behavior. In other words, it is not an anemic model.
Now I have a pre... |
I've tried Googling this using several phrases and I simply can't find this asked anywhere so I hope this isn't too silly a question.
I'm just dipping my toes into DDD and I have a toy project I'm building around Defi in the crypto space. In short the point of the project is to read a bunch of information from smart co... |
Not sure if this is the right forum for this, but I've come across a need for this pattern a few times lately, and I would love to get some opinions on options for how to handle it.
Say I have an app that takes data from an arbitrary number of third-party applications and wants to parse it into a unifying format:
{
... |
I'm building a use-case for creating blog posts, at first I thought of using an entity as a use-case parameter, and this entity would be created by the layer that calls Use Case, in my case a controller.
Controller:
//....
public function createPost(request: Request): void {
const imagesToUpload: string[] = request... |
I've been going over the Visitor Pattern to try to understand it. Is this a correct implementation of the Visitor Pattern for RPS??
Here's the implementation code:
public enum ResultEnum {
WIN,
LOSE,
DRAW
}
public interface ElementVisitor {
ResultEnum visit(Rock rock);
ResultEnum visit(Paper p... |
Let's say, there's a Product data-model. Product has the attribute - colour, which can, in this case, be red, black, yellow, white, orange. And which in total amounts to 5 different Products.
Now I want to introduce a new set of attributes, let's say, material - cotton, nilon, paper; and size - s, m, l, xl; this will a... |
I am working on a JavaScript tutorial series for someone who has no experience coding.
The format of the series is that it is a public Github repo. Each lesson is a README.md markdown document, and ends with an exercise. The exercise is usually some Jest tests that I've written, and the student needs to implement some ... |
Since I am working in a multi-instance microservice environment, I came accross a problem with making some operations being performed at most by one of the running instances at once. The solution which we used for this up to now was to have a mutex lock stored in database, that would prevent other instances from doing ... |
When I joined my company as a new comer and I was exploring the unit test suite of the product code. It is using gtest framework. But when I checked all the tests, they were testing the whole functionality by calling real functions and asserting expected output. Below is one such test case as an example:
TEST(nle_26, U... |
I'm building a client for an API.
The API takes a query param that looks something like this 2-10, that's a range and notice that it uses a hyphen (-).
Usually, data comes from another place using en dash (–) instead of hyphen.
If the api is called using an en dash instead of a hyphen, it will return empty, so we need ... |
I am trying to work on finding the following metrics
New Work - totally new code which does not replace other code.
Churn - code that is rewritten or deleted after being written
Help Others - where developer helps on someone else work
While I was working on churn and new work metrics, I cam to know about legacy refacto... |
I am currently developing an API that returns JSON structures. One of the domain objects returned is a time series, which is a potentially large list (many thousands of elements) of complex objects.
Say a time series element consists of value and status, there are two ways to represent this in JSON. Either as a list of... |
The other day, I came across this question on StackOverflow. In short, the user who asked the question wanted to extend a class from a third-party library to implement the Codable protocol, but another library had already defined an extension to do just that, and the user preferred his own implementation.
I come from a... |
I know debugging and bug fixing are related and generally, bug fixing is considered as a subset of debugging (for example here in Wikipedia, "The process of finding and fixing bugs is termed "debugging"), but I wonder wether these two terms can be used instead of each other?
|
I have a database with a 1:m relationship.
I have to display a list of parents to the user rapidly on a home screen at startup. The parent shows a single piece of information that is a sum of a particular child field for that parent.
I don’t want the expense of making large queries to the child table (essentially doin... |
Let us say I want to store on a database a userID, their nationality and if they are from the UK their UK passport number.
I could model this by having one table with userID as primary key, nationality as an attribute and the Uk passport number as an attribute , which exists only when the nationality is UK.
As an alte... |
I hope this question isn't too vague because it's more a discussion than a question. I want to write a code which can detect physical violence in a scene (with the end result being the prediction of triggers in the movie/show). I would like to do this through python (however I'm open to ideas of other codes- I'm famili... |
As the title states, I'm wondering if my current architecture is currently too granular. Additionally, I'm curious if I should be pursuing a microservice architecture in the first place.
For context, I'm building a multi-tenant document generation system and I currently have the following entities:
Tenant
Template
Doc... |
Thanks for reading my question.
I have a class which reads a configuration and based on the configuration, populates a data structure by reading from a database, which is ultimately presented to a processing layer that makes use of the data for various processing.
Configuration:
<FieldConfigs>
<ConfigField name="My... |
I studied systems analysis and design (SAD) in college/university, which primarily gave a set of methods to design a system, using UML diagrams. Flow charts, entity-relationship diagrams, etc, were used to take an idea or an existing/paper-based system and come up with the design documents for developers to create the ... |
We have a standard microservices setup (Identity Server, API Gateway, services, etc).
Some of the services schedule events to be dispatched in the future (future = anything from mins to months ahead) - the underlying mechanism is an AWS SQS queue. We are looking to implement a feature that means that something might h... |
I have implemented an append-only tree data structure as a class in C++20. Internally it uses std::vector<Node<T>> where Node<T> contains an int parent_index and T payload. A node without a parent has parent_index = -1 as special value.
I am wondering which integer type would make the most sense here. I have good argum... |
There is a minor difference between Saga pattern https://microservices.io/patterns/data/saga.html and my use case below. Saga pattern is about distributed transaction when an event is happening vs my use case below is a reconciliation pattern after events have all happened.
We have a large ecosystem of microservices (3... |
I am developing a Spring Boot Application which consumes another REST service to get the User's Account information. The same service provides multiple operations like:
GET: /userid/retrive -to get user and account information
POST: /user/create - to create a new user
POST: /userid/save - to save the user information
... |
I have a list of product price objects, List<ProductPrice>.
@Value
public class ProductPrice {
Long id;
LocalDate startDate;
LocalDate endDate;
BigDecimal value;
}
From the list I need to find prices that have a start date equal to or greater than a given start date AND an end date equal to or be... |
I wanted to know when you are done processing some query or transaction do you usually close a connection only? do you close the pool? or do you close both? Does it even matter which one you close? What happens under the hood when you do all three of these cases (if there even is a difference). I’d appreciate it since ... |
Consider this schema in a relational database:
There are two tables A, B, both having two columns X, Y. The constraints are:
X in both tables are the primary keys. (The values are unique in each table.)
The data in both tables must be exactly identical. (Each insert, delete, update request must be applied to the two t... |
It has been said that "PUT is idempotent":
The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical POST requests may have additional effects, akin to placing an order several times.
How do I... |
I have a RESTful service where clients provide product codes, start date and end date. In response, the service returns a list of price metrics for the products over the date range. Start date is optional. If not provided, price metrics for standard periods are returned.
The data is captured in PriceMetricsDto objects ... |
I have a suite of python Azure Function Apps that all together make up an integration, each containing multiple functions:
FunApp1
func1
func2
SharedCode
FunApp2
func3
func4
SharedCode
FunApp3
func5
func6
SharedCode
("SharedCode" is legitimately shared code, but it must be deployed with each Function App, pe... |
What commit type should I use when I'm deleting files from a repo?
I have seen several types over the internet, but none talk about file deletions.
Possibly the closest options that come to mind are CHORE and REFACTOR.
EDIT 1 : START
Reasons why I'm confused is because none of the definitions for CHORE and REFACTOR tal... |
In JavaScript, if I have try catch blocks in a function that is meant to be called from another function, should I also put them in the calling function or just let the called functions handle them.
Here is some pseudo code to illustrate what I mean. I have two called functions, one and two. They are essentially the sa... |
We have capital-U Unit Tests that are supposed to be testing a particular slice of our code. This code has a dependency on an IConverter<TIn, TOut> (a wrapper similar to AutoMapper). The behavior of this converter is important for the overall system, but not for the behavior of the specific unit under test.
The code ... |
I'm building a Use Case for creating blog posts, this Use Case has its own "DTO", which is basically a parameter object with only primitive data, as follows:
Use Case's DTO (Parameter Object):
export class CreatePostInput {
public id: string;
public slug: string;
public title: string;
public authorId: string;
... |
Suppose I am buying coffee. There are several types of coffee (A1, A2, A3), but sometimes I want to make a reference to all types of coffee (like if I had a coffee "grouped"). Considering DDD concepts, coffee A1 is different from all types of coffee, so that's their identities and I need to reference both specific and ... |
I'm building an API in C# .NET that needs to supply the client with some data and an image. The image is stored in Azure Blob storage. Which is more efficient:
Retrieving the image on the server side and returning it as part of the API response
Returning the path to the image along with the data in the API response an... |
Our company have a support team and a dev team. We require reproduction steps on every bug report, however sometimes the support team submit reports without and become frustrated when dev close them as "cannot reproduce / cannot fix".
Support then make the argument "if I take my car to the garage, the mechanic will lo... |
Let's say I have few entity classes:
class EntityA { LocalDate date1; LocalDate date2; }
class EntityB { }
class EntityC { LocalDate date1; }
and I want to pass them through some logic containing lots of conditional checks. Simplified version of something like:
public class Predicate {
public boolean test(EntityA... |
I work at a rather small company, around 10 devs and we are facing a lot of problems with merges and so on, I figured it could be because of the amount Hotfixes we are merging into master daily.
So I was thinking about one release branch per day, where it would be on origin and whenever a dev must do a hotfix, they wou... |
In the red book by V. Vernon it says about REST:
In RESTful HTTP, the methods are the HTTP verbs - most importantly, GET, PUT, POST, DELETE - that can be applied to resources.
Even though it might appear so at first sight, these methods do not translate to CRUD operations. It is very common to create resources that do... |
We all know that if we delete a file, the operating system is recycling it but doesn't actually delete it. It just removes it from the directory indexes, and until the data is needed and overwritten, it will still remain there.
Recently, I have written a program that can wipe a entire hard drive. The program reads exis... |
I use TypeScript. When I write the below code ESlint throws this error: https://eslint.org/docs/rules/class-methods-use-this
export class {
constructor() {
const result = doCalculations()
...
}
doCalculations(): number {
...
}
}
So I have 2 options.
Make the function static.
Move the function out... |
During unit testing it is possible to estimate the code coverage to see which share of the code base is covered by the tests.
For one part (the simple calculatable one) of a risk estimation we need to estimate the impact when a single line or a variable changes on the code base.
E.g. if a variable changes and a pointer... |
Should we put behaviors (method) in constant class in Java? If not then why? Which clean code practice/principle I am breaking while doing that?
public class TagConstants {
public static final String O_NAME = "oName";
public static final String O_TYPE = "oType";
public static final String S_TYPE = "sType";
pub... |
New Design:
We are porting Legacy code to C#.
We have Request and Response Data Contract for each set of Business Data. These are POCO generated using Schema of External vendor. We will be creating 30-40 such Classes. We have no control over the structure. Hence I extended these classes with ToModel() and FromModel() ... |
My understanding is that every PRNG or QRNG requires a state to prevent the next item in its sequence from being too predictable; which is sensible, as they're all running on deterministic hardware.
GPUs are, by design, non-Von Neumann architectures which are incapable of remembering past operations, predicting future ... |
I have the following problem:
There is an amount of nodes each containing elements of different kinds. Each node has a max amount of elements it can hold. I want to sort the elements between the nodes so that they are grouped by element kind, rather than scattered between all nodes. To execute the sorting I can do swap... |
Effective Modern C++ recommends using void futures as a way to communicate one-off events from one thread to another. Below is a minimal reproduction of that practice.
std::promise<void> promise;
void detect()
{
std::thread latent([]
{
promise.get_future().wait();
// react
}
//...do some work
promise... |
I'm practicing test driven development while implementing a network simulator: devices communicate with each other and implement little bits of functionality that respond to messages. Each device has its own view of the network topology and can be individually powered on or off.
Timing is important. If the Device is in... |
I'm looking for architectural guidance.
I've got this monolithic application. It has a payment platform functionality, where payments are made, scheduled or on demand, via some banking API.
Payments used to be stored in DB, along with all relevant info like banking transactions, etc. Making the payment is inherently un... |
I am trying to maintain proper code organisation for my codebase. I came across a situation whereby organising my code into class A, B, C is unnecessary as class C can be incorporated into class A and B. This is because the functionalities in class C are from a library which means the functions have been wrapped nicely... |
Throughout this semester my classmates and I had to do the pre-coding(?) phase of a project (requirements and such) as part of our Software Engineering course. The way our professor had us do it seems odd to me and I'd like your input.
First we were given a document with the problem and had to extract requirements from... |
I have 2 kinds of objects in my system, Car and Road.
A Car can be of various types and have properties like tire, tire size, engine, etc.
A Road can be of multiple types and have properties like terrain type, slippery, etc.
Some type of cars cannot ride on certain roads, based on the road properties and car limitation... |
I have an enum that works very well to represents date periods and the number of months in those date periods:
public enum StandardDatePeriod {
ONE_MONTH(1),
SIX_MONTH(6),
ONE_YEAR(12),
FIVE_YEAR(60),
TEN_YEAR(120);
private final long offsetInMonths;
private StandardDatePeriod (long offse... |
Recently I had my first experience writing a wrapper around FTD2XX driver for a desktop tool that communicates with an embedded device. The library provided some common device specific functionality and encapsulated low-level MPSEE and board specific configurations from the user.
While writing this library I found myse... |
I have a scenario where I have to route a list of messages that I get to respective users.
For suppose if I have
messages = [
{ text: 'hi', user_id: 1 },
{ text: 'hi', user_id: 2 },
{ text: 'hi', user_id: 3 },
{ text: 'hi', user_id: 4 },
{ text: 'hi', user_id: 5 },
];
I read in a blog where creating queues d... |
I'm making a naval warfare strategy game, based on a boardgame, in C# and having difficulty finding a good way to construct my complex ship objects (I am a beginner in the language and OOP).
Currently, each ship class inherits from an abstract base Ship class that implements the interface IShip (code below). This inter... |
In a pretty big project, I have a hierarchy of objects, let's say:
Zone object, which contains Block objects and Connection objects.
Mainliy, the Connection object links together several Block objects, all inside a Zone.
In this project, I am using the Memento pattern (together with the Command Pattern) for implementin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.