instruction stringlengths 34 36.1k |
|---|
I have recently given Haskell another go, mostly because I heard about the book Haskell from first principles and so far I'm having a blast. My background is that of a mathematician mostly working in Algebra, so I usually understand the categorical aspects decently, but I could not quite grasp the following specific cl... |
I've been coding in python for about 6 years now. I am proficient enough to understand a good amount of the language features. When I look into source code for a number of libraries such as pandas or requests I'm able to understand a good deal of what is going on.
I've worked with python long enough to develop a real f... |
I'm building a reporting tool with three core layers:
Extract data from a database
Transform this data to compute business metrics
Display these metrics in a report (a heavily formatted Excel export in this case)
My challenge is that there seems to be some irreducible complexity in the task, and I'm finding it very c... |
I'm aware that there are 4 ways to violate Liskov Substitution from here.
But I'm not sure what these violations would like in practice. Can you show examples of code that breaks the principle for each of the 4 ways?
Preconditions cannot be strengthened in a subtype.
Postconditions cannot be weakened in a subtype.
Inv... |
I've been reading a book about C#. What does the word 'set' mean in the following excerpt?
Pattern matching with the switch statement: Like the if statement, the switch statement supports pattern matching in C# 7.0 and later.
The case values no longer need to be literal values; they can be
patterns. Let's see an exam... |
I am looking for an advice (or an example) on how to organize logging streams in my cloud app (C#).
In my app there are logging events related to the application infrastructure level and I want to write them to a file (or STDOUT). I use Serilog and I will enrich those events with custom metadata like environment parame... |
I am trying to assess secure ways to implement a session handover between an app and a website in the same company ecosystem.
The Setup
Mobile Application A and Website B use the same company OpenID Connect (OIDC) provider to login their users independently from each other with completely separate session handling. Sin... |
I have a yml configuration file that list multiple application. Each application can contain multiple configuration. And of course each configuration can contain multiple mode
apps:
- name: foo
group:
- group_1
configs:
- name: config_1
options: [a, b, c]
solution: solution path
... |
I'm writing code to clean and process a large number of transcript text files. My code will be re-used in the future to process additional files which do not yet exist.
Future files will take on the same general format as existing files, and will be collected/produced using the same procedures as were used to make the ... |
I have an endpoint API for a POST request in a multi-tenant application, let's say it is for a Payment, where we have to store these fields:
tenant_id (this is the account owner)
amount
date
payer_id -- the user that makes the payment
user_id -- another user that has to be attached to this payment
category_id -- a ca... |
Let's say I have a User class described as follows:
record User (
Guid Id,
string Username,
string Password
)
{
/* some methods */
};
Let's say Usernames and Passwords need at the very least 8 characters before being considered valid. Should the domain be concerned with validating that? Or the application lay... |
I have one large class that computes ~50 different metrics (each metric has no side effects).
My code is similar to this:
class ReportingMetrics:
def __init__(self, data:pd.DataFrame, config:dict):
self.data = data
... # Common data validation, etc...
def calculate_metric1(self)->pd.Series:
... |
I'm learning rust and curious to know the purpose that we can allocate memory sizes to data types. I'm not clear yet how this could be an advantage. It can definitely save up some memory space but I ran into a similar thread that stated memory is the least of the concern.
|
I have a codebase where some classes contain both "essential" business logic, and "incidental" complexity. I am considering a refactor where I leverage inheritance to improve the readability and maintainability of the code. However, it's not clear if the base class should be the one containing the non-core logic (and i... |
I am familiar with and see the benefits of Subresource Integrity (SRI).
I understand that with SRI, once you've added a script reference with the correct integrity attribute, if the remote script is subsequently compromised, then the SRI Hash will not match the remote asset and the remote script will not download.
That... |
Currently working on a project where we have multiple services that all need to consume the same authorization service when their endpoints are hit. Right now we have the authorization boilerplate code copied into all of our services, but we're looking for a way to make things more reusable. The idea we're considering ... |
I have inherited a large C++ codebase implementing various Windows desktop applications, services and libraries using Windows MFC. There are no automated tests. We need to decouple the UI and retain a large part of the domain logic written in C++. My understanding is I can implement high-level use cases in C++ and expo... |
Given a set of interfaces, objects implementing those interfaces, and functions that use those objects, what methods exist to model mutations performed by the functions?
For example, given:
A Pet interface that includes a feed() method
Cat, Dog, and Hamster objects that implement the Pet interface
Functions that take ... |
I am making a renderer as a hobby, one thing I thought to try is making the low levelAPI be dynamically swappable, i.e. you could have an opengl or vulkan backend and switch between the two without needing to recompile or even relaunch the application.
To achieve this I am making 2 binaries, one is the executable, the ... |
I am currently working on redesigning a microservice application. Our application is supposed to serve multiple clients and due to compliance we have to persist the data in separate datastores.
We have isolated the services to be deployed for each client. there are some functionalities that are common for all the clien... |
I got a bit strange 'future ready' scenario. And I'm not sure if I got it right in regards to C# adapter design pattern.
The scenario is that to be future ready, 'to use the adapter pattern' to easily switch from underlaying frameworks.
As for example here I use an instruction to move a robot arm vendorXYZ by 10cm left... |
I am coming from the Google C++ guidelines, specifically the section on Static and Global variables. It advises against having global variables of types that aren't trivially destructible. I'm unsure if file-scope global variables fall in this category. Specifically, I have an example of this in a small C++ file (.cpp,... |
I’m considering following sentence in a document:
Lastly, a xxx algorithm is performed to improve the convergence speed (speed it takes for the individuals in the population to get closer to the desired solution of a high fitness value).
However, I am not sure about the meaning of “convergence” and if “convergence sp... |
I am building an API which, amongst other things, needs to handle users. I am building it with C# 10 and .NET 6. In order to receive/return data in the API end points, I am using records. So for example, this could be an end point which returns all users:
[HttpGet]
public IActionsResult ListUsers()
{
// The '.AsDto... |
I wish to develop an application that can generate code based on an user input.
Long story short: a user gives a formal description of a Resource (can be viewed as a REST resource) and based on this description I wish to generate an entire codebase that contains CRUD operations on that given resource.
I am currently ha... |
Protected visibility in languages like C++, Java or PHP is a strange beast: it makes fields and methods accessible in subclasses, but not in code completely outside the class.
It strikes me as somewhat arbitrary to allow subclasses to access a class member, but not any other code: either kind of code is equally ‘foreig... |
In an 8bit mcu, I wrote a piece of code of a state machine using a function pointer static void (*state)(void);.
Inside the same compilation (let's say sm.c) unit I implement all the available states.
static void state_foo(void)
{
//execute code
//check results and change state
//state = new_state
}
static... |
I've bought a samsung galaxy s21 ultra about a year ago. Today i was looking at the specs again and i noticed that the Samsung Exynos 2100 processor consists out of 1 single CPU core of 2.9 GHz, three cores of 2.8 Ghz and 4 cores of 2.2 ghz. On the Samsung Exynos 2100 info page I read that the 2.8GHz Triple-core (Corte... |
What are the generic patterns and best practices for resetting state of a database, storage, external service, etc, in Acceptance Tests?
I'm struggling with spaghetti, living in acceptance tests. It connects to the remote DB, executes SQL, Rebuilds buckets through AWS S3 API, reaches into a payment provider API to del... |
In our company we had a discussion whether formatting data in a certain locale is the responsibility of the frontend application or of the API that provides data to it.
Which of the following scenarios would be best practice?
Scenario 1
The API returns data (DateTimes, decimals, etc.) in their original data type (i.e.... |
I am designing a blog in domain driven design. I don't know how I should define models: Post and Comment.
My database:
A user can see a post and related comments. So I think that Post model can be the aggregate root and the model Post should contain a list of related comments.
On the other hand, an admin can see a lis... |
I work for an engineering firm which builds most of our physics models in Excel with VBA. For myself and many other younger mechanical engineers in the company, this is not a good solution - we grew up with Python and Matlab and are more comfortable in those languages.
I've developed a script in Python to approximate t... |
I'm writing boolean methods that do a data quality check and then performs logic. such as isRecordValidAndIsUserPrivilaged. these methods checks the record validity, and then checks the user's access )I can split each of these into 2 child methods to make the code more readable). I get that this is not following SRP, b... |
I know that the C++ standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers, but why is there no hashmap available on C++? I was asked this questions on one of my coding interviews and I did not have an answer. Even google did not give me a satisfactory answer and just g... |
I'm writing an application based on a RESTful API located in a server (written in Python).
An Android app will access the API endpoints to get, post, put or delete data. The usual.
The server has a getUser endpoint:
<app base URL>/users/<user email>
If no user has that e-mail, then a response with http error code 404 ... |
I'm trying to implement a web service API client using the guidlines i've found in this article:
https://www.oreilly.com/library/view/designing-evolvable-web/9781449337919/ch09.html
As it comes to my understanding, article suggests to implement different API endpoints as Link classes, which know how to construct reques... |
I have to build a micro service for my company, the backend is an Oracle database, but the micro service must consume five (5) stored procedures that already exist in the database (as shown in the screenshot). The database architecture can't change.
My question is: must I build only one (1) micro service that consumes ... |
I am writing some code that enables / disables a certain kind of hardware function. To enable it on, I have to call some methods, and to disable it, some others.
Of course I want this code to be clean, so I try to keep the use of if/else to a minimum. See Elegant ways to handle if(if else) else and Clarification of "av... |
I heard about Reactive User Interfaces in a React course. I would like to understand the concept, but was unable to find reliable sources. Best I could find is that they are some sort of declarative UI representation, and I would like to confirm if that really is the case. Can someone give me an explanation of this ter... |
I'm writing a class that acts as the interface to a server. The interface exposes a way to send messages to the server and pass messages back to the client through a callback. Implementations should convert messages into the appropriate format for the server and handle the sending logic. Essentially the API might look ... |
I had a discussion at work about whether to unit test a private static object we're using as data for a public component.
const data = {
45: { name: 'John' },
2: { name: 'Patricia' },
27: { name: 'Rei' },
}
The list goes on with dozens of items and in the real production example it has many more fields. In general,... |
I have a button element on index.html that invokes a function signIn:
<button onclick="signIn()">Sign-in</button>
I have a few basic options on where this function can be defined:
index.html contained directly in a script tag.
signin.js a separate file, included on index.html a la the script tag and its src attribute... |
A social network has API, but also it has some limitations like the amount of requests that can be done in one second (let's say API will give an error, if it accepts more than 3 requests per second)
I want to write a web application that allows me to send messages via API. However, I want to automatically do requests ... |
It's mostly all in the title. How do you report the runtime of a C++ program that has intensive calculations at compile-time?
If I have a program that, when I use the bash time command on it, appears to run in .5 seconds, but the COMPILE TIME CALCULATIONS take over 10 minutes, can I honestly say my program runs in .5 s... |
I stumbled on following problem, and I'm curious if it could be done better.
A while ago I wrote a factory class that looked something like this:
public class Foo
{
private IDbContext _dbContext;
public Foo(IDbContext dbContext)
{
_dbContext = dbContext;
}
... |
The way I see used most frequently
int main()
{
int i;
for (i=0; i<10; i++)
{
printf("hello\n");
}
return 0;
}
The way I’m used to
int main()
{
for (int i=0; i<10; i++)
{
printf("hello\n");
}
return 0;
}
Questions
Is the first way not cumbersome?... |
We have a few apps that communicate with each other. I work on the core backend project X. X needs to make requests to a cloud native project Y in order to process some information.
Now, locally I don't run Y because it can't run locally since it depends on a lot of cloud provider specific stuff and I also don't have a... |
I have a REST API and a SPA application, with Auth0 server issuing access tokens and enabling end users to login with their social identity provider. The API expects to receive a JWT access token with the user's external identity in the sub claim with each request. After the user registers for the first time (and provi... |
Assume the following class structure:
class Base;
class A : public Base;
class B : public Base;
class WrapperBase;
class AWrapper : public WrapperBase;
class BWrapper : public WrapperBase;
I would like to create some function like below
std::unique_ptr<WrapperBase> create(const Base* v);
That creates the appropr... |
I often have to write a function which may return an output of two kinds: "short" and "long". As an example, consider the subset sum problem: the input is a set of integers S and an integer C, and the output is the largest sum of a subset of S that is at most C. The short output is just the largest sum (an integer); th... |
Let's say there is a user table and has field called coins to represent the coins available for that user in the system. At this stage a certain user has 50 coins in his account. Same user do the following requests almost instantly, but in the following order.
Buy something for 20 coins
Insert a promo code that double... |
I have the following classes:
public class MyCaller{
@Inject private MyService service;
private void callerMethod(int arg1, String arg2){
service.serviceMethod(arg1, arg2);
}
}
@Transactional
public class MyService{
@MyAutorizationInterceptor(ADMINS_ONLY)
public void serviceMethod(@My... |
We know that RGB is additive color model and CMYK is subtractive color model. RGB starts with darkness (black) and we gradually add light; an CMY(K) image requires to be illuminated by white light.
When a printer performs printing operation, how do CMYK and RGB work together to print on white paper? And why does CMYK ... |
I'm making an UML class diagram representing classes used for authentication.
There are 3 classes:
X509AuthenticationFilter
ProviderManager
X509AuthenticationProvider
The X509AuthenticationFilter HAS a ProviderManager.
The ProviderManager HAS a List<AuthenticationProvider>
And in this list that the manager has there'... |
Context for this question
I'm currently working with small data storage media (e.g. RFID tags) that contain some fixed number of bytes that can be manipulated. The drivers that allow reading bytes from or writing bytes to the storage medium already exist, so now I'm trying to create a wrapper around the driver that wil... |
I'm currently working on a project which uses azure function apps, we also create a data access layers for each function app which are built as nuget packages and are then published to a private nuget feed. For the function apps, we have three separate environments, QA, Staging, and Production.
I want to create separa... |
I have multiple VMs set up that have the same repo and with slight differences. I use these VMs to prototype or run different experiments. Sometimes I sync or merge between them and from different branches.
I want to avoid polluting the repository's commit history as a way to rsync between them. Rsync is too dangerous ... |
First an foremost I would like to apologise if this is a trivial question, however it has been costing me a few workdays worth of freetime and I am appearantly too incompetent to figure this out myself.
I am currently tasked with developing an Android BLE-Client that scans and processes specifically Eddystone-based Blu... |
I've been curious about why Python seems to be so popular amongst data scientists.
Firstly I needed to check there was some truth to this assertion so I wrote a query on the StackExchange data explorer:
https://data.stackexchange.com/stackoverflow/query/1555958/other-tags-on-python-posts
This shows common data processi... |
Why are use-cases counted separately from the other views in the 4+1 architecture?
How are use-cases different from others views?
|
Although the splitting of web application/ web sites to front-end (client) and back-end (server) is popular, this binary division is frequently pretty far from actual complexity of architecture:
The database could be in separate server
Except client, "server" (already ambiguous term) and dababase, there are could be s... |
In my MVP app, my model (a service) returns a collection of ISession pointers. Each pointer points to an object of a derived type HttpSession or HttpsSession. The model (the service) knows nothing about any GUI, Views, Presenters, etc.
In my Presenter, I need to create and show a View, which should be different dependi... |
When designing a REST API for update request. Usually PUT is used. Question: should the resource URL include the id usually?
For instance, there is a book resource: http://localhost:8080/library/book
When updating a given book with Id, say 123, we could send a PUT request with JSON as the HTTP request body as the updat... |
I've just started learning about Inheritance vs Composition and it's kind of tricky for me to get my head around it for some reason.
I have these classes:
Person
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name)
{
Name = name;
}
pub... |
I have a question about DDD. I wonder if I should add validation in a web api controller and duplicate it in a command handler? Is it good approach to validate a DTO and a command even if the validation is the same?
For example, here I used data annotation validation attributes for a controller:
public class EmailsCont... |
I have a utility function called connectToMongoDB() which connects to MongoDB. Basically, it creates a client for MongoDB and returns that.
I'm making a library and I'm thinking of unit testing the utility functions. The way my unit test would work is by calling the function, then doing CRUD operations on it and seeing... |
I'm working with a legacy codebase that has a lot of functions with a nullcheck on the same object. Example:
std::vector<SessionNode*> * SessionManager::SessionMap;
Session * getSession(int SessionId)
{
//Try to find the Session
//And get the lock
int index1 = getIndex1FromSessionId();
int index2 = getIndex2Fr... |
On a platform with ECC memory, you can assure the compiled binary is 100% legit with EDAC daemon. (single-bit error will be corrected automatically, and multi-bit error will be logged so you can just re-run the compilation).
But on a platform without ECC memory, you cannot guarantee that the output binary is legit.
It ... |
I have a very big form - let's call it <MyForm> - consisting of the following:
text fields and dropdowns
custom selector made of selectable cards
table input (for this example 50 rows with each row having inputable text field)
cancel button and submit button which will submit all the data inputted above to the API
Fo... |
I am exploring two ways of passing certain flags representing user behaviour to the backend. When should I pass flags via headers and update routing based on header, and when is it more appropriate to pass them in the body of the request and let backend handle it?
For instance, I want certain additional information bas... |
We have an application producing 5k-10k datapoints per second. Each datapoint has more than one metric, alongside its time of creation.
We are looking for an efficient, scalable way to store this huge volume, such that aggregations can be queried by business logic shortly after storage, and such that they can be aggreg... |
I have to draw a component diagram that depicts the architecture of my system with its subsystem decomposition and its dependencies.
My system has a 3 tier architecture:
The top layer just acts as a system boundary: it gets the HTTP parameter, calls a method and returns a simple response. For this reason, my presentat... |
I'm getting ready to release a feature to production tomorrow & feel I have misdesigned said feature. I'll try to explain my scenario clearly. I'm looking for alternative design suggestions to this. My real concern is my title - the "final" class takes two parameters of the same interface type, but they MUST be in the ... |
My aggregate root is "Post" and sub aggregate is "Comment". In my database I have a table called "ForbiddenWords" with one column "Name" (it contains words for example: "sex", "porn"). If someone wants to add a comment, he can't use forbidden words. I need to create a class "ForbiddenWords" to validate a comment. Is th... |
I have an event that is raised when my job objects change state (e.g. initializing, running, complete, etc). The event is to be invoked from my set method in the State property, but before I make it that far, I'm trying to determine what makes more sense from a consumer standpoint. The event declaration is:
public even... |
I'm drawing some sequence diagrams to give a graphical depiction of the use cases written during the requirements elicitation phase for my project. This is a simple one:
Vote Post Use Case
Precondition: the user must be logged and the post the user wants to vote exists
Postcondition: the post is voted by the user
S... |
Assume a low-level API is provided without source code (e.g. DirectX).
The API provides a virtualization of hardware resources (GPU, CPU, audio card, etc.), which enables the user to call hardware-specific drivers through the OS. As a software developer, we do not care about the implementation details at the hardware l... |
We currently have a monolith public api which serves most of our api endpoints. This has introduced a bottleneck as the owning team needs to make changes to publicise anything new and other teams don't have control over their own endpoints.
To remove this we're looking to introduce an azure app gateway which will break... |
I'm developing an application that has no client-server connection by design, all of the work is done locally (no internet connection needed), so I'm wondering if I can call it a client? (I'm asking for documentation purposes)
|
The behavior of my systems is as follows
user places an order for a product
1a. order management creates a placeholder record for the order
1b. forwards the order to an external vendor.
external vendor fills the order and also says ships it for delivery
2a. then returns my system back a list of filled orders only end ... |
I have the following scenario:
My .NET Core API has two Endpoints CreateProduct and UpdateProduct.
The only difference between the two will be that UpdateProduct will need to know the ID of the Product to update
Is it bad style to create a common CreateOrUpdateModel with a nullable property for the ID that will be se... |
I have a system that publishes events to a message broker, lets call that system A.
I also have system B and system C that subscribes to the "events"/messages.
My payload/message looks like the following:
{
"eventType":"EntityCreated",
"entityId": 123,
"properties": {
"somedata1": "somevalue1",
... |
I've come onto a new a project and the permissions are done with an allow and a deny option for every permission. Until now i've only ever seen/build allow only permissions.
What is the advantage of this? It seems to introduce extra complexity for developer as well as enduser.
The only situation i could think of that a... |
In my design i have a lot of objects which have a single Run() method, which when called performs what the object should do. Is that a valid interface design? It seems as though most objects I normally use have more than 1 method.
|
My application has big integration with the database. Classes that use the database are very crucial for the system, so I write small unit tests for classes that I call Repository. The reason behind the unit-testing database operations are for example verification of caching or correct order of query execution (to avoi... |
I am currently building an application that uses the Spotify API to work with a user's playlists. My frontend is a Flutter app, which is connected to the backend, that is built with Node.js. Currently my backend handles the logic of implementing the [Authorization Code flow1 by using the spotify-web-api-node package. I... |
I'm a mechanical engineering student currently building a rubik's cube solver. I'd like to code a VSCode program (meant to interface with an arduino mega) that uses the basic CFOP method (solves cross -> corners -> second layer edges -> OLL -> PLL).
The simplest way of going about it would be to pretty much hardcode in... |
I am currently in the design phase of a binary protocol which is intended to be agnostic of the transport layer, meaning it should work on top of for example websockets as well as serial device to device communication.
In short each participant maintains and send and a receive buffer of size X. Received messages are pu... |
I am working on a portable SaaS web application that has these requirements:
The application can run as a cloud service hosted by my organization.
Clients can run the application in their own on-premises networks.
There must be business logic for customer account registration, authorization, licensing, subscriptions, ... |
List<T>.Enumerator “snapshots” list version upon creation by _version = list._version;. This allows enumerator to halt enumeration when List<T> changed during it.
This behavior likely originates from need to move what is hidden under foreach statement into forefront while in obedience to contract (for each).
foreach(va... |
The use case output port is called by the Interactor returning the response model, and the output port could be called many times with different responses.
Question: Could the output port has multiple methods and the response model divided into multiple response models one for each method?
I mean to do this
interface... |
How much (if any) unit tests should be written when you start a new templated project? In particular, let's take as an example a typical .net framework template for asp.net mvc or other similare ones that give a bunch of boilerplate.
Typically, much of this is pre-configured configuration, and you delete much of the "... |
I have a very large C++ application running on a *nix environment, which is occasionally setting a particular date attribute on a structure, way off what it should be. I know which structure and which attribute is going wrong, but what I need to do is to capture the stack trace where the value is being set incorrectly.... |
Currently, I'm reading "Code Complete" by Steve McConnell, 24.3 chapter "Specific Refactorings". I've become kind of confused with 4th paragraph, that looks like:
Move an expression inline Replace an intermediate variable that was
assigned the result of an expression with the expression itself.
Does that inline expre... |
I have a class called SomethingProvider that contains:
private static string convertMapA(string convertA)
{
switch (convertA?.ToUpper())
{
case "NONE":
case "TEST":
case "MEHTEST":
return "None";
case "MEH":
return "meh"... |
For a middleware solution I expose an API, which processes data and sends the necessary information to different parties.
In the current design we create a new client, which acts sort of like an HttpClient per request (because it holds internal state which we keep track of). Previously the clients were tightly coupled ... |
I have app which uses IOC container. I have services registered in container, and I can consume either data factory, or particular data object. Which approach is preffereable?
Consuming factory object:
DiContainer.Register(ConfigurationFactory);
class Service
{
Configuration _configuration;
Service(OperationC... |
I'm drawing the class diagram that depicts the domain model of a system. This diagram is for requirements analysis purposes so it is completely implementation-agnostic.
I want to communicate the allowed values for some attributes in some objects. This is an example:
So basically it should act like an Enum. Is the diag... |
Trying to clarify my knowledge on databases and indexes. I'd like to know how exactly it works. So I have a few questions:
When indexing a table over column or set of columns, a new table is created that holds "indexes". What exactly is stored in that table? A pointer to the row related to the index & some integer val... |
I've discovered my biggest issue with practicing interview questions and writing software more generally is keeping track of indices in python, maybe partly because my first two languages were the 1-indexed Fortran and R. When I'm iterating through an array, especially with more complicated nested for loops, I very fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.