instruction
stringlengths
71
71.9k
I was just getting some products using entity framework and was wondering which would be better to do when getting the results, or if there is no difference. Option 1 - Query the context directly return dbContext .PPCProducts .Include(p => p.Attributes) .Inclu...
This is my first attempt to model a day's time interval and the fact that the start and end are either inclusive or not: public class UtcTimeOfDay { public int HourOfDay { get; set; } public int MinuteOfDay { get; set; } public int SecondOfDay { get; set; } } public class UtcTimeInterval { public UtcTi...
I have written the following code that achieves my desired goal of converting a "raw" CSV file into a keycoded list. The idea is that a person will get the first product they ask for, and English products are coded as blank because they are the default. This gist contains a sample of the input and output data. As it st...
The assignment is to create a login system secured for SQL injections and XSS. It's in PHP and I'm using PDO with prepared statements obviously. Which from my point of view should protect against the simplest injections at least. The ones I'm throwing at the system are ineffectual. If you believe it's not secure agains...
I have written a PHP function that should round prices to a desired format. E.G. 1547.86456 That should be : 1547.85 OR if desired : 1547.86 The code has been written and it works under several conditions. BUT I wonder if I have overlooked something. AND maybe I have used solutions that could be much easier and less CP...
This script cleans up destination directory and copies file into it with new name. Can this intent be expressed more cleanly with shelly? main = shellyFailDir $ verbosely $ do escaping False $ rm_rf $ webapps </> "*" cp (m2repo </> groupPath </> artifact </> version </> (intercalate "-" ...
This is my first program on my second try to learn haskell :) import Data.Maybe (mapMaybe) import Control.Exception (try, IOException) import System.Environment (getArgs) type Rule = (Char, String) type Axiom = String type LSystem = (Axiom, [Rule]) getRule :: Char -> [Rule] -> String getRule ch [] = [ch] getRule ch (...
I was looking around for a Swift wrapper around NSUserDefaults and found some very nice projects (see e.g. SwiftyUserDefaults). Unfortunately, it all boils down to stringy keys galore... Eventually, I tried something myself and came up with the code below. I'm tempted to use it in production, but do not have much exper...
I am going through the CodingBat exercises for Java. Here is the one I have just completed: Start with two arrays of strings, a and b, each in alphabetical order, possibly with duplicates. Return the count of the number of strings which appear in both arrays. The best "linear" solution makes a single pass over both ar...
The problem was like this: Given an array: [1, 2, 1, 3, 4] where each index value shows the production of that particular day. So, at index 0, production is 1, index 1 - production is 2, so on... Then we're given some targets (N numbers of them). For a given target T, we've to find the index till which the cumulative ...
I wrote this equation parser and solver, I feel like it is well documented and tested: import doctest def swap_sign(num): """ Swaps the sign of a number-representing string. >>> swap_sign('9') '-9' >>> swap_sign('-4x') '4x' """ if num.startswith('-'): return ''.join(num[1:]) ...
I'm working on a processing sketch here. Main sketch: /* polyhedrons 3 david cool http://davidcool.com http://generactive.net http://mystic.codes April, 2015 based on: Spherical Coordinates Tutorial File April, 2008 blprnt@blprnt.com */ //import processing.opengl.*; // not needed for processing 3 ??? import java.ut...
My program is complete and working, but I would like second opinions on it. Here are the instructions for the assignment: The program will accept a string as input in which all of the words are run together, but the first character of each word is uppercase. Convert the string to a string in which the words are sep...
I have a Swing application that converts lengths. Inches to centimeter, feet to yard, etc. I’m wondering if I could make the super large HashMap a little smaller, or more efficient. Any other suggestions are also appreciated. import java.awt.*; import java.awt.event.*; import java.util.HashMap; import javax.swing.*; pu...
I am setting up a project which involves a lot of data analysis, each data point represented by a line in a large text file. In order to test for certain types of data, I added a tag to each line (It needs to remain in one file, though). Now I want to conveniently choose which type of data I want to include, currently ...
I found myself with a list of UTC timestamps and wanted to convert them into the local time zone. Using this web post as a starting point, I modified the script to grab a text file containing UTC times (one per line) and loop over each one outputting the results in a nice two column format. Is there a more efficient m...
This code creates an intro video using the Youtube API, screen text written by JavaScript with a typewriter kind of effect. How can I rewrite this as succinct object-oriented code? Also, I'm not sure if the way I've handled the setInterval and setTimeout functions is optimal. It works but I know it's far from perfect. ...
I replace this common statement: using (var connection = new MySqlConnection(connectionString)) { connection.Open(); // Do work here; connection closed on following line. } With this connection manager class that I made: public class ConnectionBase : IConnectionBase { private static readonly string ConnS...
I am just starting to implement unit testing into my project and familiarizing myself with NUnit. I have added unit tests for encryption/decryption methods that I have implemented, and am looking for more things to start testing for in my existing code before moving forward. The most basic classes that I have are my I...
I have a text file with about a hundred code value pairs [$code, Value]. For example: Sample file $codeA valueOfA $codeB valueofB . . . These values need to be initiated into textFields, radioButtons, checkBoxes, etc over "several panels" contained within a main Controller panel. I switch between panels through a simp...
When developing API methods to return JSON with details I often find myself creating the following code: $response = array('success' => false); $user = User::getSessionUser(); if($user->id > 0){ if(ItemSKU::stringIsValid($sku)){ $itemSKU = ItemSKU::getFromString($sku); if($...
I want to make some sort of NMEA AIS data generator. Now I wrote this code and it works quite well (does what I need from it), but I am sure it is bad and is to be optimized. The problem I see is that I convert integer to 6-bit word binary via string variables and I am sure it's not optimal at all. #!/usr/bin/python i...
I've been fooling around in JavaScript again, and I've come up with this simple physics simulation. I think it has a pretty simple setup, here's "psuedocode" of sorts to explain it. Constructor PhysicsEntity Private method _calculateForces - Calculates forces to be applied. Private method _applyForces - Apply the cal...
I noticed there were already countless implementations of graphsearch procedures on here, but there were a couple of features of my approach that I haven't seen in the others, plus I would greatly appreciate some experienced eyes on my code (my university is pretty miserly with constructive criticism). I wrote this as ...
I have written some jQuery that slides open a panel on click, and changes the toggles of the clickable bit from 'Show All' to 'Hide All'. It works, but I'm trying to figure out what would be the most efficient way to do it, as it seems kind of long to me, and some HTML is repeated. This is the working version and a wor...
For now, I've tried to make a line rotate on the path of a circle, but used setInterval multiple times and there might be other ways of achieving the same. I would like your thoughts before I add two more circles just like in this webpage. var width = 300; var height = 300; var body = d3.select("body") var svg = body...
I am working on a JSF 1.1 webapp. Lots of POST request take some time and users have the bad habit of clicking again when it takes too long. I am planning to target all the long running processes and add an overlay to prevent this, but it will take some time. Before it is finished, I am asked to setup a quickwin on ser...
Original question: Python PBKDF2 using core modules I'm looking for commentary on the following code, which converts from a hex seed to mnemonic (12 word phrase), and vice versa. It's for Bitcoin (BIP39 to be exact), and is going to be running in conjunction with pybitcointools, however I believe the commented URLs sho...
I've written this small MVC login application as an example for someone, would anyone let me know what they think of it? index include("login_view.php"); include("login_model.php"); include("login_controller.php"); Login_view::show_login_form(); $Login_controller = new Login_controller(); $Login_controller->validate($...
I am creating a C# WPF application. I am intending to bind all of the GUI controls via data binding to my ViewModel, rather than code behind - as per MVVM. I have made some good headway with this, but unsure about something. In my ViewModel, I am binding all the properties like this: private List<string> listBoxCodec;...
I am new to c++ and as a project to learn the language I have been working on a console application that would be able to handle and execute commands from the user. I have gotten it to work the way I want it to however I feel that I am doing it a very inefficient way (both handling the command and parsing the input int...
This method returns the list of files (absolute path) in a folder (or tree). It allows filtering by extensions or filenames. The method receives the following parameters: string path: folder path to scan for files. string[] exclude: can contain filenames such as "read.me" or extensions such as "*.jpg". SearchOption se...
Recently I wrote a program that was required to handle year and month data and so I wrote this class to encapsulate that handling. What I needed was a way to initialize the Yearmonth object based on the current local time, and allow a simple method of calculating future Yearmonth values based on a duration in months. ...
In a project of mine I needed a class "Document" to be able to notify any change in its fields. This class keep a collection of class "AnotherClass". Using an ObservableCollection for this collection is not enough because my application can't receive notification from Document if a field INSIDE an instance of AnotherCl...
You are given two strings. You have to check if the strings are permutations of each other and output "YES" or "NO" accordingly without quotes. Input: 2 lines of input each containing a string. (a to z and 0 to 9) Output: A single line containing YES or NO. Constraints: String would not contain any spaces. size...
I have this generic framework for finding (weighted) shortest paths. Also, the program demonstrates the performance of A* and Dijkstra's algorithms on a directed weighted graph. Both run in \$\mathcal{O}(E \log E) = \mathcal{O}(E \log V^2) = \mathcal{O}(2E \log V) = \mathcal{O}(E \log V)\$ time. shortest_path.h: #ifnde...
I have made the following system to automatically retry network calls if some exception is thrown. (Earlier posted on stackOverFlow, solution inspired by what @Boris answered) public static <T> Optional<T> autoRetry(@NonNull final DoWork<T> task, @NonNull final Optional<Predicate<T>> resultRejector) { for (int...
I have implemented a Service, which executes three operations, in the following order: Downloading a compressed (.zip) CSV file Decompress the CSV file Reading the CSV file and inserting the data into a SQLite database I'm more or less pleased with the performance of (1) and (2), but (3) is taking quite some time. De...
Trying to write more functional Javascript with the underscore library. Any thoughts on how to improve this to be more functional than imperative? Also, any way to do this without mapObject? The first of each pair is a "bucket" and the second is a value, I'd like to iterate over the information and get a unique list of...
I'm struggling to integrate a jquery-ui slider widget into my Meteor app. The idea is to have a slider value in a Mongo collection and the slider needs to be reactive (automatically synced between clients). I've achieved this and it works but the implementation is not very elegant and clean. It's quite hard to maintain...
I'm just beginning in Powershell - This will be my first full project, start to finish, and it's quite small. I have already had experience in C#, which helps in this .Net based language. This program asks the user for the input folder (usually a media device), and colects the data (to sort). It also asks for the des...
I'm looking to define the Rebol date format in EBNF notation. I'd like as best as possible to only define valid dates—at least those that are valid in Rebol at the moment: Date ::= DateDate ('/' Time DateZone?)? DateDate ::= DateDay31 ('-' DateMonth31 '-' | '/' DateMonth31 '/') DateYear | DateDay30 ('-' Date...
Considering the problem: Make a function to find the common elements of the lists in a list of lists. Example: common ( [ [1,2,3,3,5,11], [2,2,2,3,3,5], [2,2,3,3,4,5,6,7,18,19], [3,5,10,15] ] ) = [3, 5]. I came up with this solution: import Data.List(group, nub, sort) -- | -- This function returns the elements commo...
I saw this question somewhere: There is an 8-digit number. The first digit from left to right determines how many zeroes are in the number. The second digit tells you how many 1s are in the number, the third digit tells you how many 2s are in the number and so on, until the 8th digit, which tells you how many 7s are in...
My code below returns a JSON data based on user's input or query in my HTML page or template. However, I need to modify or do some tweaking with my JSON data in order for me to use it in my datatables plugin. I am using underscore.js to reconstruct the JSON data. def brgy_info(request): if request.method == "GET": ...
I started a C++11 library of concurrency primitives in order to study and compare their performance; provide high-quality implementation of those to use in my projects. Its main target platform is Linux x86-64. It relies upon the futex() system call for some of its functionality. Other parts of the library are platfo...
I'm a beginner in Python, and computer languages in general, and I'm totally stumped on how to format this iteration into a function. The iteration takes the sum of someone's birth year, month, and day and adds it together to create a sum of those numbers, and then the second iteration takes the first sum and adds thos...
As a part of a bigger application, I wrote code which creates a display for a countdown of a given time. It is nothing fancy, but I would still appreciate a review. I am especially concerned about: Use of JFrame - this is the second JFrame in my app, called separately by other GUI components. I read that it is not a g...
I'm looking to define the Rebol date format in BNF notation (as adapted for Rebol Parse). I'd like as best as possible to only define valid dates—at least those that are valid in Rebol at the moment: Rebol [ Title: "A Formal Description of Rebol Dates" Date: 23-Apr-2015 File: %date-grammar.reb Author: "...
The calculator supports the basic operators (Add,Substract,Divide,Multiply). At the moment, It only works with positive integers I do not validate my user input My division rounds up if it isn't an integer This is a work in progress. It is my first Python application so I want to get feedback before I keep on working...
I want to replace or improve the SELECT command of tblVisor to make it faster. Is there any way to improve this SQL command? SELECT tblVisor.supervisor_id, tblVisor.last_name, tblVisor.first_names, tblVisor.employee_job_profile_id, org_employees.last_name, org_employees.first_name, ...
I have a Login Form (which has a label that will show status of background process, username and password text boxes, Login and Cancel buttons) along with that I have a background worker to do some time taking task (in the meanwhile when Login Form loads and user provide details in text boxes). Background task keep run...
I'd like to know if the following class design is good or bad: #include <iostream> #include <vector> #include <string> #include <map> using namespace std; struct Student { string Firstname; string Surname; string IDNumber; int Age; }; class Exam { string ExamNo; int Questions; int PassScore...
Recently, I found myself frequently writing notification managing facilities. That is, one can register as a receiver by providing a callback, and another can send a notification to all registrants by invoking their corresponding callbacks. I had been bothered by re-writing this similar code again and again. Finally, I...
I wrote this validation class. I'm kinda new to the whole OO(PHP) style, so I don't know if my class is acceptable. I looked around at other people's validation classes, but most are huge (1k+ lines of code) or similar to mine in some ways. class Validation{ private $errors = array(); private $defaultErrors = ...
I've put together a class whose goal is to store objects of arbitrary type, with each type having its own vector for contiguity. I'd like to gather advice on what I have so far before I carry on. Let me show you the code, along with a main() so you can compile and run it easily (you'll need C++14 support). Here it is o...
I have a ConcurrentLinkedQueue where I put some mails in. Now I have a visual page where I want to see what's in the Queue, but of course I do not permit that they alter the Queue in any way. I put a getter, but instead of the Queue, I return a List. We know that the mail does disappear while we are watching, the use c...
This is a ReactJS component that accepts a date and displays how long ago this date was (5 seconds ago, 3 minutes ago, 5 hours ago, ...) + it uses a setTimeout to automatically update itself when the state.displayDate changes. What's going on: On ComponentWillMount: set state.date from props Update the state.display...
I'm an amateur programmer, new to Java and while attempting the Project Euler Archive 12 (Highly divisible triangular number) I ran into extremely long run time, with no result as of yet. Is it efficient and what should I do to improve it? Is there a special method to follow when sorting factors of numbers? Basically I...
I am going through the CodingBat exercises for Java. Here is the one I have just finished: Given a string, compute recursively the number of times lowercase hi appears in the string, however do not count hi that have an x immedately before them. And here is my code: public int countHi2(String str) { if (str.len...
My script reads two .csv files and generates one dictionary per .csv file. import csv # First dictionary first_dict = {} with open(first_file, 'r') as f: csvReader = csv.reader(f) next(csvReader, None) # skip the header for row in csvReader: key = row[0] first_dict[key] = row[1] # Second dic...
This came up when I answered another post. Is there a better way? public class Bits { public static void MinMaxI(ulong _bits, out long _min, out long _max) { // ? unsigned range with at least one value bit if (_bits < 2 || _bits > 64) { throw new System.ArgumentOutOfRangeExce...
I need to write a TextureManager class which stores Texture objects; the problem is I'm using an std::map<Texture *, const char*> map to store Texture objects using a key. Searching elements through a map is not ideal because of performance issues (I'm writing a C++ library, so performance is important). I've had the i...
I've got a quite simple WPF application, trying to implement a correct MVVM pattern. The application in itself is simple: one listItem and one textbox + button for searching. On init, the entire content of a "large" (~50k to ~1million lines) file is loaded into the listItem. When the users enters text in textbox and cl...
I have a class with which I want to persist a conditional expression: boolean x = a [GT] i I am only concerned with the boolean outcome of that comparison. 'a' '[GT]' and 'i' are supplied as arguments at runtime. public class RuleClauseCondition { RuleClauseOperator operator; Double threshold; ...
I wrote an implementation for a simple queue in C++ (for practice, since there's an stl queue). I've been trying to focus on memory management and the rule of three. Any suggestions/improvements? (Personally, I feel like there has to be a better way to overload the copy assignment operator). #ifndef QUEUE_H #define Q...
I currently have two partials that I use for signing up and signing in. The code is essentially the same in both except for different images to represent sign up/in via Facebook/Twitter. _sign_in_via.html.erb looks as follows: <div class="sign-up-via-links"> <div class="row"> <div class="col-md-12"> ...
I'm writing a function for generating solutions for a backtracking search problem. To that end, I need to mark an item from a list by removing it from that list, and placing it in a second list. So I have a pair of lists: non-marked items marked items and my method generates all distinct list pairs of possible markin...
After resigning active state (going to the background), the mainWindow property of the main window in the app returns false. Nevertheless, I need a to find that window even when my app is not active, so I came up with the following code, which works: public let App = NSApplication.sharedApplication() // just some sugar...
I had the following three Tcl procedures, which calculate positions along three edges of a rectangle: #---- Numbered pins at the top --------------------------------------- # Given a list of triplets (number, name, index), place the pins for the # signals "name<index>" along the top edge, positioned vertically at 'y' #...
Here is something I've been working on today.. I been trying to determine how to build a website, that has a form, and that form allows a user to make a simple URL to give out. In the future it will also create a website, or possible websites (based off of varying templates that I have built for it). I just started tr...
This is a Java calculator I made for my programming class. I know there must be vast room for improvement. Please bear in mind the fact that this only accepts an integer, then an operator, then another integer, and finally the = button to function correctly. Also please bear in mind the fact that it prints the result u...
I need to create an instance of Show of a somewhat complicated type that represents a C++ function. The "serialization" gives me a Haskell interpretation of the said function. It works as I wish but it looks utterly horrible, with the string concatenations, point-free conversions and nested let bindings. How could I i...
I have tried to simulate a cart (only partially completed). I just wanted to see how the code upto this point can be enhanced. I am trying to learn about the usage of directives. Here I have used 2 directives: msgpallette- to show the messages when something is added to the cart item-container - to show each item in m...
I have a very simple C program that continuously reads from a temperature sensor and displays the temperature on two 7-segment LEDs. Reading is simple, but to display the LEDs I need to write to 14 GPIO pins on every iteration. It gets real ugly. I am running this program on an embedded device (BeagleBone Black), which...
I have this code that requests the graph API from Facebook to respond with a shared count for a particular URL (could be multiple on the page). Graph returns a full number (135934) and I take that number and abbreviate it into more friendly numbers (135K). Basically I'm looking for any help on improving the code to be ...
I need to optimize this code block below, this method converts a Datatable object to the Object that I am passing by parameter, in another words, this serializes the object, however I have to run this block 1 million times when reading data from the database, so this is the bottleneck of my application. Obs: All my ob...
This is an updated version of my previous Java program that asks the user for a sentence and then separates the words and then converts the sentence into Pig Latin. My previous program was working, but there was some tweeking that needed to be done which I did after getting positive feedback. Apparently, my loop in the...
There was a Tweet from @ExcelEasy earlier this week, that linked to this article, to which I replied with a little challenge: @ExcelEasy well done! #Challenge: make a more #OOP one without using the form's default/global instance! #becausewhynot Of course I wouldn't just leave it at that, so here's my own implementat...
Previous question was a little portion of the mailQueue. I finished the MailQueue, which has the ability to start and stop itself. I also implemented some more threads for sending when the load becomes greater. This is because we do send at some points over the 15000 mail in a short time. The last MailQueue did need 2h...
This question is a follow up of Calculate min/max values for signed or unsigned integral number with any valid number of bits (up to 64) I was answering the question Given two int values, return the one closer to 10, and I indicated that something like the following snippet of code could be a different approach for s...
I'm a beginner in Java and I tried to create a program that will perform basic arithmetic operations on binary numbers. BinaryOperations class: package binaryoperations; import java.io.IOException; import static java.lang.System.in; import java.util.Scanner; public class BinaryOperations { public static void main...
I'm new to iOS development and also Swift. I'm working on a project consisting of a menu that leads to my various experimentations with the iOS SDK. I've written the menu titles and segueIdentifiers in a plist and I'm populating an array of NavigationItem in viewDidLoad(). Is the following code idiomatic, particularly ...
I have written an implementation of Mitchell's best candidate algorithm. Mitchell’s best-candidate algorithm generates a new random sample by creating k candidate samples and picking the best of k. Here the “best” sample is defined as the sample that is farthest away from previous samples. The algorithm approximates Po...
I have a class called FirmwareFile which represents and Intel HEX format file. The file is constructed with the name, build time and build date, at a later point file data is retrieved from the database (another class handles this) and is passed in with the setData(byte[] data) method. After the data is set, the method...
I've been reading up on OOP concepts such as: polymorphism, inheritance and encapsulation and would like to know if I am even close to using these concepts correctly. interface Canine { public function bark(); public function howl(); } interface Feline { public function chase(); } interface Mammal { c...
After I've discussed pointer semantics with Loki Astari previously, I finally managed to code the TextureManager class using auto_pointers. But the problem is that I need to pass an SDL_Renderer object to my class' constructor as an auto_ptr. But the object I want to pass is a raw pointer. How should I do it? Also, I'm...
I have created a program to validate a Canadian S.I.N. using Luhn's Algorithm, and was wondering if there was any way to make it more efficient. From what i can tell, it is already extremely efficient, but any tips or advice will be greatly appreciated. import javax.swing.*; import java.awt.*; import java.awt.event.*; ...
I am creating an automated test system (scope bloat - the original intent was a one-off bash automation of a particular test case that has turned into creating a system that will do many other things). I've done a few things similar to this, but somehow never got to using classes; everything was down at the functions l...
I have this very easy functionality to find, toggle and remove classes from my html elements. The thing is that I find my self repeating the same code with just different name classes. I basically wrote the same method 9 times. I know that is you keep writing the same thing over and over again there is a more efficient...
I'm new to JavaScript (and programming) and taking a course. I was tasked with creating a bubble sort on any array using JavaScript. Of course, since this is an algorithm challenge, no sort method allowed. After I wrote this, I looked around at other implementations of bubble sort. I only found one that used a similar ...
I have added bidirectional Dijkstra's algorithm into my pathfinding "framework", and I would like to make good use of C++ programming idioms, eliminate all possible memory leaks, otherwise improve readability, but I need your help for that to happen. That's what I have scrambled: shortest_path.h: #ifndef SHORTEST_PATH_...
I recently started looking into CQRS when using Entity Framework and the impact it has had on my systems has been overwhelming. I implemented the following patterns described in these blog posts: Query implementation Command implementation I have implemented these with Autofac as dependency injection, and Entity Fram...
Previously, I use to always navigate through the $parent $scopes in order to send or change data from one Controller into/in another. I then created my own ScopeFactory as a way to storing each Controllers $scope and then getting those scopes from other Controllers. Having not experienced any problems with using this m...
I am a self-taught programmer. I decided to learn design patterns by reading about them, and then coming up with their implementation in PHP. I know that learning would be virtually impossible without code review. I will be grateful if you could review my implementation of the Memento design pattern and point to any sh...
This program is a random password generator. It asks the user how many chars they want their password to be and how many passwords it should generate. I used the rand() and srand() methods to generate random letters. I used dynamic allocation to create a char array based on user input. The comment line is where I trie...
The open source project I work on uses Antlr4 pretty heavily, but I don't know much about it. I thought I would use April's Community Challenge as an opportunity to learn something about grammars, lexers, and parsers. My calculator only handles integer multiplication, division, addition, and subtraction, but it does ha...
I am learning C++ and I decided to implement a Directed and UnDirected graph. (I haven't learned how to do inheritance yet, so they are distinct classes.) I have not handled any error cases (i.e. trying to remove a vertex that doesn't exist.) I am interested in any comments/criticisms of my approach. #include <iostrea...
The Cardshifter team has been working at "translating" a very complex Java class into JavaScript, to make it more accessible to somebody who would want to fork the game and make their own modification, which is an objective that's been close to our hearts since the very beginning (for the game to be very "moddable"). ...
I am using play framework with scala and here is a scenario on which I would like to have your opinion. Let's say I have 2 custom exceptions that I can throw, which are EmailTaken and AuthFail. What I need to do here is, whenever any of these 2 exceptions happen, I need to return a json with 3 keys success, errorCode a...