instruction
stringlengths
34
36.1k
I am writing a parser for a fairly complicated language in C++. The Parser class is given a list of tokens and it builds the AST. Though only a part of the parser is completed, the Parser.cpp file is already more than 1.5k lines and the class has around 25 functions. So, I plan to break the large Parser class into smal...
I very often get myself in a situation where I need a different behavior of a component which depends on the concrete type of a different Interface. To illustrate my question, I have written a small code piece which will show what I mean. In this Example I'm trying to instantiate an food object from an animal object. i...
Library A is licensed under GPLv3. I want to write a program that uses that library as a dependency (programming against interfaces and using classes in that library), so I have to put my own program under GPLv3 as well, or under GPLv3 with a linking exception. I also need a second library B which is licensed under th...
I would like some input to the following problem. Our product consists of many separate "modules" which can depend on each other. To bundle them up to a final product we create another "module" to bundle all these modules to one. The biggest problem is customer specific code. Let's assume customer A like module B in ...
I have multiple factories, each is responsible for creating instances of an inheritance tree. For example (syntax or semantics maybe incorrect), struct InterfaceA {}; struct ImplA1 : InterfaceA {}; ... struct FactoryA { vector<InterfaceA*> create(); } ... // (repeat for B, C, etc) foo is template class template...
Suppose you're building some library, C or C++ doesn't really matter for this question, IMO. The features (or implementation thereof) depend on capabilities of the target system. A simple, probably contrived example: Some feature depends on whether the system has a working int64_t (64 bit integer type) or not. Assuming...
Let's say I create my own website and design a discussion forum in that. Now, I have multiple types of users in my system, and millions of accounts per type of user. Since the website is very popular, 100s of new threads are created every second. People post on these threads (lets limit them to only text for now) rapid...
We have a system that currently has approx 25 customers (will never expand from this) that each have a public facing web service which allows each other to query each others internal application information. e.g search application number (e.g PAR1056) or it's applicant name (e.g Bill Bob) and recieve a list of matching...
I have this bot that I've created for Twitter. It's written in Python. It lives on my Raspberry Pi and I've set up a cronjob to run it every 60 seconds. Part 2 of the project is to build a web app that I can use to configure the bot - instead of messing with the code directly. In Part 3, I want to extend the web app wi...
I'm currently working with a client's website in which we are using ajax calls to show the content of the pages, we are doing this in a single div and obviously you don't move from the index. My client wants the browser's back button to work, but since you're not moving to a different page or anything, I don't think th...
Some time ago I switched from Microsoft ASP.NET 2.0 (WebForms, never knew Microsoft's MVC) to Ruby on Rails and learned it's MVC approach, after which some things in ASP.NET MVC seem to be weird. In RoR the best practice is to put the model logics (various ORM queries) to a model. I noticed that programmers seem to avo...
I'm building a meeting app where users can create, join (by invite), and edit events like meetings, outings etc. Think What's app chat groups. So I'm looking into designing how the android app would stay in sync with any new or updated events that the user belongs to. Any ideas how to design this? I have a few ideas: 1...
I'm planing to use Try/Catch and Database Transaction in Laravel5 and my own PHP project to validate any errors occurs then rollback avoiding lost my transaction or information during user do their transaction to Database. I'm sure to find out if some method done with success status or non success status but I don't un...
I have 2 modules (containing multiple classes). Let's call them Module A and Module B. Module B has a dependency on Module A: Module B -> Module A. Now, I have created an utility class C, which A and B are supposed to use but the utility itself depends on functionality found in A and B, thus A and B also depend on C. S...
When using the new Java8 streams api to find one specific element in a collection, I write code like this: String theFirstString = myCollection.stream() .findFirst() .get(); Here IntelliJ warns that get() is called without checking isPresent() first. However, this code: String theFirstS...
I can't quite figure out the time complexity of this algorithm I've written for finding the modulo. I've added it here in psuedocode. Modulo(int x, int n) // x is the dividend, n is the divisor e := 1; while(n^e < x) e++; end e--; //This first part above is clearly O(log x) while(e >= 1) ...
I have a small question about the following answer from a stackoverflow question. There seem to be 2 ways to pass parameters through a @BeginForm() to a Controller. Using a Hidden field: @Html.Hidden("clubid", ViewBag.Club.id) Using the BeginForm: @using(Html.BeginForm("action", "controller", ne...
I am a PHP developer and I used to build web applications with one PHP file per page for a very long time. This resulted in duplicated logic and messy code (even though I didn't know it at the time). Then one day a co-worker introduced me to the MVC methodology of organising your web application code base. I also learn...
This is a bit difficult to describe, but I'll do my best. In Python, I can use string.startswith(tuple) to test for multiple matches. But startswith only returns a boolean answer, whether or not it found a match. It is equivalent to any(string.startswith(substring) for substring in inputTuple). I am looking for a way t...
I have around 30 not-changing "objects" (the amount of them is final, no more can be added or removed). Each object has an id as well as some booleans describing what the object is and what it isn't. Now, each objects has a variable that must be changed at runtime. Most of these variables are just an integer, but some ...
Currently to create releases for our project, we're using Travis CI to upload binaries whenever a tag is created. We're using semantic versioning, so our tags have the form v<Major>.<Minor>.<Patch>. Our version number is set by CMake, and to avoid problems with it getting out of sync with the tag version number, we're...
I'm working with a large enterprise application custom CMS. The content managers have some level of control of the HTML, but there are a number of elements that are created by the dev team for more advanced functionality (server interaction, etc). So for example the dev team may provide a <view-cart></view-cart> cust...
I have a list of unique 8 byte random ids and new ids are generated often. Let's say that the total number of ids can become at most N (let's say 100,000). Now, I want to map each of these ids to a unique position in an array of size N. What is the best way to map it? Context: I was reading about how instant chat mess...
I'm trying to figure out the best way to tackle running a one-time SQL script when a service instance starts up. Here's the scenario: We run multiple Amazon instances of our service in parallel. Each instance connects to the same MySQL database. With each service update we want to run a one-time SQL script to update t...
I will illustrate the problem with a specific case. Suppose we have a bit-flag style enumeration type defining different kinds of validations. It's tempting to define an enumerator like FULL_VALIDATION with all bits set. The most obvious (and superficial) justification for it is convenience. Users no longer need to exp...
Recently, I've been learning a bit more of C++ and the dangers and uses of operator overloading, and the readability boost it provides to arithmetic types (like Complex numbers). A while ago, I was playing around with Rust, and I really liked how they handled operator overloading, that is, via Traits in the std::ops cr...
I've been reading on event sourcing lately and really like the ideas behind it but am stuck with the following problem. Let's say you have N concurrent processes which receive commands (e.g. web servers), generate events as a result and store them in a centralised store. Let's also assume that all transient application...
I am bit confused about how Open Closed principle can be applied in real life. Requirement in any business changes over the time. According to Open-Closed principle you should extend the class instead modifying the existing class. To me every time extending a class does not seem to be practical to fulfill the requireme...
I have a python program which collects links from wikipedia, and stores the article names in one file, and the links between them in another. For the first file, every article name is stored, and then padded to be a length of 32 bytes. For example, if the article name was Cat, it would be stored as: 43 61 74 00 00 00 0...
I'm working on some sort of a Level Editor but I'm not quite sure how I want to handle the two different states: The Editor state and the Player state. In this first state game elements can be moved around and tiles can be drawn. In the second state the game elements get their physicsbodies and the player can be moved ...
For example, from the book JavaScript: The Good Parts, I stumbled upon this passage: Much of the complexity of class hierarchies is motivated by the constraints of static type checking. JavaScript is completely free of those constraints. In classical languages, class inheritance is the only form of code reuse. So wh...
This is a question which I have wondered (and been asked) about for a long time. In (most? all?) programming languages, an index begins at zero for an array, string, etc. I recognize it became convention over time, adopted in many languages, but can anyone point to the origin of this? I thought, perhaps, it had to do w...
I have a requirement whereby my users will need to be able to build their own forms. Which they can specify different datatypes: Text DateTime Checkboxes All customisable mandatory/optional. I've seen an example DB design on here which suggested the idea of storing the forms, form elements, element types and element su...
I'm working on website and java application for my project and I'm writing report and there is question that say "What is the architecture of the project" I don't know what should I write because I don't understand what does it mean
In JavaScript, RegEx objects can be instantiated with flags such as g for global matching and i for case-insensitive. Intuitively, it makes sense for i to be a property of the constructed RegEx, because the RegEx engine is making a scanner where 'A' and 'a' count as the same token. I can't come up with a similar argume...
Say that I create an ordered set structure, and I choose to implement it as a binary tree. I name my structure OrderedSet because I feel its underlying implementation isn’t necessarily important to the user, and I go on my way. Later, I come back to my code and decide that implementing it as a red-black tree may have b...
I am iterating over a collection and want to delete some entries of it. Example: For i = 0 To Node.Nodes.Count If i >= args.TotalNumberOfNodes Then Node.Nodes.RemoveAt(i) End If Next i As you can see, if one condition is true, I want to delete the item from the collection. If I pass now a List of 20 it...
I need to import 100,000 products from one database to another using the results from a RESTful API. But I can only do this overnight. So if I can't get the job done in one day, I need to spread it out over multiple nights. I have an endpoint that will return a list of ids for a given set of criteria. I have an endp...
I am writing a modeling script that is composed of many functions, and I'm trying to keep a document going that looks something like this: build_model(data, outcome_variable) returns(model) clean_data(data, outcome_variable) returns(cleaned_data) clean_character_data(data, outcome_variable) returns(data_wi...
If I use malloc, does malloc always use the same algorithm regardless of what it is allocating or does it look at the data and select an appriopriate algorithm? Can we make malloc faster or smarter by choosing a more efficient algorithm? In my tests, the builtin official system malloc of Ubuntu is 10 times slower than ...
Scenario: A customer places an order, then, after receiving the product, provides feedback on the order process. Assume the following aggregate roots: Customer Order Feedback Here are the business rules: A customer can only provide feedback on their own order, not someone else's. A customer can only provide feedback...
So I have the following piece of code in use all over my system. We're currently writing unit tests retrospectively (better late than never was my argument), but I don't see how this would be testable? public function validate($value, Constraint $constraint) { $searchEntity = EmailAlertToSearchAdapter::adapt($valu...
I'm reading Yung-Hsiang Lu's book, Intermediate C Programming, and I'm working through the chapter on stack memory. When defining the value address he provides this code example: int f1(int k, int m) { return (k + m); } void f2(void) { int u; u = f1(7, 2); // RL A } He goes on to describe how in th...
I am working on an implementation for an existing public API. Now I needed to change the implementation to throw an exception for a failure condition about which previously the API consumer was not informed in any way. So basically I added a new possible exception. Is the addition of this exception an incompatible chan...
I have 2 sets--inputs and outputs--of 70 32-bit integer variables and 70 bools (140 vars altogether). These need to be accessed and modified from 3 threads. What is an appropriate design pattern to facilitate thread-safe read-write access to each of these 140 variables without locking all of them under a single mutex (...
Currently our Python application is deployed like this: Development team work on issues, commit code and create a Pull request Pull request is integrated to Development branch QA and Operations team test & deploy Development branch and then move it to Staging If all is good after a week we move it to Production. Pyth...
During our sprint planning meetings, we use a planning poker deck to reach a consensus on estimates, with the cards indicating how many days we estimate to need. We then use these estimates combined with our estimate for how many days we can work this sprint to determine what items we will do this sprint and which ones...
I have 3 subclasses (LowState, MediumState, HighState) which derive from the same superclass (State). Within the superclass, State, I have declared several variables which need to be accessed and changed from the 3 subclasses. Is it possible to instantiate these 3 subclass objects from the same superclass object so th...
Say my website contains 2 functions: Allow a user to change their own password Allow an administrator to change a user's password (the user must change again before they login) Now let's say that there is a business requirement which stipulates that a user is not allowed to reuse a previous password. In 1, it is ok ...
I have a function which sends data to a third-party's server using a library they've supplied. The function is very simple. It just takes a list of objects to send, loops through each item in the list, and calls the third-party library's function to upload an object. The problem I'm running into is that my list of obje...
I just come to a small company. There are more than 500 solutions in different VS.Net versions and even VB 6.0 projects. They share several dll. Is there a way to map relation between each program? How can I know in advance what solutions references to a DLL and will have an impact if I change this dll solution.
This question comes to my mind having just lost some money while ordering Pizza. Most internet merchants (atleast in India) use synchronous page redirection for integration with Banks and payment gateways. It works like this: when you visit a merchant site and checkout something it redirects you to the payment gateway...
Normally, I don't anticipate exceptions and if I get them, its something that I can't fix in my code - bad user input or connectivity issues with the database. But errors do occur so at the very least, I want to inform my user that something went wrong and log the error. My exception handling generally looks something ...
Say, for example, you have a program that sends a message to a server and that server validates it. Note: The server validation process can have additional test cases due to it being implemented in various countries (you would have to comply with their rules). If you wanted to automate the testing on this, you could ...
My project started out as spaghetti code. The more DRY and extensible I make my code, the more it looks like configuration files and code than runs them. Is that a good thing or does that mean I am doing something wrong? I am writing a program the scrapes semistructured data from websites and transforms it into a commo...
I have been playing hangman with my friend over an app for a while now, and we have a gentlemen's understanding between us that we are both "cheating" by using online software both to solve the given word (lookup words with given length, filter words with letters in known positions) and to form new words with the rando...
I am working on a signal processing project that allows for parallel processing on data streams as well as inputs and outputs to and from multiple endpoints. The signal chain is broken down into "endpoints" and "nodes". Endpoints can be declared either input or output, and nodes are anything in between. The two types ...
I have Spring+Java Server Faces (Facelets) application for which I would like to create Single Page Application (SPA) version, e.g. using AngularJS (which is the best and most popular GUI framework). But after some investigation of technologies I have come to conclusion that REST (which is necessarity for AngularJS) ir...
In Java: private State current_state; As "State" is a superclass, I can then assign subclass objects to current_state, effectively making current_state point to a different object: current_state = low_state; What is the equivalent of doing this in C++. My understanding is that references can't point to different obje...
I have a requirement where I need to display certain stats on Admin Dashboard in my web application (Angular+Java). These stats (transnational data) are being generated on different servers (connected via LAN to my web app host server) by C++ programs. Since we don't have a centralized database we can't just store stat...
I just wanted to make sure that I understand and can properly articulate the difference between these two concepts. I've always thought of an implementation detail as being the internal workings of some concrete class behind its exposed public interface. ie: User:getEmailAddress returns a string. It may fetch this...
I have some integration tests around stored procs. Typically I do the test setup using Dapper. This is fine for simple cases, but in some cases to setup up the system correctly it would be far simpler to call the necessary stored procs. It would be simpler because some entities have many relationships and constraints a...
Suppose I have a Map which is a private member variable of my class A. In the same class I create an instance of class B, call it objB, by passing the map to B's constructor. Obviously this is wrong, because I have leaked a private field to an object of a different class. That class might later on decide to modify the...
I am redesigning a system by which conference participants can choose which track they want to attend. Participants express their track preferences arranging them in order and submitting them at a certain recorded time (which is useful for prioritizing earlier submissions). Each track also has a different quota and som...
I have an array in the format: $array = array( 0 => array( 'name' => 'Item 1', 'level' => 1, 'points' => 10 ), 1 => array( 'name' => 'Item 1', 'level' => 2, 'points' => 12 ), ... 24 => array( 'name' => 'Item 1', 'level' => 25, ...
Example: We have a base class Base and three subclasses which all implement their own version of doSomething(). In an intermediate function f(Base b), we want to call the relevant version of doSomething() depending on which object has been passed. Why do we need to declare doSomething as a virtual function in Base? Sur...
It seems to me like Observables are basically wrappers for promises with some helper methods. It also requires a huge library to go along with it. Do the benefits of these helper methods outweigh the cons of importing a library?
I am learning algorithms and data structures from this awesome resource Algorithms. Rather than doing dry reading I am trying to re-write all the code myself so that I can learn coding as well as design decisions at the same time(like: what APIs to expose and how to do assertions etc.) so, below is my simplified code w...
I need to help to validate whether my understanding of when to use Dijkstra and when BFS are correct. My way of understanding BFS and Dijkstra, when to use what, am I correct? As I see it. Being given a graph, that can be imagined as N-ary tree, where edges have no special value (all are same length) and we just want ...
Please ignore performance issues, I am interesting in data flow, safety, modelling, reasoning. I wonder what are the limitations of exception approach to error reporting implemented like in Java compared to Haskell-like (OCaml, and Rust use same/similar approach AFAIK). As far as I know in both cases error is part of t...
I am trying to figure out the best way to define the responsibility of checking preconditions. Let's consider the following case: we have an Event class representing a sports event and a Matchup class modelling a matchup between players of that event. The event has a set of matchups Set<Matchup> matchups and we can add...
There is a finite set of unique strings and a limited key space. One key corresponds to one string value and a function must exist to perform the resolution. There is no need to support other associative array methods except lookup. Looking up a key without a value leads to undefined behavior. I would like to find out ...
I'm trying to design a simple way of abstracting away data persistence behind an interface, but I'm having a hard time figuring out how much fine grained control should be exposed to higher layers. Limit, Filter, Order, etc. Defining an interface for a dumb data repository is all fine and dandy for the basic CRUD oper...
I have been developing in Java since 8 months, and I didn't face a case where I went to serialize an exception, I'm asking because I saw the serialVersionUID and how Eclipse advise to add it explicitly in the Exception class that you define. So, I think that every(or the majority) exception is being serialized and I do...
My understanding of REST that is enables modelling service operations as representation of state and transition from one state to another making use of HTTP. I have always understood resources as representations of service side state until recently when I read this article by Jimmy Bogard whom I know to be a smart deve...
Most of the time we need to understand someone else' code for example I am studying Graph Algorithms from Sedgewick's online resources, the particular code example is taken from cycle detection algorithm here: private void dfs(Graph G, int u, int v) { marked[v] = true; for (int w : G.adj(v)) { ...
Let's assume there are multiple contexts with the same logical entity but with different notions. Creating such an entity should have the side effect that in all other contexts the same logical entity should be created. I do this simply by sending a domain event which contains all required fields for all contexts. The ...
I have been learning algorithms and trying to solve problems and now I have the following problem: In a 4x4 matrix, and it contains fields with height. There is a start field with given height also the maximum height a field can have. To be able to traverse from on field to another the height of the current field must ...
I am currently trying to write my own Depth First Search. I have created a class called node. class node{ private: bool is_visited; <data structure to collect edges> public : size_t get_number_of_edges(); void set_is_visited( bool val); bool get_is_visited(); }; Node is bas...
Consider the below method- public void operationOnList(List<String> list) { list.add(1); } It is obvious that if list is null this method will throw a NullPointerException. My question is should I instead check for null explicitly in this case? public void operationOnList(List<String> list) { if (list == null)...
I need to permit users to upload large files to my web-server even if the browser is closed. How can I implement this functionality. I have gone through the feasibility of google drive app but it dose't provide the details of on-going uploads.
At the moment I have three different sources where my data are. 1. A Dataprovider, 2. inhouse access DB and 3. Salesforce. Now I want to build a datawarehouse (using ms software) where I want to store the data and create reportings via e.g asp.net mvc or excel. Since we have really small datasets (all together is about...
I've been learning about UML diagrams and such. While doing so I came across a problem. Which diagram should be drawn first when designing a system, given that use case and such are completed? Is the activity diagram drawn before or after the sequence diagram?
My question: is there a canonical way of creating a dictionary of dictionaries and providing an outer/inner key pair? Is there a NugetPackage out there with an implementation? In my code, I have now a few places where I have a property like this private readonly IDictionary<string, IDictionary<string, SomeType>> _nest...
In our Rails application, we are adding notifications. Some of these are blocking: They stop the progress of whatever resource they are added on, because some information on that resource is missing. Other notifications are simple notifications, and only provide information. Today I had a discussion with another progra...
I want to monitor batch jobs which get triggered by an REST API. This batch jobs are long running native data processings. So naturally, I want to return immediately after a REST call e.g. uploaded some data, and the long running job was started. I have two usage scenarios for job monitoring in mind: - An user of this...
Say you have the hierarchical storage concept of "Foo." "Foo" holds an id, various values, and zero to many "Foo." Obviously, in turn, the child elements can hold zero to many Foos. The data is purely hierarchical: a given Foo will belong to zero to one Foos, and thus there is never a concern of multiple parents. The d...
Say I have a class with multiple parameters: case class Foo(a: String, b: String, c: String, d: String, ... ) Now say I want to parse an instance of Foo from a Map[String, String]: // returns either the parsed Foo as Right, or error message as Left // example: Map("a" -> "1", "b" -> "2" ... ) returns Foo("1", "2", ......
Updating the iOS version on an old iPhone tends to make basic operations like startup, placing calls, and checking settings take longer. The change from eg iOS 7 to 8 on an iPhone 4S has a very perceptible effect. I can understand why newly introduced features are more demanding therefore require more CPU time to run,...
If I find an Open Source project I like, but I rewrite the entire thing because it's poorly written. I don't mean the question where you rewrite it slightly different, so I can say it's mine or anything like that. I've seen those questions and answers. This is actually the opposite. Example (only an example), I take...
I'm writing a page that will show the user statistical data about some of our products. Basically the user can get results between a specific time frame, and also add on other data to lookup by. For instance, I want to grab all the user clicks between 5/5/16 and 5/10/16 for our product. Then I have the option of filter...
I am building on a CMS where dependencies and files needed for a page get stored in the database. Because this can be very dynamic, I serialize these paths into one Database field into my pages table. I am trying to store these file-paths on retrieval into an array to use it in a switch and parse it into a web page. I ...
A lot of messaging frameworks have the term "topic". In a ddd microservice architecture, do these topics always reflect the domain events?
Here I have a very basic ILS (Integrated Library System) done a long time ago (made with C#/SQL Server), in production for years. But now I have a demand of make this system MARC 21 standard compliant, and with this demand came the doubt: Since this standard have a lot of register types, and each register type may have...
Background The following code snippet is taken from a problem in, Visual C# 2005: How to Program, by Paul and Harvey Deitel (pp. 735). The code snippet is more or less an application for accessing data using 2 threads via a buffer (called shared). Just skip the code snippet, and look below if you would like a brief des...
While I was reading this question, the top voted answer quoted Uncle Bob on coding standards, but I was confused by this tip: Don't write them down if you can avoid it. Rather, let the code be the way the standards are captured. This bounced in my brain, but I couldn't find a place to stick. If a new person joins t...
I've spent some time reading the common copyleft and permissive software licenses. Is there a license which allows the creator of an application or algorithm to broadly specify who may use/distribute the product based on their own personal prejudices? I understand that people use dual licenses to force commercial entit...
In texts about TDD I often read about "remove duplication" or "improve readability" during the refactoring step. But what makes me remove an unused function? For example let's say there is a class C with methods a() and b(). Now I think it would be nice to have a method f() which is driven into C. In fact f() replaces ...
I have a master table T1 which has 1000 records and a ColRef a key column. There are lots other tables all linked by ColRef. I have a Stored procedure which takes few hours to process. I want to split this process like creating a view from T1 select records like 1 to 250, 251 to 500, 501 to 750, > 750. and run this fro...
I (recently inherited) a asp.net web application in production. After fixing a generic bug in the area of making a table selection - we have a problem regarding security policies not allowing access to a certain active x plugin. Our client is reluctant to allow permissions (this has fixed the problem on our test enviro...