instruction stringlengths 34 36.1k |
|---|
Let's say we have a struct Vector2i { int x = 0, int y = 0 };
And create a Pointer to it via Vector2i* pointer = new Vector2i;
Where would int x and int y be stored? Heap or stack?
Are all members of an instance a Pointer is pointing to automatically on the heap because the vessel is?
Are members of stack created vesse... |
When does an object truly belong to a class? I'm familiar with the "has-a" relationship, but in the case of an Employee object, it "has-a" 401k, but it's not really composed of a 401k object. As an employee, my 401k does not make me who I am.
What I'm getting at is, I don't feel that I should need to reach into the E... |
So I'm working on this game where I have a nested class which has to get access to the member functions and variables of the outer class in order to perform it's functionalities. In particular the outer class contains member functions and data related to game objects whereas the nested class extends an AnimationTimer w... |
I have an array of integers representing connectivity of nodes.Consider the following states of the array after each time it's changed:
0|1|2|3|4|5|6|7|8|9 => Root of each node is itself
0|1|2|3|3|5|6|7|8|9 => The root of 4 is 3
0|1|2|8|3|5|6|7|8|9 => The root of 3 is 8, so now 8 is root for 3 as well as 4.
And so on..... |
In every website I have ever made I usually make the back-end API using NodeJS and run it on a certain port and make the front-end using React and run it on a different port and make requests to my NodeJS API. Is this the optimal approach to making a web app where I don't want anyone but my front end to access my API? ... |
I am currently thinking about how I would implement a software I did write some years ago with a Clean-/Hexagonal-/Onion-Architecture. This shall not be a "Grand Redesign from Heaven", since I'm not involved in the project anymore, but rather I'd like to learn what I could have done better.
One thing that I have probl... |
I'm implementing a registration system where I would care of having a clean DB with only unique email addresses.
uniquenes could be simply obtained by comparing email addresses strings.
But considering what various email providers policies, allowing you to use same address e.g. inserting dots or plus signs...
Resource:... |
In a MVVM application (Xamarin.Forms, FWIW) I have a viewmodel that stores settings explicitly
public class SettingsPageViewMode : INavigatedAware
{
ISettingsRepository settingsRepository; // injected
public void OnNavigatedTo(NavigationParameters navigationParameters)
{
var settings = settingsRepo... |
I have a custom TextBox that validates its input. Whenever the validity of the input changes, a ValidityChanged event is raised and the user is informed about the validation results. My question is what to do when the user changes the input, but the input still has the same errors.
For example, let's say the input shou... |
I our team we use a gitflow approach to maintain our codebase. But there is one case in which we struggle.
We are in the following case, we have two feature branches (feat/A, feat/B) that were create from develop.
feat/A is now finished, so we merge it into develop, well this feature now lives in develop, it is waitin... |
With the inability to go into to much detail, imagine the following situation:
You are developing a library that needs to run on various embedded platforms (AVR, ARM, etc..). Some functionality of said library needs some sort of time keeping (not an actual time but along the lines of "it is now x (mili)seconds later th... |
We have a build server that will transpile the JS source into the bundle file. I now need to inject values that are dependent on the environment the application is executed. The problem is, since the app is already bundled, I don't see a way of injecting it in a clean way.
Alternatives I've seen on other teams are cre... |
We are developing a new REST Api for our Spring MVC legacy enterprise web application (before this it was communicationg with Adobe Flex frontends).
As a general rule we stated that we were creating a @RestController for every model we have in our application. We have also a BaseController for handling the CRUD operati... |
What are efficient algorithms for immutable dictionaries/sets? By efficient I mean they either have better or comparable time and/or memory performance compared to their mutable versions. I don't necessarily mean this in the context of functional programming, where I've seen immutability equated to persistent data stru... |
I was trying to create an integration test for my service where 100 clients would connect, login, send request, and log all responses for some configurable amount of time.
I was build a class for the client using async sockets and it works fine. I started them all up using Task and Task.Factory, sent the login, and po... |
I'm designing a programming language for a game, to be used as the main way of interacting with the game, as opposed to using other methods of control, such as the arrow keys or mouse. My plan is to have the user control game objects through objects in the language.
if unit1.health > 20 {
unit1.attack(Enemies.ene... |
The reasons may vary from breaking principle/guidelines of OO to considering protected as part of public API.
Then, what should we do if some derived classes have same members? Should we declare them in base class and inherit them? Or should we declare them in derived classes multiple times?
For example, class Warrior ... |
For example: While performing functional testing of a form in a web application, we will test the fields by entering different kind of random input values.
In general, we as users of the web application do not actually enter random values into fields.
So what is the use of incorporating all those testcases which may/ma... |
I come from a python background. I typically write long unit test descriptions that link the test to a user story. The test is as much about justifying why the code exists and how it fits into the larger system as it is about testing for correctness. As such my tests often have about as much docstring text as test code... |
I'm developing a software system, which provides HTTP REST API, and I want to achieve a very modular and flexible design. So, there is a core functionality and feature modules, which handle only the logic related to each specific feature. The goal is to be able to add/remove modules in a flexible manner without the nee... |
When requiring to use dependency injection, I always use IoC containers such as Ninject, Unity, or the built-in one in ASP.Net Core MVC. However, I've just come across the idea of "why not creating an object factory" and then instead of intercepting calls to parameterized constructors (via IoC containers), retrieve tho... |
I have a concept that I am struggling to design in a DDD CQRS manner, and I hope to find some insight.
In the old days (before I knew DDD) I would have used simple inheritance, and that's how my mind is wrapping around the following...
I have a domain concept: Property
There is a SingleValueProperty which has a Proper... |
We are building a notification service whose work is to send push notification to end user. There are two types of notifications
Group notification where we send same text notification to all user's in a group. This is easily achievable as everyone subscribe to a group and we send a notification to a group.
Personali... |
How to declare static function with array and pass next into other class?
class A
{
//static
public static $data = ['Los Angeles', 'New York', 'Washington'];
//const
const DATA = ['Los Angeles', 'New York', 'Washington'];
}
Which approach is better and why? Maybe for string or int better is other appro... |
I've come across a method resembling the below snippet.
public void process(Data row) {
Value value1 = row.getValue1();
Value value2 = row.getValue2();
boolean saved = false;
if (value1 != null) {
if (relevantValues.contains(value1)) {
addRow(value1, row, only1collection);
... |
I have multiple data sources that I need to search across and return back to the client (web app).
For example the sources are:
an elastic search index
a sql database
Is there an efficient way to perform paging across two sources? At the moment I am searching on one, and then reducing the searchable items on the sec... |
I have a created a Java project. My project is a collection of classes that allow a programmer to manage local networks (create network, delete network-access to device, get information of SSID) and other functions in the local network. The architecture of program is based on CMD commands. All classes are reusable by p... |
I am working on a ruby on rails learner project that uses multi-tenancy. This project has states(tenant) and cities(sub-tenants). User can only belong to one city. For first level i.e for states I have decided to go with separate schema approach using the Apartment Gem. Now my question is can I use table level multi-te... |
I have had a discussion with a coworker about breaking a return statement and the statement that calculates the return value in two lines.
For example
private string GetFormattedValue()
{
var formattedString = format != null ? string.Format(format, value) : value.ToString();
return formattedString;
}
instead o... |
I have developed a windows service with Message Broker (RabbitMQ)
The purpose of the service is to receive data over TCP/UDP connection. Parse the incoming data which is in HEX format and convert them to objects and save the object to the database. Also the service performs some calculations and checks to send out aler... |
What's a good way to design a RESTful URL pattern to get one and many results by ID ?
One (Response: single item)
/invoices?id=a/b
Many (Response: array of items)
/invoices?id=a/b&id=bar
The above approach looks nice in theory but raises a couple of concerns
What (JSON) should be returned if id is omitted, {}, or [... |
I'm trying to figure out a win/lose algorithm where we have to have (around) X winners per day spread across the day without knowing the number of participations.
A user sends a request to an application that immediately decides at random whether the user has won or not. We don't know the number of requests when we sta... |
I have a class that internally uses an interface that is defined externally. Testing this class becomes difficult since I need to mock out this interface but I am required to reference the external library (which may be quite big) since the test is in a separate test project. Are there any ways to decouple this interfa... |
I was writing an app(learning) and I found this problem.
I have 3 table Orders, Customers and Suppliers.
An order can only refer to a customer or a supplier and there is no conceptual difference between a customer or supplier order.
What is the best / most performant way to store it?
Create 2 separate tables: Customer... |
Sometimes i have code along the lines of this:
public abstract class A
{
protected abstract void DoSomething();
}
public abstract class B : A
{
/// <inheritdoc />
protected sealed override void DoSomething()
{
SpecialFunctionalityOfClassB();
... |
In our codebase we have a lot of controllers with a very similar structure:
@my_model.update_owner(something)
if @my_model.update_attributes(params)
return render_object(@my_model)
else
return render_validation_error(@my_model)
end
Although the structure is not exactly the same everywhere, it seems feasible t... |
I've reported to a third party what I consider a very serious performance bug in a widely used product. Older versions worked fine. Newer versions are practically unusable except for what I consider trivial situations. I have provided test cases showing older version performance versus newer version performance.
After ... |
Does visitor pattern lead to violation of SRP? Take this for example:
class 401k
{
public void MakeContribution(Contribution contribution)
{
contributions.Add(contribution);
}
// using double-dispatch here (violation)?
public Money CalculateBalance(I401kBalanceCalculator balanceCalculator)
{
retur... |
Here is a weird problem in Angular:
<input #pin1 type="password">
<p>You entered: {{pin1.value}}</p>
If you type something in <input>, the <p>'s content will not change which means pin1.value does not have value, does it mean the variable reference #pin1 does not work?
On the other hand, if we add a function to pass t... |
This question might be a bit vague and answers might come up quite opinionated but I don't know how to rephrase it so here it goes.
How can a developer build a solid vocabulary when working in a specific domain?
As we all know, naming things is one of the hardest feats in this craft. Furthermore, it is highly likely ... |
I have an interface with only a single method that could be replaced by java.util.function.Function from the JDK:
interface DataModel {
boolean apply(Map<String, Integer> input);
}
The replacement would be
Function<Map<String, Integer>, Boolean>
However, I wonder whether I should keep this interface since at least ... |
I'd like to implement a multicast function. Currently, I'm in the design phase of this.
The basic idea is to have a class, to which std::function can be added, an interface like this:
template <typename ...PARAMETERS>
class MultiFunction {
private:
// some container to store functions
public:
//... |
I'm currently doing up class diagrams for a project I'm working on. I feel there's something that should be represented in my class diagram but I'm not quite sure.
I have a .csv file which the whole system essentially works on, which is created by a java class on a once off basis (i.e it will never be done again). I... |
Say we have a class "Felidae", and a class that extends it, "Felis".
Felis is an extension of Felidae, but what is Felidae? Is it the inheritor (or inheriter) for Felis, in common terminology?
Given I'm not sure that inheritor is the accepted term, I want to ask, if there is any formal, or at least, very common term fo... |
Supposed I have a common block of code between two controllers where the only difference is the concrete class that the block uses. Both clases implemenet a common interface
so I am using an interface to interact with the object.
The block of code is a series of steps that interact with functions of the concrete class.... |
If I've got a script that uses a config file (or defaults to a generic config file) that calls another module which needs the config file passed to it as a parameter should I always
File 1 (the script): /bin/runner
include doer.py
... initializing backup conf file
backup_conf_file = "/etc/thing.conf"
... processin... |
I have a script which returns the ID's of the warehouses (4,1,2,10,9) in order how close they are to the customer.
$warehouse_rank = array('0'=>4,'1'=>1, '2'=>2, '3'=>10, '4'=>9);
When I lookup a product from the database, I return a breakdown of which warehouses have it in stock and the quantity. Like so:
$product_bre... |
PHP, C#, Python and likely a few other languages have a yield keyword that is used to create generator functions.
In PHP: http://php.net/manual/en/language.generators.syntax.php
In Python: https://www.pythoncentral.io/python-generators-and-yield-keyword/
In C#: https://docs.microsoft.com/en-us/dotnet/csharp/language-re... |
I have searched and found a few questions talking about testing in relation to feature branching. My question is a little different.
We are a scrum* team of 4 to 5 developers with a dedicated on-team QC. We do active development on a family of applications with large amounts of legacy code. The application family incl... |
I'm integrating a messaging feature into an application written in Javascript and would like to know which is the preferred data structure of storing messages.
The two structures I can think of so far are these:
const thread = [
{
id: 1,
user: 'joanne',
message: 'Hello, How are you?',
},
{
id: 2,... |
I am building a service which acts as a proxy to third party data providers for the end-user. My service uses tokens for authorization and if the user does not have a valid token it responds with 401 Unauthorized. If the token is valid but access to the resource is denied my service responds with 403 Forbidden.
The ser... |
Is it a good practice to use #ifdef during development to switch between different types of behavior?
For example, I want to change the behavior of existing code, I have several ideas how to change the behavior and it's necessary to switch between different implementations to test and compare different approaches. Usua... |
My application uses a relational database but there is a feature requirement to display a survey form to users at the end of each quarter/year etc. I understand that this data maybe used to do some analysis in near future but the issue is the form would have many key value pairs and I am sure that it will keep on chang... |
I have a Java app which acts like a command server for other devices and communicated with them via MQTT. I want to add a new functionality and don't let my sender class (implemented as a thread) send another message if the receiver class (also implemented as a thread) doesn't allow him to, let's say when a message con... |
I recently had my final exam for a software engineering course for my masters program and one of the questions on the exam was the following:
Unit Testing is considered:
a. White-box Testing
b. Black-box Testing
c. Either
In my 7 years of software development experience, unit testing has always taken a white box appro... |
I have a system ("an engine", which is a piece of code) that takes in several parameters returns some output. The input parameters are several distinct and constrained sets. I can enumerate all of them (currently 1064 sets of inputs) and run them through the engine to produce the same number of outputs.
The engine co... |
I have two stories (I know they are missing the benefit part)
As a Credit Management User, I can view the current and previous payroll
differences for Offices.
As a Credit Management User, I can receive an email containing a PDF of the
current and previous payroll differences for Offices.
The two are related in tha... |
I've been reading about how memory-mapped I/O actually works and I cannot understand how the system assigns an address or address space to a specific device.
Let's say I had two devices that I wanted to use in a memory-mapped scheme, and they were identical devices (hard drives maybe?). If they both monitored the addre... |
Kinda new here and also learning new db concepts. I got little bit confused about terms: Roll-back and Roll-forward. I read definitions and thought I understand it. I found some little tasks about transactions and it got me confused.
Example:
Question_1: Which transactions (when system is recovering) will do roll back... |
I'm developing a desktop JavaFX application that connects to a local WildFly app server via the REST protocol. WildFly describes itself as an
application runtime that helps you build amazing applications.
and the way I view WildFly is for development use only, so when I eventually want to deploy my app to the public... |
I'm a beginner in DB. I have studied some basic examples but now I'm studying more complex cases that involve many tables related to each other. I'm studying how to model a DB for a conference system but there is a detail that seems difficult to model.
The detail is, a conference can have multiple registration types an... |
(JAVA) I have about 50 Getters, all return the same text, tag, type. Text and tag are String and type is int. The purpose is a forms that use repetitive fields along with form specific fields. I am having trouble with simplifying and reusing code?
public class DataTransferClass {
private DataTransferClass(){}
public c... |
We're having a lot of fun and success using Azure Functions, but looking for advice on two related design issues. Our first challenge is that we need to communicate job state back to the UI. So the customer has a list of items, and each one can have background processing associated with it. The UI should reflect either... |
In Domain Driven Design, the Domain Layer can have several (traditional) services. For example, for the User domain, we may have:
A UserFactory, that builds User objects in different ways
A UserRepository, which is responsible for interacting with the Persistence Services in the Infrastructure Layer
Is a UserService ... |
I try to write "clean code" for most of the time. But practically find it very hard, meaning - gradually business requirements changes dramatically or the business requirement which seems like just a condition force to modify existing code.
If we go for "extend" instead of "modify" approach, implementation seems clean.... |
Using C# it's common practice (I think) to omit indentation and brackets with nested using statements like this:
using (var fileStream = new FileStream("filename"))
using (var streamReader = new StreamReader(fileStream))
using (var myCustomReader = new MyCustomReader(streamReader ))
{
///...
}
I've been refactoryi... |
I have a table of data and I can create , update and delete rows. I have apis to do these operations. The following steps happen
I create a row and send a create request to server.
I update some values in the row and send an update request before the response of create has come.
In server since the create row has not ... |
I'm trying to add error handling to a function that reads data from a DataSource (which performs all the parsing etc. required). Unfortunately (due to a lack of versioning until now) some of the values that I try to read from the DataSource may fail to parse (because they are malformed or simply missing), resulting int... |
I need to implement JWT tokens in my ASP.NET Core API app to handle authorization.
My question is, what is the risk of generating my own JWT token within my API app as opposed to having it handled for me through a third party solution such as Azure Active Directory B2C or Identity Server?
There's a nice article written... |
I keep running into a problem at work, and I'm hoping that others know a solution either from personal experience or from best practices.
I am not a programmer. I do, however, heavily use RDBMS tables which are populated by code that our programmers write. I also use other products of our developers'. Most often, these... |
I am building a web app with a lot of different API calls: our own proprietary REST API, third-party library API calls, etc. All of these calls either retrieve data, update data, delete data, or create data. Virtually all of our third party dependencies provide JavaScript APIs as well as Node APIs. Initially I gravitat... |
I am writing a library for some data structures in C that will be used in embedded systems. I have had issues designing and coming up with a solid error handling plan. This API is only subject to logic errors which is why I am so conflicted. By this I mean the preconditions might be: "x != NULL" or "index < size of con... |
I am designing a program with the flow as outlined below. Note, these are all network calls, there is no system I/O (hard drive).
Initially, multiple independent API calls need to happen - they don't rely on the others at all. The response from these will be processed and if they meet certain criteria, they should spa... |
Context
I recently read about the object-oriented technique of making a distinction between objects and passive data structures, best summarized in Clean Code:
"Objects hide their data [...] and expose functions [...]. Data
structures expose their data and have no meaningful functions."
I am considering using C# s... |
I’m trying to figure how best to define a Use Case using Clean Architecture and DDD. Let’s say I have an application that handles the pick, pack and shipping of a delivery. Here is the flow:
User enters a deliver to populate the screen with shipping information
User selects line items and clicks a button to Pick
Use... |
The definition of UTM(Universal Turing Machine) is a Turing machine that can
simulate other Turing machines, so as far as I can guess operating system is a
UTM, since it can run multiple programs on a OS.
|
We know that writing JUnit tests demonstrates one particular path through you code.
One of my associates commented:
Manually writing unit tests is Proof By Example.
He was coming from the background of Haskell which has tools like Quickcheck and the ability to reason about program behaviour with types.
His implica... |
I have data flowing from Kafka into MongoDB real-time. This is just raw data and various APIs are served using this data in real time.
The APIs respond using aggregation queries. However when data to be aggregated is large, the response time of the API is too high.
What technology or methodology can I adopt to achieve ... |
i am faced with the following scenario and i wonder if you guys have some tips for me on how to approach this.
One of my colleagues is going to leave the company in a few month and i am ordered to do a rewrite of his application, since the technologies he used are outdated. Problem is, there are no requirements and th... |
I have some Scala code that I wish to unit test using ScalaMock:
class CancellationManagerSpec extends FlatSpec with MockFactory {
"Cancelling a shipment" should "check shipment is not already shipped" in {
val manager = mock[CancellationsManager]
(manager.checkStatus _).expects(*, *).returning(true).once()... |
I if may point out I don't have a code issue nor the requirement for code review, hence posting here.
I'm generally looking for a better understanding on how to truly architect a SignalR .Net Client project to prevent multiple HubConnections being instantiated.
I/We have a prototype in a staging environment, which succ... |
I have a mainly Scala application and I am interested in approaches to integrating Python code into this application in a way that is proven by you personally to be successful.
In this context
integrating means allowing Scala code to call Python code, somehow, and use the results or access the exception
successful mea... |
I have some code that reads five numbers from a database:
class Repository extends DatabaseRepository
{
function getCoefficients(string $model)
{
return $this->getDatabaseLink()->query("
select a, b, c, d, e from coefficients
where model = ? and active = 1
", $model)->ge... |
Say that we have a class Car that contains objects of type Wheel
class Wheel {
public:
void SetFriction(double f) {
friction = f;
}
private:
double friction;
};
class Car {
private:
std::array<Wheel, 4> _wheels;
}
Now, I want to offer the owner of a Car access to the friction of the Wheels.... |
I'm working on a web application that manages specimen freezers so our researchers can manage and inventory all the gross stuff they've made. A freezer looks like this:
1 Freezer
+- X Racks
+- Y Boxes
+- Z Cells
+- 3 Cassettes
+- 5 straws
So, pretty much what's going on is I have a potentially inf... |
Notwithstanding its popularity, is there any empirical evidence that shows that Dependency Injection (and/or using a DI container) helps with, say, reducing bug counts, improving maintainability, or increasing development velocity on real-life software projects?
|
I often come across methods/functions which have an additional boolean parameter which controls whether an exception is thrown on failure, or null is returned.
There are already discussions about which of those is the better choice in which case, so let's not focus on this here. See e.g. Return magic value, throw excep... |
Say, I have a table Categories. On a page I have a header and for each category the colour of a header varies.
A colour is of the presentation level and I've heard that what's related to the UI/presentation level shouldn't be stored in a database.
There must be exceptions. However, in this case I figure that a colour ... |
I inherited 1 million lines of C++ legacy code. Throughout the code variables like bCPCHAR bPCHAR, bCPDOUBLE and bPINT are used. They are defined like this:
bCPCHAR: const char *
bPCHAR: char *
bCPDOUBLE: const double *
bPINT: int *
I was thinking of removing this level of indirection, especially because bCPCHAR and ... |
eSpeak implements SSML parsing. SpeechSynthesisUtterance, at least as implemented at *nix, does not parse SSML input at Chromium or Firefox browsers.
How to identify and extract the relevant portions of eSpeak for the purpose of including the code at Web Speech API implementations at modern browsers to be able to parse... |
one of the first modules I’m working on in a python program I’m putting together is a journal.
I’m getting comfortable using the print function, but for this project it would be great if i Could differentiate some of the text output from others. For example, here’s a text output sample from the program:
November_29_201... |
We have an application that has a mix of both fast (< 1 second) and slow database migrations (> 30 seconds). Right now, we're running database migrations as a part of CI, but then our CI tool has to know all of the database connection strings for our app (across multiple environments) which isn't ideal. We want to chan... |
I’m new to API development and I have a question that might seem dumb, but I literally have no experience with API design, so bear with me.
Having said that, my question is: should different resources point to different scripts on the server? Or all resources should point to the same script, with different arguments?
E... |
I understand task as task in C#, but this questions is not related to C#.
Let's say I have single thread and two tasks (both CPU-bound). I would like to run them concurrently, without running one of them at the expense of starving completely the other one. How this could be implemented without assuming the code will so... |
I'm trying to understand how this method works and everywhere I check it I find there's something faulty or maybe it's that I'm not understanding something from the method.
Here there's an explanation of the method for reference.
Some things of the method don't make much of a sense for a while or do-while loop. I mean,... |
We want to design a solution for generation and validation of OTP(One Time Password) process. We decided to create OTP process as a separate micro service. Since OTP need to be communicated to users we felt a need to create a separate micro service for communication (SMS, mails etc.).
While designing we came up to a p... |
I have 4 entities: Event, Message, Flow and Document.
Event table stores a limited (seeded) number of records. Message has many events and each event can be related to many messages. The name event_message was given for the intermediate table.
As you can see, the convention for intermediate tables are: {tablename}_{t... |
I've been using the APIs of a ticketing service which returns arrays of data more or less complex based on the entrypoint called. In order to simplify my life when consuming such API I wrote some classes to map locally arrays to objects so I can:
get suggestions from the IDE when coding instead of checking always the ... |
This is more a question about structure than coding. So i have a class named Planet and all planets have their modifiers for example: Is breedable? Damageable? etc. I already have a base planet class but i dont know how i will do that in a scalable way since i need to check if any planet has a certain modifier.
BasePla... |
So I've been flirting with Event Sourcing and CQRS for a while now, though I've never had the opportunity to apply the patterns on a real project.
I understand the benefits of separating your read and write concerns, and I appreciate how Event Sourcing makes it easy to project state changes to "Read Model" databases wh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.