instruction
stringlengths
71
95.1k
I found a code on my computer that i wrote a while ago. It is based on an exercise from O'Reilly book Programming the Semantic Web. There is a class, that stores RDF triples, that is data in the form subject-predicate-object: class SimpleGraph: def __init__(self): self._spo = {} self._pos = {} ...
I have the following interface: public interface ILogger { void Log(string message, string title, StatusType type, DateTime timestamp); IAsyncResult LogAsync(string message, string title, StatusType type, DateTime timestamp, AsyncCallback callback); void EndLogAsync(IAsyncResult result); } Implemented as a...
I am trying to remove files based on an array of prefixes, from files present in sourceDirectory. I am using prefixFileFilter to get the list of files with the prefixes. After that I am removing these from the original list. Is there any better approach? package sriram; import java.io.File; import java.util.Arrays; im...
There is my SSCCE to generate a value of discrete random variable. values is set of value the RV can take and procents is equivalent to discrete pdf. Can you anticipate any issue with this snippet? import java.util.Random; public class RandomTest { public static void main (String[] args) throws Exception { ...
I form DOM nodes as strings and append them to DOM tree like below using jQuery. var dom = '<div><div style="display: inline-block">first name</div>' '<div style="display: inline-block">last name</div></div>'; $("#contacts").append(dom); The above code is a small sample. In most of my cases dom will hold...
Can someone have a look at my script and maybe find something which can be optimized, as there shall be later 100 of it running. First of all this script shall be triggered once per day to receive data from a website into a sheet called "getdata". Some fields of "getdata" are transferred to "blindcopy" in a certain ord...
My aim is to avoid using threadpool threads for CPU bound work, thus avoiding a situation where IIS stops responding to new requests. Can you see any problems with the code below? Is this a safe/clean approach? Can you offer any improvements? private static ConcurrentQueue<Job> Jobs = new ConcurrentQueue<Job>(); ...
I am building an application that opens Wireshark services (Wireshark has several services) in order to to different things on Wireshark files like edit, change format, statistics, etc. Each option usually uses a different service, so I want to build my classes with inheritance. I was wondering if what I want to do is ...
I am learning PHP OOP. I am familiar with PHP, and limited use of OOP, but not writing OOP. I have a small successful website that uses large associative arrays but is now suffering performance problems because the arrays soak up memory (My teamarray contains 16k teams of the data below, plus more). I am rewriting the ...
I currently have a method in my repository that will run SQL and map the reader to objects: protected IEnumerable<T> Query<T, TFactory>(string sql, List<IDbDataParameter> parameters = null) where TFactory : IFactory<T> { List<T> list = new List<T>(); var factory = Activator.CreateInstance<TFactory>(); var ...
I've written a Time class that records the time of day and performs simple timing operations (add 2 times, convert a time object to an integer and back again,etc.) following the prompts in How to Think Like a Computer Scientist: Learning with Python. class Time(object): """Attributes: hours, minutes, seconds""" def __...
I have written two programs to find out a loopy path in a directed graphs. The first version is a pure functional recursive solution, but its complexity is exponential. The second version following it achieves a linear complexity, but it doesn't look perfect either. def GetACycle(start: String, maps: Map[String, List[...
I am new to JavaScript development, so I'm seeking help in guidelines on how I can better organize my code in a better way. This is what I have for a small app I am working on: var app = app || {}; app.p = function(){ ... }; app.q = function(){ ... }; app.r = function(){ ... }; app.init = function(){ ... }; app.onloa...
I have this prime factor generator for some number n. It returns list of all prime factors. In other words, product of the list equals n. def prime_factors_generate(n): a = [] prime_list = sorted(primes()) pindex = 0 p = prime_list[pindex] num = n while p != num: if num % p == 0: ...
I have a function for finding factors of a number in Python def factors(n, one=True, itself=False): def factors_functional(): # factors below sqrt(n) a = filter(lambda x: n % x == 0, xrange(2, int(n**0.5)+1)) result = a + map(lambda x: n / x, reversed(a)) return re...
I am creating a commercial API for the first time for responsive webpages/web applications (mobile devices). I am new and, sadly, working alone as well as new to Javascript (long complicated story). I was just wondering if someone from the industry could offer their professional opinion on the following format of a "ge...
I am looking for advice on making the following code shorter. Any help is appreciated. public String determineWinner(String winner) { winner = ""; if (playChoice.equals(compChoice)) winner = "The result is a tie."; else if (compChoice.equals("R")) if (playChoice.equals("S") || playChoice.equals...
When I have a place with limited space, where I entry a text that can be few letters or huge amount of text because it's dynamic, I'm using this code to make the text fit the specific space. #region TextSizing string textSizing = databaseTable.Description; using (System.Drawing.Graphics g = System.Drawing.Graphics.From...
I have made a class for generating html form elements: class input { public $tag = 'input', $type = 'text', $customClass, $name; public function __construct(array $cfg){ if ( isset($cfg['name']) ){ if ( isset($cfg['tag']){ $this->tag = strtolower($cfg['tag']); } if ( $this->tag === 'i...
As an example, suppose I had a large amount of data about a set of Restaurants for a large set of Dates in a database that I need to analyze / output to the user. I have a custom class that holds the data for each restaurant for each date: Public Class DateData Public Property Var1 As Double = 0 Public Property...
I came across a situation where I'd like to improve my code, but don't really have a clue about what I could do... It's for a game I'm making, I want to get a perimeter surrounding a unit, but I don't want tiles inside the perimeter. I'm pretty sure there is a better way to do this. (@x and @y are the unit's coordinate...
I need help refactoring this method. It is way too long. def report_total(feed_event, advisor) count = 0 advisor.activity_feed_events.each do |lead| if lead == SignupFeedEvent count += 1 else if lead.is_a?(feed_event) if lead.event_date > (Time.now - 7.days) ...
I have a mammoth SQL statement, however it's taking a long time to load (27 secs on the server). I think the issue lies with the IN statements towards the bottom (the IN statement is repeated too, can this be stored so it only does it once?) (taking it out shaves 23 seconds, anything under 10 will be brilliant) but i'm...
I just started learning how to write code in Java. I want to turn the code to OOP with fewer methods, using classes like Sudoku rather than int[][] puzzle. import java.util.Random; //Generates a Sudoku puzzle through brute-force public class SudokuPuzzle { public int[][] puzzle = new int[9][9]; // Generated...
I've just started to practice coding in OOP and just wanted to ask if my code's pattern is correct. I need your comments or suggestions so I can improve it. sample_class.php: <?php $host = 'localhost'; $db = 'sample_db'; $user = 'sample_user'; $pass = 'sample_password'; $conn = new PDO("mysql:host=$host;dbname=$db", $...
I want to determine which separator is used in a csv file. CSV.foreach will return something like this: ["something1;something2;something3"] The code beneath does the trick, but something better must exist. I find it annoying to have the need for sep_count. Do you know of a method that returns the most frequent of the...
I have a controller. It functions as follows: A user imports a file and decides whether the files contents contain new entries to be placed into a database, or existing entries entries to be updated. The user clicks on the import button and is sent to the controller below. If there are any warnings or errors, the valid...
I have a process that runs as 32-bits regardless of the architecture. In it, I want to be able to spawn a process from the 64-bit program files menu (e.g. c:\program files instead of c:\program files (x86)\). I tried using System.Environment.GetFolderPath, but for a 32 bit process, both SpecialFolders.ProgramFiles a...
I have two functions to split string to array of strings. Input string is: (1Letter E|V|R) + 8 number, last component of string (1Letter + V) + 8 or less numbers. I'v got two functions advised to use, both of them are working properly. But I can't decide which one is better to use. 1st: - (NSArray *) componentSaparete...
My purpouse is to select every character which is surrounded by { and }, this is easily achievable using this regexp {\w*}. I've developed an extenstion method for strings: public static IEnumerable<string> ObtainTokens(this string originalString) { Regex expression = new Regex(@"{\w*}"); foreac...
I've got dictionary of lists of tuples. Each tuple has timestamp as first element and values in others. Timestamps could be different for other keys: dict = { 'p2': [(1355150022, 3.82), (1355150088, 4.24), (1355150154, 3.94), (1355150216, 3.87), (1355150287, 6.66)], 'p1': [(1355150040, 7.9), (13...
My company's web application projects are heavily based on user controls. One common case is like we want to reuse the UI visual elements but note the packaged original logic . I have read some very smelly code in some user controls code behinde. if(WebConfig.CurrentProject == "xxx") { //do xxx's logic ddlPos...
I have this code: Tabzilla.fillZGContacts = function(){ if (!Tabzilla.panel.id) return; $.ajax({ url: 'zgcontacts.json', success: function(d){ // "Type","Name","Link","Contact","Location","Icon" Tabzilla.zgContacts = d; var countries = []; d.rows.forEach(function(row){ ...
I am studying graphs and I am trying to make a library in C# for myself and anyone else interested, that is didactic and simple, so I can remember how to solve common problems. I would like to improve it. How can I improve, for example, the DFS, complete the Prim's algorithm and implement the Kruskal's and Dijkstra's a...
['content', 'answers', 'comments'].each do |t| break if results.length >= MAX_RESULTS Question.search_tank('', :conditions => conditions.merge(t => "#{search_term}"), :page => 1, :per_page => 5).each do |q| next if matched_qs.include? q.id matched_qs << q.id r = {:title => q.content, :value => app_ques...
I'm wanting to throw an error when reference keys are missing, however instead of failing through a integrity check, I want to list out the missing keys. I've created the below which works. However I'm hoping there is a way to optimise it and reduce the number of lines of code. DECLARE @NonRefKeys INT SELECT @NonRefKe...
This reads a list of points from a file with a certain format: <number of points> x1 y1 x2 y2 How I can make it better? from collections import namedtuple Point = namedtuple('Point ', ['x', 'y']) def read(): ins = open("PATH_TO_FILE", "r") array = [] first = True expected_length = 0 for line in i...
After experimenting with different design approaches for the past two years, I've created a library for managing and processing dynamic content to be displayed on a single HTML view. This library is PSR-0, PSR-1 and PSR-2 compliant. I'm quite happy with this design but want to make sure it can stand excessive use. It's...
The following is a new question based on answers from here: Small PHP MVC Template I have written a small MVC template library that I would like some critiques on. The library is located here If you are looking for where to start, check out the files in the lib directory. I would really love to hear your critiques o...
I was looking for a way to start elevated (i.e. administrator permissions) and/or invisible processes via batch in Windows. It turns out that this is kind of impossible with batch only, so I googled some vbs stuff and hacked it all together into a neat command line power utility. The interface is as follows: exec [/a...
Developing some industrial WinForms application for some industrial setting, I wanted to provide users of our software with a convenient way to back up the database the software uses (to send it to developer for investigation of any issues that might arise, or just to keep it at hand in case something goes wrong). The ...
I have code that is accessed by multiple threads. If by any chance it has a problem, all accessing threads will wait for recovery. By default, the first thread that fails, will have to recover and all others will have to wait. When the process is complete, everyone leaves the method. [TestMethod] public void Recover...
I wrote this Sundaram's sieve in Coffeescript to quickly generate prime numbers up to limit: sieve_sundaram = (limit) -> numbers = (n for n in [3...limit+1] by 2) half = limit / 2 start = 4 for step in [3...limit+1] by 2 for i in [start...half] by step numbers[i-1] = 0 start...
I have this code for a website I'm working on. It uses window.scroll events to parallax some items. It's running a bit slow on average machines. Is there any way I could improve it to make it run faster? $(function() { // Tell the DOM that JS is enabled $('html').removeClass('no-js'); // Navigation Waypoi...
I have a nested for-loop that populates a list with elements: a = [] for i in range(1, limit+1): for j in range(1, limit+1): p = i + j + (i**2 + j**2)**0.5 if p <= limit: a.append(p) I could refactor it into list comprehension: a = [i + j + (i**2 + j**2)**0.5 for i in range(1, limi...
I have strong feeling that the code below is ugly at least as there are 2 same "cons". I would appreciate if you advise me ways to improve it. The code produces all allocation by n items from list lst. (defun allocations (lst n) (if (= n 1) (loop for i in lst collect (cons i nil)) (loop for i i...
def get_all_friends(uid, client) friends = client.friendships.friends(uid: uid) total = friends.total_number get_friends(total, 0, uid, client) end def get_friends(total, cursor, uid, client) left = total count = [200, left].min friends = client.friendships.friends(uid: uid, count: count, cursor: cursor) ...
The code above is a implementation of a lock-free queue that makes the assumption that there is exactly one Consumer thread and one Producer thread. This works as intended? The memory barriers is used in the right place? The code has race points? PS: I know about the existence of lock-free queue implementation in .NET ...
I have a GiftCard class where I have method can_deliver? and deliver! that I think can be refactored to better looking code : def can_deliver? (self.sent_at.nil? && self.scheduled_at.nil?) || (self.sent_at.nil? && self.scheduled_at && self.scheduled_at < Time.now) end def deliver! return unless self.can_...
Pythonic way of expressing the simple problem: Tell if the list needle is sublist of haystack #!/usr/bin/env python3 def sublist (haystack, needle): def start (): i = iter(needle) return next(i), i try: n0, i = start() for h in haystack: if h == n0: ...
I've written the following program as a submission to the German Federal Computer Science Competition for highschool students. The program makes the following simulation with a given number of days and a given α. In order to simplify my code, I use a shellscript to run multiple simulations in parallel. You can get all ...
function C = convolve_slow(A,B) (file name is accordingly convolve_slow.m ) This routine performs convolution between an image A and a mask B. Input: A - a grayscale image (values in [0,255]) B - a grayscale image (values in [0,255]) serves as a mask in the convolution. Output: C - a...
Purpose: Educational Requirement: Given 64KB of memory, implement your own malloc and free Method: First-Fit struct Header { unsigned short next; //in blocks of sizeof(Header) unsigned short size; //in blocks of sizeof(Header) }; static Header* _dBuffer; static Header* _dTail; static public void dInit() {...
This is a piece of C89 code testing a function titled logging_function(), which takes two arguments and uses them to log a bit of information. In this case, the first argument to the function is the string to be logged, and the second argument is a string holding a path in a filesystem to a log file. The first string ...
I am a CS student about to enter my junior year. I am attempting to get better and better at programming and thought that this would be a good place to toss my code out there to see if some of you could give me some tips on how to make it better. If you've got tips as to different websites I could go to for this sort ...
I'm writing a Telnet parser in Haskell that can run within any monad that implements some event-handling functions. When it finishes processing a block of input - whether because it read it all or because it was interrupted by an event handler - it returns the remainder of the text and a continuation for more input. Ri...
I've written a script to generate DNA sequences and then count the appearance of each step to see if there is any long range correlation. My program runs really slow for a length 100000 sequence 100 times replicate. I already run it for more than 100 hours without completion. The first function is seq(), it randomly g...
Are there ways to avoid this triply nested for-loop? def add_random_fields(): from numpy.random import rand server = couchdb.Server() databases = [database for database in server if not database.startswith('_')] for database in databases: for document in couchdb_pager(server[database]): if 'results' in serv...
Is this an acceptable way to make sure a java.sql.ResultSet is always closed, and also make sure that an Exception caught is propagated to the caller? Please don't hesitate to review other aspects of this sample as well. public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus) throws Except...
What do you think about this? #utils.py def is_http_url(s): """ Returns true if s is valid http url, else false Arguments: - `s`: """ if re.match('https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&%?#-]{1,300})?',s): return True else: return False #utils_test.py im...
So basically jqueryphp is a jQuery plugin that allows you to call any PHP function within client-side JavaScript: jqueryphp@github I wrote it as a response to projects such as PHP.JS and other JavaScript emulated PHP function libraries. I realize that my solution will only be useful in contexts where latency is not muc...
For example, given a 2D array (a matrix): {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} What are the solutions to find a number, such as 6? Here's the code I tried using binary search method: int main(){ int sample[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 6; int lowX, highX, lo...
I have a CakePHP function here that gets info for a twitter screen_name from the twitter api and writes it to a mysql db. I'm just looking for feedback about other ways to accomplish this that might be more efficient with fewer loops maybe. The challenge is, there are many screen_names that need to be processed for a $...
To start with Common Lisp I am doing Project Euler using this language. Usually I manage to solve problems but I am quite sure that my code is not as efficient as it could be in Common Lisp. That is why I need a review from experienced lispers. This is my code for problem 35. Please offer any improvements. (defun prime...
I'm trying to figure out a pattern to best accommodate this pretty ugly code: var userDiscounts = _discountRepository.GetUserDiscountsForUsersWithDiscounts(new List<int> { buyerUserId, sellerUserId }).ToList(); // Buyer. var buyerHasFreeCommission = false; var buyerDiscounts = userDiscounts.Where(ud => ud.UserId == bu...
I'm a code banger from way back trying to learn good Python style. Here is my attempt at the classic game. I'm trying to learn Tk, because I have a couple codes that need GUIs. Any suggestions or comments? from tkinter import * import random # use a class definition to hold all my functions class MyApp(Tk): def...
I am reading lot of articles regarding memory leaks. But i am not sure about below code. I usually do coding in this way. Can anyone tell me, will they leak memory? I have doubts in following 3 scenarios (marked them in code). I got these suspects after reading this post var orderDetails = $("<root/>"); function GetOr...
I have written a basic image upload function that handles up to five file inputs, intended to be hosted live on the internet very soon. As far as I know it's secure and works well (minus checking the range of the first 100 bytes and looking for magic numbers), but please tell me if you can see any flaws or areas where ...
I am very new to programming and this is my first functional code. It works fine but I'm sure that I could use a lot of optimization. If you see any blunders or would be able to help condense the script that would be fantastic. #!/usr/bin/python import sys, getopt, subprocess, os, tempfile, shutil, time file_name = s...
I humbly submit the following for critique. This was my final project for an Intro To Java Programming class ("handed-in" already, I can't make changes). The abundant commenting is required by the professor. Design and implement a stringed musical instrument class using the following guidelines: Data fields for your...
I am using ElasticSearch and Tire for search in my app across all models. I would like to refactor autocomplete method because it looks to complex for me. Am I using a good pattern for searching across model? Model class Link < ActiveRecord::Base include Tire::Model::Search include Tire::Model::Callbacks tire....
I have a Python file with several function definitions in it. One of the functions, named 'main' will be called as soon as the Python file is run. Example: myFile.py import sys def main(arg1....): ---code--- --more functions-- main() When a person wants to run my file they'll type: python myFile.py arg1 arg2 ... ...
Let's say I have three files: a page that is used for searching data called search, a file that handles requests called controller, and a file that has functions which the controller calls based on what POST parameter is passed. From the search page, I post some data and specify my action (search) via AJAX to the contr...
I'm making a family tree. The following script allows the user to expand branches of the tree. It works fine, but there must be a better way. You can see it working here. $(function(){ $('.oc').prepend('<img src="icons/bullet_add.png" alt="more" width="16" height="16"/>') $("ul[id|=Nested]").hide(); $("a[id...
The first block of code is my main app.js that is included on every request. It is essentially a library of functions and objects that include related functions (ie: app.utils) that I can use on other pages like page1.js: ./app.js var app = window.app || {}; (function($){ app.req = app.req || {}; app.utils = a...
I had a question regarding my code which downloads a file from S3 with the highest (most recent) timedated filename format: YYYYMMDDHHMMSS.zip from boto.s3.connection import S3Connection from boto.s3.key import Key import sys conn = S3Connection('____________________', '________________________________________') bucket...
I have a helper class that I am using to return the selected items in a number of IEnumerable POCO collection but I'm not happy with the implementation. One of the reasons for using this method is that the collections area returned by RIA services as ReadOnlyObservableCollections and I don't believe they support LINQ b...
I'm fairly new to mvc and almost finished my auth class I wanted to check that I'm using it all correctly any feedback would be welcome. I used the PIP framework to get started http://gilbitron.github.com/PIP/ here's the controller <?php class Auth extends Controller { protected $username; protected $password; public...
I was fixing a bug in the code and it was something like this: int const ROW_LOC = 1; //.... Foo ( x , y , ROW_LOC ) ; so it was passing that constant to a method ... and this ROW_LOC constant is being used in multiple other places in the code too. For ONLY ONE place in the code because this constant was getting passe...
I have following method which highlight matched word in text: # Hightlight matched term # # Ex(for term: some): # "<span class="bold">Some</span> CEO Event" # def highlight_matched(matched_word, text) regex = matched_word.gsub(/\*|\"|\'/, "") .split(" ") .map { |s| "\\...
I have a mixin function which is as follows - function mixin(receiver, supplier) { for (var property in supplier) { if (supplier.hasOwnProperty(property)) { receiver[property] = supplier[property]; } } } To test this function, I am using the ok method of Qunit - test('Mixin Test R...
I have this Sundaram's sieve to generate prime numbers up to limit in Common Lisp. (defun sundaram-sieve (limit) (let ((numbers (range 3 (+ limit 1) 2)) (half (/ limit 2)) (start 4)) (dolist (step (range 3 (+ limit 1) 2)) (dolist (i (range start half step)) (setf (nth (- i 1) numbers...
I've been on stackoverflow looking for an alternative to the ugly if-elif-else structure shown below. The if-else structure takes three values as input and returns a pre-formatted string used for an SQL query. The code works right now, but it is difficult to explain, ugly, and I don't know a better way to do re-format ...
So I started wondering why it takes 3.5 seconds to AcceptChanges for one changed record in a large DataTable. I wrote another implementation of AcceptChanges (VB.NET) - Me is a DataTable here: Public Shadows Sub AcceptChanges() 'this way AcceptChanges is 35 to 700 faster than Microsoft's way '35 is a speed factor w...
I want your suggestions on this algorithm: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace FCFS_Console { class Program { static void Main(string[] args) { //----------------------------------------Reading I/O File----...
This is a command line BlackJack game created in Java as my final project for an advanced programming class. What do you think about it? Have I used OOP correctly? What grade should I get for this? :D Any concept in game that could be improved? I used JRE 1.7. And to make Unicode characters work you must use Unicod...
I would like a review regarding the following code in which I index and search the City model. Currently both solr (with sunspot gem) and elaticsearch (with the tire gem) are show. I am migrating from solr to ES and want to make sure I am not making any major mistakes. I am new to ES. class City < ActiveRecord::Base ...
I have a dropdown that contains around 100,000 rows which make up a list. <input id="search" type="text" /> <ul> <li>item 1</li> <li>item 2</li> ... <li>item 100,000</li> </ul> I have a text box which acts as a search, so as you type it matches the input to items in the list, removing what does not...
I am writing an object in C# to mimic jQuery's various functions. That is, calling the constructor is akin to calling the $() function of jQuery. For example, var a = new JQuery("div").eq(0); Assert.AreEqual("$(\"div\").eq(0)", a.ToString()); I also have an Append function which concatenates two or more existing JQuer...
I want to convert a java.lang.String to a java.lang.Integer, assigning a default value of 0 if the String is not convertible. Here is what I came up with. I would appreciate an assesment of this approach. To be honest, it feels a little squirrely to me: String strCorrectCounter = element.getAttribute("correct"); Integ...
I have a child iframe in my page that will load content from a different web application in a different virtual directory than the parent page. The DOM will look roughly like this: <html> <!-- Content from www.contoso.com/WebApp1/Home --> <div id="parentDiv" /> <iframe> <!-- Content from www.contoso.com/...
I've written a couple of functions to check if a consumer of the API should be authenticated to use it or not. Have I done anything blatantly wrong here? Config API_CONSUMERS = [{'name': 'localhost', 'host': '12.0.0.1:5000', 'api_key': 'Ahth2ea5Ohngoop5'}, {'name': '...
I have a string that must be splitted into an array of strings so using strtok makes perfect sense but before that I want to allocate the array of strings and thus I count how many words in it. static inline int countWords(char *str) { int count = 0; char *buf = str; if(isgraph(*buf) > 0)//chec...
I've planning to create crosswords game for Android platform. Basically, crossword is a matrix of TextFields (EditTexts) and TextViews. Each crossword might be in american style (first TextView in every question stores question number, and there's no TextView with clue) or swedish (first TextView stores arrow indicati...
I just learned about Maybe in Haskell, so I decided to try to use it with a binary search. Here's the function: binarySearch :: (Ord a, Int b) => [a] -> a -> b -> b -> Maybe b binarySearch l e beg last | lookat < e = (binarySearch l e i last) | lookat > e = (binarySearch l e beg i) | lookat == e = Just i | otherwi...
I have been coding for some time (3 years I think), and have recently been wondering if my coding pattern is any good. Any kind of feedback is welcome: EDIT: The thing that concerns me most is that I have read a lot around that getters/setters are bad for OOP. Is this true? //Point3D.as public class Point3D { priv...
I have three methods that are really similar but do slightly different things. This doesn't feel very DRY to me, but I can't think of a way to reduce the duplication. Here are the methods, I think they're fairly self explanatory: # Present a date as a string, optionally without a year # Example output: "December 1, 201...
I need to write a jQuery plugin that doesn't take an element to work. Example call: $.funkyTown(); ... not called like this: $('#foo').funkyTown(); ...in other words, I need this plugin to act more like a "utility" plugin (vs. apply itself directly to a matched element(s)). Here's what I have written so far: ;(functi...
I wrote a small script as an answer for a Stack Overflow question, which referred to counting lines of code and comments (in C and C++ style). f = File.open("test.txt") loc = 0 comments = 0 while line = f.gets if commented ||= line.match(/^\/\*/) commented = nil if line.match(/\*\/$/) comments += 1 elsif l...
I am trying to solve the "Meeting Point" problem from interviewstreet.com: There is an infinite integer grid at which N people have their houses on. They decide to unite at a common meeting place, which is someone's house. From any given cell, all 8 adjacent cells are reachable in 1 unit of time. eg: (x,y) can b...