instruction
stringlengths
34
36.1k
I am trying to create an authentication client and server for my project, and I am trying to think of ways on how a potential hacker could modify my code and use it to hack the servers. Do people actually do this often and if so, how do programmers try to get around it in open source projects?
I've never done anything with statistics, so I'm unsure of how to start with this problem that I need to solve for some software that I'm working on. Basically, there are three parameters An integer parameter (A) that can be a range of (for the sake of argument) 1-10 A Boolean parameter (B) that if present weights the...
I'm designing an API. And, this API will be used by client. Currently I've two behaviors in a class definition. To illustrate the scenario, sample implementation looks like the following- public class Session { // instance field declaration goes here void connect() { // method definition goes here ...
Java has been designed to run on a virtual machine to allow portability for programs. However .NET has been designed from the start specifically for Windows. Than what is the reason for .NET applications being compiled to bytecode for the CLR? Was it simply to copy Java? Or is there a technical advantage to just compil...
I have a single data structure that holds a relatively small amount of objects (ca. 1500) and several methods that are acting on it. Is there a programming pattern to iterate the methods over the data instead of writing significantly more boilerplate code?
Let's say I have a few methods that access the File System, and I want them to be a bit robust, I want to throw errors so the user can react: If the file doesn't have read / write rights, I want to inform him/her. If the file does not exist, I want to prompt him/her to chose another one. And so forth. Thing is, the ...
I'm wondering how to manage empty results returned by search queries in a REST web-service : I there was a query like my_ressource_collection/{id} and the resource didn't exists i would return 404 - Not Found But, if my URI is more like a search query like : my_ressource_collection/?fromDate={fromDate}&toDate={toDate}&...
I have a solution split into two projects : A class library containing all of my model classes (lets call it Business), and an ASP.Net MVC project. My Business classes are meant to be generic and work for multiple types of projects. For this reason, they don't contain any data annotations/associations to other classes,...
I am working on a file-system-like application where I use CQRS/event-sourcing to handle the state of folders and files (creating, moving, renaming, etc). Each node (folder or file) is represented by a single aggregate (as they are standalone unit with own ID). Now I am about to implement deleting of the nodes, where t...
Suppose I have 4 types of services I offer (they are unlikely to change often): Testing Design Programming Other Suppose I have 60-80 of actual services that each fall into one of the above categories. For example, 'a service' can be "Test Program using technique A" and it is of type "Testing". I want to encode them...
In Go, is it idiomatic to check for nil and return an error if a parameter is nil? Should pointer method receivers ever include nil checks? I've seen a lot of code in other languages where people applying defensive programming also checked for nulls and threw an exception when a null was passed in. I am wondering if th...
When practicing TDD, how do you test a domain model? If you don't test, how do you account for code coverage? We want to have 100% coverage (or as much as possible), but despite hours of training videos we cannot find the best solution. UPDATE: Given a domain model I want to write of User which has properties: Id ...
This is currently the way I'm organizing it. myProject/ README subproject1/ __init__.py classA.py classB.py driver.py basicTest.py Driver imports from classA and classB and provides some additional functionality. basicTest also imports from Driver and classA. I've been u...
This is the second project I'm working on which will use a design that I'm not 100% confident about. I'd like some feedback, maybe recommendations for a better design, or verification that this would be acceptable by more proficient programmers: I have a device that I need to interface with. Be it via TCP, UART, UDP,...
I got started with programming back in the DOS days. One of my early projects involved overriding the keyboard interrupt service routine with my own. Now I'm trying out NodeJS to update myself, and I feel there is a similarity between the non-blocking design of NodeJS and my old experience with interrupt service routin...
Given a data set of arbitrary size, what algorithm would be appropriate for performing the polynomial regression on the data set such that the highest degree of the polynomial is n? If there are multiple of such algorithms, what is more efficient for particular data sets (other then the obvious line fitting the data se...
Suppose you have a function that allows you to find the sum/minimum/maximum of a data field: void g(DataField* d, Operation* op){ // applies op->f(...) on all fields of d } Operation would be defined something like: struct Operation{ virtual void f(...) = 0; } struct Sum : public Operation{ virtual void f(...) ...
If I develop an application, I'll often use a project structure like this: MyApp.DataAccess.Implementation MyApp.DataAccess.Contract MyApp.Business.Implementation MyApp.Business.Contract MyApp.CrossCutting.Implementation MyApp.CrossCutting.Contract MyApp.Application For each layer I'll create two assemblies. One for ...
I currently own a website where players can look-up their statistics of a game. When someone that is not in my database yet requests their statistics, I am calling the API with a PHP cURL request and storing them in my database. Then I have a cronjob that runs every minute, takes 1/5th of the players in the database an...
For speed we sometimes return response to consumer before state is saved in DB. Sometimes (Mostly for our automated consumers) this can break because the want to make actions on the saved data before it is saved. I wrote this little helper public async Task<TEntity> GetWithRetry<TEntity>(Expression<Func<TEntity, bool>>...
Like many Javascript-based rich web apps these days, I have some complicated validation rules implemented on the front-end. The same rules are supposedly repeated exactly on the Java backend but I always find small deviations. As a believer of the DRY principle, I think something should be done to systematically fix th...
I'm looking at different patterns and techniques for implementing logic to convert object from one class to another, and the most elegant seems to be explicit cast operator overloading (in C#). However, it seems to me that it violates the Dependency Inversion principle, as it requires one concrete class to have referen...
I have been struggling with functional programming concepts for a while. I read that in functional programming, variable immutability is a fundamental thing. You don't change the state of a variable. But I can achieve the same effect in Java by using the keyword 'final'? So why cannot Java be used as a functional langu...
I was hoping that someone could explain the exact difference between an Assembler and Entity Translator. Martin Fowler describes the Assembler as a sort of Mapper(?) which converts DTOs into Domain objects and vice versa. When you're working with a remote interface, such as Remote Facade (388), each call to it is ...
I'm running a Twisted web server and trying to figure out a good way to handle retries from the client. In normal operation the client makes a request of the server with some JSON data and receives a JSON response. Every request includes a header with a unique identifier. I'm trying to handle the case where the client ...
Let's start with an example. Let's say, I have a method called export that depends heavily on the DB schema. And by “depends heavily” I mean I know that adding a new column to a certain table often (very often) leads to the corresponding export method change (usually you should add the new field to the export data as w...
I am working on a geometric wrapper for a space jet exhaust impingement solver. A key part of the solution is determining what the jet can "see" and therefore hit. My model is grouped with nodes or grids arranged in 3 or 4 sided elements which are further grouped into bodies. Shading for bodies is handled via outwar...
Programmers all seem to agree that readability of code is far more important than short-syntaxed one-liners which work, but require a senior developer to interpret with any degree of accuracy - but that seems to be exactly the way regular expressions were designed. Was there a reason for this? We all agree that selfDoc...
I have been researching how to build a newsfeed that sorts the order by relevancy. I have been following along Facebook's Edge Rank and Etsy's Activity Feed Architecture and I can't figure out how these companies calculate Affinity. The database stores a percentage value for example 0.75 Given I have a set of activity ...
I have the following classes: public abstract class StaticFileController<File, QueryData> : AsyncController { private string _resourceName; public StaticFileController(string resourceName) { _resourceName = resourceName; } //This method receives _resourceName protected virtual ...
It is good programming style to include all necessary dependencies in a header that references them. Often this includes declarations that are placed in the STD & global namespaces (like cstdio). However, this creates problems when a second programmer wants to wrap such an include file in a new namespace to encapsulate...
I'm a Java Developer, I created a Desktop Application , that is Free, and now I'm about to finish the payed version. my question is when I create a startup and other developers work on my code. How can I prevent them from copying the source code and take it home or leak it?? and is there is a software for that, what th...
I typically make all my methods private unless and until they need to be overriden by a sub-class. At that point I modify the base class to make that particular method protected virtual. Is it accurate to say that this is a violation of the "Closed to Modification" principal? If so, that would imply that I should choo...
I will approach this from two directions (+ raw HTML itself being de-facto third) Proprietary HTML-generating code Code generating facilities provided by a popular library Proprietary HTML-generating code Example -- in a project I've inherited, there is a code that generates HTML for you, using proprietary methods w...
I understand how to get a general picture of the big O of a nested loop, but what would be the operations for each loop in a nested for loop? If we have: for(int i=0; i<n; i++) { for(int j=i+1; j<1000; j++) { do something of constant time; } } How exactly would we get T(N)? The outer for loop would...
I'm trying to design an application, something quite generic over a .NET C# Stack. It's supposed to be an desktop application intended to control industrial equipment and to perform measurements and testing, however it's planned to be able to switch later on different UIs dealing with different I'm trying to have a pr...
I want to know how Random number generator(RNG) works in any PL(Programming language). I know the random methods has short periods. i.e they start repeating the values after specific number of time. Seeds are used to initialise the random numbers generated by the RNG. IF any PL uses its own SEEDS, how specifying my see...
I'm looking for an algorithm that can generate optimized syntactically valid variable names (for javascript in this case) without collisions. So as general rule I would want something that generated aa, ab, ac .... az, a1, a2, a3, a4, a5, a6, a7, a8, a9 ba, bb, bc.... bz, b1.... zz...z9... aaa,aab.... it does not gen...
I'm looking to secure an API based on a shared key and a given username and datetime. The API gives access to trusted third parties and does not require the input from a user in order to access their account (i.e. no OAuth user interaction flow). The third party does not know, nor should require, the user's password. /...
I have an iOS app where after exceeding a certain limit, part of the user interface changes a color to alert the user. I'm using MVVM to accomplish this and division of labor looks like this: Model - fetch limit value and from the storage View Model - compare limit with current value and pass bool (over/under limit fla...
As I understand, the BIOS code/bitstream that is held in the ROM should be generic (work alongside with multiple CPU types or ISAs). In addition, I saw mentioned on the web that it is possible to dump its code (and to "disassemble" it). So, in which language, instruction set or machine code is it written? Doesn't it ne...
In an application, I have a recursive folder structure (like folders in OS X or Windows file system). Each folder can contain three kind of things: Other folders (hence the recursive structure) Employees Tasks Here are the simplified models for those elements: class Folder: parent_folder: Folder class Employee: ...
I was reading "In MVC should a model handle validation?" because I was curious about where validation logic should go in an MVC website. One line in the top answer goes like this: "controllers should handle validation, models should handle verification." I liked that, but it left me wondering why we wouldn't do data va...
I'm working on a distributed application for a graduate class I'm taking. There has been much discussion around implementing a way to maintain peer connection health statuses. Think Gossip. One of the primary themes for this project has been how we should rely on UDP communication to overcome the "excessive" bandwidth ...
I understand C and C++ are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quite true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (especially when working on embedded systems) it's very likely to...
In statically-typed languages such as Java, code such as the following is common (not much of a realistic example, I know): public String flip(String text) { String result = ""; for (int i = text.length() - 1; i >= 0; i++) { result += text.charAt(i); } return result; } public int flip(int valu...
I just noticed that the universal newline feature of file operations seems to be on its way out. The documentation for Python 3.5 open's mode parameter indicates that it's deprecated: 'U' universal newlines mode (deprecated) At least as far back as Python 3.2, open contains a similar "backwards compatibility only...
I'm working on a small scale API project but as it will be used and maintained by people that are not Software Engineers to trade I am attempting to keep the design as separate and identifiable as possible, using SOLID has made this easier. But a few of my objects require to change (say made "active") which then in tur...
I think there isn't a large enough degree of separation between Business Logic, Data and Presentation in some of our products. I'm trying to explain this to collegues but I'm finding it difficult as I can't think of any examples or links which back up my feelings about specific instances which I think break MVC. Our (v...
I'm writing a PHP application where a block/module of domain logic is subject to frequent, significant changes over time. The complication is the application needs to be able to use not just the latest version of the module, but any version that it has previously used, so it can reproduce the results of data that that ...
Introduction I am implementing a abstract Java class of a processing framework*. By implementing the function execute, I am able to add business logical functionality. I would like to add logging at the start and end of every implementation of every of my execute functions. Also in between some logging, if specific thi...
All examples of semantic versioning I've seen show 3 components in use. No more than 2 period characters. At $DAYJOB, we use 4 components in our release numbers: 5.0.1.2 Does Semantic Versioning allow for this? And as a higher-level and more arguable side question, does it really even matter? I started to think it mig...
I know that according to GPLv2 if my non-GPL program links and calls internal functions of a GPL program, my own proprietary program must then be open-sourced (if it's distributed). But suppose that there's an interpreted script program (e.g. in Python) that is a self-contained, non-binary executable, so I can execute ...
Background I'm writing an image handling class. For this question two requirements of the class are of interest: Must have "deep" const correctness. Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data. By deep constness I mean the following. Consider this example clas...
Catalyst: Recently my team has been tasked with bringing in house a large software project that has been worked on for over 20 years. Some of the old development team is still around, and originally the plan was to have them mentor us and bring us up to speed. After quick investigation, it's been determined that this p...
What is the best strategy for maintaining easy to follow code when keeping things DRY means you have to pass a lot of parameters to shared functions? In my specific case, I have a grails based app, and have implemented a system where to reference object B from object A, I have taglibs, gsp's, javascript and service co...
BusinessModel: I have a ice cream shop and I designed classes to do my supplier based financials based on industry types(Lines of business). I sell ice creams of many types, which I buy from different suppliers, and at the end of the month I try to reconcile my account by line of business using classes I created for co...
I am attempting to determine which data structure I should use for the following information: ("Water", 100F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, ""); ("Tuna", 60F, 184F, 30F, .01F, .001F, .064F, .05F, 0F, .011F, .05F, ""); ("Chicken Breast", 62F, 197F, 30F, .01F, .001F, .027F, .07F, 0F, .013F, ...
Given three sides of a triangle. I have to determine by writing a program using C language whether I can make a valid triangle or not using these three sides of the triangle. So how should I proceed ? We all know that a triangle is a geometric shape with three positive sides. However, any given three sides won’t necess...
I started learning Python yesterday and I ran into a problem. I like to hear some thoughts on it. As an exercise, I decided to build a chatserver. As part of the exercise, I wanted to write some inheritance code. Class A def foo print "foo" Class B(A) def bar print "bar" c = B() c.foo() >>> prints: foo ...
Whenever a user interacts with a resource while not logged in, I need to: Redirect them to a secure page. Show a signup/login dialog (which is usually partially customized based on the resource, and may have a link to a no-login version of the resource). Send the user to the resource (if they login). This is a...
I've been working more with concurrency in Ruby recently, and I keep seeing various articles using "threads" and "process" interchangeably. What are the actual definitions of these terms? Is a process composed of multiple threads? Let's say I use a web server. Am I correctly understanding the following? Each web serv...
Observer pattern aim: the observer class responds to the changes of the observable class state. Problem. There are different processes inside observable class that should be observed. Those events are independent and the state is not single value but rather itself is a set of different processes. That might be bad de...
I've been researching how to properly design a mongo schema and came across this blog post on their site: http://blog.mongodb.org/post/87892923503/6-rules-of-thumb-for-mongodb-schema-design-part-2 The idea for partial normalization for faster reads makes great sense but what I can't understand is how to implement such ...
When calling some function in a Python application, the function often calls functions deeper down which again call functions deeper down, etc. It is easy to unknowlingly pass a bad value to the top-level function which will cause a failure further down. Naturally, the parameters should be checked and exceptions raised...
For a database. Should I use an UUID or an integer for the primary key? I will never exceed 2^32 in amount of rows, so an integer should be more than plenty. I would prefer to use an integer, as I find it easier to work with, especially when using different languages. Question: What is the advantage of UUIDs over integ...
For example, I have a game, it has 5 enemies which attack once sequentially at each round: class Enemy{ }; class Game{ public: Enemy enemys[5]; }; I want something to indicate which enemy has attacked and which has not, now I have 2 solutions: 1.add a counter "enemyIndex" to indicate which enemy is attacking, aft...
I want to multiply two numbers but since I don’t have long enough registers in the current architecture need to “break them down” into shorter ones and somehow perform the calculation. For example: 2048.125 x 2048.125 (2048.125 =>4001hex) but with the binary point beyond the 4th bit position (Q12.4 signed) and upwards ...
I'm starting a new MVC 5 project from scratch. I'm using EF 6 (Database First) and Identity 2.0. My solution consists of 3 different projects: Data (where I have a .edmx and my DB context), Resources (for localization purposes) and Web (the web project itself). I'm using ViewModels for all my views, by default. Every t...
I was stuck with some validations for quite a while. I have been thoroughly searching the internet to find ways to apply the validations I require. I came across many methods for validations even certain Nuget packages. But in most cases my requirement was not fulfilled. I did a remote validation, which for me was the...
I'm currently in the process of rewriting an older library for managing documents. I'm having difficulties to specify an interface for the management of links between those documents. Previously they have been specified simply as the primary keys of the other documents. But in order to have a more object-oriented inter...
I'm building a WPF application, using MVVM, and Prism. It's worth noting that I'm the only developer working on a large project, so resources are limited. Here's what I currently have: Models - POCO's ViewModels - contain instances of POCO's, and utilizes the service layer based on user interaction. Views - bound to V...
We are trying to establish a 6LoWPAN network. Our Devices have only the 6LoWPAN connection so we need a bridge to connect them to CMS server. A small computer (something like BeagleBone) which runs Linux acts as a bridge and communicates with multiple devices via 6LoWPAN and provides TCP connection to server. In this...
I'm working on a simple DI library, and on the subject of using services through interfaces, I can't find the usefulness. Perhaps it's because I dont fully or properly understand how an interface should be used during the process of injecting dependencies. Here's what I (think I) understand: DI consists primarily of c...
I have a number of classes with a single public method. Looking at this answer, I tend to agree with what is stated. The OP lists some examples, which I interpret to be used like (new VideoCompressor)->compress($raw_video); While the readability improves slightly by calling the explicit method name, I feel it is almos...
I have a bunch of modules. I can break these modules into different categories that are complete and do not overlap. For example, three categories, with ids that can be expressed as Animal, Vegetable, and Mineral. I further break these categories down into subcategories, which again are distinct, complete and do not ov...
The core of the CMS Drupal is not based in object-orientation in version 7. For writing pluggable modules, it has a "hook" system, whereby you can alter the behavior (by altering passed data) for defined system functions. For instance, Drupal ha and API through which you create arrays to define forms that are translat...
I am working with digital images that people have manually categorized on a number of parameters. I want to be able to find images that are similar or dissimilar based on certain categories. For instance, we might want to pick two random images from our database that have similar "significance", but are otherwise as di...
I'm developing a little framework (in Scala) where I want to define clean and simple interface for the users of the framework. Some of theses interfaces have to be implemented by the framework itself, but I want to hide theses implementations from the user to keep the "surface" of the framework small and simple. My ide...
Suppose I have a class that is a readonly collection or immutable objects, e.g. public class ReadOnlyInts : IReadOnlyCollection<int> { private readonly IReadOnlyCollection<int> intCollection; public ReadOnlyInts(IEnumerable<int> ints) { intCollection = ints.ToList().AsReadOnly(); } #region ...
I'm creating a visualization tool for workout data, specializing on bicycle rides. I'm looking for ways to generate more value from the data that was recorded. Since there usually is a GPS track available I was wondering if and how I could extract possible visited towns or special locations during the trip. I'm especia...
In Meyer's Object-Oriented Software Construction (1988) he defines the open/closed principle as follows: A module will be said to be open if it is still available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs. A ...
I'm having a peculiar issue to solve. What I am supposed to implement is a bus transit simulation in which there are passengers coming at some random generated time intervals and are added into a queue and they wait for the bus to arrive at bus stops and bus stops there and they board the bus until the queue is empty. ...
I've never really done network programming so this is all new to me. What I'm attempting to make is a Peer to Peer "chat" client. The idea is that anyone can connect to someone whose IP they know. All chat messages are to be distributed to everyone. What I'm getting stuck on is the peer discovery. What I've done so far...
Whenever we are writing destructors in C++ (though this concept could apply in other languages) could we just not write delete this; and it would delete whatever data is inside of the class? Is this a good or bad idea? If it is bad, would this not delete all the memory we had allocated to the object?
Imagine that you have an object code file from an untrusted source. You want to run this code to know the result of its computation, and you want the code to perform fast, so setting up a whole virtual machine is a last resort. You also want nothing to happen to your system after the code is run. Having that in mind, a...
I'm trying to eliminate a lot of repetitive code in my Python and this function repeats itself in various forms. Is there not an easier way I can just pass a variable (using a list or similar) to the function "Create_me" and then get it to: Create the global variable "var1". Take the global variable and use it in plac...
I'm a bit stuck using the single responsibility policy. I have a class named Parser, which can be configured to parse input a certain way. For the sake of convenience I will limit the configuration properties to a single property config in the following example: class Parser { boolean config; State state; ...
Null is considered bad, because of nullcheck. My question is, what other way there is, that would have replaced this null problem? How could that have been avoided?
I am learning about coding to an interface in OOP programming. I understand you should code to an interface so you can 'swap out' functionality. However, I have a situation where I feel I can reuse an interface again rather than simply swap it out. interface GetFile { public function getFile(); } class GetFileFro...
Often when writing code I wonder what the best way is to discriminate between types (by which I don't necessarily mean types used in typesystems). That brings up 3 questions: What is better? When is it better? What are the (dis)advantages? Using properties to discriminate class BinaryExpression { String operat...
I have a console application that will make modifications to 1200 systems remotely using SCCM. One of the items to be modified is a GUI menu app that is XML driven to display buttons that launch other applications. I need to change the XML. Changing the XML wouldn't be terribly hard, but overwriting the file would be a...
Within C, say I have a number of variables, floats, integers etc, is there a way that I can group them all into one object, lets call it a system, and then create N copies of such an object. Further, is there a way to assign to each copy of the system a particular value of a variable T such that each system has a diffe...
I currently experimenting with DSLs with xtext. I want to implement a quick fix for the dsl I'm writing and I'm wondering, if there is a possibility in xtext or xtend hook (or something else) to generate a dsl fragment code from the DSL grammar and a given Ecore node. For example Model: entities+=Entity*; Entity: ...
I am working with Spring Boot + Jersey + JPA/Hibernate to build a RESTful API. The issue I am encountering right now is when I have a relationship in my JPA Entity that is lazy loaded I get a lazy load exception when Jersey goes to serialize the object. My question is what is the best way to avoid this / best practices...
I am still trying to find the best security solution for protecting REST API, because the amount of mobile applications and API is increasing every day. I have tried different ways of authentication, but still has some misunderstandings, so I need advice of someone more experienced. Let me tell, how I understand a...
I am trying to do the following: HTML Code <body> <form name="myform"> <table> <tr> <td>First Name:</td> <td><input type="text" id="first_name"></td> <td><p id="demo"></p></td> </tr> <tr> <td><input type="submit" id="Submit" onclick="valida...
Suppose I have an n-high pyramid of numbers like: 1 5 8 2 5 4 8 9 3 1 2 8 3 7 2 How can I algorithmically walk through every possible path from the top of the pyramid to the bottom? To better explain, let me represent the pyramid this way: 1 2 3 4 5 ----------- 1 | a 5 8 | b 2 5 4 | c 8 9 3...
For example, greater or equal to 50 and smaller than 100 (>=50 && < 100) smaller than 10 or greater than 40 (<10 || >40) I have been thinking about how to represent mathematical range in a file and database, the range may be input by non programmer and I need to keep the input simple, but at another side, it also ne...
Suppose in the application, there is a type Teacher and a type Students. A Teacher may have a list of Students. So in design, class Teacher has a field of type Collection of Students (aka List). Suppose I want to register (insert) a new Teacher with his all new Students. I either could make a Teacher object and set its...