instruction
stringlengths
71
71.9k
I am trying to create a simple library for C to handle OpenGL matrix operations. You can see the vec3fscalar here. #ifndef __MATH_MAT4FSCALAR_H__ #define __MATH_MAT4FSCALAR_H__ #include "vec3fScalar.h" typedef struct mat4 { double m[16]; }mat4; mat4* newMat4(const vec3f *c1, const vec3f *c2, const vec3f *c3, con...
The task is to build a WinForm app which populates a tree from 3 different data sources and shows its content. 1 ComboBox at top - to choose datasource. (File System, XMLFile, SQLDB) 1 Button next to ComboBox - to select datasource path. (Or Connection String) 1 TreeView Control at left - to show tree. 1 RichTextBox t...
I am writing a C++ library which will interact on files, memory buffers and remote files accessible with the HTTP protocol. To handle that, I've decided to create some classes that will use the following interface: DataStreamInterface.h class DataStreamInterface { public: virtual bool open() = 0; virtual void clos...
I need to resolve "multiple paths" specified like so: p1 = 'item.element.[compact|fullsize].documents.[note|invoice]' A list like this is expected: ['item.element.compact.documents.note', 'item.element.fullsize.documents.note', 'item.element.compact.documents.invoice', 'item.element.fullsize.documents.invoice'] Cod...
In one of my object I needed a sequence I would use to increment an Id field just like we often do with classical databases. As I have not found a suitable solution, I wrote one. This solution uses objectify. The first approach I came with was to have a class with a static AtomicInteger field like this: public class My...
I have been learning C++ for the past few weeks, and I made my first try with policy classes. Ultimately my goal is to use policy classes to manufacture wrapper classes on an std::vector. Part of what the wrapper class does is generate a custom allocator class that depends on the policy classes. That's the inspiration ...
I am trying to do a cross-database query without having to enumerate the variable t. public List<Models.MCMessageCenter> GetMsgCtrsWithReloInfoByUserId(Guid userId) { var t = GetMessageCentersByUserId(userId).ToList(); List<Models.MCMessageCenter> result; using (var ctx = new TEDREntities()) { ...
I want to implement a wavefront-reader in Java. Therefore I've created some classes to extract a Vector3f and Vector2f (I use JOML for these model classes) or a Triangle (my own model class) from a certain line of a wavefront (.obj) file. I only want to read a special wavefront file (not all types) and only some certai...
Following Pimgd's question, I decided to take a look at the TIS-100 myself. This is my solution to the 3rd challenge, building a differential converter. Requirements: Read values from IN.A and IN.B Write IN.A - IN.B to OUT.P Write IN.B - IN.A to OUT.N Instruction set: I got the basics down, but I'm doing some...
I have a C++03 library with lots of classes. I'm interested in trying to take advantage of Rvalues and move semantics under C++11 for two or three critical classes. Once of the critical classes is a SecBlock, which is effectively a secure array class. It has a secure allocator and deallocator, and its used nearly every...
Recently I started to learn Haskell. I did this by making exercises on the Internet. The problem of making these exercises is that I never know if I solved it the correct way. I currently wrote a function which I think looks really ugly, but I don't know how to improve it. I hope that someone could give me some tips to...
As a beginner, I tried to implement TicTacToe in Haskell. How can I improve my code? I have refactored my code: General TicTacToe in Haskell Utils module Data.List.Utils where import Data.List (intersperse) surround :: a -> [a] -> [a] surround x ys = x : intersperse x ys ++ [x] nth :: Int -> (a -> a) -> [a] -> [a] ...
I found some Python exercises that were made by Google in their Python classes and decided to spend some time with them. Given the following description: E. Given two lists sorted in increasing order, create and return a merged ist of all the elements in sorted order. You may modify the passed in lists. deally, the so...
I am trying to write a Haskell application that parses a bunch of complex numbers from a Mathematica output and then produces a PPM image. The end product looks like this: The code to create this is as follows: module Main where import PPM import System.IO import Control.Applicative as A import Control.Monad.ST impor...
I have two links in my header: Register Login I am not creating it dynamically. If the user clicks on "login," the login form will be visible, similarly for the register form. My registration: <?php include 'configdb.php'; global $connection; if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['email']) &...
I have a working solution for 'Cut the tree' problem but it is not fast enough. Problem Statement: Atul is into graph theory, and he is learning about trees nowadays. He observed that the removal of an edge from a given tree T will result in the formation of two separate trees, T1 and T2. Each vertex of the tree T is...
After optimizing my function which I plan to use in Project Euler 95, I've run into a wall concerning further improvements. This code is destined for my library of project Euler functions, so while readability is nice, it definitely takes a backseat to performance. I have verified that the output is correct by non-rig...
Can I get some help on shortening the amount of code I have in this program? import requests import gzip import sys import urllib from tabulate import tabulate from bs4 import BeautifulSoup from io import BytesIO # firstly it will display a list of movies, the user will then type in the torrent they want to download ...
I am aware that the malloc is a potential memory leak, but with an execvp coming, and that never returning. The purpose is to do something like: daemon my-blocking-program arg1 The idea is to daemonize ourselves, null stdin/stdout, and then execute whatever program was specified in the arguments. This is very similar ...
Just came home from a vacation, and I have a bunch of GoPro videos that I want to compile into a fun music video. In order to support this process, I wanted to write a script that would take all my videos and create a 'summary' thumbnail collage for each video. The idea is that it'll allow me to skim through my videos ...
I am using the function inputSetup to prepare an array for a multi-select directive. I am passing in an array with the existing selections ($scope.item.categories), an array with all the available categories, and a string the carries the context of the values "category". Formatting the array to add the value "ticked" ...
I have n numpy arrays which all contain time series data for t periods. It is not an option to instead have one nxt matrix. I am storing all these arrays in a ResultSimulation object. I seem to have repetitive code, which I am wondering how to shorten. It starts with ResultSimulation.v0 = ResultSteadyState.v0[::-1].cop...
I have a Mapview which shows a bunch of locations (Events). Here's the code of an Event object. class Event: NSObject { var latitude: CLLocationDegrees! var longitude: CLLocationDegrees! var coordinates: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude...
I decided to take a more general approach while implementing the TicTacToe game in Haskell. Util module Data.List.Utils where import Data.List (intersperse) surround :: a -> [a] -> [a] surround x ys = x : intersperse x ys ++ [x] nth :: Int -> (a -> a) -> [a] -> [a] nth _ _ [] = [] nth 0 f (x:xs) = f x : xs nth n f ...
This program creates a text index of 3 different files in Python. While this works correctly, I am still a beginner in Python. I used a list of class objects. Can this code be further optimised? class ListNode : def __init__(self,w,docslist) : self.word = w self.docslist = [] self.docslist....
This is one of my very first jQuery plugins. In short: it makes a slider out of an <ul> list filled with <li> items containing <img>s. Just follow this JSFiddle link to see it in action. I therefore wanted to know if there were any flaws in my code. I would like it be reviewed by anyone who would be willing to let me k...
Problem Statement: A DOTA game has N heroes, each with a distinct rank from [1..N]. In DOTA every formation is characterized as a permutation [1...N] of ranks of players. A formation is Imba when the sum of ranks of every two consecutive players is less than or equal to (N+1). Given N, you are to print the le...
The scenario question: "I'm having difficulties with splitting a single row into two individual ones." My test schema is: CREATE TABLE T (id int, old varchar2(24), new varchar2(24)) ; where old and new are strings that need to be split, an example row: INTO T (id, old, new) VALUES (14, 'L-D / T-...
I'm trying to build a simple server software for training purpose, most likely a IRC server, but I'm not there yet. I'm currently implementing a TCP socket class, to ease the use of the C socket API. It uses the addrinfo struct and getaddrinfo() (which add some constraints). TcpSocket.hpp #ifndef TCPSOCKET_H #define TC...
I'm using a one-dimensional array with length \$W(\text{weight capacity})\$. Is this is any better than the solutions with a two-dimensional array \$W, n\$ where \$n\$ is the number of items? I'm looking for code review, optimizations and best practices. class Thieves: def __init__(self, details, items): s...
As a beginner in Go, I'm seeking feedback on a web framework middleware I wrote up. I reckon that knowledge of the web framework is not needed for the code review. The goal of this middleware is provide an easy to use library to sign requests received by the web framework. Effectively, there should be a prefix in the A...
I've refactored the previous version of my local source control, and revised a few things. It's mostly the same, but there are a few minor differences, like the argument separator, one new command, and (hopefully) cleaner code. How does it work? Each "project" written with this has a specific file structure that looks...
Previously, I wrote the following code: bool Line2d :: IsOnLine(Point2d & point) { double dx = end.x - start.x; double dy = end.y - start.y; return (((point.x - start.x) * dy) == ((point.y - start.y) * dx)); } double Line2d :: GetSlope() { double dx = end.x - start.x; double dy = end.y - ...
The function below implements safe multiplication of two 64-bit signed integers, preventing overflow from occurring: // Multiplies two 64-bit signed ints if possible. // Returns 0 on success, and puts the product of x and y into the result. // Returns 1 if there was an overflow. int int64_mult(int64_t x, int64_t y, int...
One of the biggest pain point in the entire rubberduck code base, is the way commandbar menus and menu items are created and wired up - something needs to be done to straighten that up, and while I was refactoring the App class and got to the point where I needed to address the dependencies of RubberduckMenu, I had an ...
I have been working a simple 2D Game using C# language with OpenTK (OpenGL wrapper/binding for .NET). It uses a lot of sprites. Since it uses lot of sprites, I think it's important to make everything implemented properly in order to prevent performance loss and gain more performance boost. Also, I take care of the comp...
I am practicing LinkedList problems. How do I make it production level code as is mostly expected in a coding interview? Any other Suggestions? package LinkedList; /** * @author Amogh Antarkar * @email antarkar.amogh@gmail.com */ import java.util.*; public class LinkedList{ public static void main(String[]ar...
I'm working on a rather large SharePoint project that's going to contain helper classes for a variety of item levels (sites, webs, lists, items, etc'). When writing code I'm expecting that the same site and authentication will span across multiple contexts (as in you might use a list helper, and then an item helper wit...
Problem Statement (HackerRank) You have a list of integers, initially the list is empty. You have to process Q operations of three kinds: add s: Add integer s to your list, note that an integer can exist more than one time in the list del s: Delete one copy of integer s from the list, it's guaranteed that at leas...
Oftentimes I find myself using context inside threads, multiple times. The problem is that I do not want to hold a long-lived strong reference of it in my threads to avoid leaking it. I keep a weakReference to it in global space and when my activity dies, it will obviously not prevent any GC events or such. I have made...
I've created a single page web application (that should work offline, without a database, etc.) using bootstrap and JavaScript to act as an Euler question viewer (text only). It simply renders the text taken from the text file (http://kmkeen.com/local-euler/project_euler.txt). How it works: Content of the text file is ...
Here is the source of the question. The solution on GitHub. Revision 1. Revision 2. Revision 3. @200_success' suggestions from revision 3: The iterator's next() will throw a NoSuchElementException if we run off the last element of the list while iterating. Iterator.remove() is implemented. The implementation of Singl...
I'm sharing this REST API controller code in order to make it work better, also, to become a better developer. I'm having this issues with the application that API handles and I also need to improve code for make it work faster and better. This is the code is being used more then applicationg starts to increase memory ...
I’ve been dabbling in Clojure by solving programming puzzles. This particular puzzle is from HackerRank, with the objective of figuring out how much chocolate one could eat given three parameters: The cost of a piece of chocolate How much money you have The candy shop owner will give you a free chocolate for x number...
Honestly, it should be an incredibly simplistic function, yet it has become the following atrocity: function rotate(arr, n){ // step 1: pick n different elements in the array var allIndexes = []; for(var i = 0; i<arr.length; i++){ allIndexes.push(i); } var pickedIndexesToRotate = []; var valuesOfPicke...
Can you please tell me how to improve this code? <?php include 'configdb.php'; if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['email']) && !empty($_POST['password'])) { $getUserData = getUserByEmail(); if (mysqli_stmt_num_rows($getUserData) > 0) { die( '{ "stat...
Here is my game logic: Tic Tac Toe - player Vs player Player A (first player to enter his name) is getting 'O' and is starting Players choose the desired spot to put their sign(X or O) using the arrows keys and pressing enter Possible to change the board location via a menu Possible to change the score area location v...
I have working code that uploads and resizes images. What im trying to figure out is how I can direct the browser to another page or view kind of the way facebook does, but still call the resize function in the background. Right now, the code waits to complete the resize before doing anything else. The Call to the upl...
I created a 2048 game clone in Java. However, I am only writing the fundamental algorithm for the game such as the movement, the losing condition, and the algorithm to generate a new tile. This algorithm should be generic enough to work not only on 4 x 4 grid, but also on any size of square grid. Any review / feedback ...
Problem Statement Shil, Aditya and Utkarsh go to a candy shop. There are N candies present in the shop, which are indexed from 1 to N. All three of them select one candy to eat. However, a candy tastes delicious if and only if, the index of candy chosen by Shil is strictly less than the index of candy chosen by ...
I have two functions, a collection of possible error codes, and a unit-testing framework. The parsing of a character into its unary prefix and payload is handled by a few named functions and macros nlz, nlo, lsb and msb for counting leading zeros or ones and generating masks of ones on the right or left. The nlz functi...
I've just converted a class for versioning Couchbase documents from Java to C#, but I'm not 100% familiar with the Couchbase API so would like some feedback. The original class can be found here. Update I'm specifically looking for help in the areas of what exceptions are thrown and where should I be checking for them?...
I'm trying to implement a small full-text search in Ruby. I feel like I've laid down the foundation but I've encountered a blocker that has gotten me thinking that something with the design is incorrect. The general concept is that a Document is the basic unit. Multiple Documents form a Collection. The InvertedIndex ta...
I wrote a neural net, and a Trainer class that automates training the net using a training set; a set of input, and the expected output value. Originally, I was just returning currentError from train to be the highest error so far in the training routine. Obviously though, currentError isn't actually the worst error, a...
I'm trying to toggle a dropdown box that will appear and disappear upon clicking the button. var clickState = false; $("#show").on("click", function() { if (!clickState) { $(".animated").removeClass("off"); renewElement($(".animated")); $(".animated").addClass("on"); clickState = true; } else if ...
I made an attempt at a menu, that comprises of just replacing <div>s by showing and hiding. Kind of like a drill-down technique. I have the feeling that it is extremely long-winded. Can anyone offer a cleaner technique? $(document).ready(function () { $('.first').show(); $('.second, .all, .seventh, .sixth').h...
I've completed the "Sequence Counter" level of TIS-100, but this is horrendously inefficient. My cycle counts are at about twice the minimum possible according to the charts: I'm not really as concerned about the other metrics. I struggled to figure this one out. And there's definitely bits of my code which I know l...
I have created a DLL library that controls an robotic arm. Could you tell me if my design is correct? The robot communicates over serial port. The code works but I would like to receive a feedback regarding the design as I don't have enough experience. Robot (uArm) is moving cards from one bin to another. I have the fo...
I know this might be a relatively large amount of code, but I'm just looking for any improvement, big or small, on my coding as I can. As part of my self-study in programming, I decided to make a calculator in Java Swing with MVC in mind. The calculator will be capable of handling lengthy sequences of different operati...
I applied for a job as a C#/.NET Junior Developer, and had a test to do:: Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this valu...
I'm trying to learn more efficient coding so I'm doing some challenges. I have a challenge where I'm given some hex data. I know that hex data is XOR encoded with a four character long ASCII key. The only thing I know about the clear text data is that it contains "a lot of '#' and space characters". I don't know what t...
Each field is prone to throw an exception if not found. If one element not found, then the next should be checked. I have put each element in a separate try/catch. Is this a correct approach or can it be optimized? def getLinkedinDetails(self, gearman_worker, gearman_job): driver = webdriver.PhantomJS('/usr/local/b...
Please review my code and tell where I can improve my program. #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #define BUFFER_SIZE 1024 #define TOKEN_SIZE 32 #define TRUE 1 #define FALSE 0 int isKeyword(const char* token) { const char keywords[32][20]={"auto","break","case","char", ...
During the past few days, I have written a small C++14 library which mainly provides the cppsort::sort function. It is designed to efficiently sort small arrays when their time is known at compile time, and to fall back to the standard library std::sort otherwise. While I am rather confident that the new sorting method...
I am creating instance of the same object to populate its properties twice. I need to give this object to another developer who just don't need constructor at all, as he is sending me object through WCF service. var a = new Earth(); a.ID= 11; a.UpdateUniverse= true; a = new Earth(a); // use age and Taxrate to populate ...
- INTERRUPT HANDLER - > READ FROM IN.1 THROUGH IN.4 > WRITE THE INPUT NUMBER WHEN THE VALUE GOES FROM 0 TO 1 > TWO INTERRUPTS WILL NEVER CHANGE IN THE SAME INPUT CYCLE I was stuck on this one when I went to bed last night. But of course, like any good programmer, sleeping is when I get most of my work done. M...
I have added the full code of my current Gmap component, which is a convenience object to abstract Google Maps functionality: define(["jquery", "gmaps"], function( $, Gmaps ){ var CompGmap = function(){}; CompGmap.prototype.makeGmap = function( el, params ){ return new google.maps....
Having answered this question over on Programmers.SE, I found myself wondering how much effort it would be to write a descriptor that can automatically figure out what the 'destination' attribute would be, e.g.: class Demo(object): foo = Something() would redirect access to the foo attribute to _foo by default. T...
In order to perform form validation, I have created a custom object: define(["jquery", "validate", "activities/new/common/components/BaseFormdata"], function($, Validate, BaseFormData){ var FormData = function(options){ this.defaults = { name: "", privacy: "", ...
I have made my first program that draws a colored rectangle on-screen. I want to know the best practices of making OpenGL and GLSL programs. #include <GL/glew.h> #include <SFML/Window.hpp> #include <iostream> #include <string> #include <vector> #include <stdexcept> #include <cassert> #define GLSL(src) "#version 400 co...
I've created a UserControl that should act as a control inside a Window: XAML: <UserControl x:Class="MyApplication.UserControls.DateTimePicker" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:conver...
Imagine you have a series of n points randomly generated in a box in 3D space. You also have a list of distance bounds, e.g. points 5 and 3 should be between 1.0 and 2.0 Angstroms apart. There are various methods to get from random coordinates to a solution that fills some or all distance bounds. Below is an implementa...
Is it okay to return IEnumerable<KeyValuePair<string, string>> from a private method instead of returning a read-only dictionary? This allows for shorter/simpler code. Note: In the below code, PropertyDictionary is a static property that returns an IReadOnlyDictionary<string, PropertyInfo> that was created through refl...
Recently, I have started to enter the realms of embedded systems programming. And, as my first major project, I thought I'd do the obvious: FizzBuzz. However, this is a little different: this is a game. Like my FizzBuzz Challenge, the user must enter either Fizz, Buzz, FizzBuzz, or the number itself. Here is the genera...
This code works and does the job, but it's poor, rudimentary and has some issues with the scrolling event. Can somebody help me to optimize the scrolling event? Prototype Structure and desired behaviour: There are two containers, .layout__left (red) and .layout__right (green). The green container will have the main co...
I use PDFminer to extract text from a PDF, then I reopen the output file to remove an 8 line header and 8 line footer. Is there a more efficient way to remove the header/footer, either in place or without re-opening/closing the file? Please mention general best practices I did not follow. # convert PDF to text def writ...
I am interested in removing leading/trailing whitespace in a .csv file, and I was wondering if there's a better way to execute this: with open("csv_file.csv", "rb") as infile: r = csv.DictReader(infile) fieldnames = r.fieldnames #Creates list of fieldnames for row in r: for f in fieldnames: ...
I got bored and started making a game using HTML5, CSS3, and JavaScript/jQuery. I've been working on it for about 2 weeks and it was running pretty well. Today I opened it and was moving the player's ship around the screen and noticed that it became very slow as the game went on, starting at 10 seconds after the page ...
I want to know if my code is good, with reasonable efficiency, and if it is possible to improve my code and how. What would you suggest? import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class FindAllPermutationsWithRepetitions { public static void main(String[] args) { Stri...
Just wanted to run through my PHP session handling and get some feedback and tips with regard to what is good (if anything!), what could be better and what is either plain wrong, or using out of date methods. Just as a bit of background, I have only ever dabbled with PHP (and many years ago that was) and want to try an...
I would like to create two date formatters only on first call. In Objective-C I would use dispatch_once() but now working in Swift. Am I doing it correctly? My code is based on example that was using class instead of static but it looks like it's Swift 2.0 doesn't support it yet. class HomeContentItem : NSObject { ...
I'm having a hard time rewriting this method to something more legible and understandable for the reader. static Stream<Class<? extends MyType>> collectMyTypes(Object o) { return Reflection.lineage(o.getClass()) .flatMap(c -> Arrays.stream(c.getDeclaredFields())) .map(Field::getGenericType) .filter(...
This code simply receives a very basic 'password' (numbers, letters, nothing fancy). After you press enter, it will display it back. The only special key I'm handling is backspace (code 8 in ASCII). uses crt; var pass: string; key: char; len: integer; begin clrscr; key := chr(0); pass := chr(0); write(...
I have a Python class for which I'm often going to want an instance with the default arguments, but I want the class to allow creation of instances. For brevity I'd prefer that the default instance be accessible as a property, so that it can be accessed without a method call. However, the code to achieve this in the wa...
I'm working on a script that focuses on faster mousing. It has hotkeys to: snap the cursor to hard-coded locations, swap the cursor to the location where it was last swapped from, and save and snap to custom locations. I've been steadily refactoring with an eye to DRY and other principles. For example, the script us...
I'm writing an Python application that uses frequently datetime and Unix timestamp. I know Python is 'batteries included', however, I found that converting between datetime and timestamp in Python 2.6 is not trivial. That's why I wrote this utility class. This code works as expected, for Python 2.6, 2.7, and 3.4. I wan...
I'm trying to parse Double from String in Java. The string input is not necessarily a number, any non number input should be treated as 0. Given below is a solution using try-catch, where a Array of string is converted into a Array of Double: public static void main(String[] args) { // Array of strings to be parsed...
I am working on a payment process. Upon a successful payment process, I have to create multiple records. For that, I have made this class: class DatabaseMaintainer def initialize(merchant, card, payment_method) @merchant = merchant @card = card @payment_method = payment_method end def maintain_recor...
I have the following two unsafe methods that I would like to refactor: public static unsafe void UnsafeMethod(byte[] array, int pos, short value) { fixed (byte* numRef = &(array[pos])) { *((short*)numRef) = value; } } public static unsafe void UnsafeMethod(byte[] array, int pos, int value) { fi...
Here is an attempt to extend the Kadane's Algorithm to return the sub array itself instead of the sum of maximum sub array. This must work irrespective of the original array having all positive or negative numbers. public class MaxSubArray { public static void main(String[] args) { int array[] = {10, -9, ...
Following-up on CommandBars, Buttons and Commands: Cleanup is on the menu, I decided to try a more ambitious approach, as suggested in Nikita's answer. It works, but there are a number of "gotchas" that I'm not sure how to clean up. So I have an ICommand interface, and its generic counterpart: public interface ICommand...
A while ago I've written a custom validation method for .validate(). It is a local validation plugin, with some limited validation. I was required to write a validation method with the following requirements: Must accept a custom string. Must allow a maximum value. Must allow a minimum value. Has to allow to have dyna...
I'm receiving an language string out of an PHP file which returns an array like this: DIR_LANG\en\home.php: return array( 'welcome_string' => 'welcome @ home! ' ); And my Lang class: <?php class Lang { private static $langArray = array(); private static $lang = DEFAULT_LANG; public static func...
I want to make my code more efficient by instead of repeating my code again for level two, as the only change from level one to level two is the random numbers change from 1-10 to 1-100. I think I can make these a variable making max_number = 10 for level one and max_number = 100 for level two and use the same code, ha...
This code adds the toggle functionality for mobile devices. So, for width lower than 990px, the panel collapses, and the user can toggle to open / close it. angular.module('app') .directive('ngContentToggle', function($window) { return { link: function(scope, $element){ var w = angular.element...
In order to reduce redundancy in my app, I have added the method self.find_or_keep(object) to many of my models in order to find existing records with the same values, so I can reference the already existing ones instead of creating new records. Basically, this method checks most attributes for equality between two obj...
The idea for the code I have written came about due to the acts_as_versioned gem which automatically nests a Version class onto an ActiveRecord model. I wanted to use this same type of concept where a class has a companion class, however, one drawback of the gems implementation is that sub-classes don't get their own ...
I am testing the WIFEXITED to see if a child process exited abnormally or normally. According to documentation, it should return a non-zero status for a child process that terminated normally. #include <wait.h> #include <unistd.h> #include <iostream> #include <sys/types.h> int main(int argc, const char* const* argv) {...
I'm working on an PHP application that will allow (but not require) chunked file upload (from jQuery File Upload on the front side). I tried to find appropriate code and was only able to find the example from the JS library, that is, in my opinion, too bloated (it includes image resizing, etc). I made my own, really ba...
I wrote a simple dll which is able to calculate all common holidays, but, I would like to optimize the code in readability and flexibility. Federal state public enum Bundesland { BadenWürttemberg, Bayern, Berlin, Brandenburg, Bremen, Hamburg, Hessen, MecklenburgVorpommern, Niedersach...