instruction stringlengths 34 36.1k |
|---|
If I create a function to calculate the square root of a number, I suppose i should write a single unit test (maybe two, to test how it handles negative numbers).
But what if I have a function which has a lot more possible outcomes. E.g. let's say I have a (simplified) function to calculate your tax rate. It would dep... |
The java.util.Predicate interface contains the test(...) method, whose JavaDoc description states that it [evaluates] this predicate on the given argument and that it [returns] true if the input argument matches the predicate, otherwise false.
Should I take this to mean that test(..) always returns a true or a false an... |
Given a file containing at most ten million 7-digit integers with no
duplicates. What is an efficient way to print these numbers in
ascending order using just 1.5MB RAM and reading the data just once?
What if duplicates were permitted?
I have come across above question at google but id not find any relevant ans... |
I've made a virtual processor with a simple instruction set and memory model as a learning exercise (and mostly just for fun). I can write programs in its assembly language, assemble them with my assembler, and successfully run them on a virtual machine.
I've been wanting to write a compiler for a higher-level language... |
I need to be able to sort an object by multiple conditions, and these sorts need to be configurable from the application.properties file (as in it should be possible to specify in the file the sorts to apply and the order).
So in my design I created a comparator for each one of the sorts, and then an enum with a suppli... |
I'm wondering if you had something like a list and a subdocument of items. Does MongoDB save them all as a single document, or does MongoDB regard the subdocuments as independent documents. This is in regard to the 16mb document limit.
E.g.
list document:
{
items: [
{
_id: 1
name: "item1"
}
{
... |
I am writing system requirements for a tender.
Functional requirements consist of mostly improving the system (add/remove data fields, improve statistics and activity log, exchange more data with other systems) without adding any new processes.
What should I put in as business requirements? Can I leave that section e... |
I'm building an REST API that exposes a callback method for a 3rd-party service.
Let's imagine that there are two similar (but not identical) 3rd-party services. They both call back my API (POST /api/callback), but have different request formats (JSON):
Provider 1
{"sender": "Provider1", "field1": "value1", "fieldN": ... |
I am trying to marry the git flow approach (w/ dev, test, uat, staging, prod env) & automated build and releases in Visual Studio Team System (VSTS). Slightly struggling due to VSTS needing a persistent branch to 'anchor' builds on - I am curious what other people do.
Our Approach
branch newFeature from develop branch... |
I often hear that a test should contain only one assertion (Disregarding testing attributes of a class) and where the whole pre-conditions for the test should be setup before the assertion.
In our application we have many tests where a user of the application logs in, performs some actions, then the state of the applic... |
In Uncle Bob's clean architecture, why can't MVC controllers call entities directly? It seems like since the controller depends on the inner layer, they should be able to call entities when needed. If the entity has to change for something in the presentation layer,then you'd add another class to handle that,is this co... |
I currently work as a Solution Architect within a Scaled Agile organization. We also have Product Owners who are in terms of the Company a "higher rank" than the technical oversight group that the Solution Architect's belong to. The technical oversight group sets the standards and looks at process improvement ideas. Oc... |
In my C# project I need to swap data providers in the future so I have created interfaces to build future providers off of. But this is the first time I have worked with interfaces that are "complex" or have collections and sub collections within them.i.e.
My Interfaces:
public interface IPortfolio
{
string FirstN... |
Here is my problem: I want to read input from different HID devices such as a gamepad, racing well, joystick, etc. Pretty much any game controller. The issue is that they all have different inputs.
The gamepad has buttons, switches and sticks while the racing well might have a gear stick. I managed to abstract all the... |
What is better?
if ("a".equals(x) || "b".equals(x)) {
//do something
}
vs
private static List<String> validAlphabets = ImmutableList.of("a", "b");
if (validAlphabets.contains(x)) {
//do something
}
The above code sample is in Java, but this applies to any programming language.
Is one approach better than the ... |
Let's say I have an entity Foo. That entity could have a 5 states: A, B, C, D, E(in real application number of statuses can be larger). I store that entity in a database and map it to class. Every day I run cron command that takes all records from DB:
records = service.getRecords()
foreach(records as record) {
}
So ... |
I recently interviewed at Amazon. During a coding session, the interviewer asked why I declared a variable in a method. I explained my process and he challenged me to solve the same problem with fewer variables. For example (this wasn't from the interview), I started with Method A then improved it to Method B, by remov... |
I have seen some people asking about sharing business logic with more than one application, and answers generally discuss putting it in a class library. I'm fine with that, but usually the examples have two applications, and they just make a class library with the business logic they both care about, and both applicat... |
I have a document object and a list of operations that can be applied to that document in sequence. The types of operations are known in advance, but not their parameters, the order of operations or their number. For instance there may be a DB from which we pull a specific list of operations and corresponding parameter... |
I am used to D coding and Python where the class definition also contains each method definiton. So it is my preferred style of coding.
I abhor having to switch to the .cpp file and use that long qualifier name.
So, since I rarely call a function more than 2-3 times, isn't it a good idea to inline most of my code? My... |
A developer is tasked with writing a service that will iterate through a number of records and send notifications for each one. The type of notification might be different per record, so you can imagine logic like this:
switch (record.DeliveryPreference)
{
case "email": SendEmail(record); break;
case "sms": Sen... |
This is just a quick question about standard CLI-parsing design.
Say we have:
foo -abc
for most CLI-parsers, a single - dash (as opposed to a double dash --) means you can group single letter options together. Such that the above is synonymous with:
foo -a -b -c
my question is - for grouping, is it possible or advis... |
I'm learning about system design for the first time and am really intrigued by reliability. Given a setup where you have a master that replicates and writes data through to a slave, how do you persist/maintain availability of data to users if the master goes down? Lots of these architectures I find online seem to have ... |
So there are a fair few blog posts about that introduce CSS modules. For example:
the official documentation: https://github.com/css-modules/css-modules
a post from CSS Tricks: https://css-tricks.com/css-modules-part-1-need/
These show us the syntax, and what they do, and how to use it.
But what actually is CSS Mo... |
I don't know if I am over-complicating stuffs but here is our setup.
3 Code hosting servers (QA, Stage, and Production)
3 main git Branches (dev, stage and master) for respective servers
10-15 developers working on git sometimes working on same file concurrently.
Developers are only allowed to merge and push to dev, M... |
I will directly come to our current working flow so that you can understand the problem in a clear picture.
I am attached in Laboratory Automation System in which Analyzer (a machine that performs medical tests) sends data to Host (our Automation System). Every analyzer is assigned a unique ID (Machine ID) and is saved... |
I'm new to DDD and trying to wrap my head around it by writing a prototype for an application (Core-Logic-Layer).
My domain model looks like this atm. (I leaved out parts, that weren't necessary for the problem):
So we have an aggregate root DebitAccount that has assigned Estimations (about costs / income that will oc... |
Perhaps this story should be titled "BDD definitions for agile service stories"...
For our .NET-based stories (always vertical slices) we use definitions matching the well known BDD format.
Sometimes the story involves work explicitly in a dependent system (here this is SAP). When this happens it does not touch the use... |
As the title says - how to keep track of functionality as the application grows large?
My company use Word-documents where the application has been broken down into chunks called "use cases" - which vary in size and complexity. The problem is that some of them quickly become large and hard to read, as you have to scan... |
I'm trying to flesh out an eCommerce system using microservices (.NET Core and Kubernetes), event sourcing (Kafka), and CQRS. The particular use case I've been thinking about is as follows.
There is an inventory microservice designed to use CQRS. Updates are fed into Kafka as events, which the inventory microservice ... |
I have a repository pattern employed in my .NET Core 2.1 project. While implementing the edit/update scenario, I have a doubt.
My domain:
public class Component
{
public int Id { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public string Narration { get; set; }... |
My lead dev complained that I have too much logic in a nested catch block. My code goes something like this:
try
{
// some setup and a network call
}
catch (CustomEx ex)
{
try
{
KindaLengthyRecursiveRetryMethodThatHandlesCustomEx(numTimesToTry);
}
catch (AnyException ex2)
{
// Lo... |
I have an online game server that works as follows:
Once a player connects, he is in one of predefined sessions (consider them physical location, e.g. Island, Underground location, etc.).
Then any action (movement, attack) is always broadcasted to all other players in the same session. Also when he enters a sessi... |
Im developping for my company a software where clients can requests app deployements and upgrades.
Each request has 3 status (Validated, Started and closed).
For every type of request (deployment or upgrading) and for every status , each application has it own logic to execute.
I used the factory design pattern to ha... |
I found various libraries in C#, PHP, Python, etc. for workflows. By workflow I mean something like an employee wants personal time and that request starts with the employee and finishes in some repository after approved/disapproved. (Very small example. In reality it is much larger.)
In my question I know I can ente... |
Assuming the context of a CRUD:
After performing a database DELETE, should an application's deletion method check if the records were actually removed from the database?
If so, how valid is it for the other "altering" actions (CU)?
|
I am trying to tighten up my process for tackling a feature request. Currently, we use trello to manage feature requests using cards. They typically look like this.
Card Title: Invite a friend
Card Description: Allow the user to send an invite.
I then interpret the feature and start writing code to fulfill the reques... |
Assume in C we have the following array of one item:
int a[] = {2000};
2000 in binary would be:
11111010000
If each memory address can hold 1 byte (8 bits) of data, then howcome
in some tutorials, it is mentioned that each array index is stored in one memory address? it's not possible since 2000 has 11 bits and needs... |
I read this blog post recently:
The Two Pillars of JavaScript
Part 1: How to Escape the 7th Circle of Hell, which is essentially a criticism of object oriented programming, and advocacy for funtional programming instead.
Some key points made:
Constructors violate the open/closed principle because they couple all call... |
This just came to mind, and not really sure how to search for this.
Let's say you have the following classes
class A
{
public:
virtual void Foo() = 0;
virtual void ManyFoo(int N)
{
for (int i = 0; i < N; ++i) Foo();
}
};
class B : public A
{
public:
virtual void Foo()
{
// Do... |
I'm having a dilemma where I would need to implement a better way for our Project Model with dynamic property depending on the country.
So what happen in our application we have dynamic fields for a projects depending which country it is. For instance the project model in the Australia has Foo but not in the project mo... |
Let's take some classic enterprise example: Order and OrderItem
public class Order
{
public Guid Id { get; set; }
public ICollection<OrderItem> Items { get; set; }
}
public class OrderItem
{
public Guid Id { get; set; }
//...
}
Now, what's the most reasonable way to update the order's items using PUT ... |
If I have two different producers that could produce the same message for a Kafka broker, how can I ensure that only one of the two message occurrences gets processed?
Is the only way to have an input topic, then a consumer that dedupes and saves to an output topic?
Or could the relatively new "exactly-once" functiona... |
I have a template repository consisting of a folder structure, scripts, makefiles, example files (text templates) etc.
The easiest way would be to clone the repo, delete the .git folder and create a new repository. Then I’d need to update the template manually.
Branching can be difficult due to great differences betwe... |
What is the Java way to say in a text that a function belongs to a specific class?
For example, when writing a C++ commit message, I say
TimeInterval::toString() now uses a UTC timezone
I.e., I utilize :: to designate the toString() as a method of TimeInterval.
Is there a similar convention for Java?
|
I am creating a program, and I would like to know the best practice for creating a class which defines different fuel types
For instance, I have the following class that I have written in python:
class Fuel():
def __init__(self, fuel_type, energy_density):
self.fuel_type = fuel_type
self.energy_dens... |
edit
I asked this question not because this is my opinion, but because I am trying to understand someone else's. Personally I prefer IoC via DI (in my specific case Simple Injector) but not everybody shares this opinion and I am trying to get some insight as to how maintainable code would be without DI.
end edit
I've b... |
In the context of Progressive Web Apps (PWA) there are two terms that I am trying to better understand:
Service Workers, and
Web Workers.
What is the difference between them and their intended use? Are they similar in any ways? Or may be they are in some relation?
In my current understanding, a Service Worker is tru... |
I'm reading on DDD and came across this excerpt:
Let’s consider a drawing application. The user is presented a canvas and he can draw any points and lines of any thickness, style and color. It is useful to create a class of object named Point, and the program could create an instance of this class for each point on th... |
How to implement HTTP's PUT that works with child collections when using DDD's rich domain models?
Let's say we've got an aggregate root with a nicely encapsulated collection of items:
(I omitted persistence specific properties like Id for brevity)
public class Foo : IAggregateRoot
{
private readonly List<Bar> _it... |
Or in actuality, how to tell if a certain technique has became a standard in certain language / framework?
As I understood from my readings so far, PHP supports DI in PSR-11 while Laravel uses it out of the box...
But does this mean DI is a standard for PHP and Laravel or they just helped you to do it right, should yo... |
I am working on a microservices system in c# (.Net Core) where for simplicity we place each microservice in it's own repo.
Some services are very generic and some are very similar (although for different domains).
Naturally over time as the number of services grew, we identified a lot of re-usable code and patterns acr... |
In my understanding, even if i want to overwrite a byte in middle of a file, OS and/or disk will read the content of the size of page, modify one byte and then write the contents back.
What is the fundamental reason that disks are designed this way to have read-modify-write cycle ?
Is hardware or physical properties of... |
I'm currently designing a ledger API, that should work with different implementations (e.g. based on Blockchain, traditional databases, or files).
Its purpose is to add/get messages to/from a concrete ledger. The messages get encapsulated in transactions, which have additional meta data like time, and author, etc. Init... |
I order to achieve the DRY principle I want a functionality that logs processing time of some other functionality for example for each group of classes with a Base class.
So the most logical way is to place it in an abstract class and make a virtual method between the StopWatch Start and Stop. But I was thinking about ... |
We've got a system called Foo hosted as a repository in Github.
The system depends on a couple more microservices, called Bar and Baz. Each of these microservices is hosted as a separate repository.
We are getting lost when doing Issue Tracking since there is no single repository where the Issues live. A single Feature... |
I have a PHP script which has a group class and a component class. Each group consists of several components. My group has attributes groupName, groupId and componentList. My component has a componentName, a componentId, a componentStatus.
It is necessary to assign a groupId to a component to create it (so the componen... |
I receive daily from an external source a very large amount of data (around 250GB with 260 million rows of fixed width text) distributed over 5 text files. I am writing a Java application that should combine a first group of data (files 1-4) with a second group (file 5) based on some business logic.
But accessing/readi... |
Every now and then we programmers need to communicate with external systems (not under our own control). It's frequent that in such cases we need to keep track of some sort of identifiers that these external systems use. And more often than not these identifiers are integers.
In such cases, should these external identi... |
Consider you have a GravityLogic and a WeakForceLogic class. In themselves both provides tons of business logic. Now you want to create interactions between those which produce a complete different set of result. Would you rather create GravityWeakForceInteractionLogic class if this is going to generate a lot of new a... |
Let's say I have a library code main.cpp, where are 3 classes implemented: Inner1, Inner2 and Outer. Inner1 and Inner2 are only being used in main.cpp and they're not going to be used anywhere else.
On the other hand,Outer class is intended to be used by users of my library, i.e. to be a part of API. I also don't want ... |
I am currently working on a project for a production facility. The machines in the production are saving so called 'Telemetry Data', measurements like water pressure, plastic volume or temperature into a database. In this case we are using a ElasticSearch Cluster. My task is to develop a web application which gives the... |
I am working on Java program which will listen multiple kind of events from multiple sources and store information to multiple sinks.
Each interface will have its own source to listen and own sink to store data. Event frequency can be hundreds of thousands events per second.
As event frequency is of great magnitude, t... |
Here is a a part of the documentation of Qt's QElapsedTimer:
bool QElapsedTimer::hasExpired(qint64 timeout) const
Returns true if this QElapsedTimer has already expired by timeout milliseconds (that is, more than timeout milliseconds have elapsed). The value of timeout can be -1 to indicate that this timer does not e... |
I'm writing a software library for some numerical computations. I'd like to use Boost Unit Test framework to write a hierarchical unit-test covering not only basic input/output behavior of functions but also the higher functionality, e.g. correct results to some test problems etc.
However, I'm afraid, that I'll get los... |
So I've been coding in Java for a decent amount of time, but recently, I've started a class that cares about my coding design. In the past, if I had two methods inside a class that needed to edit the same variable, I would make the variable a class variable. However, I know that some people prefer creating their method... |
Scenario: I fork a project and submit a PR on Feature A, and then another on Feature B. I want to continue working with both features while I'm waiting for the PRs to be merged (theoretically they might never be if the upstream is abandoned).
Updated Requirement: I’ll have to push the changes to my fork remote so that... |
I have a bunch of if statements written in PHP for a project I'm working on. The pattern is that when the $price increases by 5 cents every time magazines are increased by 10. When the amount of magazines reaches 91, the price anything above it are fixed.
if($total_magazines <= 10 && $total_magazines >= 1)
{
$p... |
In context of pure functions in FP, apart from several benefits mentioned like easy to reason about, testability it also says "order of evaluation does not matter" since output remains same for given input. Probably I being from OO background finding it difficult to understand what it actually means. It would be great ... |
I need some expert guidance. I'm trying to learn the concepts as well as implement them, and it's possible I might be over-engineering some. But that's OK, because I am wanting to learn and gain experience more so than keep it simple. I'd like to apply the concepts of DDD and CQRS in my project but I'm having troubl... |
I am working on a quiz for a computer science course. I would like to check that the following statement is false:
A recursive call may never generate more than one recursive call for
the recursion to terminate
We have put this statement as false and I would like you to confirm that it is false. In almost all cases... |
so I need to flowchart something similar to the picture.
The the first flowchart on left and the 2 flowcharts on the right is on different classes.
The someClass have a instance variable named MyVar and 2 methods named setMethod and getMethod.
The getMethod and setMethod uses the instance variable myVar how would I s... |
I am developing a web application for an industry that desperately needs it. Working with a consultant in the industry, I’ve rapidly developed a prototype in 2 months that we will be testing with a company they consult with. The software will be used with 4-8 employees who will be testing it.
The prototype has been con... |
Is it ever good or bad to have a constructor create new instances of classes that it needs versus passing in a reference that you want the new class to have ?
So basically it's the difference between:
A classA = new A();
B classB = new B(classA);
and have class B constructor assigning classA to its field/property.
com... |
Let's say I have a project that needs to do the following:
Multiple calls to read from the database where each call is a different query and returns back a value object (just has getters/setters). Let's say we end receiving 20 value objects
Perform some logic with the data from these value objects
I'm trying to brai... |
I'm not sure if this is the right forum, but I'm really looking for an advice on this.
We've a procedural decision engine, which is fairly rudimentary, to decide application routing. It's basically multiple if-else statements (about 30 of them) in series. For example:
if (application.isBlue && (!configs.isBlueAllowed)... |
I'm looking for the "Holy Grail" (best practise) of how to update an entity with REST?
There are three main approaches I've found so far:
Always send full entity, regardless what has been changed and just
overwrite the previously stored data. (This is the one I'm using
right now, but it's ugly because of hidden fields... |
I'm prototyping some single machine, single user software with a client-server model; the first client for which will be a CLI, but I expect a (local) webapp/GUI to come later.
For the CLI, I'd like to be able to either connect to an existing server instance to run whatever commands, or start one up for the duration of... |
Problem overview:
I'm creating a spring application just for learning purposes. I would like to create a microservice just for files, which:
at the beginning would have only two basic endpoints upload/download a file (used by other microservices, not by a user directly)
create db only for that microservice with thefil... |
I am considering a CQRS refactoring process. It is more of a learning exercise in my spare time. The use case is similar to a price comparison website where a user enters their details for a mortgage and they are presented with mortgage options from service providers. For example, a user enters the minimum deposit; ... |
There's a sort of pattern that I've sort of stumbled myself into "discovering" that seems extremely useful, but I've never seen it described before. It's sort of a way of achieving inheritance through an interface. It's really wierd where the class "becomes" the thing that it accepts. (Written here in C# but it doesn't... |
Let's say I have the following function (in JavaScript, for sake of example):
function foo() {
var bar = function () {return 'lol';}
return bar;
}
This function returns other functions. I had the misconception that this was called a generator, but on reading around, that's something different entirely. Googling th... |
Here's an example taken from http://json.org/
Is there a name for this kind of diagram?
|
Often I want Arduino board to control several peripherals. Writing program for all of them in one document using #define SOME_PIN 4 constructions seems pretty inconvenient to me. Especially in such a case when you have to modify old code which was written a long time ago.
I chose to use the following approach to organ... |
I am designing and prototyping an ncurses C++ wrapper. It's a hobby project, nothing too serious. I will omit include guards and stdlib includes etc.
Consider the following files:
application.hpp
#include "ncurses_forward_decl.hpp"
#include "window/window.hpp"
#define PPCURSES_VERSION_MAJOR 0
#define PPCURSES_VERSION_... |
Assume we are in the world of car rental application :)
Let's say that I have 3 types of cars with 2 categories of price:
Car type Price category
------------------------------
Sport High
Luxury High
Economy Low
Values of High and Low can change over time, so they should be a sepa... |
My application backend consists of a bunch of standalone tasks linked together by messaging queues. They all need to access the same SQL database in order to run and store their results.
Right now, all the tasks are accessing the SQL database directly, but by not having a centralized entity to manage access to that dat... |
Haskell is one of the few non-strict languages out there.
In his paper Why Functional Programming Matters, John Hughes uses (memoized) lazy evaluation (as well as higher-order functions) to implement a couple of nice algorithms where he is able to separate:
how data is generated.
how this data might be manipulated.
ho... |
I've been doing some research on RESTful architectures and JSON responses. I'm trying to understand which method of laying out JSON responses is "correct" or if they are both acceptable.
For instance, using the swapi, I've seen JSON responses that reference URIs for embedded objects:
{
"name": "Luke Skywalker",
"h... |
I am building travel blog using React as frontend Javascript framework along with GraphQL. I am doing this project by myself as a pilot test and I am currently in a phase of translating photoshop design in HTML/CSS/JSX.
What bothers me is what will be the best way to store blog posts in database, fetching them and show... |
I am developing a project using Laravel. My workflow is:
route directs to controller
Controller calls eloquent models
Eloquent models perform queries (tipically CRUD and find)
Controller returns either a view or a JSON string
Lately I realise my queries are getting too complex. Complex enough that I find myself writi... |
In my system I frequently operate with airport codes ("YYZ", "LAX", "SFO", etc.), they are always in the exact same format (3 letter, represented as uppercase). The system typically deals with 25-50 of these (different) codes per API request, with over a thousand allocations total, they are passed around through many ... |
I was studying Lamport's mutual exclusion algorithm from the original paper, and noticed a difference in the release phase to the one given in Wikipedia. In the original paper, author states that :
To release the resource, process Pi removes any Tm:Pi requests
resource message from its request queue and sends a (tim... |
To simplify deployment and project management tasks I maintain a monorepo containing several packages that each have a semver version. To be clear, I don't mean several repositories managed from one place, I mean a single Git repository that tracks several packages with a common toolchain. Note that this does NOT imply... |
To avoid magic numbers, we often hear that we should give a literal a meaningful name. Such as:
//THIS CODE COMES FROM THE CLEAN CODE BOOK
for (int j = 0; j < 34; j++) {
s += (t[j] * 4) / 5;
}
-------------------- Change to --------------------
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int su... |
Is it possible to use semantic tags in UML associations (among classes) to express the wider semantic nature of the relationship?
For example, consider the relation that Doctor TREATS Patient. Beyond the TREATS relation, we also want to express that it's a medical and humanitarian relation. Is it possible to somehow ta... |
I'm working on a small python project and have a general_code.py file where I have functions that I use throughout the project. Some examples:
def to_boolean(var):
return var in ['True', 'true', '1', 'y', 'Y' 'yes', 'Yes']
e.g 2
def get_last_line(in_file, block_size=128, ignore_ending_newline=False):
e.g 3
def s... |
At my work every line of code must be reviewed and this review is formalized in a merge request.
Now we are a facing a situation were one developer developed a prototype for a new product which is now going in production. There are a few hundred commits and lots of line changed all in one branch. I'm wondering what wou... |
I am researching before starting to work on an API for a web-service I am building. The goal is to be very quick and easy to adapt and use for other developers but fairly hidden for clients using a collection of Webapps to make calls to the service behind the API.
It is the first time making an API for more than intern... |
Background
I'm currently working for a relatively small ticketing company with many clients and customers.
We have developed an 'open' (as in it can be used by anyone) Serverless GraphQL API in Node.JS. The API is made up of fine grained services that implement their own security, exposed using GraphQL through AWS API ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.