instruction stringlengths 34 36.1k |
|---|
Suppose that you see the following pattern in code:
function foo() {
...
var someFlag = false; // Until contested
for/while/if () {
...
// Possibly deeply nested in some non-trivial logic
someFlag = true;
...
}
if (someFlag) {
// Additional processing of some ... |
If an Entity doesn't have an unique ID, we usually use auto increment number to distinguish entities. But sometimes, we have to hand that ID over to people so that they can use it. So using auto incremented numbers is not a good fit for this.
Think about IDs you give to students to distinguish them. In that case, IDs s... |
When writing block code in languages like C++ and Java, people usually argue over whether brackets at the end of a line should have their own line.
if (condition) {
if (condition)
{
However, I have never seen anyone even suggest the second format below. Are the following equivalent, and if so, why have I never seen t... |
Below is a line that handles socket connections in a simple Haskell program.
mainLoop :: Socket -> IO ()
mainLoop sock = accept sock >>= forkIO . handle . fst >> mainLoop sock
The "flow" of data in the function is not consistent: it's left to right when using bind >>= or >> (sequence?), but right to left when using fu... |
I have set of spatial points defined by coordinates (x,y) . I want to find the bounding rectangle of given area that maximizes the number of point inside the rectangle. The obtained rectangle should have sides parallel to coordinate axes.
Please suggest.
|
I am working on a networking project. Where I am creating a dashboard to view real time status (CPU/memory usage, up/down traffic and few others) of multiple routers by calling API request to server which will call another API request to the routers ( Mikrotik Routers, they offer api to do configuration and get statuse... |
I was working on migrating over a project which uses a static logger, and a static email service.
The email service logs emails sent, and the logger service sends an email if there are any logging issues (like DB down, etc.). If the email service fails, it can also log the issue.
If the logger fails, it tries to send... |
I'm part of a development group with 5 teams, total of about 40 developers. We're following the Scrum methodology, with 3-week sprints. We have a continuous integration setup (Jenkins), with a build pipeline taking several hours (due to extensive automated tests). Basically, the development process works well.
However,... |
We are supporting data exchange in JSON, XML and SOAP for our customers.
The bird view of the data flow would be like this
Partner 1 sends request for some data with XML data
Partner 2 sends request with JSON
Partner 3 sends request with SOAP
To have a general approach for all partners.
We have created a file for ... |
I would like to know if the code below is a good implementation of the state design pattern. Everywhere I see the state pattern to hold the context and a change in state doesn't return anything. But in my example below, I return the new state (i.e. North/east so on...). Please review and help.
public abstract class Dir... |
I'm writing a simple web server in Haskell, and putting in a bit of logging. I've got some calls to a logging function in a chain of IO >>=. It all feels a bit manual. Is there a better/more "Haskelish" way?
log :: (Show a) => String -> a -> IO a
log label val = getCurrentTime >>= \time ->
putStrLn ("[... |
I started a job as junior programmer a few months ago. The system we are working on has been in production for ~2 years. I wasn't involved in the begging of the system and the design.
One thing I have noticed is that the system major version is already 11.Y.Z. Form my experience working with other systems and libraries... |
Are there useful programs that don't take inputs such as:
A user's keyboard input;
an interrupt from a clock;
data from another server etc.
A program that computed/printed out predefined data could be turned into a file, right?
|
I'm working on a PHP app, using three main branches: 'master' (current stable release), 'bugfix' (for patches) and 'next' (for next minor version).
We store the current version number in the code - it's used for a few things including checking for updates to the app, and also simple cache-busting for CSS/JS files (like... |
I've got a relatively high-traffic public-facing product-based website backed by SQL Server as the point of authority. It has some search capability on some of the columns of the Items table (year, color, that kind of thing), and then a need for a full text search on the Description column (also in the Items table, ea... |
I'm trying to process XML files that are too big to fit in memory. They range in size anywhere from dozens of megabytes to over 120GB. My initial attempt had me reading the files as plain text, in chunks of a few thousand characters at a time, and looking for individual completed XML tags in the little String chunks:
F... |
I am using Rust 1.15.1 and, recently, I stumbled over a problem I could not find a straight forward solution for.
When you look at examples using pattern matching they usually destructure the object in the match expression and continue to work with members within that object. However, I'd like to NOT destructure it, bu... |
I'm about to start developing a single page web application that is very simplified a multi user documentation system. The front end will probably use Angular2.
The project has a short deadline, so I've been looking for "shortcuts", i.e. using various ready made services instead of implementing everything from scratch.... |
I have JavaScript object which is converted to JSON and sent every time the user changes some filter for the search (for example, after he clicks the button or select/unselect item in the list). Data gathered through this JSON is filtered and used for building database query. After query is executed, results from datab... |
Problem:
Comments deteriorate when renaming a variable/class/method/etc in Visual Studio. Occurrences of said symbol in comments do not get updated by refactoring (no surprise, how could VS know).
Partial solution:
In XML comments (say, in a <summary> tag), we can use <see cref="..."/> to refer to anything and get it u... |
I'm writing a program that has one class called Driver, which reads audio, sends it through an effects chain and then sends it to an audio output. The effects are created from dynamic libraries (using either LADSPA or LV2 interfaces). So I wrote a class called DriverMediator that manages the shared libraries that conta... |
If you need to access application information from a database for analytics, is it better to copy the information first and analyse the copy or is it okay to analyse the data retrieved fresh from the application database?
|
What are the techniques and technologies that people use to store spatial data over time that performs fast when querying?
For example, you have a map where people add data at certain locations over time. How would you implement fast querying for the data available on a certain date (that date and before) or exactly on... |
Assume I have a modal dialog where I allow the user to change values of an encapsulated configuration through different UI components and I want to save the effort to implement a validation per component or restrict the component models to allow invalid values to be chosen/entered and rather validate the state of all v... |
I have a library in C where the API uses "objects" to interact with the application. These "objects" are opaque pointers that are created, destroyed, and modified via API calls.
These "objects" do not exist in a hierarchy and their lifetimes are loosely managed. As a result, the library has to keep pools of these objec... |
A construct I often use when the list of "things to make a decision on" gets too big to be practical in an if/else or switch statement is to make a table with values and callbacks. For example, something like this (C):
struct keymap {
int key;
int (*callback)(struct data *data);
int end;
};
...
struct ke... |
I'd like to write an Angular2 application that consumes a REST API backend.
However I'm worried about the number of req/sec that such a request will generate, due to Angular "watches" or equivalent change detection algorithm
Should I limit from the beginning the watches (data binding? change detection algorithm?) to on... |
Here is the scenario where I have difference of opinion with the developer.
We have this module that needs say - a username, password and server-IP-address as inputs from the user. First scenario, if all information is right, the user is able to get the functionality working. Second scenario, if any of the informatio... |
In a web application I'm working on, there are 3 types of scripts (same applies to stylesheets):
Those needed on every single page (e.g. jquery)
Those needed on several pages, but not all (e.g. a lightbox library used on pages which show user uploaded images)
Those needed on a single page (e.g. something specific to t... |
I am working on a team where my mates introduced the service & repository pattern. We work on Lumen micro framework. So from the controller, the call is passed to the service and then to the repository.
We use controller injection. The service and transformer are injected into the controller's constructor. The service ... |
I'm new to DDD + CQRS, and I'm working in a project that has this implemented, but I wonder why the guy duplicates the models.
I understand, that one is for writing (commands) and one is for reading, but both implement the same fields, except that ReadModel only has getters.
Is there any advice against having the field... |
For example, when you submit a Register form, you have to check in the Domain Model (WriteModel in CQRS) that it is in a valid state (example, email address syntax, age, etc).
Then you create a Command, and send it to a Command Bus.
I understand that Commands should not return anything.
So how do you handle an error be... |
Let's say I want to have a function to load a project's data from both a json and a file path, the first idea which comes to my mind would be having a couple of functions such as:
def load_project_from_json(json_data):
...
def load_project_from_path(path):
with open(path) as f:
load_project_from_json(f... |
In my contrived example, I have a rectangular grid of nodes, where each node is either empty, of Type 1 or of Type 2. All nodes are directed to the eight nodes around them (horizontal, vertical, diagonal). For each of the nodes of Type 1, I want to find the distance to the closest node of Type 2. For all points, their ... |
For example, with Spark SQL's data DataFrameReader, you can invoke something like sqlContext.read().schema(customSchema).json(path) where schema function returns DataFrameReader itself with the added configuration of customSchema. Similarly, Jackson's ObjectWriter has with function which returns ObjectWriter itself wit... |
Doesn anybody have practical experience with implementing a (micro)service based on AWS Lambda?
My team is currently working on an MVP. We started with a monolith and that has worked very well. It's a new business domain and we still have to learn a lot about which bounded contexts make sense and where to draw boundari... |
We are implementing many algorithms which typically have lots of shared, publicly known and security-relevant parameters.
Currently, we simply use a class holding all the parameters and two predefined global objects:
class PublicParams(object):
p = q = 0
def __init__(self, p, q):
self.p = p
sel... |
Team can have N users and users can have N teams.
One user can have N answers.
Answer belongs to one user.
I need help to build database structure. Important is to get team record from any answer. User can answer only with one team
|
I'm relatively new to jwt.io and authentication and I'm using JWT.io in following manner.
Server Side
Once user logs in, I generate a token with userid embedded inside and pass it back to the user in the message body
Client Side Browser/JS
I'm storing the token in localStorage and for each subsequent request, I'm passi... |
There is an ongoing debate about the following property, and if it should be tested or not. We're working in C#.
MyClass prop => value;
Should I be writing the following unit test :
IMyClass _viewModel = new MyClass();
Mock value = new Mock<Bar>();
Assert.AreEqual(value, _viewModel.Prop);
Personally, I say YES, becau... |
Background
In our start-ups documentation, we got this:
Difference between a pull request and an issue page
In a nutshell, an
issue page should only include information and discussion about the
issue itself (ie clarifying requirements, suggesting edits to the
requirements etc) It should never include any informa... |
I have built a blogging application, running in several containers that are managed with docker-compose.
Now I'm wondering - how does one run multiple instances of such application on one server?
I'm thinking about two scenarios:
What is the right way to connect my project to the port 80, so I could run it along with ... |
When I first started learning PHP (about 5 or 6 years ago) I learned about Ajax, and I went through "the phases":
Your server returns HTML data and you put it inside a DOM's innerHTML
You learn about data transfer formats such as XML (and say "oooh so THAT'S what it's used for) and then JSON.
You return JSON and build... |
Please excuse the poor example/analogy, I'm only interested in the code sample.
I have a Dinner_Chair class (inherited from Chair class). It is as follows.
Dinner_Chair = class(Chair)
Private
theUser: Person;
Public
Dinner_Chair()
{
Back = new Back();
Seat = new Seat(... |
We are working on one legacy framework and it is continuously evolving.
Problem 1 : If somebody want to run the application with latest code then he/she spend lots of time in doing so (like somebody forgets to commit code or commits partial code).
Solution : We started using Jenkins and integrated it with our SVN repos... |
I am currently working on an algorithm for comparing two list of objects. Something like this:
I have a lists of sales:
class Sale
{
protected $client;
protected $products (ArrayCollection of Product objects with id and amount);
protected $status;
}
And I am receiving an unordered list of SaleProducts li... |
Let's have a simple class, and main method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
bar bar = new bar();
bar.foo("a");
}
}
public class bar
... |
I am working with jQuery like elements from the cheerio library to manipulate SVG images.
These objects represent XML nodes and have a hierarchical internal structure.
I am writing a function (in JavaScript of course ) that visits each child node and, if it is a Basic Shape (ellipse, circle, rect...), calculates a set... |
Backstory
I have an XML type document (SSML, which is used forText-To-Speech), which will be used to generate audio files when ssh transferred to a remote server. As such, I will need to include metadata for the ID3 tags that typically are used in audio files (Genre, Title, Composer, Album, etc...).
My approach thus fa... |
Consider this example of method injection:
static void SaveEmail(Func<string> getEmailFunction)
{
dbcontext.SaveEmail(getEmailFunction());
}
static string GetEmail()
{
var frmUser = GetUserForm();
return frmUser.GetEmail();
}
static void ExampleCall()
{
SaveEmail(GetEmail);
}
In this example, we are ... |
The Scrum Guide defines a single unit that consists of a Product Owner, a Development Team of 3-9 members, and 1 Scrum Master for somewhere between 5 and 11 members. I've seen instances where the Product Owner may have support staff or the team may not have a dedicated Scrum Master to vary that number slightly, but it ... |
I'm trying to design an asynchronous component. Requirements on this component are :
Component might receive events at any point in time
Component might start a long-running operation and wait for its result. This operation is executed by outside system.
Long running operation might be cancelled, either by the compone... |
I have come to a struggle to design invoice generator module in my project. I have following design;
Once an invoice is generated , it will be stored in database. In case user need to regenerate an invoice in the future and if product has been changed (e.g price), regenerated invoice will be different than the origina... |
Let's say I have an application which eventually saves and retrieves it's data to/from DB. For the sake of explanation let's imagine the application deals with students.
I have a complete API that lets me work with business logic classes and seamlessly save/load them from/to the database. So I can instantiate a "Stud... |
I have a table/collection called scores and it has 3 relevant identifiers based on which calculation need to be done.
sample
{
score : Number,
company : String,
zone : String,
unit : String,
timestamp : Number
}
Everyday we get huge amount of data in this scores table which has 3 identifiers. On client side dashboa... |
I'm trying to provide a convention, or standard, for a parent controller to communicate with a directive in Angular.
Basically the directive will have a "settings" object containing callbacks and initial data received from the controller, and an "api" object containing public functions.
I've created a service called "... |
I'm reading about pure-functions in functional programming and am wondering, whether a function being deterministic implies that the function is also side-effect free? (and vice versa?)
|
Say we have 2 Classes: Account and Contact like this:
class Account {
string Id;
string Name;
}
class Contact {
string Id;
string FirstName;
string LastName;
}
An account can contain many contacts. This data is managed in a class "DataManager" which acts as the repository for the rest of the progr... |
I deploying a web scrap server using scrapy. The scenario is a Linux server running mongoDB (or maybe mySQL I'm not sure at all...) and python scripts with scrapy framework.
The main question is what to use to provide data to other servers. I'll try to explain:
I have a delphi app running in another server, the idea is... |
There is an enterprise project, which all the business implemented in databases and in the stored procedures, and web API is just like a light wrapper which get the request and deliver it to proper SQL server sp and return the returned response from SQL server to client.
(except some discussions, and pros and cons of t... |
I am coming more from the web development angle. We build a module, test it and then deploy it. Some people call this last step (deploy) as 'release'. What's the difference? or are they the same things?
|
I'm currently setting up a Jenkins pipeline for a web application and am wondering which methods of deployment are most common or recommended.
Currently Jenkins polls the SCM for new commits and triggers build when there are new commits.
Assume that the build process is:
composer install
phpunit tests
rsync workspace t... |
I am designing a new application that deals with a lot of business logic.
To avoid the usual entanglement between different application layers that often sneaks into such systems over time, I want to implement clean separation of concerns right from the start. Broadly speaking I want to separate:
presentation layer
bu... |
I was hired to develop a custom Qt application for a customer, but I'm concerned about the licensing.
My software will not be publicly distributed and it is going to be used exclusively by this customer.
Do I need to disclose my source code for this customer, if I link my application with Qt libraries, such as QtCore a... |
In our company, we need to do many seemingly not complicated things, like develop Mobile UI.
Let's say the experienced programmers costs us 4x as much as the beginners.
Both are basically able to complete the seemingly simple things in the same amount of time.
The difference is, that the experienced programmers produce... |
I'm migrating my team's app to use NSURLSession instead NSURLConnection's because of the numerous now-deprecated APIs in the NSURLConnection family of classes and protocols. As part of that, we need to decide how often the app should be creating a new session vs. reusing sessions that exist.
Based on Apple's documentat... |
I have a stream of binary data. Assume no prior knowledge about the expected pattern in input data.
The symbols can represent binary data or other symbols, hence hierarchical.
The output should minimize space, but does not need to be optimal. But the algorithm needs to be online - that is, with more input, the represen... |
We're just starting off with using Entity Framework Code First approach and I'm playing with the Code Migrations system.
So we were wondering, are the migration files intended to be treated as generated code and shouldn't be modified or are they supposed to be generated for you as a scaffold and then you can add extra... |
I am building a JavaScript application that makes AJAX requests to a PHP API Back-end to load JSON data for different views.
The app UI consist mainly of a left sidebar menu which has items loaded that when clicked on will create a View for a Right content panel. Like this image...
The left sidebar will have up to 6... |
With the help of AOP, I can remove the logging code from my business logic. But I think it can only be used to log simple things (i.e. logging method entry/exit and parameter values).
However, what if I need to log something in my business logic? e.g.
public void SomeDomainMethod(string id)
{
//Get user by Id
Us... |
Company is new with microservices. Conceptually, it makes a lot of sense, and really describes SaaS applications as the true enterprise grade apps that they're meant to be. I've had applications talking to REST APIs for a long while, so it seems like a good fit.
However, there are concerns with downtime. Specificall... |
I'm currently writing a program to read a body of text and compare it to search-engine results (from searching for substrings of the given text), with the goal of detecting plagiarism in, for example, academic papers.
The two strings being compared are the original paper and the plaintext of the webpage (as returned by... |
So I was searching for a good way in ASP.Net Core to create some "controls" that render into a view. So far I found there are 3 options, and I wanted to get some feedback on them.
ViewComponents: These are like mini controllers and use methods like actions to render from a razor page (view). I believe they can have ... |
Background: I need to render the same information in two text formats. To do this, I have a set of model classes that store the appropriate information. I then need to render that same information in two different ways.
Each model has a list of 'actions'. Different actions have different attributes.
How do I handle... |
What is the best option for sharing DAL code.
We have a nice c# library that wraps SQl.Data.SqlClient methods like .ExecuteNonQuery, ExecuteReader, ExecuteScalar etc. Its adds logging and helper functions around Parameters and generally returns nice pre-polutated IDataRecords. This is boilerplate code that we would lik... |
Background
I'm researching the ability to add some services on top of git web hosts (ie github, gitlab, bitbucket etc, I'm not even sure what they're called, I borrowed that term from the github wiki).
An example of what I'm trying to do is integrating a spreadsheet with one such git web host so that whenever a user a... |
I am using Java, Spring and Jersey.
I have a REST API A which receives a query parameter called q and sends this to another API B to get a response.
I need to implement a change where I first need to pass the query from the client to another API C and use the response from API C to create a new request, i.e. basically... |
Should one make a code change by beginning to refactor at the "entry-point method" or the "inner-most method" of a call-stack?
A colleague and I were talking about a code change that would go through many application layers and touch a number of classes. The end goal was to assign a variable to a SQL table name at the ... |
I am writing a type of Queue implementation that has a TryDequeue method that uses a pattern similar to various .NET TryParse methods, where I return a boolean value if the action succeeded, and use an out parameter to return the actual dequeued value.
public bool TryDequeue(out Message message) => _innerQueue.TryDeque... |
I'm writing a framework that automatically documents applications dependencies in a distributed system, the idea is to produce something close to an UML component diagram of the whole system at runtime.
Components are usually applications or one of the resources they consume (database, HTTP API, file...).
Each compon... |
I'm working on a piece of code processing loads of messages and passing these to another service. This process may fail, resulting in a faulted reference to the service. Whenever a failure occurs, the message accepting code should continue to accept messages, but just discard those for a predefined period of time after... |
Let's say we have a rather large project written in Python using the Django framework that is made up of multiple modules (proper term in Django is a project made up of multiple apps, but for the sake of generality we will use the term "modules"). This is to achieve low-coupling for easy maintainability (among other ad... |
I'm doing a code review at the moment on Java Android code. I am looking at a function where a programmer has decided to use a switch statement to wrap a single condition.
I am considering making a comment that this should be an if block instead. What are your thoughts, what would you do if you saw this in code?
It loo... |
I'm concerned about floating-point determinism and the fact that different CPUs have different implementations of FPU operations such that the same C++ code will have different results when compiled and run on different machines.
How can I test my code on other platforms (i.e CPUs) without having to physically buy new... |
Backstory
I'm a newer developer and have just started on this project and I've been trying to avoid copy-pasting code wherever I can and make the page be built as dynamically as possible, so that when someone comes along and wants to add features here or there, they don't have to add code into 20 different places. So f... |
I know that transactions use locks. It is claimed that actors liberate us from shared state and locks
make sure all crashes are the same as clean shutdowns: this can be done through practices such as shared-nothing and single assignment (which isolates a process' memory), _avoiding_locks_.
Is the Actor Model an alter... |
I have traditionally not utilized much of other peoples code libraries in my code, but now I am starting to use open source projects more, and am needing an efficient way to understand quickly how to utilize their methods, classes, and objects. What are the best practices used to accomplish this most efficiently?
La... |
Looking for resources that teach multithreading in Android and list best practices. I want to do some image processing on the preview frame of the camera (already have this part set up) but want to parallelize the processing. Results from the async processes should come back to the main thread and update the UI.
I'm c... |
I have a number of visual studio solutions and projects (many projects may belong to multiple solutions) that I would like to add to Visual Studio Online (GIT Version). An example would be:
Solution 1
Project A
Project B
Project C
Solution 2
Project B
Project C
Project D
Should each Solution be created as a Projec... |
I’m working on a proof of concept for a personal project and am unsure how to go about handling ‘permissions’ on content that is uploaded into the application.
Problem:
In this application users will be able to upload media/files onto the web server. Some content will be public, some content will require the user to b... |
I can find many questions about libraries to use for representing amounts in some currency. And about the age old issue of why you shouldn't store currency as an IEEE 754 floating point number. But I can't seem to find anything more. Surely there's a lot more to know about currency in real world usage. I'm particularly... |
having a bit of trouble getting started with this problem, and not much luck googling solutions.
I can't use MS Project to display gantt charts, so am wanting to use VBA to draw a pretty gantt chart in Excel from an Access database of tasks, time to complete task, preceding tasks, etc. I know VBA, but am having troubl... |
What strategy would you use to detect memory leaks?
I was asked this question in an interview that was mostly focused on C++, and couldn't find an answer. I said that there are tools that do it and that I would use them, but that wasn't sutisfactory, and I had nothing else I could think of.
When I searched later for an... |
I have a custom non-blocking I/O server that supports (among other things) HTTP and websockets.
I have two timeout concepts for connections:
idle: connections that don't do anything are closed after (by default) 5 minutes of inactivity
lifetime: connections that are older than a certain age (1 hour by default) are kil... |
I have an ASP.NET MVC 5 site.
I have several complex view models - usually subsets of a far larger model. Should I create items in the repository that take the ViewModels - then just use Dapper.net to map them to some SQL?
If not I would have to map the ViewModel to the Model somewhere. I can then use the standard Mode... |
I want to set up basic "permissions" for a website. It has a basic "roles" system where users are part of certain groups and get all the permissions allowed to that group. However, I need more than just a basic Role, Permission, and Role_Permission setup because I want to allow for specific exceptions - certain users m... |
Is it possible to submit a pull request if I originally cloned a repo locally rather than using the GitHub "fork" functionality??
The scenario is that I have created a local clone of a repository and made some changes. I would like to submit these back via pull request. I can create a repo on GitHub and push my changes... |
I'm currently working through Robert Sedgewicks "Algorithms in java" (3rd edition, german) on my own and am currently at one of the more complicated questions there. I think I may have the starting point for a solution, but I'm not sure if its really the best way to go.
The exercise (translated):
Create an abstract da... |
There is a software component Processor that processes objects Item in a dedicated thread. Item may be processed multiple times (more specifically, it's a timer object).
One of the fields of Item is a pointer to BaseObject. So all derivative classes of BaseObject (for example DerivedObject) can reside in Item. Item in... |
I am frequently writing parser and mappers of some sort. This means that the switch statement gets used a lot and often many if statements for checking for valid input.
This of course creates a lot of cyclomatic complexity. I usually split out value parsers. So I have some data format and I have to convert/map the data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.