instruction
stringlengths
34
36.1k
I have two objects as member variables of a class. std::unique_ptr<Object> specificObject; std::vector<std::unique_ptr<Object>> objects; I know that specificObject will always be within objects. How can I point to specificObject without using shared_ptrs as I do not want the ownership of the objects in the container t...
I'm working on a Scala data-processing program. Essentially we start with a collection of many small data objects, say, (eventId: String, basicInfo: Basic) and gradually filter out some objects and add more information by joining the original collections with other data sources (typically on the eventId field), or by ...
The question above is an abstract example of a common problem I encounter in legacy code, or more accurately, problems resulting from previous attempts at solving this problem. I can think of at least one .NET framework method that is intended to address this problem, like the Enumerable.OfType<T> method. But the fact ...
I am developing a feature related to Microsoft Outlook which has support only for Windows library. However, I have to put this into a web page for the users. In the process of consuming the windows application into a web page, I have written a Windows application using C# and integrated it with a WPF solution and tryin...
Today I had an argument with someone. I was explaining the benefits of having a rich domain model as opposed to an anemic domain model. And I demoed my point with a simple class looking like that: public class Employee { public Employee(string firstName, string lastName) { FirstName = firstName; ...
I would like to discuss a question about best practices regarding exception handling (e.g. in Java). Normally, when setting the attributes of a class, I check the arguments in the setters for validity, and if the arguments are not valid, I throw an IllegalArgumentException. Besides the setters, sometimes also the cons...
For example, you are given the source 1234 and the target 24. The task is to use the standard arithmetic operators +-/* placed within source, without changing the order of the digits of source to create target. In this example the solutions are: 1 * 2 * 3 * 4 = 24 = target 12 + 3 * 4 = 24 = target Another example: tar...
I have to generate a code that will send through SMS or Email to implement the One Time Password (OTP) requirement of our client. I just finished creating the design using strategy pattern, . . This it the first time I've used strategy pattern in real life projects so I would like to ask if I'm doing it right. Below is...
I have a script that throws exceptions when something goes wrong. However, for the purposes of testing I also want to capture specific points although I'm not sure whether they would be deemed errors or not. Below is an example: if ($model->fetchCurrentlyProcessing() > 0) { throw new App_Exception_CurrentProcess('T...
Suppose I have an array of n numbers. The rules for the array is as below: All the numbers must add up to 1000 If a number changes (positive or negative), all the other numbers in the array must be adjusted so that the sum of the array is still 1000 The hard part - all numbers must be greater than or equal to 0. Numb...
What is ES6? Is it JavaScript? Or multiple language supporter? I searched for it but can't understand it, especially the page on Wikipedia. Is it better than Javascript? And what can I do in my web developing using this language? So what ES6 is, and how can I use it in my web app developing ?
I'm finding it difficult to understand Microsoft's motive behind building conceptual "projects" like this. They ship MSBuild.exe and NMAKE.exe together with a Visual Studio 2015 install but they both appear to serve the same purpose. If they are both (in a practical sense) equivalent but using different formats, I won'...
As a part of an algorithm I'm making I need to make a function that takes the current date to a function and gives out a number between 1-6, and not the same number for two consecutive dates. And it should always return the same number for a given date. A simple solution would be to make any Monday 1, Tuesday 2, Wedne...
I heard that AngularJS is becoming quite popular, and at the same time ReactJS is also. But if AngularJS already takes care of MVC with 2 way binding between model and view, would ReactJS actually be needed? I thought ReactJS is binding model to view, but not binding view to model (say, if it is a form text input fiel...
E.g. in a domain model with two aggregate roots: book author Is there a specific term that refers to a collection of aggregates of the same root type (e.g. a collection of books)? In Confusion about the meaning of the word aggregate in domain driven design I read the term aggregate type, which might or might not fit,...
I'm reading this tutorial on Perlin noise: http://www.angelcode.com/dev/perlin/perlin.html which seems to be the clearest one but still not perfect. A lot of details are skipped and a lot of code unexplained. My general question is, why do we need vectors for Perlin noise (instead of just noise values at specific coord...
This is a pretty generalized question which I am asking. Scenario 1 I have a product 'Pen' which has a quantity of 1. Now 2 users a and b has come to buy the product.User 'a' clicked on buy now and has started the payment processing and once the payment is completed the order for the product will be created and I woul...
I have been programming professionally for a couple of decades. Some years ago, the framework word was not so widely used as it is today, but I still believe we've been using "frameworks" for a very long time before they were called that. For example, the Java SDK has parts that can be considered frameworks; like for e...
In PHP I have this if statement ( $first and $second will evaluate to true or false): if ($first && $second) { // evereything is OK } else { throw new Exception()... } My real code is much more complicated, I am trying to make simple example here. I want to turn this if/else into one if with negation like this...
Trying to learn Clojure and you can't help but be told continually how Clojure is all about immutable data. But you can easily redefine a variable by using def right? I get that Clojure developers avoid this but you could avoid changing variables in any language just the same. Can someone explain to me how this is any ...
Is it bad practice that a controller calls a repository instead of a service? To explain more: I figure out that in good design controllers call services and services use repositories. But sometimes in controller I don't have/need any logic and just need to fetch from the database and pass it to the view. And I can do ...
I write Python code for scientific computation. As it is research I face among other two problems: the demands are quickly changing results need to stay reproducable Imagine you have a package A that is needed in an old project and then again in a new one. The new project however requires some changes (This would no...
I've found a paper describing a particular algorithm I'd like to use, and published with the paper is a GPL licensed source code for the algorithm. I am wondering if I can re-implement the algorithm from the paper (obviously without using any of the original code), distribute it closed source, and not be in violation o...
I've been doing a bit of research on the subject. I know unordered_sets are hash tables, where the key and value are one and the same. What I'd like to know is how the compiler figures out where in the table each object belongs.
(TLDR) To build a parser for a recursive grammar by composition of individual parsers (e.g. with a parser combinator framework), there are often circular dependencies between some of the individual parsers. While circular dependencies are generally a sign of bad design, is this a valid case where the circular dependenc...
I'm currently a first semester IT student, and I'm wondering if it's better to write my method to find something e.g. in a C# List, or to use any built in method to do these, such as LINQ or .Find or .OrderBy method with lambdas? I heard from a senior that the .NET optimizes my code according to the contents and amoun...
How does construction work with dependency injection? With the following code: public class AdvancedSearchController : Controller { private EmployeeController _employeeController; public AdvancedSearchController(EmployeeController employeeController) { _employeeController = employeeController; ...
The goal is to develop something similar with a quiz application: there is a server to which players connect. At some point, a game is started. The game consists in asking the players a few multiple answer questions and determining the winner based on some criteria. The server spawns a new thread for each client (I kno...
Promises is a fairly new pattern for me, so I'm still building my intuition for them. I recently came across a case where some code in an adapter-like bit of code was once synchronous, and then became asynchronous, so promises were introduced. Consider: function runCalculation() { var params = this.getParams(); thi...
I'm fairly new to Java and GUIs and am trying to work on a side project. I'm finding that as I continue to make more and more GUIs within eachother, I am continuously needing to access information that originated in the first GUI, from within deeper GUIs. For example, I have a variable in the first GUI, after a user cl...
Note: In my ignorance of the difference between Programmers vs StackOverflow sites (which I know now), I had posted this question on StackOverflow earlier. What I'm looking for is some elaboration, for example, on the comment by Gene. Once I am able to build an abstract syntax tree (AST) for an input, then: regardles...
I've been programming for years with primarily-imperative languages (C++, C#, javascript, python), but have recently experimented with some functional langauges (Lisp, Haskell) and was excited to try applying some of the declarative-style programming ideas in C++. I have a custom range-based STL replacement library I w...
Trying to solve bogo coupon logic with proper design pattern, but having trouble identifying one. Use case: "Buy iPad get SmartCase for free" Suppose we have the following objects: Product: - getPrice CartItem(Product p, quantity): - getPrice Cart: - getItems() - addItem(CartItem ci) Coupon(code): - getCode...
This is a design pattern academic question exercise. We have a Resource class and a pure fabrication class ResourcesManager to manage objects w/ type Resource. The question is Given the following two definitions: public class Resource { } public class ResourcesManager { public static Resource loadFromDb(int resID) ...
Generally when writing automated unit tests (eg JUnit, Karma) I aim to: cover all the boundary conditions get a high level of coverage. I heard someone say: coverage and boundary conditions aren't enough for a unit test, you need to write them so they will break if the code changes. This sounds good to me in theo...
While I like benefits of strong typing system, there is one thing that worries me the most. I think of strong type system as means of forcing design choices. If a team builds a system unaware of its poor design, types will only reflect bad design choices. For example, a programmer often finds he needs to access (hopefu...
Its like, I want to call .moveToBefore(Node) on a Node object and have the node relocate to before the node passed in. The problem arises if the node passed in is the head node. The List object will still reffer to the old head where as the old head will actually follow the new head further down the chain. I guess this...
Brief: I have several very large math expressions written in Matlab/Octave syntax. I want to evaluate them within a C++ function by copy and pasting them in, however the problem is they contain "^" operators that cannot be overloaded to work with doubles. Details: The expressions consist of scalar variables with nest...
Given the following code I have to draw the corresponding class diagram: public class Shop { List<Client> clients; Storage store; User chief; Set<Invoice> invoices; } public class Invoice { Map<Product, Row> rows; Client client; } public class Client{} public class Product{} public class Stor...
If we look at the definition of "dynamically-typed programming languages" in Wikipedia, it says: Programming languages which include dynamic type-checking but not static type-checking are often called "dynamically-typed programming languages". and Dynamic type-checking is the process of verifying the type safety of...
I have a very basic RESTful service written using the MEAN stack (MongoDb, Express.js, Angular.js, Node.js) and utilizing the Mongoose ODM. Product schema var productSchema = new mongoose.Schema({ name: {type: String, required: true, maxlength: 250}, _prices: [{ amount: {type: Number,required: true,min: 0.0}, ...
Short question is: what can qualify for potential tail call recursion optimization (TCO) or tail recursion elimination (TRE) if the compiler or interpreter supports it. The summary of this question is in the section "Or is it true that, one simplest way to think about it" below. I saw the Stack Overflow question "What ...
I have a programming problem, that I don't know how to solve. And while I have provided a sample of my code, I am interested in a conceptual answer on how to resolve this problem. On a tradeOffers event, I call a function to get a list of offers and process them one by one using async.forEachOfSeries from Async.js modu...
I need to extend a third party class I cannot modify. The class's dependencies are for the most part injected through the constructor, making them easy to mock. However the class also uses methods from a trait that call global services directly, destroying test isolation. Here's a code sample that illustrates the probl...
I had this idea of different write models being used in different bounded contexts, but both being the same aggregate instance (the same events). For example consider a User aggregate that is used in Administration and User contexts (that is the admin and the user-interface parts of the application). And the domain mo...
Lets take this for example... entryText.addTextChangedListener(new TextWatcher() { TextView wordCount = (TextView) findViewById(R.id.wordCount); TextView charCount = (TextView) findViewById(R.id.charCount); @Override public synchronized void afterTextChanged(Editable s) { wordCount.setText("W:...
I have a question about storing encrypted passwords in your database to help secure them. I have a class that encrypts the password passed in and returns a string. This string has 3 parts too it, all separated by a colon. The first part is the iteration, the 2nd part of it is the salt, and the third part of it is the e...
I've got a conceptual question (which is probably better posted here than on StackOverflow?). I want to develop a client application that maintains a persistent connection to a server, and exchanges text data back and forth. An IRC client is a great example. So, these are givens: There is a fairly steady stream of inc...
Consider the following situation: You have a clone of a git repository You have some local commits (commits that have not yet been pushed anywhere) The remote repository has new commits that you have not yet reconciled So something like this: If you execute git pull with the default settings, you'll get something li...
In a project we have a rather formal code review, which is currently done manually and documented in Excel sheets and Word docs. We would like to improve the current code review process by integrating it into a Git workflow (utilizing tools like Bitbucket Server, which we already have, Gerrit, etc.). The current idea i...
The name database host, how the name indicates "the server that hosts the database", should be the server ip, that hosts that database. I don't see any relation of it with the scripts that try to access it. But conversely, what I see the explanation mostly is : "As long as the program ( php/.net scripts ) are on the s...
From Agile Software Development, Principles, Patterns, and Practices: Pearson New International Edition: Sometimes, the methods invoked by different groups of clients will overlap. If the overlap is small, then the interfaces for the groups should remain separate. The common functions should be declared in all the o...
PROBLEM: There is a coding imperative (S. McConnel, Code Complete) that one shouldn't code on language, but by means of it, e.g. doing right style things even if language doesn't have some possibilities. Javascript is a script language in its heart, but it pretends being OOP very much. I want my Javascript and Java cod...
I've been learning about NoSQL Databases for a week now. I really understand the advantages of NoSQL Databases and the many use cases they are great for. But often people write their articles as if NoSQL could replace Relational Databases. And there is the point I can't get my head around: NoSQL Databases are (often) ...
I know that the data is passed through HTTP, but I'm not sure if I should be passing data through HTTP headers, or HTTP bodies. Which one is the convention for APIs? Also, theoretically using PHP, which would be easier to process? Based on what I know, using headers seems to be the easiest method. POST body POST /api/v...
I am in the final stages of development of a simple embedded system. The device performs PID coefficient estimation and then instantiates a PID controller with the estimated coefficients. The architecture of the program is cooperative multitasking. The file main.c defines a series of void task_...(void) functions and c...
I'm maintaining a system providing a typical synchronous web service REST API. It routes each request to one of several possible backend services. Now there is a new backend I want to use, but there is a problem - it has an asynchronous API - I will need to do a request, and then wait for a callback request. I'm thinki...
I am attempting to build an attendance program which could analyze if someone is sitting in a seat. The seats are fixed making knowing where each seat is easy, but I don't really know where to start to determine if there is someone in the seat. I have tried to do some research but it is all quite complex. I thought tha...
I'm writing an application for which I want to use some 20-year old open source code. The original code is kind of antiquated in certain aspects, for example, it's written in K&R C rather than C99; it has to manually compute certain things that are now defined in C standard library headers; there are no tests; and so o...
Many low level programs use the volatile keyword for types for memory mapping and such, however I'm sort of confused as to what it REALLY does in the background. In other words, what does it mean when the compiler doesn't "optimize away" the memory address?
I've heard that Clojure macros are easier to write but not as reliable as Racket's hygienic macros. My question has 2 parts: How does gensym differ from hygienic macros? What do Racket macros provide that Clojure's don't? (be it safety, composability, or anything)
I have followed the tutorial from Amazon to get started with the Echo. I made a skill and setup an application server on their AWS Lambda for basic testing. I have a few questions about the Echo, skills and AWS Lambda: When I create a skill does it reside on the Echo itself or does the echo have to go out to the inte...
Is batch processing possible in jdbi with the below condition? If one insert query in the batch fails because of violating some constraints ( Primary key, foreign key violation.. etc) will it resume processing next set of insert queries in the batch?
I am creating a 2d game for a website where the universe can grow extremely large (basically infinitely large). Initially, the universe is composed of 6 stars that are an equal distance from the origin (0, 0). My task is to be able to generate more stars that will have "paths" (edges) that connect to each other. How ca...
I am trying to understand the generic repository implementation. I have seen this line (or similar to it) in many examples: public interface IRepository<TEntity> : IDisposable where TEntity : IEntity Can some explain the parts to this? Also, I'm having a hard time understanding the IEntity and how it plays into the ...
It seems as if this example implementation of the Observer pattern is drawn from the book Headfirst Design Patterns, OReilly, which I am currently reading. Here is a UML diagram from the book It's not very cleanly visible, but the methods, composing the Subject Interface are: registerObserver() removeObserver() notif...
In my node.js application, I have a queue class which has push and pop methods and a data property. I have an Event class which handles an event and pushes it on to the queue. If I think object oriented, is the relationship between queue and event better modeled as "is a" (inheritance) or "has a" (composition)? First a...
At our team, in addition to individual units of work (Stories), we have longer-running themes of work (Epics). Multiple stories make an epic. Traditionally we've had feature branches for each Story, and merged those straight to master when they pass QA. However, we'd like to start holding back on release of completed s...
Though it might be trivial for someone, I find it a little inconvenient when someone formats the string while passing it as a parameter to a method. For e.g. AddMessage( string.Format("{0} (" + Constants.Message1 + ")", Path.GetFileNameWithoutExtension(document.FileName)), string.Format("{0}" + FileE...
Backstory While developing with Qt Signal/Slots, I came across a few segmentation faults that had me puzzled as to what was causing it. Eventually I figured out that you could actually pass a slot function without providing it any of its arguments, which of course would cause a Segmentation Fault if the argument was us...
Is there any convention to where we should declare the module.exports no Javascript/Node.js module files? Should it be in the beginning of the file like: module.exports = Foo; function Foo() { this.bar = 'bar'; } Foo.prototype.getBar = function() { return this.bar; } Or should it be in the end of the file: f...
Case in point in Entity Framework, but this is a design question which has applicability to any ORM. In the current application we have a couple of ORM data classes which do stuff not directly related to the function of that class. One example is the Document class, which is a database representation of document stored...
I need to understand the proper name for an object that has cropped up in two projects now. Here is the conventional representation for the MVC pattern: However there is another "Model" that is normally present in MVC, which passes the data between the controller and the view (and back): What is the second mode...
I want to understand why we use the term "network topology" as opposed to "network graph", or another term, to talk about the structure of networks. I'm working on a network design for a project, and want to make sure I don't use any terms that I don't truly understand. Wikipedia defines network topology as "the arrang...
Referring primarily to here, it suggests that values which are constant in JavaScript (using the keyword const) should be named in SHOUT_CASE. I'm of the opinion though that mutability is much more important (and rare) than immutability, at least in JavaScript, and that having so many variables put in SHOUT_CASE would ...
For the Red-black tree insertion fixup the book distinguishes between 6 cases, 3 of which are symmetric. The cases are (z is the node being inserted): Case 1: z's uncle is red Case 2: z's uncle is black and z is a right child Case 3: z's uncle is black and z is a left child Case 2 is a subset of case 3, as we can tra...
Here is a typical C++ code: foo.hpp #pragma once class Foo { public: void f(); void g(); ... }; foo.cpp #include "foo.hpp" namespace { const int kUpperX = 111; const int kAlternativeX = 222; bool match(int x) { return x < kUpperX || x == kAlternativeX; } } // namespace void Foo::f() { ...
I can't find many tips for how to design complex json structures beyond the obvious tips of not trying to nest too deeply, using defined data types, etc. For example, if I have a location that needs to have security scanning done on all of its segments and devices within the segments, there are many options of how I co...
This is from Effective C++ (Meyers): Classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors I don't understand why non-polymorphic classes should not declare virtual destructors. Assuming I have a parent class and a child class, with no virtual funct...
We're working on a project wherein the business users operate on a set of data that is periodically published. We've labeled the publishing milestones as Versions, and, due to some business constraints, end up duplicating the data set for each Version that gets published. During the work cycle, it often becomes pruden...
For service methods that call repository methods to interact with database how could I unit test these service methods? For example, public function updateSlideshow($data){ // do some logic and method calls (I can test those methods, // but for this method that call repository ...) $r = $this->blockRepo->u...
I'm designing a price list table for my database. It will include Customer, Model, Start_date, End_date, Price, Currency, RRP When I update a new price list, which is sent every now and then (maybe every 1~3 months), I need to update the prices but I would like to keep the records of what has already been raised. Curre...
Considering a small embedded C project, how to decide if certain constants belong to a global configuration file the header of the "module == compilation unit" on top of the the actual C file or inside the code? I am talking about constants that can often change, and need to be conveniently located for the end user...
In this very simplistic but realistic scenario, I have 2 combo web/database servers (A) behind a load balancer and a single IP address. They also permit access only from one IP address -- the client (B). On each database server, we need to store read-only secret identity information (like email address, username, etc.)...
When programming in C I have found it invaluable to pack structs using GCCs __attribute__((__packed__)) attribute so I can easily convert a structured chunk of volatile memory to an array of bytes to be transmitted over a bus, saved to storage or applied to a block of registers. Packed structs guarantee that when treat...
Say I have an array of strings, like this: var folders = new[] { "Foo", "Bar", "Foo\Bar" "Foo\Bar\Baz" }; And that I have an object that represents a folder - something like this: class Folder { private readonly string _name; private readonly IEnumerable<Folder> _folders; public Folder(str...
However, there are some classes that should have only one instance. Sometimes they are factories, which you can use to create the other objects in the system. If more than one factory exist, clerical control over the created objects may be compromised. From : Agile software development : PPP What clerical control Unc...
When Eclipse is written in Java and Java is platform independent, why does Eclipse offer different versions according to platforms? I assume it should be write once, use anywhere code.
I'm developing a MVC Web application with a REST interface. The REST controller performs actions on persisted items through a service class, which translates exceptions coming from the persistence layer. When a request involves an item that not exists in the database, I would like to return 404 code, but actually thi...
I have a tree that has n-levels. For example here I have four levels: Each node has two children (except for the last one), however everyone except for the first and last node of each row has two parents. I'm trying to figure out a scalable way to get all paths into a List of Lists, so that for this example, I will ha...
I have been developing and deploying many ASP.Net MVC web applications under Windows Server 2008 R2 & Windows Server 2012 R2, and I used IIS 7 & IIS 8. At the same time I know that I can deploy my ASP.Net MVC under Linux and Unix, without the need to change my code. Today I created a console application which is being ...
I'm creating an API, and I want to overload a function for strip: QString MyClass::strip(); QString MyClass::strip(QRegularExpression open); QString MyClass::strip(QRegularExpression close); QString MyClass::strip(QRegularExpression open, QRegularExpression close); Obviously the second and third conflict. What is the ...
On a mobile device, a set of operations has been saved in the local DB with a wrong date (because the system date was set in the future). Then the device regularly doing synchronisation with a server DB, the erroneous operations have been propagated to the server. Later the wrong date has been detected by the mobile us...
I'm an experienced developer, but have not done many code reviews. I'm being asked to review code written in Python but I do not know Python. Does it make any sense at all to review code in a language I don't know?
As I was beginning to tool around a bit with node, I was told that I needed to undergo a little bit of a paradigm shift since I was coming from a PHP background. I would ask questions like, "I have my script working in terminal, now how can I upload it to the server and access through an AJAX request?". I was told that...
I am attempting to write a program for a competition (we're allowed to consult Stack Exchange, as long as I'm not given physical code) that takes in a list of 5000 people's names (distributed fairly evenly from A-Z, but are real names - not random character strings, and each name is unique) and sorts this list of peopl...
Is the definition for "Secondary Index" anything more specific than just "Any index that is not the primary index"? EDIT: Here is some research I have done: Search Google. I evaluated the first 20 results. These included: a) links to websites for priopetary DB products such as DynamoDB, Oracle, MySQL, etc. (and theref...
At a recent interview I was asked to write an algorithm which: Given a string text, and string subtext, finds the starting character positions of each subtext found within the text. "hey hi how are you hi" = 5, 20 I was forbidden to use any System.String functions (Substring, IndexOf etc). I wrote this in C#: IEnumera...
This is a crazy idea that I just came up with, and I'm interested in knowing if it would be workable, or if someone already wrote about or implemented it. Imagine you are on a platform (a game console, iOS, ...) where you cannot implement a JIT compiler due to technical reasons1 - you cannot make writable memory execut...
The Problem Suppose we are given a variable-length list of objects containing a fixed-length list of positive decimal numbers as attributes. JSON Example [ {a: 0.1, b: 0.6, c: 0.0}, {a: 1.0, b: 1.3, c: 0.2}, {a: 1.2, b: 0.1, c: 0.3}, {a: 0.2, b: 0.2, c: 0.5}, {a: 0.8, b: 0.2, c: 0.6} ] Create an qu...