instruction stringlengths 71 95.1k |
|---|
Provided Object.prototype hasn't been modified, will the following snippet work in major browsers?
var obj = {length:0};
var push = Array.prototype.push;
push.call(obj,'1st value')
push.call(obj,'2nd value');
Many have responded that the above code is bad practice, but what makes code like this any better?
Array.proto... |
I have a large namespace, but I don't want enum constants to be a part of it. In cases where an enum is related with a class, I coded enums inside the class so I can reach it using the class name. However, if an enum is related with namespace functions, what is the best way to do it?
Use another namespace and put the ... |
I am progressing through the problems listed at projecteuler.com as I learn Scala (my blog where I am covering this experience). I have written a function to produce all the Fibonacci numbers possible in an Int (it's only 47). However, the resulting function feels imperative (not functional).
val fibsAll = {
//ge... |
The basic requirement of my code is to accept a file input, parse it, convert it to a java type (A DTO essentially) for use in another component of the system.
I should also note that I am not actually parsing a file from a filesystem, the FileParser will be used by a Message Driven Bean that has the contents of the fi... |
I'm trying to make an MVC3 application with an exchangeable data layer. I currently have this in a single file (Global.asax.cs) for brievity.
It seems to be working as I want but as I'm new to DI I really would appreciate comments on this code.
public interface IDataLayer
{
dynamic GetItem(int id);
dynamic Save... |
Whenever a button is clicked, the following need to be performed:
All siblings of the clicked button get toggled
All edit_button get toggled, except for the edit_button within the same span as the clicked button (note: the excluded edit_button can be the same as the clicked button)
The JavaScript is working in the wa... |
Just wondering if I could solicit some feedback on a stored procedure I'm running and whether there's a more efficient way of handling the scenario (I'm pretty sure there will be!).
Basically I have a single SP that I call to return a list of records (Jobs) that may have one or more statuses and a sort order (I'm using... |
I have some code which looks like this:
do {
hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched);
if (hr == S_FALSE) { break; }
llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;
} while (hr != S_FALSE);
It is bad because hr == S_FALSE is checked twice on every iteration.
I could write it lik... |
Is there any different in performance for the following 2 queries.
I'm just wondering what is the better of the two:
var res1 = (from a in _ctx.DataContext.Actions
join e in _ctx.DataContext.Events on a.EventId equals e.EventId
select a).Single(a => a.ActionId == actionId);... |
Before I start working on a quite JavaScript heavy application I would like you to review my JS MVC approach.
How can it be improved?
Are there any mistakes/issues I should be aware of?
Since the entire app will have multiple modules I would like to split the code into standalone modules that can be loaded as require... |
I was wondering if this code can be coded better in terms of semantics or design. Should I return the LOS as numbers? should I have the constants be read from the db in case the user or I want to change them in the future?
def get_LOS(headway = None, frequency = None, veh_per_hr = None):
if frequency != None and head... |
I'm learning a little Scala by writing a little card game. What I want to do here is check that the Traversable[Team] supplied has the same number of team members for each team.
How can I clean this up?
val teamSizes = teams.map(_.members.size)
require(teamSizes.foldLeft((true, teamSizes.head)) {
(tuple, lastSize) =>... |
How can I improve up this code?
Is it ok to write code using Invoke and Action so liberally or is this bad?
Performance is not an issue as I'm not using Invoke 50,000x in a a row (a lot of other things will be done in-between, making the performance hit null).
The primary goal is to run my list of tasks either by Item... |
I'm working on set of methods that locate DVR surveillance footage, based on timestaps.
The files are in the following format:
<drive>\<year>\<month>\<day>\<camera>\<hour>-<minute>-<second>.<extension>
Example:
Z:\2011\07\02\000001\00-13-15.mkv
through
Z:\2011\07\02\000001\23-45-13.mkv
The videos are in 15ish minute i... |
I am a C# developer, dont know much about vc++ or c++, never used it, for some reasons i have decided to use a c++ dll in my app for downloading content from the web.
I dont want to use WebClient.
I want it to download html content by providing Url of the resource, the dll will return the string response.
this is the c... |
Rather than doing what is essentially a large switch statement for every possible type, is there a better more generic way of converting to a specific type with reflection? I've looked up TypeConverter but don't understand the documentation.
if (header.Property.PropertyType == typeof(Int32))
{
header.Property.SetVal... |
I've been researching various patterns for structuring my business logic & data access, particular in the context of C# and the Entity Framework. I've come up with a basic idea of how I think I'd like to do it, based on several SO answers:
https://stackoverflow.com/questions/1169188/ef-objectcontext-service-and-reposi... |
I have a requirement where I need to build a grid with dynamic columns. I am dealing with a large dataset so I would like to use server-side paging, sorting, filtering logic so that I render only a page-size. I think I got the basic functionality working but just wanted to get my approach reviewed.
An action route will... |
I've built a discrete event simulation system, similar to the bank problem presented on the wikipedia page but with a key difference.
Let's say, that a TELLER can service two CUSTOMERS at the same time, and that the CUSTOMER-DEPARTURE time depends upon the number of CUSTOMERS a TELLER is servicing concurrently; I need ... |
The below code works fine with no errors and no problems.
However, I think that it is too long, and I want to refactor it by separating the three parts (as commented on the code) by creating a new method for each of them, so that I can reuse them later.
I tried to separate Part 2 and created a method which takes an IQu... |
I have a method to parse strings. It can be used to parse a float using a specific culture and then get a new string with a specific out-culture. The same applies to ints, doubles and decimals.
The code that I've written is quite repetitive for each of the different parse methods which makes it hard to maintain (espec... |
So, consider the following code:
public class OneConcreteTypeOfOutputFormat
{
private Dictionary<Type, IEntityWriter> writers;
public Dispatcher()
{
this.writers = new Dictionary<string, IEntityWriter();
CreateWriters(writers);
}
private void CreateWriters(Dictionary<string, IEntit... |
I often use jQuery plugins for front-end functionality in web applications. This requires me to write code like this, where I am assigning a function to an object property:
var trainingDiary = $("#training_diary").fullCalendar({
dayClick: function(date, allDay, jsEvent, view) {
var title = prompt('Event Title:')... |
I have roughly 40 or 50 functions that are similar to the one provided by the code below.
I kept all the common calculations between multiple functions separate such as service_coverage_area . I then kept all the specific calculations that are not repeated or needed by any other functions in the function that needs tho... |
Should the following be considered wtf code?
abstract class BaseCat
{
public virtual void SayMiau()
{
Console.WriteLine("MIAU!");
}
}
class StrangeCat : BaseCat
{
private readonly bool _canMiau;
public StrangeCat(bool canMiau)
{
_canMiau = canMiau;
}
public override vo... |
For a little background, I'm a contributor to SquishIt and decided that I should start cleaning up the mess of unit tests (my updated version of one set of tests vs. original set of tests). After tackling only part of the "rewrite", I figured it would be a good opportunity to learn, try, and understand BDD style testin... |
I'm trying to optimize performance for recursive directory listing with some exceptions:
function listdir($basedir) {
global $root, $ignore_dirs, $ignore_files, $filetypes, $ignore_starts_with;
if ($handle = @opendir($basedir)) {
while (false !== ($fn = readdir($handle))) {
if ... |
A short while ago, I have submitted a coding exercise to a
potential employer. The response came back the next
morning and you can guess what it was from the subject
of this post.
I am not totally at loss, but I need another programmer's
perspective. Is there anything that jumps out?
The idea of the exercise is si... |
I have a method with too many parameters.
How would you refactor it?
Things I considered so far:
pass an array to the object and check for required keys (no code hint, phpdoc, programmer doesn't know which are required)
pass an object (silly method with getters and setters, programmer still doesn't know which are req... |
I'm hoping some folks can take a few minutes to review some code I was working on today.
https://gist.github.com/1115202
Essentially, I'm doing a lot of work in Node.js at the moment and I'm a big fan of Promises.
Since 99% of the work that I'm doing involves performing several asynchronous actions and then parsing the... |
I am new to erlang (2 days to be honest) and I would highly appreciate some peer review. I am doing these exercises and was a bit stuck at this point:
2) Write a function which starts N processes in a ring, and sends a
message M times around all the processes in the ring. After the
messages have been sent the proc... |
I was told this is the place to come for input/feedback on your programming. I am always looking to improve either by personal review or outside opinion/help. Would the community here be willing to provide positive criticism of my script below?
/********************************************************************
* Au... |
I am trying to get in a lot of practice for interviews so I am trying to write as much code as possible, and getting feed back from excellent programmers like "you". Can I get some general feed back on this small bit of code? Any recommendations on style, good practice, etc. is greatly appreciated.
Normally I would put... |
I'm writing a BitTorrent client. Part of the protocol is an exchange of length-prefixed messages between peers. The forms of these messages are described in the official specification and also in the unofficial specification that is maintained by the community. This is my code for writing out this messages into a strea... |
I found the following two types of exception-handling in Business Logic Layer.
ASP.NET 3.5 Enterprise Application Development uses a similar method like the first one (I read it few years ago).
I also found this on Stack Overflow, but it doesn't answer my question.
I'm wondering which one is better design and efficien... |
I guess I might use delegates. But I'm not certain if I can apply for it.
Sorry if the code is a mess. I'm a beginner and am still learning. For that reason, I need a little of help to improve this code. It's not finished.
I'm creating a Math quiz system. And there are many questions as you will be able to see in it... |
I'm just looking for more feedback on style/approach regarding this small problem. Also, if you have tips to make it more readable or C++-like, please let me know.
Also, why is the problem asking for the sum and mean of each name and all names, while the sum of a single element is itself? Am I missing anything in terms... |
What I am creating is essentially a binary clock face with touch input for setting values as well as displaying - so I need to convert both ways between an int and a binary sequence in a BitArray.
I cobbled this together (borrow and modifying a bit from a couple different examples I found):
public class BinaryConve... |
I wrote below code to crypt and decrypt some bytes in three algorithm with Java
but I do not know if I wrote them in correct mode or not.
Please tell me about truth of code.
First class:
public class Cryptography
{
Cryptography() {}
public byte[] Encryption_AES128(byte[] plain , byte[] key) throws Exception
... |
I will make it more reader friendly after I get the algorithm completed. Does anything with the quick sort algorithm stand out as for why it is not working 100%? This is not homework; I am just practicing problems out of books and I am caught on this one.
Hints, more so than answers, would be more appreciated. Please d... |
This is a short piece of code but I feel like it could be done more elegantly. What am I missing?
The goal: if there are any items in a list, and none of them have a given property, set one of them to have that property.
static void GuaranteeAtLeastOne<T>(IEnumerable<T> list, Func<T,bool> getter, Action<T> setter)
{
... |
<?php
class Database
{
private $_dbh;
private $_stmt;
private $_queryCounter = 0;
public function __construct($user, $pass, $dbname)
{
$dsn = 'mysql:host=localhost;dbname=' . $dbname;
//$dsn = 'sqlite:myDatabase.sq3';
//$dsn = 'sqlite::memory:';
$options = array(
... |
I have a NumPy array of about 2500 data points. This function is called on a rolling basis where 363 data points is passed at a time.
def fcn(data):
a = [data[i]/np.mean(data[i-2:i+1])-1 for i in range(len(data)-1, len(data)-362, -1)]
return a
This takes about 5 seconds to run. I think the bottleneck is the li... |
I've got a case where I need to call a couple of methods, checking if they return null, and return some property from the result of the second when neither returns null.
I've thought of two ways to do this - one "verbose" and one "concise". For the purposes of this question, I'll just call the return types 'dynamic' s... |
I'm writing a method that takes (1) an array of ints and (2) an int. The purpose of the method is to find the indices of the two numbers in the array that add up to the value passed in as the second parameter to the method (sum) and return those values in an int[]. Exactly two numbers in the passed in array will add ... |
This code gets me where I need to be, but my word it is ugly.
I am checking for the existence of two $_GET variables with if() statements. I am setting the variables to empty strings first so I do not get an error when I echo them back.
$getvar1 ='';
$getvar2 ='';
$np ='';
if(isset($_GET['getvar1'])) $page_id = $_GET... |
I'm just curious if this is clear to the average person.
template<typename IteratorType>
inline IteratorType skip_over(
IteratorType begin,
IteratorType end,
typename std::iterator_traits<IteratorType>::value_type skippedCharacter)
{
typedef typename std::iterator_traits<IteratorType>::value_type value_... |
I've been seeking to optimize this algorithm, perhaps by eliminating one of the loops, or with a better test to check for prime numbers.
I'm trying to calculate and display 100000 prime numbers has the script pausing for about 6 seconds as it populates the list with primes before the primes list is returned to the cons... |
I have an mail object that returns its headers as an Enumerator of Header objects, which have two methods, getName and getValue. I need to convert that to a nice Clojure map so I wrote this short function:
(defn extract-headers [message]
(reduce (fn [hs h] (conj hs {(.getName h) (.getValue h)}))
{}
... |
I am using the following template to program my 2D games in. Is there any way I can improve it?
Splash screen:
package com.dingle.template2d;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class template2d extends Activity {
@Override
public void onCreate(Bundle savedI... |
How would I accomplish the same thing in a functional paradigm?
Player.prototype.d2 = function(ratingList, rdList) {
var tempSum = 0;
for (var i = 0; i < ratingList.length; i++) {
var tempE = this.e(ratingList[i], rdList[i]);
tempSum += Math.pow(this.g(rdList[i]), 2) * tempE * (1 - tempE);
}... |
This is my personal project. This class is responsible for running jobs asynchronously that are registered using dependency injection.
All improvement suggestions are welcome. It can be as small as using a better name for a variable, re-architect the whole class, whatever. I'm just trying to improve myself.
GitHub
usi... |
I am learning Scala while solving some exercises and I am currently solving an exercise where I need to initialize a Sieve of Eratosthenes.
I am using the following code:
val sieve = Array.fill[Boolean](100)(true)
for (p <- 2 until sieve.length if sieve(p) && math.pow(p, 2) <= sieve.length) {
for (i <- p * 2 u... |
I am working on using STL and in general safe C++ practices. Instead of posting large samples of code I am working with a small sample to catch problems before I move onto larger ones.
How do you find out if an istringstream found an input that is not of the desired type? That is, you have a string and you want to ver... |
Looking at $wpdb class, I found get_row, and I am unsure if the function automatically prepares the query. I believe it does not and I may have to reexamine my code to prevent a future disaster.
Here is what my code looks, and I feel that it is vulnerable:
$wpdb->get_row("SELECT * FROM `my_table` WHERE column = '".$_GE... |
In my model, I have things called Reports that have known workflow associated with them.
I've got a requirement to output at which state a report currently is.
public abstract partial class Report{
public virtual string StateStatus(){
if (Check.IsSuccessful) return "Approved";
if (Check.AreClarifications... |
public static DateTime ObjectToDateTime(object o, DateTime defaultValue)
{
if (o == null) return defaultValue;
DateTime dt;
if (DateTime.TryParse(o.ToString(), out dt))
return dt;
else
return defaultValue;
}
The code feels too wordy and smells bad. Is there a better way?
|
I created this class to keep track of a user's role:
class UserRoleHelper extends AppHelper
{
public $helpers = array('Session');
private $role = NULL;
const CUSTOMER = 'customer';
const ASSOCIATE = 'associate';
const MANAGER = 'manager';
const ADMIN = 'admin';
const DEVELOPER = 'de... |
I have designed this model which is very flexible. For example, you can create asset types, assets and combinations of them infinitely. It is the front end to a Python Pyramid website, so all the validation and business logic is handled by the web app.
However, not being a db guy, I have this sneaking suspicion that th... |
A naïve quicksort will take O(n^2) time to sort an array containing no unique keys, because all keys will be partitioned either before or after the pivot value. There are ways to handle duplicate keys (like one described in Quicksort is Optimal). The proposed solution only works for the Hoare partition, but I've implem... |
I am trying to create an extension method that builds a POCO object (copies all the fields) for an Entity Object.
When Entity object is simple (no navigation, no sub collections), it works fine.
I want to improve it so it could also deal with sub-entities.
For this example I take Nortwind database and use Customer an... |
In the index view a user can search with any combination of one to all of the following parameters: firstname, lastname or ssn. The found search results are displayed in the search results view. In my HomeOfficeController I have written the code like this, but most of the code is repeating.
Can someone suggest a neater... |
I was asked to make a Java application with main class q2.
How can I make it better and more efficient?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Sort extends q2
{
public static double SWITCH;
}
class q2 extends JFrame
{
public static void main(String[] args)
... |
Here is a link to the code on JSFiddle.
This is my first attempt at playing with canvas. Before I move on doing anything else, it would be nice to have insight from somebody who knows canvas and JavaScript better than me.
Things I am looking for:
Ways to optimize animation
Ways to optimize the lazer drawing (I know I... |
While this is working very well for storing setting variables for my applications, I've been using it for a number of years and really feel there is something better. I'm perhaps just looking to use some newer functions from the framework.
public string Value { get; set; }
public string Name { get; set; }
... |
I am trying to solve an exercise in which I am given the following function:
/* squeeze: delete all c from s */
void squeeze(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}
the exercise is:
Write an alternative version of squeeze(s1,s2) tha... |
For a personal project, I'm working on a Java profiler that specifically targets ThreadPoolExecutor and its subclasses and provides statistics about throughput of executed tasks. To support this I've written the following utility classes, which are intended to help compute a smoothed average rate of events over time. T... |
I have several utility classes who should only ever have one instance in memory, such as LogHelper, CacheHelper, etc. One instance to rule them all.
I've never implemented Singleton in Java before, so I wanted to post my first pass and see if anybody had major issues with this, or just helpful critiques. I want to mak... |
The following implementation is of a repository proxy.
I will post only the code for NHibernate Repository here. Everything else (including configurers and tests) can be found on the pastebin.
P.S. : I changed all the XML-like comments to their more readable representation, so the actual code still has nice XML docume... |
Please review this.
public int InsertQuery(string Query)
{
int LastInsertedID = -1;
MySqlCommand MySqlCmd = new MySqlCommand(Query, this.sqlConn);
try
{
MySqlCmd.ExecuteNonQuery();
LastInsertedID = int.Parse(MySqlCmd.LastInsertedId.ToString());
}
catch (Exception excp)
{
... |
I wonder what is better code practice or just what looks better in Java:
Version 1:
protected Boolean doSomething(int amount) {
if (amount < 1) return false;
return insertToDb(fillImages(fetchInfo(REQUEST_URL, amount)));
}
Version 2:
protected Boolean doSomething(int amount) {
if (amount < 1) return false... |
I am currently reading The C++ Programming Language (Special Edition) and am learning about using templates. One of the exercises asks you to program a generic version of quicksort. I am hoping to build a namespace called Sorters that has a class for each sorter, just for learning purposes. I would like to also be able... |
This is a class from my rails application. It is used as non-database model in my RoR application and uses syntax similar to AR design pattern. I wonder is there a way to make this look more like Ruby code?
class Role
def self.all
role_list = Array.new
r1 = Role.new
r1.id = 1
r1.symbol = :owner
... |
I have something like this in my program:
private void tspBrush_Click(object sender, EventArgs e)
{
currentTool = new Brush(tileLayers);
UncheckToolstripButtons();
tspBrush.Checked = true;
}
private void tspBucket_Click(object sender, EventArgs e)
{
currentTool = n... |
I am preparing myself for some job interviews. This is a simple array (with the error handling left out for brevity). Any input or suggestions on style and the use of templates would be appreciated.
#include <iostream>
template <class T>
class Array {
public:
explicit Array(const int&);
Arra... |
I am attempting to learn R programming by going through the questions in Project Euler.
The code below is my solution to problem 5 which asks for the smallest number that is evenly divisible by 1 through 20.
The code works but takes a very very long time. Project Euler states that all of their problems should take a ... |
I'm writing GUI controls and there are many places where there are many nested ifs checking for some result.
function TMyObject.GetCursor: TCursor;
begin
if CanDragX then
begin
if CanDragY then
Result := crSizeAll
else
Result := crSizeWE;
end
else if CanDragY then
Result := crSizeNS
el... |
Is this code too cryptic? Simple yes or no question. Feedback is optional.
int recursive_euclidean( int num1, int num2 )
{
int gcd=0;
if( num1 == num2 || num1 < 0 || num2 < 0 )
( ( num1 == num2 ) ? ( gcd = num1 ) : ( ( num1 < 0) ? ( gcd = num2 ) :
( gcd = num1 ) ) );
else
( ( ... |
Here is a class that I made to validate forms data. I will really appreciate any criticism and hints.
<?php
class formvalidator {
public $filtered, $errors,$db,
$fields_type = Array(), $error_msgs = Array();
public function validate($form, $fields, $error_msgs) {
$this->fields_type = $fields;... |
I've been reading Cracking the Coding Interview and at the very beginning I got to the strange statement that the next complexity will be \$O(n^2)\$.
public String makeSentence(String[] words){
String sentence = "";
for (String w:words){
sentence+=w;
}
return sentence;
}
I can't get it. Why is it \$O(n^2)\$? ... |
I have the need to programatically create a context menu using names for the menu items which aren't known until the program loads user data.
Here's how I have implemented it. I'm not happy with the cast to get the menu item text to find out which item they have clicked on. Is there a better way that I'm missing?
publ... |
I have a windows forms application in which a backgroundworker is called again and again.
I need to avoid concurrent access of the code in dowork method for the backgroundWorker; but also need to ensure that the code in the dowork method is called; hence I cannot simply avoid running the backgroundworker altogether if ... |
I am working on a script that collects all comments from my DB and inserts them into a hash. I then do a collect on the comments hash and split the comments into two separate comment hashes (vid_comments & wall_comments)
w_hash = Hash.new
w_hash["comments"] = []
contender.subscriber.videos.collect { |v| w_hash[... |
Presented for critique are a pair of classes which automate Sizer Creation and Layout in wxPython.
import wx
from wx.lib.combotreebox import ComboTreeBox
from wx.lib.agw.floatspin import FloatSpin
wx.ComboTreeBox = ComboTreeBox
wx.FloatSpin = FloatSpin
class FormDialog(wx.Dialog):
def __init__(self, parent, id = -1... |
Each product in my e-commerce website has Arabic and English values for the title, description and excerpt. I have this method EditProduct to update those values based on current culture (Arabic or English)
public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)
{
... |
I am still uncomfortable and new with working with classes.
I have made a User class that will return stuff about the user.
<?
class User {
public function age($id) {
$birth = new DateTime("$id");
$now = new DateTime();
$age = $now->diff($birth)->format("%y");
return $age;
}
... |
The point of this algorithm is to see if an element exists in a NxN matrix that has its rows and columns sorted.
What would you change? What did I do well? Both perspectives help so I am not left guessing.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
/... |
I have implemented mutex and conditional variables using the futex syscall. I believe that my implementation is correct, but would like it to be verified by someone else. Any suggestions for further improvements in the performance of the mutex and conditional variables would also be appreciated.
#ifndef __SYNCHRONIZA... |
Aim:
Use C++0x features to make function interposition safer. The problem is that it's easy to make a typo when wrapping and interposing on functions.
Prototype Implementation:
#define MAKE_WRAPPER(x) static const wrapper<decltype(::x), ::x> x(#x)
namespace {
template<typename Sig, Sig& S>
struct wrapper;
templ... |
I have the following (extremely simplified) database structure:
Table: Competitions
Id: string, unique
Table: Persons
Id: string, unique
Gender: string
Table: Results
CompetitionId: string, references Id on the Competitions table
PersonId: string, references Id on the Persons table
EventId: string
RoundId: string... |
Unlike most(?) smart pointers, boost::intrusive_ptr has a non-explicit constructor. Given that, one could write
typedef boost::intrusive_ptr<Foo> FooPtr;
FooPtr MyFactory()
{
return new Foo(a, b, c);
}
Or one could write
FooPtr MyFactory()
{
return FooPtr(new Foo(a, b, c));
}
The latter is more consistent wi... |
I have two snippets that are going to be used in a walkthrough and I'd like some feedback on which one is more easily understandable
1
property int hours, minutes, seconds
property real shift: 0.0
property bool night
function timeChanged() {
var date = new Date();
hours = date.getUTCHou... |
This working script directs incoming traffic to different locations depending on the value present in the session for referring URI. If there is a present value, it sends the user back to their original location. If not, then a random number is generated, checked against and used to direct the visitor to one of two pos... |
This is my implementation of quicksort (algorithm taken from Cormen book). This is an in place implementation. Please let us know issues with this or any ideas to make it better. It performs at logN.
import java.util.ArrayList;
public class MyQuickSort {
/**
* @param args
*/
public static void main(... |
I have an application in which I am querying an XML web service continuously every 2 seconds in a thread. The returned XML is very big and I am retrieving lots of stuff from them using XPath and plugging the values into labels in the GUI, using delegates for thread safety.
But the way I've done this, it looks bizarre t... |
Below is what I have come up with for a router/dispatcher system for my personal framework I am working on. Can you please review and tell me any improvements that could be made?
The first part is an array of URI -> to class/method/id_number/page_number using regex. I have only included a partial list of routes, ther... |
I have got this working ok, I just think that it can be improved and reduce the amount of code. If anybody could help that would be brilliant.
// Max Length Input
$('input[maxlength]').each(function() {
var maxCharLength = $(this).attr("maxlength");
if(maxCharLength < 0 || maxCharLength > 5000){
... |
I'm spec'ing out a API for a task scheduler and I would be thankful for your thoughts. This is what I've got so far:
public void Configure(Context ctx) {
// Single tasks
ctx.Run(() => Tasks.First()).Every.Midnight;
ctx.Run(() => Tasks.Second()).Every.Day(8,0));
// Multiple tasks
ctx.Run(() => {
... |
There's another exercise from Thinking in C++.
This time it asks this:
Write a program that uses two nested for loops and the
modulus operator (%) to detect and print prime numbers
(integral numbers that are not evenly divisible by any
other numbers except for themselves and 1).
And this is what I think:
//... |
I'm an amateur programmer (self-taught). Anyway, this class provides a few methods to access Google's unofficial weather API. I'm having trouble on how to go about handling parsing errors in parse_xml() so any suggestions there would also be helpful.
<?php
class weather {
private $_location;
private $_url = 'http... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.