instruction stringlengths 34 36.1k |
|---|
I'm currently developing my first game in Java language.
The game is an endless runner with obstacles to avoid and enemies to kill. Unfortunatelly im still not experience enough and many times im just improvising. I have no idea if my method of loading of obstacles is good or bad in terms of performance (how fast a ga... |
I am working on a web application for ranking some products based on some factors.
The user send a search query to 5 restful webservices which by their turn send a response in a JSON format and sometimes in an XML format (responses are not structured the same way, since webservices are different) . I choosed to reforma... |
I'm thinking that I could simplify my life by making an exception handling class that I can just ship all exceptions to and it will handle appropriately.
Ideally:
def dostuff():
try:
dothis()
except Exception e:
Handler.handle(e)
To avoid
def dostuff():
try:
dothis()
except ValueError e:
#handl... |
I have a state machine like code, which has state A,B and C, with a function changeState(char i) which can change the state of a system, and each state can also call changeState(char i) to switch the system to another state:
struct State{
State(char aName){
this->name=aName;
}
char name;
};
void ch... |
I have a Node.js server using PassportJS that uses social login via Google, Facebook, and Twitter.
The Node.js server hosts an API that uses the PassportJS middleware to authenticate routes and securely serve the data. The API exists to serve an iOS application which will be where the user "logs in" through Google, Fac... |
We are 4 developers working on a PHP-mySQL web project. Currently we work together as described below:
All project files except DB is hosted at GitHub
All project files except DB is hosted at GitHub
DB is on our production server
We have local web server and php installed and working locally, connection to DB is remot... |
Assumptions
One of the advantages of header-only libraries for C++ is that they do not need to be compiled separately.
In C and C++ inline makes sense only if the function is defined in a header file*.
Traditionally, in C, .c/.h layout has been used, where the header represents the minimal public interface of the tra... |
Despite Joel's missive that software rewrites are to be avoided under pain of death, it is still fairly common place. A lot of the existing software is good, but here and there, parts of it niggle, so for a while, you continue along your way.
"You can't polish a turd, but you can roll it in glitter"
So you tweak it her... |
As a user of pip install package and then pip freeze > requirements.txt, I was surprised to see a requirements.txt like this:
# Flask
# License: BSD
# Upstream url: http://github.com/mitsuhiko/flask/
# Use: For API.
Flask==0.10.1
# Flask Scripting support for Flask
# License: BSD
# Upstream url: http://github.com/tech... |
I want to map an integer (let's say 32bits) to a valid path.
The integer is an autoincrement value stored in the database.
I also don't want at any case any folder to have more than N subfolders.
That is because in WIN-NTFS (for example) after a specific number (around 1000) things are going really slow.
So I devised a... |
While designing my first 'serious' C++ library, I'm asking myself:
Is it good style to derive ones exceptions from std::exception and it's offsprings?!
Even after reading
Designing exception classes
What is a 'good number' of exceptions to implement for my library?
I'm still not sure. Because, besides common (but may... |
I tried to use Command Pattern for implementing Undo and Redo in my project
public abstract class Command
{
protected Form Receiver { set; get; }
protected HtmlElement Element { set; get; }
abstract public void ReDo();
abstract public void UnDo();
public Command(Form receiver)
{
this.Rec... |
I've just started learning to program in C, and to improve my understanding of pointers and arrays, I tried to refer to the elements of an array without creating any pointer at all:
for(k1 = 0; k1 < ROW; k1++){
for(k2 = 0; k2 < COLUMN; k2++){
array[k1][k2] = k1*COLUMN + k2 + 1;
printf("[%d][%d] = ... |
We use exceptions to let the consumer of the code handle unexpected behaviour in a useful way. Usually exceptions are built around "what happened" scenario - like FileNotFound (we were unable to find file you specified) or ZeroDivisionError (we can divide by 0).
What if there is a need to specify the expected behaviou... |
We are trying to adopt the microservice approach to our newly developed application.
However, we found that there are too many repos, branches, and releases need to be managed. Originally, we only have 2~4 repos to manage for an application. After adopting the microservice approach, we may have 10~20 repos for an appl... |
So I'm making a bug tracker to help me learn Ruby on Rails. My current setup is something like this:
Each Project has_many :metadata and has_many :permissions, through: :metadata. Also some other stuff, but that's all that's relevant to this question.
Each Metadatum (bad name, I know, but it'll work for now) has_many... |
Concerning normalization of a one to many relationship, I am not sure how to represent a collection with a specified capacity in a database. I can think of two ways to represent an entity A with a one-to-many relationship with B:
When Table A is created with n capacity, insert n rows into Table B. The amount of rows... |
I am very confused about Adapter and Delegation design pattern. In Adapter pattern we bring an intermediate class to interact with another class. And in Delegation pattern we also bring an intermediate class to refer/interact with another class.
|
I've been going round in circles trying to figure out the best way to unit test an API client library I'm developing. The library has a Client class which basically has a 1:1 mapping with the API, and an additional Wrapper class which provides a more user-friendly interface over the top of the Client.
Wrapper --> Clien... |
TL;DR
What are the good practices of iterative search of a better solution?
Well, if I knew everything in advance and could immediately suggest 146% correct solution for a given context, I'd probably be the richest man in the world, but definitely I am not.
Thus some space and time for experimentation is needed.
In ca... |
I have a matrix M with size NxN where each position M(i,j) is an integer representing the relationship between item i and j. If i and j are the same item then the positions M(i,j) and M(j,i) are 0.
What I'd need is to regroup these N items in subgroups of 5 elements each one. The value of each group would be Σ(M(i,j) f... |
Context is a single page app with a rest backend.
For things like state and city lists, which rarely change, is it better to store them on server and load from client, or store them directly on client as javascript objects?
I am in favor of putting them on client to avoid writing boilerplate code (things like when stat... |
I am currently designing some networking code, and this code expects the caller of the code to give it a port and hostname to connect to.
Since I am still in the development phase, I can still change many aspects of the code and more advantages and disadvantages come in for the code. However, some aspect of the code ha... |
I want to mark such methods in my application code with a comment that highlights that these methods are expected to get called by the framework / compiler the application is written for, even if the application code itself contains no calls to them.
F.ex. the methods called by an Inversion of Control framework, like t... |
A common requirement for licenses is that they must be included with the software. Should licenses for testing frameworks with this clause be included if the test code is not something that is being shipped?
In other words: when a library's license asks to be included, is it only with software that directly uses that l... |
Just curious. The most I have ever had was a for loop within a for loop, because after reading this from Linus Torvalds:
Tabs are 8 characters, and thus indentations are also 8 characters.
There are heretic movements that try to make indentations 4 (or even
2!) characters deep, and that is akin to trying to define... |
When FaceBook or Google give me an API key, are they just storing it in a database?
Unlike a password, where you can hash and salt it before putting it in the database, it seems to me that a key needs to be stored as-is (or else in a reversible form) so that they can provide it to me upon request.
My concern is with s... |
I have been looking at Microservices for a while now. The concept is not new but it's communicated in a lightweight manner. So, I am very excited about this.
However, there is a question that I am not sure what the answer is: is each microservice supposed to have its own isolated data storage model completely? Consider... |
in normal php web application after login we use session_id that came from web browser to check if user loged in or not.
But in REST API authentication I read some tutorials that say php should send back authentication "token" for android app to save it and give it back to php server for every request.
my question is w... |
Using a mock instead of hitting a 3rd party API like Postgres or Stripe can often be necessary when writing tests. A problem I've seen is when the API can unknowingly diverges from the data the mocks return. How can I maintain the contract between test data and real APIs? This is a Javascript project.
|
Is it improper programming to set a variable equal to the result of a function that accepts the same variable? The languages in question here are c#, javascript and PHP (not sure if this works in C families, personally).
var a = 1;
a = alterData(a);
|
I need an idea or concept how to reduce http request.
Conditions:
1000s of users(android/iphone) active
100s of small images (150kb/image) to be fetched
Simply by giving each image a hardcoded link, server will have to handle 100 * 1000 http requests.
How could I minimize the requests?
|
I wrote up a site using Mustache to template it. Right now though, the template is embedded in the page, which defeats the purpose of using the template since I'll need to copy it to any other pages that need it.
I read that it's possible to store the template in an external page, then use Ajax to load the template whe... |
There are a couple of answers on SE comparing single-row table vs. name-value-pair table used for config settings, but I haven't seen anyone arguing for using XML (or JSON) as a name-value pair model.
Option A
UserID AppID ParamID Value
1 1 10 5.40
1 1 11 J... |
I understand that programming languages can either be run in a VM (Java, etc) on every OS that supports the VM natively or can be compiled to machine code (C, etc) for each platform.
What I don't necessarily understand is why programs (whether dealing with graphics APIs like OpenGL, DirectX12 or Mantle, or not dealing ... |
Coming from a Java and C# background, I've learned to use int (32 bits) whenever I need a whole number, and double (64 bits) when dealing with fractional values. Most methods from their respective frameworks (JVM and .NET) usually expect these two types.
My question is, why don't we use both long and double for consist... |
The way I've been accustomed to User Interfaces is to see everything as a div. Where a div is essentially a box and they can be stylized in CSS.
<div class='container'>
<div class='header'></div>
<div class='mainbody'>
<div class='someusercontrol'>
</div>
</div>
</div class='footer'></div>
</... |
I am developing a web application which will be run by multiple companies.
Each company will have its own instance of that web application and its own database. The web applications and databases will be running on the same server.
But each of these instances will be talking to one single Web API application to retri... |
I'm coding something that will check a specific static location's directory, and if it exists, and a certain process has not run in n minutes, it deletes that directory's files and all sub-directory files.
The catch is that this directory is constantly being written to. As soon as this service detects a build process t... |
Common sense seems to be that usage of global variables is bad, in particular if they are used as real variables (i.e. changing state; e.g. Why is Global State so Evil?).
How does it come then, that virtually any language I've used so far implements them nonetheless, especially the modern fourth generation (4GL) langua... |
I am looking for an efficient algorithm to find the k'th minimum element in an unsorted array of n elements, where 1 <= k <= n. The obvious thing is to sort the array first, then pick the k'th element, which will result in a running time of O(n * log(n)) But I guess it can be done in a more efficient way, since sortin... |
Although in the code below a simple single item purchase in an e-commerce site is used, my general question is about updating all data members to keep an object's data in valid state at all times.
I found "consistency" and "state is evil" as relevant phrases, discussed here:
https://en.wikibooks.org/wiki/Object_Oriente... |
I am currently working on JavaEE application (Spring, Hibernate). I have to put a big XML file (more than 1 gigabyte) on a relational database (Postgres).
The application does not use batch processing. I've done some searching but I did not find any solution for the design of the DAO layer: if I use only one transactio... |
I like using final variables whenever possible. Often those variables have to be closed afterwards. Note that I'm currently working on Java 6 so there is not closeable interface, but the same applies to later Java versions as well. For example:
final InputStream in;
try{
in=new InputStream(...);
//...
}catch(.... |
I am working on a polyglot web app project that has functionalities that can be separated, but that rely on each other. I am unfamiliar with the following (what key words to even search for, what concepts are in play):
I have a few different sources of disparate data that are separately created/ingested into a data sto... |
I have sometimes the usecase that I need to check if a variable is of a specific type and if so cast to it to access a property/function of it.
Example:
if (state.isInstanceOf[StateA] && state.asInstanceOf[StateA].isFlagBlaBla)
How can this be improved ? I could use match/case but is there a better option (shorter... |
Here is my business rule:
Anyone (anonymous users) can make an Application (as in to apply for something). Applications can be updated until they are reviewed and approved by an officer. Approved applications cannot be updated.
Therefore I created an abstract class
abstract class Application {
//various fields of... |
I started learning AngularJS and ASP.NET MVC, but am not sure why to use them both together in the same project?
Aren't they both MVC frameworks? Should I be using them both in the same application? Isn't it one or the other?
|
In the lecture we are taught that we can solve All Pairs Shortest Path(APSP) with matrix multiplication.
In APSP we are creating a distance table for all the distances between each nodes in the graph. And now the question is "Is it possible to solve Single Source Shortest Path(SSSP) problem with matrix multiplication? ... |
For example:
Only job applications that are not yet in review or approved, can be updated. In other words, a person can update his job appliance form until HR starts reviewing it, or it's already acepted.
So a job application can be in 4 states:
APPLIED(initial state), IN_REVIEW, APPROVED, DECLINED
How do I achieve... |
Here's an example:
I have a chat module in my app, and there's a ChatService class that is responsible for networking, and there's a ChatNotificationService helper class that is responsible for sending out and receiving broadcasts of messages, and there's also a ChatNotificiationDelegate protocol that has methods on it... |
We are developing a REST API which among others is going to be consumed by an HTML5 frontend via javascript. The application is for use within the organization and usually has about 300 users, but we want to scale well up to 1000 users or so.
Normally connections to the API will be made within the LAN so the quality a... |
I know javascript uses duck typing and at first I thought this would make polymorphism easy compared to strongly typed languages like C#. But now my functions that take arguments are littered with things like:
if(myObj.hasSomeProperty())
or
if(myObj.hasSomeMethod())
or
if(isNumber(myParam))
etc.
This is really ugly ... |
In Programming in Scala, there is this statement:
For instance an empty mutable map in its default representation of HashMap takes up about 80 bytes and about 16 more are added for each entry that’s added to it. An empty immutable Map is a single object that’s shared between all references, so referring to it essentia... |
The C++ Core Guidelines have the rule ES.20: Always initialize an object.
Avoid used-before-set errors and their associated undefined behavior. Avoid problems with comprehension of complex initialization. Simplify refactoring.
But this rule doesn't help to find bugs, it only hides them.
Let's suppose that a program h... |
Martin Odersky finished one online course on Scala with an unanswered question:
Can we implement one concept in terms of other ?
Objects in terms of higher order functions?
Higher order functions in terms of objects?
It is clear that high order functions can be implemented using objects but I am not sure if it works... |
Is it considered good practice to have:
Single, general directive that has multiple data-* parameters and serial data is binded from controller
Single, general directive that has config and serial data is from controller
Multiple directives that has some pre-defined config inside directive, some of config is by dat... |
I have created a programming language that is based on java for a personal project. The language already has generic classes and functions and the generics are completely compatible with primitive types (which I decided not to turn into objects, autoboxed or otherwise).
I am currently designing the Standard Library and... |
I overheard a discussion about using timestamps as unique identifiers when storing some data in a database. Person A pointed out that there's a risk of collisions. Person B replied that it's very unlikely to happen with the identifier generation rates at question.
My question is: how likely is it? Is there a way to es... |
I am wondering what is a good, performant algorithm for matrix multiplication of 4x4 matrices. I am implementing some affine transformations and I am aware that there are several algorithms for efficient matrix multiplication, like Strassen. But are there some algorithms that are especially efficient for matrices that ... |
We have the following Git hierarchy structure in place, where each child is forked from the parent. If we build something in Client1 that will be useful in the entire hierarchy, what is the best way to push the changes up to the parents (whether just one level up or all the way to the root), given that we don't wish to... |
Suppose I have a front-end which is mostly a single-page application written using angular, grunt, and bower. And suppose I have a backend, which is mostly just a REST API sitting on top of an ORM, which stores/retrieves objects from a database, using things like grunt, express and sequelize.
The angular application d... |
In many books and tutorials, I've heard the practice of memory management stressed and felt that some mysterious and terrible things would happen if I didn't free memory after I'm done using it.
I can't speak for other systems (although to me it's reasonable to assume that they adopt a similar practice), but at least o... |
I'm working on a REST api following the JSON api specification and I'm struggling with the "no data" responses (described here).
A server MUST respond with 404 Not Found when processing a request to
fetch a single resource that does not exist, except when the request
warrants a 200 OK response with null as the pri... |
After almost 2 years learning how to code (in Powershell) and some help at Stackoverflow from time to time, I'm now finally on my way to release my first GUI project.
I intend to release the compiled .exe of my project plus the .ps1 files at github or similar with the hopes that other experts can help me with tips how ... |
I thought one of the cornerstone of OOP is that, we have objects, which are the items we are interested in dealing with, and then we send messages to them.
So it may seem natural that, I have a collection of items, and I need to put them into one string, so to do it:
["x", "o", "o"].join(" | ") # joining a tic-tac... |
I have a Product class which has among others an attribute Ean13 that encapsulates an EAN13 code.
Here is a prototype of the Product class:
@Entity
@Table(name = "tb_produtos")
public class Product implements Serializable {
public Product() {
}
@Id
@GeneratedValue
private Integer id;
@Many... |
I was researching about Extreme Programming, and started reading a book by Kent Beck called Extreme Programming Explained. There he mentioned practices and principles one of which confused me. It said that iterations must short.
If iterations are good, we'll make the iterations really, really short - seconds and minut... |
As the title says, why does Node not support several event loops in one Process? The idea, is that node spawns a user decided number of threads, which each have an event loop. When a new callback is added, it is scheduled to one of the threads loops. The reason, probably against this idea is because now each thread can... |
I'm creating a client to a third-party soap web service in my application. Here is the way I'm thinking of doing it:
Create a ClientFactory that makes a client based on the wsdl file, and sets needed options on it, then returns it.
Have several Request objects, preferably implementing the Request interface, that take ... |
How should a service communicate with an activity in real-time?
BroadcastReceivers seem too slow and unreliable. Sometimes they appear too slow or stop working entirely. As an example, there was a delay of a few minutes between sending and receiving broadcasts with one of my test applications.
I can't get traditional c... |
I'm trying to append text to a large amount of strings (in the thousands), and also do some other string manipulations.
However, I have about 60 lines of if/else and string appending and it takes several minutes to go through so many lines of text.
It does several checks, but the main part of it uses:
newstring += appe... |
I'm trying to build a web-based SaaS solution, and I hit a road where I'm not sure to use multi tenancy or multi instance. I will try to describe what I'm trying to achieve, and each approach advantages and disadvantages (my opinion, according to what I read). Please include your suggestions in case I missed anything i... |
I'm wondering what the exact definition of the header-field Sec-Websocket-Key is.
The field is used for Websocket connections. The client asks the server to upgrade from HTML to Websocket. The request can look like this:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Ke... |
I own a stateless architecture, exchanging a JWT token between client and server at authentication time.
I want to store in database (once per day) a timestamp related to the user access.
Indeed, I would like to be able to show who was accessing the app, with a margin of 1 day (kind of rather online users).
A... |
I looked at a number of other licensing questions and did not find anything that I felt related to this particular issue.
I am working on a simple web app, nothing special, and intend to license it with the MIT license. The foundation for this app was generated using Clementine.js (here is the GitHub repo). Clementin... |
I was building an application for a few months and I come to realize a pattern that emerged:
logger.error(ERROR_MSG);
throw new Exception(ERROR_MSG);
Or, when catching:
try {
// ...block that can throw something
} catch (Exception e) {
logger.error(ERROR_MSG, e);
throw new MyException(ERROR_MSG, e);
}
So... |
We just started implementing the Git source control for our project and the Admin says we should not be creating any new branches for the enhancements that we are working on instead everybody should pull remote master branch into their machine and make changes and push the commits to remote master branch.
I somehow fee... |
Per MDN
A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.
Based on this statement is it acceptable to call methods in a class ... |
I'm planning on incrementing counters in statsd based of various events within my application. I have logging in place for these events. So, from my viewpoint I have two options:
Update the application itself to call Statsd
Add log parsing (such as logstash) that executes the request to statsd based off matches
I'm l... |
How can a bug could occur on static, fixed input data only "sometimes"? The following is simply an example I have observed, but I am not interested in an answer specific to the GD library.
I have some PHP code to render SVG files, utilizing the GD Graphics library. It often stops working, and no error is given. The str... |
I'm looking for a conceptual approach to a problem.
I'm building a web app that imports data from a source I don't control. The data quality is pretty high, but occasionally, the data does not make sense. So I want to expose the exceptions (based on data rules) to users in a modal so that they can accept the funky dat... |
Reusable code (ex. libraries and frameworks) and code written to solve a specific task and not meant to be reused as a general tool (for example, code being used only by my 6 person team in a private repository) differ greatly in purpose, so I imagine there could be vastly different strategies, best practices, advice, ... |
Business Context of the Problem
Our iphone app allows users to pay merchants and earn rewards.
Users can also do things like:
View transaction history
View their points and available rewards, or claim rewards.
Earn money by referring friends, view a history of converted and unconverted referrals.
View running deals at... |
Trying out a Knapsack variant where the rules are
Any item you take must fit completely in the bag
Usable metrics of the bag are length(l),width(w),height(h) and you can assume that if the products fit into the bag both individually and together by total volume, there is a way to pack them in
Price value must be maxim... |
I'm trying to create a solution for the Closest pair problem using d-dimensional points. I've done a thorough search on google but it seems that there is no explanation for the d-dimensional case apart from what is on wikipedia:
the divide-and-conquer algorithm can be generalized to take O(n log n) time for any consta... |
Is there any standard that says that udp packets must not be combined together by operating system?
In other words can I be sure that when I send small udp packets by sendto or analogues, I will receive udp packets of the same size by recvfrom, if I request length, which is far more than the size any of the sent packet... |
ES6 added fat-arrow functions (=>), which have two major differences from normal functions:
shorter syntax (including implicit return if you use a single-expression body)
inherit this from surrounding scope
These are both very useful features, but seem to me completely separate in their value and application – someti... |
What do you think about code like this:
public class ThisClass
{
// this method uses only public members
public void DoSomething()
{
AccessToPublicMembersOfThisClass.DoSomething(this);
}
}
// EDIT: this class is not nested!
internal class AccessToPublicMembersOfThisClass
{
internal void sta... |
Context : I'm a IT student who is trying to implement a small application for my family. Every year, we offer each other gifts. Each one of us pick a name of a family member in a hat, and have to offer him a gift. The problem is, we always have some problem doing it:
Problem 1: When we pick, sometimes someone pick his... |
I have a class WorkflowItemSearchCriteria whose instances represent a set of values and references that will be used to return a filtered result set of workflow items based on the given search criteria.
class WorkflowItemSearchCriteria
{
string ID { get; set; }
Client TargetClient { get; set; }
Person Super... |
There has been a discussion in chat relating to a question (the question itself being irrelevant to this one), that has revealed I may not know Python whatsoever.
In my mind, although terminology differs across languages, we may generally categorise functions as:
[free] functions
static methods / static member functio... |
I want to know if my implementation is modular and loosely coupled such that pieces can be replaced easily.
Any concrete class that extends the abstract class HexGridLayout will be expected to update the field coords by using the field center of the HexGrid.
Does passing HexGrid to the HexGridLayout break the modulari... |
Since we are becoming more and more reliant on computing, including very critical tasks of day-to-day life, I was just wondering how those vital components are tested.
More technically, how are the compilers and assemblers tested? (I suppose this relates to the halting problem!!)
|
What would be the advantages of using PHP_AUTH_USER and PHP_AUTH_PW instead of the verifying the credentials under method - post .
Why i should use:
$_SERVER["PHP_AUTH_USER"]; and $_SERVER["PHP_AUTH_PW"]
instead of
$_POST["user"]; and $_POST["pass"];
what actual difference does it make ?
what are the advantages an... |
Pretty straight-forward. I'm implementing an interface, but there's one property that is unnecessary for this class and, in fact, shouldn't be used. My initial idea was to just do something like:
int IFoo.Bar
{
get { raise new NotImplementedException(); }
}
I suppose there's nothing wrong with this, per se, but it... |
We are using Java as a backend development language.
We are using a List variable as
method() {
List recordsList = new ArrayList<Record>();
.
.
recordsList.add(records);
.
.
recordsList.flush();
.
.
recordsList.add(new Record());
}
Should we consider Split Temporary Variable refactoring pattern in... |
I have an Asp.net MVC5 application structured like this:
Core
Domain project
Infrastructure
DAL project
Utilities
UI
UI project (contains ViewModel at the moment, will probably put that
into separate project as I expect that application will grow through
time)
It works through Unit of work and a generic repositor... |
I'm maintaing a linter library, so this it's basically a set of rules checked against some code one can pass to it. Say, we have rule A which checks some set of cases.
Now imagine that some commit extends this set - by extend I mean that the cardinality of set is bigger but non of "old" members is gone, we've just add... |
I would like to publish a python module and would like to publish it as the same license of python
Below is a example of how Perl module does:
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
in Python 2.7 license:
(1) GPL-compatible doesn't mean that we're... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.