instruction
stringlengths
34
36.1k
While reading Python Cookbook I came across these two lines: from collections import OrderedDict from collections import defaultdict Now see the naming conventions of the functions in these lines. The first one has CamelCase and the second one has all small caps. Why are these two named in different style? I ...
Quite a while ago there was a concerted trend in the industry to move towards adopting templating to separate markup from logic, or something like that. The result was much more pleasing to the eye and I would argue much easier to develop and debug. I had no idea what to expect this weekend when I started examining rea...
Let's say I have an interface FooInterface that has the following signature: interface FooInterface { public function doSomething(SomethingInterface something); } And a concrete class ConcreteFoo that implements that interface: class ConcreteFoo implements FooInterface { public function doSomething(SomethingI...
Currently I am working on a project to make a product for company X. The team I am working with is selling similar service to many company with similar product, where 40% of the code is reused and 60% customized feature made to particular company. Previously there were no version control until I suggest using git recen...
Let's say I have an interface IDataAccessObject<TSource> with CRUD methods to access a data source. I have an implementation StrategyDataAccessObject<TSource>, which uses an strategy pattern in order to fetch and update data. All persistence strategies should implement IPersistenceStrategy<TSource>, so for instance, I ...
I have a mobile application which retrieves x number of ContentItems from a Web API, however I need a way to only display content that the user hasn't seen before on screen. (Just to be clear, the user only ever see's a single item of content once.) Imagine the content class to be like this: public class ContentItem {...
What's a good approach to exposing web services of different versions on the same URL? I don't want to have different URLs for different versions so I can change which version consumers are using from the server side. If version is in the URL, it's not optional and I can't provide a sensible default. Offhand I can thin...
Traditionally, a function that want to skip certain items during processing will accept a Collection or var-args argument, but in the Java 8 world I think I should switch to Predicates. Now, since the code I am working on is mainly for testing, most of the exclusion will be ad-hoc "literals", so I am suggesting users u...
I have seen the phrases "instantiate an object", "instantiate a Square object", or "a Cat object is instantiated." (p.17, p.22, and p.26 of The Object-Oriented Thought Process, 4th Edition, Addison-Wesley). And then when reading Design Patterns (the Gof book), I keep on reading "instantiate a class", as in "it must ins...
I am developing an in-place sorting algorithm that leaves the array into a state where it is basically a succession of sorted subsequences of any size (most are bigger than log2(size(array))); then it merges the said subsequences in place. Once the described state has been reached, the algorithm in its current form sim...
I'm following the paper: Towards a Unified Behavior Trees Framework for Robot Control and attempting to implement my own behavior tree. I believe that I have the correct logic working for the main nodes: Sequence, Selector, Condition, and Action, but I'm only allowing nodes to return Success or Failure for now. Addit...
We're developing a transactional application in .NET (ASP.NET MVC, C#, Workflow Foundation, EntityFramework), and want to implement a system whereby users are notified of work that needs to be done based on events in the system. For instance, if an external interface call results in the cost for Widget A to be updated...
I understand that according to the C++ spec there is no such thing as a "method", and some (many? most?) C++ programmers consider "method" to be a Java-ism. On the other hand, even on a C++ forum people seem to talk about methods without twitching. I am looking for known conventions or common practices regarding this...
I stumbled across some posts on the main stackoverflow community about whether you can have a 'memory leak' in Java and it (maybe unsurprisingly) creates a lot of contentious debate. At some point I had decided that Java applications don't have memory leaks (or have them all the time depending on how you look at it) b...
In C++, Say I have a Buffer class (cannot be inherited) which is given and can support the following operation: class Buffer { public: void write_buffer(Data); Data read_next_data(); }; Now I want something like BufferWriter and BufferReader. There are some requirements: BufferWriter should only write but not...
I need to write a program which takes 4 inputs as follows N = The number of integers to be generated (10 < N < 10000) Start = The minimum value of the integers (100 < Start) End = The maximum value of the integers Step = The minimum difference between any two integers (100 < Step) and generates N integers with...
Unlike Java, C# does not share static data among entire generic type, but per each constructed type (i.e. Array<int>, Array<string> and so on). Creating those instances does not seem a problem, but if I am not mistaken removing duplicate instances could be a problem (similar case was a problem for C++). Thus my questio...
I need a design recommendation: I have a class that send a http request via another class WebServiceHandler() I am hesitating between the following two implementations, which one to choose?which one is more accurate from OO point of view? First implementation: /* WebServiceHandler class is charged on sending http reque...
This has been puzzling me for a while. For example, we have a REST API that provides basic content to a system, consuming and producing JSON. At this endpoint it produces a URL to a picture and a description, and is found like thus: //localhost/myApi/pictures/1 { id: 1, description: "This is a pretty picture of...
A friend asked me whether adding a single bit more memory doubles the amount of memory you have, as the bit doubles the amount of representable states. My brain got stuck thinking about it. Doubling the amount of bits doubles the amount of states we can simultaneously represent. Am I performing a category error. What d...
I have the following method to test: public List<MarkId> getMarkIdList(ICar carDoc) { ICourseCar courseCarDoc = courseCarRep.get(carDoc); List<MarkWag> markWagList = courseCarDoc.getMarks(); List<Integer> markIdList = new ArrayList<>(); for (MarkWag markWag : markWagList) markIdList.add(mark...
I am trying to implement proper a Post Redirect Get on a PHP site (question is language agnostic in nature however). I thought about it, and realized that running this code on every request seems to give me the behavior I'm seeking. if (! empty($_POST)) { header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST...
Here are my requirements: Generate Excel reports for users, attaching them to emails Additionally, insert hyperlinks into those emails where the user can view the same report on a web page. I have a Windows forms util that I use to generate the Excel spreadsheets and email them. I have a Web API app that will serve t...
I'm trying to compute the FIRST and FOLLOW sets of a CFG (using Python). To do this I need to recognise terminals and non-terminals. I can (as a human) read them, but I was wondering if there was computational logic for inferring terminals and non-terminals, if one's given only the grammar. It sounds like one'd need to...
I would like to program a software that will heavily utilize client side development (JavaScript), and I want to communicate with the server. Is there a way similar to SignalR where I can keep communicating with the server to get new updates if any? Something similar to LinkedIn where when there is a new update, it wil...
I'm going to save some string payload in the database. I have two global configurations: encryption compression These can be enabled or disabled using the configuration in a way that either only one of them is enabled, both are enabled or both are disabled. My current implementation is this: if (encryptionEnable && !...
I am reading GoF, and the intent of builder is mentioned as to separate creation of complex object from its representation. I couldn't understand what representation means in this context. What does it mean? The Text parsing example provided in the motivation section doesn't seem to separate construction from represen...
I'm making a framework in Java and have a method in my abstract class, BasicPhase, called processAction (snippet below). It takes two abstract classes as parameters since the user should implement them in child classes. However, it results in the user being required to constantly downcast every time they override the m...
I watched Raymond Hettinger's Pycon talk "Super Considered Super" and learned a little bit about Python's MRO (Method Resolution Order) which linearises a classes "parent" classes in a deterministic way. We can use this to our advantage, like in the below code, to do dependency injection. So now, naturally, I want to u...
Langs like Java knows about true method overloading: class Overload { void demo (int a) { System.out.println ("a: " + a); } void demo (int a, int b) { System.out.println ("a and b: " + a + "," + b); } } Whether langs like PHP — doesn't. So when you stand in front of a problem of processing something depe...
Given that Python allows for multiple inheritance, what does idiomatic inheritance in Python look like? In languages with single inheritance, like Java, inheritance would be used when you could say that one object "is-a" of an another object and you want to share code between the objects (from the parent object to the ...
I am reading "Less is exponentially more" and there is a list of advantages of Go, first of them, quote "regular syntax (don't need a symbol table to parse)". What does it mean "regular syntax"? What properties define "language X does (not) have a regular syntax"?
Suppose I were to modify a said piece of code and put it back on github, would I have to update the license header. This is the code(Licensed under the Apache License, Version 2.0): https://github.com/MasterAwesome/android_device_oneplus_onyx/commits/master/liblight/lights.c The commit "Use liblights-caf" is from Googl...
So, I'm still working on my small GUI "library". (C++ with boost) The goal is to provide a simple solution for small SPI displays, using a Raspberry or some embedded board. Thus, I ended up having a Widget class from which concrete widgets are derived. Examples would be a textbox or an image frame. Widgets can contain ...
I'm new to REST API, so I decided to get familiar with it by designing a small web service API. I have its design written down and would like you to review it. I feel like I have made some mistakes in designing it and understanding REST concepts, which I try to address with questions on my design at the very end. I'm m...
In response to Aaronaught's response to the question at: Can't I just use all static methods? Isn't less memory used for a static method? I am under the impression that each object instance carries around its own executable version of a non-static member function. Regardless of how much overhead is involved in calling ...
I am working on a legacy code base and I need to find a way to write unit tests for this project. The project has a three layer architecture (UI-Biz-DAL as we call them) and DAL is totally implemented using ADO.Net and Typed-Datasets and it is full of SQL Scripts. Our Biz classes have methods that are responsible for d...
Short version of the question: What is a proper way to implement object cloning with deep copy, using generally accepted OOP principles? I ran into this while looking into the Prototype Design Pattern in the GoF Design Patterns book, but I think it applies to general object cloning. Wouldn't it be, each class has to p...
I came from a highly functional and procedural background in programming, and never knew that a type is the same as an interface. As in the Design Patterns book by GoF, it says: A type is a name used to denote a particular interface. We speak of an object as having the type "Window" if it accepts all requests for the ...
Imagine that you first write a compiler for your language where you necessarily report errors to the user. Compiler also collects location information for backend tools. They must know where the program elements are located. Later, when you are done with your compiler, you decide to provide IDE support as well. The edi...
I'm planning a project that consists of the following parts: REST API in Lumen Web client in Laravel Product website in Jekyll These separate products are going to be running on the same server. I'd like to have a development environment that mimics the production environment as closely as possible, that's why I'm g...
I thought a class is supposed to define, or give a blueprint, of attributes and methods for an object. And then, an interface is to provide a set of methods, as a contract for its clients. (and so a class also gives an interface as well, because a class also define a set of methods). But say, if we have a class called...
I've seen it's very common for a compiler to be made in the language it's compiling. What is the benefit of this? Seems like it makes the process for outsiders (and the developers for a while) more difficult. Take for instance: coffee-script gcc typescript jdk elixir etc. It seems like it just makes things more tri...
My friend asked me for help with his task: "Redeem a lattice parser with any programming language" - the problem is that he can't clearly explain me how the lattice parser should work. I've tried to google a bit, but all I've found are some academic documents which doesn't help. All I know at the moment that it is rela...
Context: I am developing a visual studio plugin that generates layer diagrams. I want the tool to be able to produce an intermediate output, which is the data representation of what is being rendered in the diagram. The idea is that this serialized data can then be checked in together with the source code which would a...
From previous experience, I had always thought that, if you are going to use variables inside of a for loop, it was much better to declare them outside of the loop vs. inside the loop itself. I recently had a code review done and had several younger developers claim that this was not true and that I should be putting m...
I’ve released a piece of code into the public domain (henceforth “PD”), via The Unlicense. Recently, I’ve found someone forked that code and made some modifications without any acknowledgment/attribution. That is absolutely fine (it’s to allow that kind of freedom that I’ve released it into the PD in the first place). ...
Simply put I'm new to the company, should I rather write advanced techniques with things like templates, std techniques..etc to make a first good impression and have my colleagues trust/be impressed at my work or should I be more concerned in writing more solid/based standard code for each current problem to be solved?...
On comp.lang.c++.moderated@googlegroups.com, Greg Herlihy posted the following extern "C" function: extern "C" { int func() { wchar_t memoryName[256]; wchar_t mutexName[256]; wchar_t eventName[256]; mbstowcs(memoryName, "MemoryName", 256); mbstowcs(mutexName, "MutexName"...
Came across this problem -- You are given a grid with numbers that represent the elevation at a particular point. From each box in the grid you can go north, south, east, west - but only if the elevation of the area you are going into is less than the one you are in, i.e. you can only descend. You can start anywhere o...
I'm storing some data in Cassandra, then after analyzing it puts in several table, I have its aggregation as daily, weekly, monthly, yearly basis. But after some time if some user reads the content I'm changing it in to read and unread status based on user activity. But as per my current design either I need to update ...
I have been reading every now and then on the virtual machines of programming languages like Java, Python and Lua. They all have a notion of bytecode, into which the source code is translated and that is excutable on a virtual machine (register or stack based). Now on an x86 architecture, all code resides in RAM which ...
Let's say we have an app where the users gain points and can exchange them for rewards. The exchange request, in pseudo-code, could look like this: function exchangePointsForReward(userId, rewardId){ user = getUser(userId) reward = getReward(rewardId) if (user.points >= reward.requiredPoints){ giveR...
We have a class in which mainly data processing(XML nodes) is done by mainly 3 methods. Now code in itself strictly follows DRY principle. For e.g. Process Children (reads data from child nodes) Process Choose Element (conditional data check) Extract Single Field (extract data from single node with no children) To gi...
I have three classes that are circular dependant to each other: TestExecuter execute requests of TestScenario and save a report file using ReportGenerator class. So: TestExecuter depends on ReportGenerator to generate the report ReportGenerator depends on TestScenario and on parameters set from TestExecuter. TestScen...
In Java and PHP (although not strictly required), you are expected to write each class on its own file, with file's name is that of the class as a best practice. But in Python, or at least in the tutorials I've checked, it is ok to have multiple classes in the same file. Does this rule hold in production, deployment-re...
I'm designing an analytics system that feeds all events to Elasticsearch. The event lifecycle is as follows: Visitor does something. Custom analytics server gathers data, makes an event out of it and puts it into Elasticsearch. One a day or so, custom batch processor aggregates a large set of events from Elasticsearch...
I am rewriting a website that has a back-end database for containing meta-data that is displayed to the user when they enter a text code. Background: The old/existing system stored this data in XML files with a master index XML file that pointed the correct data file based on a GUID. The way this is currently handled f...
This Stack Overflow question is about a child having reference to its parent, through a pointer. Comments were pretty critical initially of the design being a horrible idea. I understand this is probably not the best idea in general. From a general rule of thumb it seems fair to say, "don't do this!" However, I am wond...
Just a quick question about a design pattern for creating custom exceptions. The question is more about the order of parameters. If you can specify more data in the exception, should the parameter for it included in the constructor, come before or after the overload parameters? Before: public FooException : Exception {...
I find myself unsure about what exactly it means to have different representations of a RESTful resource. The canonical example is for an API to provide an endpoint - say /v1/users/:id - and allow the client to select the best representation of the resource between JSON, XML, HTML or PDF depending on the media range v...
We are using Java as a backend development language. One year back, we wrote a method which uses switch cases based on Enums values. Since we are continuously adding enum members and according adding cases in the method, the method has grown to very large extent. Currently, we have around 100 enum fields and correspond...
I've only just become interested in this domain, so sorry if I'm not using the correct terminologies. What I want is the following: Say I have a set of rules (or constraints), I want to derive some implications of those rules. For example, in Conway's Game of Life, there are 4 basic rules. From these rules, we can see ...
We use Git and Jenkins as our build&release system and each build is assigned a version number which looks like this: 6.0.12345. Here, the 12345 part is a counter which increments with each build. The counter is stored on the build server in a simple text file, which is rewritten every time a build occurs. It's worth n...
I have some VHDL design that I plan to release as open source. I like MIT License for its simplicity and would like to use it for my code. However, I am not sure if it is OK to use it with hardware design, as it says "software" pretty much in every sentence. Are there any particular things I should consider when releas...
When Instant was introduced with JSR-310, convenience methods were added to perform conversion between Date and Instant: Date input = new Date(); Instant instant = input.toInstant(); Date output = Date.from(instant); I wonder why it was chosen to be this way instead of, let's say, having Date output = instant.toDate()...
I've just refactored some code that managed a global state cache of values that didn't have locking to use double check locking. Other than moving the initialisation to a single source (the cache was being set in a controller method), the main reason was to make sure only one thread was performing the initialisation at...
I'm writing my first "large" program in C# and WPF. It's a Database system (MySQL) that has three main items, Contracts, Companies and People. I have the main UI down for the Companies section of the Database and I'm now looking at managing user privileges before I go any further. I've hit a roadblock really on what wo...
One part of my program fetches data from many tables and columns in my database for processing. Some of the columns might be null, but in the current processing context that is an error. This should "theoretically" not happen, so if it does it points to bad data or a bug in the code. The errors have different severitie...
I work for a big company and I'm responsible for a large java application with thousands of junit tests. Since I moved to this role, there have been 200-300 broken tests (likely broken for years). The tests are old and fragile and they're a mess of spaghetti dependencies that typically end with live sandbox data. My ...
What is the origin of "Program to an interface, not an implementation"? Does it originate from Design Patterns, 1994, by GoF, or from a computer scientist or from some concepts in computer science earlier?
I have often wanted the same feature which is asked for e.g. here and in many other questions on SO: Being able to specify that something satisfies multiple interfaces without specifying the concrete type. e.g. in C# pseudo syntax (IEnumerable<string>, INotifyCollectionChanged) GetStringData() { return /* an objec...
I'm an iOS developer primarily. In building my current app, I needed a server that would have a REST API with a couple of GET requests. I spent a little time learning Ruby, and landed on using Sinatra, a simple web framework. I can run my server script, and access it from a browser at localhost:4567, with a request the...
Q: What is the best way to move a large company to Cucumber with at least 15 years of legacy software requirements maintained in a requirements database? Currently considering: 1) Migrate Everything Downside: we don't have unlimited time/budget, we have to move forward to survive, we can't stop everything and GC 100% o...
Is there an existing named software design pattern similar to Observer, but for the case where only a single observer is supported rather than a collection of observers. I find that I use this pattern fairly often, particularly in cases where an adapter has the ability to provide fan-out (notify multiple observers) on ...
I am new to the world of Javascript and their frameworks, and I feel a bit lost with this. I am trying to follow the official toutorial of AngularJS. In one of the first sections, it reads Install Node.js If you want to run the preconfigured local web-server and the test tools then you will also need Node.js v0.10.2...
I want to model (TV)Events and Reminders and I’m wondering what’s ‘the best’ way to model this. The requirements are roughly When an Event has no Reminder, a Reminder can be created When an Event has a Reminder the Reminder can be deleted an icon is shown on the Event A separate Screen exists presenting all Remin...
We are studying a prospect of using Ghostscript in a commercial product (Windows desktop application). I read about sidestepping licensing GS altogether by simply suggesting to the users that they can download and install GS on their own to improve their experience (the software actually works without it, too, but most...
As I understand it, in DDD, it is appropriate to use a repository pattern with an aggregate root. My question is, should I return the data as an entity or domain objects/DTO? Maybe some code will explain my question further: Entity public class Customer { public Guid Id { get; set; } public string FirstName { get; ...
When Apache released its list of best practices, they recommended avoiding the addition of an empty panel conditionally and gave the following example of what NOT to do: if(MySession.get().isNotLoggedIn()) { add(new LoginBoxPanel("login")) } else { add(new EmptyPanel("login")) } However, I see a lot of this ty...
we are working on a JAVA EE project which handles huge amount of data, but has to provide full-text-search option (in hungarian language). So we started to think about what kind of architecture could fulfill our requirements. My thoughts are the following: Using ElasticSearch as a database is an antipattern so it must ...
Can someone please explain the differences in C# between: throw throw new and exactly how exceptions "bubble up" as I've heard they do? In my daily job, I've used just try/catch to mostly control the flow. I've divided the code into various "blocks" each one enclosed in a try/catch so I could log and debug exactly w...
I recently thought about the use of unsigned integers in C# (and I guess similar argument can be said about other "high level languages") When In need of an integer I am normally not faced with the dilemma of the size of an integer, an example would be an age property of a Person class (but the question is not limited...
For example: class Data { private String field1; private String field2; public void someEditMethod() {} } class DataRepository { public void save(Data data) { // save to DB } } I need save Data when editing. How better? internally: .... public void someEditMethod() { repo.save(th...
I'm in the midst of deciding which platform to use to implement a new kind of display server / window manager. It seems that it isn't possible to replace the DWM on Windows systems according to MSDN docs. But then, how do folks go about doing fancy 3d stuff like this video of a 3d window manager framework for the DWM w...
For an open source project created by 2 authors, is it proper for an MIT License to have two authors? The MIT License (MIT) Copyright (c) 2016 FIRST NAME and SECOND NAME
How do you make an class that properly warns a developer in the future that they've made a mistake somewhere in their implementation that resulted in an object that gets deconstructed in a state that prevents the release of it's resources? Background: I recently upgraded to Visual Studio 2015 and began reloading and co...
According to this question and just about every style guide I've ever read, large methods are bad. However, suppose I have a method that does the following: Receive a JSON String from some service and store it as a Dictionary For various parameters in the Dictionary, creates connections to other services, such as usin...
I have recently come across two terms: Software Engineering and Craftsmanship. I would like to know what the difference is between Software Engineering and developing software in a Craftsmanship style. Intuitively I understand that these two approaches are not exactly the same, but I am not sure whether they are comple...
There is a portion of our codebase written in the following style: // IScheduledTask.cs public interface IScheduledTask { string TaskName { get; set; } int TaskPriority { get; set; } List<IScheduledTask> Subtasks { get; set; } // ... several more properties in this vein } // ScheduledTaskImpl.cs public...
I am investigating Camel for connecting various services. I understand the core concepts but I was curious about more specific implementation details. This application would have a browser client front-end that communicates using Ajax REST calls into the ESB. Imagine that the end user sends personal information and ...
I recently started working with JS Promises. What I always like to do, is create function, which returns a Promise with the final desired result, but I only do 1 operation/then. Consider something like this (this fetches the versions of an npm package in an array in reverse order): function packageVersions(name) { re...
We're looking to add personal pages generator for our users, which is simple enough while all of them are on our domain. We also want to enable them to purchase their own domains through us, and serve these pages on their domain. We currently use Google App Engine for all of our deployment and server needs, and it has ...
I have a library where I want to use a logger but I don't have (and cannot) create any interface for it because I'll be using it on different systems that have nothing in common (and won't have). So this won't work: public void Foo(ILogger logger, ... other params) { logger.Info(...): } To overcome this problem an...
I'm a amateur programmer, I'm not used to working with Git. It's my job to help test new code, for a while now this has included pulling the branch containing the issue, merging it with the main branch, and pushing it to the test environment. There are a lot of steps involved with a incredible amount of different opti...
In the past few years, we've been using dynamically typed versions of PHP. However, in PHP7 we have an option to enable 'strict types': PHP RFC: Return Type Declarations PHP RFC: Scalar Type Declarations (Note: Scalar Type Declarations repeatedly uses the phrase "weak type checking" or "strictly typed" versus static/...
In C#, when you call a constructor, you can add one or more property initializers in curly braces: var foo = new Bar() { Armpit = new Flapdoodle() { Limpet = 2 } }; What if that feature were generalized to "set properties on a return value": var baz = foo.Armpit { Limpet = 4 }; This would be handy in cases like this:...
The problem I have this structure that I want to create a "constructor" for it. struct example { int x, y, z; /* various members */ struct another *another; /* pointer to another structure */ } The two different ways I know of Using functions that create and delete structures on heap I can create structures...
One of the things the coffeescript programming language is criticized for is its treatment of variable declarations and scope (example). The answers to this question (and the blog I linked to above) seem to hinge on the false dichotomy of variables either being able to be shadowed or else be global. In any language wit...
I have spent quite some time learning all possible design patterns but I cannot find the ideal one for the following case. I am developing an iOS app where we are using multiple analytics tools like Google Analytics/Facebook Analytics and it is possible that in the future we will add some more (our company is obsessed ...