instruction
stringlengths
71
39k
I've recently been doing some mods to some old code I've been maintaining for a couple of years now. As part of a wider set of scripts using YAHOO YUI 2.2 (yes, that old) for dialog-style panels, I have a function that listens to click events on 3 buttons in a given panel set: addFooListeners = function (panelType) {...
There's got to be a better way than this that preserves the logic while sparing me the multitude of lines: sub has_path { clearerr; my %Graph = gref(shift); my $A = shift; my $B = shift; my $C = shift; my $D = shift; my $E = shift; my $F = shift; my $G = shift; my $H = shift; my $I = shift; my $...
My homework question states: Develop a class to measure distance as feet (should be int), inches (should be float). Include member functions to set and get attributes. Include constructors. Develop functions to add two distances. The prototype of the sum function is: Distance Sum(Distance d); Please check out...
Okay... here's the beast: SELECT SUBSTRING(DischDate, 7, 4) + SUBSTRING(DischDate, 1, 2) as YYYYMM ,Type ,SubType ,Diags ,Count(*) as Count ,SUM(Charges) as Charges ,SUM(Payments) as Payments FROM ( SELECT DISTINCT ID ,Diags FROM ...
I have written a simple spinner wrapper, but was wondering if any of you could think of any ways to make it more robust. It only handles strings at the moment. MySpinner: package a.b.c; import android.content.Context; import android.util.AttributeSet; import android.widget.ArrayAdapter; import android.widget.Spinner; ...
This is a simple list of items in a list, which allows the user to dynamically generate that list of events. Then a controller action does the work of serializing that into the database. The issue is that there's the PHP-generated HTML segment, and there's a separate JavaScript segment to do the additions (for when som...
I've been writing a function: float turnToRequestedHeading(float initialHeading, float requiredHeading, float turnRate) I keep thinking there must be a clever way to do it, but it escapes me. All values are in Radians, Headings between -\$\pi\$ and +\$\pi\$, and turnRate between -0.5 and +0.5. If the requiredHeading i...
I'm looking for the most commonly used style for writing the delete_item() function of a singly linked list, that find a matching item and deletes it. Is what I have the 'typical' or 'normal' solution? Are there more elegant ones? What seems inelegant to me about my solution below, although I don't know a better way to...
This function in my Profile model receive a hash from a search form and should filter the table depending on those values. I guess there is something like a pattern for such a standard behavior, right now I ended up with this (unfortunately I had to reproduce the code here, so it might not work for some reasons, but yo...
A little background first. I've been working on a fairly large Rails application which quickly grew into a breeding ground for "smelly" code. One antipattern we were using a lot was storing objects in an STI lookup table and having lots of scattered logic based on the name of the object. Here's a dumbed down example o...
I have a class whose purpose is to display a comment. I'd like to be able to instantiate it by passing a Comment object if I happen to have it available, or just the values if that's what I have available at the time. Unfortunately PHP doesn't allow overloaded constructors, so here's the workaround I came up with. cl...
I intend this to be a general question on writing an effective set of test cases for a controller action. I include the following ingredients: Ruby on Rails RSpec: A testing framework. I considered doing a vanilla Rails question, but I personally use RSpec, and I feel many other folks do too. The principles that come ...
Please review this: from os import path, remove try: video = Video.objects.get(id=original_video_id) except ObjectDoesNotExist: return False convert_command = ['ffmpeg', '-i', input_file, '-acodec', 'libmp3lame', '-y', '-ac', '2', '-ar', '44100', '-aq', '5', '-qscale', '10', '%s.flv' %...
I have 2 functions used for parsing a house number and I think these can both be improved. Any suggestions? input: 45a - 47b or 45a bis 47b output: 45,a,47,b public static string[] HausnummerAufteilen(string hausNummer) { string[] result = new string[4]; string[] resultVon = new string[2]; ...
<% @descriptions.each_with_index do |description, i| %> <% description.tale2.each do |tax_ref| %> <% if condition %> <% if condition %> <% if condition %> <%= $text_first_describe%> <%= $paren_author_yr %> <% ref_sp_uniq.each_with_in...
I need a code review for best practices and code correctness of the following piece of code. run executes a program and validates in output. If the output is valid status can be found in VALID_SOLUTIONS. elapsed = None tmpdir = tempfile.mkdtemp(prefix='structure-%s-' % os.path.basename(instance)) try: for r in range(...
I'm building an ASP.NET MVC app and would like some feedback for my way to query/execute statements to the ORM. I'm using Fluent NHibernate, and have mixed the UoW provided by NHibernate with a Command pattern. ICommand.cs (Core layer) using NHibernate; namespace MyDemon.Core.Commands { public interface ICommand<o...
I have a small solution to the following hypothetical problem: Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions. When I purchase items ...
Is there a better (more pythonic?) way to filter a list on attributes or methods of objects than relying on lamda functions? contexts_to_display = ... tasks = Task.objects.all() tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks) tasks = filter(lambda t: not t.is_future(), tasks) tasks = sorted(tas...
I'm currently working on several projects for my company to help reduce the amount of calls we have to deal with so we can focus on higher priority task, such as server resource reduction, etc. The first project on my list was to reduce the number of proxy issues a user has when migrating from an internal network to an...
I've written an abstract class in C# for the purpose of random number generation from an array of bytes. The .NET class RNGCryptoServiceProvider can be used to generate this array of random bytes, for example. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyLibrary { ...
I have a small 10-liner function that writes some data to a file using an std::ofstream. I did not explicitly call .close() at the end of my function, but it failed code review with the reason that it is better to explicitly call it for style and verbosity reasons. I understand there is no harm in calling .close() expl...
How does this class to resize an image look? using System; using System.Collections.Generic; using System.Web; using System.Drawing; using System.IO; /* * Resizes an image **/ public static class ImageResizer { // Saves the image to specific location, save location includes filename private static void saveI...
Here you go: #define abort(msg) (fprintf(stderr, msg) && *((char*)0))
Please have a look at these iterators which I use for my Sudoku solver. They behave slightly different from STL iterators and don't implement all functionality that would be needed to use them in a stl context. But the basic idea behind them was to clean up the code in the Sudoku program that makes heavy use of the thr...
I have a class that spawns threads to process data. I am working on instrumentation code. When the process is started, time = System.currentTimeMillis(); When it completes, time = System.currentTimeMillis() - time; I have a method to retrieve this time: /** * Get the time taken for process to complete * * @return T...
I am learning clojure and decided to start out by trying to write a solution to a fairly simple algorithm, reservoir sampling. As I stated, I am learning clojure specifically and problem solving in a functional language in general. Can someone please take a look at my code and critique it on it's "clojureness". Am I...
I implemented a solution to this coding challenge on the Code Golf. I have decent experience with C/C++, but it's been a while since I've used them extensively. #include <math.h> #include <stdio.h> #include <stdlib.h> // Prototypes struct BTnode; struct BTnode * bt_add_left(struct BTnode * node, int data); struct BTno...
I'm trying to learn a little bit about functional programming and as my tool I chose F# since I'm a .NET developer and the environment is more natural to me. In one of my pet projects I'm dealing with dates, so I created a function to get the last date where a given week day occurred. For example, last Tuesday was yest...
My own CMS is currently using jQuery, but as one of the goals is to have the whole project to be very small, I've decided to write my own basic library. I only really need to select elements and modify them using results from my server (via Ajax). The JavaScript-library v0.01: (Attempt 1) (function(){ a=this.Funct...
This code writes to Excel using the COM interface. The general issue is that any exception handling has to handle the "Excel is busy" exception. This occurs if information is sent to Excel quicker than it can handle it - eg. latency when a workbook is loaded/created, or the user is playing with the scrollbars (there ar...
I'm writing a logger extension that allows multiple threads to log a process, and then dump that log to the main log in one atomic operation. The point of it is to make the logs easier to read when many threads are executing. Is this test valid and clear or not? /** * Test that thread logs do not interlace * @throws ...
I have a block of code below. The allDone() method at the bottom should only be run if the allCompleted == true. It should run through each of the statements to test. allCompleted: This starts as true so the below logic works right. run*.Checked: This is based on a check box in a form. This block should only run if th...
I got sick of manually xrandering things on my computers (especially since I always just sequence monitors from left to right and set each at the highest resolution) so I wrote this: #!/usr/bin/ruby def xrandrPairs (xList) ## Takes a split list of xrandr output and returns [[<display name>, <max-resolution>], ...] p...
I'm working on a web application that I inherited from a colleague long gone. To connect to the MySQL database I use the following classes: statement.php <?php //class sql //{ class Statement { private $m_connection; function __construct($connection) { $this->m_connection = ...
The point of this question I'm actually using it while developing a simple application and it seems to cover all my needs. Also it uses PDO so that we don't really have to worry about SQL Injection. I know I usually code strange, but I hope you could give me suggestions and feedback in order to improve it. Code: Databa...
Please take a look at my program and let me know how I can improve it. /* " To Print A Line On The Display Screen" Date:5th January 2011 Programmer:Fahad */ #include <iostream> using namespace std; class Print { public: void print_(); }; int main() { Print Obj; Obj.print_(); system( "p...
The function below is called to determine if a given file is the archive of another file. I'm also looking for a way to supports wildcards. For example if the original log file is serverw3c.log and we type serverw3c*.log, it returns true for the following: serverw3c.log.2011-02-04 serverw3c.log serverw3c.log.20110204_...
After asking this question, I decided to write a test and determine the fastest way to wrap an index (where my maxSize is always a power of 2). There are 3 functions that I'm comparing: // plain wrap public static int WrapIndex(int index, int endIndex, int maxSize) { return (endIndex + index) > maxSize ? (endIndex ...
I have a piece code similar to below: But I keep having this nagging feeling that there has to be an easier way! Any ideas? var synch = false var indexArray = new Array(); var rowCount = theTable.find('tr').length; $(".views").each(function(index) { indexArray.push( $(this).val()); // Not the real code but somethin...
I have written another program in C++. Excluding the point that the class definition should be in a separate header file, is there anything that needs to be improved? /* Date:5th January 2011 Programmer:Fahad */ #include <iostream> #include <string> using namespace std; class Persons //A class that will sto...
I've got a Clojure function here that's meant to parse a string of form: "DDXXXYYY" where DD is meant to be discarded, and XXX and YYY are string representations of integers. (defn split-id [tileid] (map #(Integer/parseInt %) (map (partial apply str) (partition 3 (drop 2 tileid))))) Or, written ...
This is what I've done so far: $block-height: 180px; @mixin block { float: left; margin-bottom: 20px !important; margin-right: 20px !important; overflow: hidden; } #content h2 { height: 30px; } #top-bar { overflow: hidden; } .block-1 { @include block; width: 340px; height: 390px;...
I haven't had anyone help me out with code review, etc, so I thought I'd post a Python class I put together for interfacing with Telnet to get information from a memcached server. import re, telnetlib class MemcachedStats: _client = None def __init__(self, host='localhost', port='11211'): self._host ...
I basically have an AJAX-fetched skin (html/css) that's loaded into a dummy element (id=SkinContainer) when the page is loaded, and then the content of one of its divs (contentdiv) is fetched with another AJAXHTTPRequest. At any rate, when the page is loaded, the user can click a button to swap the theme/skin. Below is...
Instead of writing four almost identical setOnClickListener method calls, I opted to iterate over an array, but I'm wondering if this was the best way to do it. Do you have any suggestions for improving it? /* Set up the radio button click listeners so two categories are not selected at the same time. When one of th...
I wrote the following Ruby script several years ago and have been using it often ever since. It opens a text editor with the list of files in current directory. You can then edit the file names as text. Once you save and exit the files are renamed. The renamer allowed me to maintain spreadsheet-like file names thanks t...
I just want to make sure there aren't any deadlocks or inconsistencies (the code is also available on GitHub). Disclaimer - In real life, I would not implement a queue myself, but use an existing implementation. This is just preparations for job interviews. package org.basic.concurrent; import java.util.ArrayList; im...
I wanted a class which executes any number of tasks but only a certain amount at the same time (e.g. to download various internet content and keep the overall download speed at a good level). The class I wrote seems to work but there are probably things that can be improved. Do these locks make sense? Should there be ...
I have inherited this snippet of jQuery JavaScript and am currently brushing up on my jQuery. NetBeans IDE complains that Anonymous function does not always return a value. So there is not always an explicit exit point. I am aware that the $() shortcut is not being used. This is because it is running within a WordPress...
The following code retrieve custom post types with their custom taxonomy. I'm just a beginner in PHP and I would like to know tips in order to improve readability and perhaps efficiency. home.php: <?php /** * Template Name: Home * @package WordPress * @subpackage Prominent * @since Prominent 1.0 */ get_header(); ?...
Question + Desired Outcome The code below works currently, however I'm not convinced the utilisation of an Array to iterate through numerous non-existent form fields is anywhere near efficient enough for my liking. Can this process be improved to effectively eliminate the first step in the Suggested Solution? Desired O...
Is there a better way to accomplish the following? /** * Performs an access check given a user. * * @param Cas_Acl_Sid $user The user or SID being checked. * @param Cas_Acl_Privilege $privilege The privilege to check. * @return int|null 1 if user access allowed, 2 if group access allowed, false if access is denied...
I started to write a code with top-down tests. My first version, grow to something like this: public class Worker { public void Execute(Foo foo) { //Do X on Foo //Do Y on Foo //Do Z on Foo //Get Bar from Foo //Do A on Bar //Do B on Bar //Do C on Bar } } then this started to ...
This seems a bit wrong because there's a lot of business logic going on inside the bootstrapper. Is there a better way to accomplish what's going on here? <?php /** * Zend_Application Bootstrapper * * @copyright 2011 Case Western Reserve University, College of Arts and Sciences * @author Billy O'Neal III (bro4@cas...
I am trying to write a LISP interpreter in C#, so I started with a tokenizer. I haven't finished it yet (have to handle floating point numbers & symbols), but I already rewrote it two times because I can't wasn't satisfied with design. public class TokenizerException : System.ApplicationException { public Toke...
I wrote this sieve of Eratosthenes with MPI, but I'm not sure if it's good enough. Should I use MPI_Scatter and MPI_Gather instead of collecting arrays of separate processes in the root process? Also, I'm not sure if I call printArray(myArray, (N/size)-1); right, where myArray is an array of pointers. GCC gives a war...
Here is the pertinent code: index.html <!-- DOM INITIALIZATION --> <script type="text/javascript"> $().ready(function() { getThemeInfo(); if (themeSelect==2) { ReplaceJSCSSFile("css/skin1.css", "css/skin2.css", "css"); // overwrite CSS } AJAX_LoadResponseIntoElement("skinContainer", "skin" + themeSelect + ".tx...
This sample code works fine, but it looks awful. How would you improve this? data.Add(((Adress)(((OwnerIDList)owner.Adresses.Value)[0].Adress.Value)).FirstName.Value.ToString()); data.Add(((Adress)(((OwnerIDList)owner.Adresses.Value)[0].Adress.Value)).LastName.Value.ToString()); Why do we use .Value in FirstName.Valu...
public boolean connectedOnGameServer = false; public final Object conGameServerMonitor = new Object(); public void connectedToGameServer() { synchronized (conGameServerMonitor) { if (connectedOnGameServer != false) throw new RuntimeException("Player connected twice"); connectedOnGameSer...
I'm writing a quiz application in PHP and am querying the DB for questions and their associated answers. I then wrangle the result set into a usable array for my front end. However, it always seems like a wrestling match and I'm wondering if I could have got to my desired array structure more efficiently. What I wanted...
I recently had a discussion in the forum of an API, because they changed an exception from checked to unchecked. I believed it needs to be checked, because it is recoverable. The arguments of "the other side" were verbosity and tediousness of try/catch or throws. If it were purely theoretical question, I'd be right, bu...
I have a rectangle with size w and height h. Now I want to split this rectangle into n new rectangles that are as similar as possible to a square. Afterwards I'd like to calculated the center of each square. public static List<Point> getCenters(int number, double width, double height) { List<Point> points =...
Here's a function that interpolates between a given value and a value fetched out of a legacy serialization buffer: template<typename T> T interpolate(Buffer& buffer, const T currentValue, const float prop) { T bufferValue; buffer.readT(&buferValue); return currentValue + (bufferValue-currentValue)*prop; } ...
I am building up a basic folder tree with a list of strings in the form /root/node/node/node. Here is the basic algorithm I am using currently to build this collection and fill in my TreeGridView: // This method gets the list of folders and leaves, then trims out any folder paths // that are already encompassed in a la...
For interop purpose, this is something that I always do (C#): public static extern BigObject InteropWithCPlusPlus(); where BigObject is ( you guess it) a big object, it's not something small like int, or double. Now, is this a good practice? Or is it better to do the interop in this way: public static extern void Int...
Could this be made more efficient, and/or simpler? It's a path-finding function. It seems to work, but do you see any potential cases where it could fail? // Searches for a path from [start] to [end]. // Predicate [passable] should take an std::pair<int,int> and return true if the node is passable. // Nodes in path a...
I've written this rather naïve branch-and-bound based IP solver. Are there any obvious JavaScript optimisations that could speed it up? I am not looking for asymptotically better algorithms, just simple speed optimisations effective on problem sizes with 5-6 variables and minSize values up to about 500. /** Represents...
I've got some legacy code which I need to maintain and its got this function which works perfectly fine, but I'm trying to understand if it is working using acceptable coding practices or not... I am trying to understand if it is safe and secure to operate the site with the function as-it-is. The function would be call...
I'm going over the interview questions from "Cracking the Coding Interview" and one of the chapters (Chapter 7) deals with Object Oriented Design (OOD). The requirements for one of the problems are as follows: Imagine you have a call center with three levels of employees: fresher, technical lead (TL), product man...
I want my application to support multiple UI-languages (aka i18n). To do so, I have built the static class below, to automatically translate the form and all its contents to the desired language. It looks into a resource file for the user's Culture, and replaces the .Text properties of the controls with the strings it ...
I use named scopes all over the place. When I have a named scope that deals with two different tables, I tend to query the second table in a sub-query. That way, if I mix and match with other tables I don't need to worry about reusing a table alias or having ambiguous column names that only appear in bizarre scenarios...
I've implemented the GroupBy extension method for IEnumerable<T> type as an excersise to deep a little more into LINQ. What do you think about the source code? Code: static IEnumerable<IGrouping<TKey,TElement>> GroupBy<TKey,TElement>(this IEnumerable<TElement> source, Func<TElement,TKey> keySelector) { //Grouping ...
The CMS I use uses the Xalan XSLT processor which is a XSLT version 1.0 processor. Editors who use WYSIWYG fields within the CMS can save content that will look like either: <story> <p>Story Text which may have <em>formatting</em>.</p> </story> or: <story>Story Text which may have <em>formatting</em>.</story> or ...
I've written a lengthy procedure that I call a few times to apply filters defined by the customer to a table, as I didn't see how I could turn my column name string into a LINQ column and how I could turn my action string into an action on a string in such way that the function can be used in the LINQ query like: priva...
The main view in my (toy!) Todo app is, of course, to display the list of tasks. These are grouped by some criterion, and the tasks structure below is actually a list of pairs (header, list of tasks). {% for tasks in tasks %} <p class="list-header">{{ tasks.0 }}:</p> <ul> {% for t in tasks.1 %} <li...
I need help to refactor my code. I usually had a hard time figuring out how to make my code reusable. I have an XML file that hold the data for each Tag element. Tag element should have child nodes LastClocked, and TotalClocked. I first thought of creating Tag object and do serialization. But, I found Linq to XML is mu...
The code pretty much explains what I am doing here. Just wondering if anyone can think of a better way. public class AttachmentQuery { /// <summary> /// Initializes a new instance of the <see cref="AttachmentQuery"/> class. /// </summary> /// <param name="type">The type.</param> /// <param name="sta...
Below are two solutions to the FizzBuzz problem in Python. Which one of these is more "Pythonic" and why is it more "Pythonic" than the other? Solution One: fizzbuzz = '' start = int(input("Start Value:")) end = int(input("End Value:")) for i in range(start,end+1): if i%3 == 0: fizzbuzz += "fizz" if i...
Often I generate long lines of code such as the following... shippedItems.AddRange(OrderItem.Fetch(market: this.MARKET, shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE, orderPlacedAfter: serverTime.AddDays(-7), orderPlacedBefore: serverTime.AddHours(-85))); ... which adds the results of a method call to an existing l...
I've created and I manage a point of sale web application built in PHP which has thus far followed no clear guidelines or methodology for development; it's operation is completely procedural. In turn, because the department that's using it requests new and different features like it's a Las Vegas buffet, the software h...
I have a parser for CNF formulas in Dimacs format, which is very slow. Any suggestion on how to improve its speed? I did some profiling and I might have to replace Scanner. Is there anything faster? A possible input for the parser is: c A sample .cnf file. p cnf 3 2 1 -3 0 2 3 -1 0 The code: /** * Parses a stream f...
The following is like the Unix "tail" program. It was assigned as an exercise in Chapter 5 of Kernighan & Ritchie's The C Programming Language. Because I've only read through most of Chapter 5, I'm still unfamiliar with certain topics, such as malloc(), which may have been more appropriate to use, I don't know. I've do...
I had a question about using the modulus operator in Python and whether I have used it in a understandable way. This is how I've written the script: #sum numbers 1 to 200 except mults of 4 or 7 def main(): sum = 0 for x in range(200+1): if (x % 4 and x % 7): #is this bad??? sum = sum + x ...
Is there a way to do this using parameters so the value is automatically converted to whatever datatype the keyfield has in the datatable? This code should be reusable for future bulk update applications hence the constant and the check on multiple datatypes. private const string DBKEYFIELDNAME = "CustomerNr"; ... ...
I have some small applications that I want to secure. I've been using the following setup that I think is fairly safe, but I've never been able to set my mind at ease that it really is. Could you give me some reviews on the security of this? It doesn't need super-security like credit card data, but I suppose secure i...
Here's a method I made that's supposed to print out multiples of any numbers up to any quantity: def DisplayMultiples(multiplesOf, count) i = multiplesOf while i <= count if i % multiplesOf == 0 puts i end i += 1 end end Any suggestions on how to improve the code to something more fitting to th...
The below is \$O(n^3)\$. I'm sure there is a way to improve this.. //vector<string> flight_path; given as parameter //vector<int> flight_number; need to fill //vector<segment> flight_segments; known, contains segments (dep, arr, flightnum) //Purpose of the function is to take in a flight_path and give back a list of /...
I am primarily a Python programmer and have finally ditched the IDE in favour of vim and I will admit, I am loving it ! My vimrc file looks like this: autocmd BufRead,BufNewFile *.py syntax on autocmd BufRead,BufNewFile *.py set ai autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,with,try,except,fin...
I have a function that takes a column title, and a response.body from a urllib GET (I already know the body contains text/csv), and iterates through the data to build a list of values to be returned. My question to the gurus here: have I written this in the cleanest, most efficient way possible? Can you suggest any imp...
I was playing around with LINQ and I came up with the following idea for composing locks taking advantage of C# Monadic syntax. It seems too simple, so I thought let me post it on StackExchange and see if anyone can quickly spot any major problems with this approach. If you comment the lock inside the atomic implementa...
I have created a small server program that encrypts text using a named pipe: #define UNICODE #define WIN32_WINNT 0x0500 #include <stdio.h> #include <windows.h> #include <signal.h> HANDLE hPipe; DWORD WINAPI ServerProc(LPVOID lpVoid) { hPipe = CreateNamedPipe(L"\\\\.\\pipe\\testpipe", PIPE_ACCESS_DUPLEX, PIPE_T...
I am looking for any possible improvements on this tagging widget. I ask for special attention to be paid to my blur handler in the event of a autocomplete option being specified but any optimizations or critiques are welcome. Demo: http://webspirited.com/tagit Js File: http://webspirited.com/tagit/js/tagit.js ...
I was writing a piece of code (a custom EntityProcessor for Solr, but that isn't too relevant) designed to break lines of input based on a string delimiter (toMatch below). Characters are read from a stream and then passed to addChar. The assumption is that each character comes in a stream and look-ahead isn't allowed ...
In my spare time I decided to write a program that would systematically identify prime numbers from 2 to 18,446,744,073,709,551,615. This is for fun and learning, as I know it will take too long to actually ever reach the upward value, but I'm using this to explore parallel processing. I know this is not a traditiona...
The general idea of the code is that I have a + or - icon (".trigger") that is click-able and will expand or collapse the content (".cont") directly following it (there are many of there expand/collapse pairs). I also have a span("#expandAll") that, when clicked, will expand or collapse every block. Please review my f...
I'm trying to apply string.strip() to all the leafs that are strings in a multidimensional collection, but my Python is a bit rusty (to say the least). The following is the best I've come up with, but I suspect there's a much better way to do it. def strip_spaces( item ): if hasattr( item, "__iter__" ): if ...
I have an extension method that does this: public static IEnumerable<T> ToIEnumerable<T>(this T source) where T : new() { return new[] { source }; } I need to be able to convert any object to an IEnumerable. For example when I use the .NET Except method: public static IEnumerable<TSource> Except<TSource>(this IEnu...
I think there are some confusing and weird indentation problems in this WordPress file (single.php). Any suggestions on improving indentation and readability? <?php /** * The Template for displaying all single posts. * * @package WordPress * @subpackage Starkers * @since Starkers 3.0 */ get_header(); ?> <?php g...
I'm new to Java and find it hard to grasp the concept of objects. I wrote a simple guessing game to practice the concept of OO programming but I am not sure if I am doing it correctly. The objective of the game is to guess a number from 0-9 with 3 players and the first player who guesses it correctly will win the game...