instruction
stringlengths
71
39k
I have two helper methods that return li for view with the li for current view having id as selected. def get_li(a) li = "<li" li += ' id=selected' if (a[:controller] == params[:controller] && a[:action] == params[:action]) li += ">" + link_to(a[:text], { :controller => a[:controller], :action => a[:action]}) + ...
I needed a function that would take a list of folders and removed all sub folders, so that only the top level folders stayed in the list. For example, given the list: c:\stuf\morestuff c:\stuf\morestuff\sub1 c:\otherstuf c:\otherstuf\sub1 c:\otherstuf\sub2 I wanted the list to be reduced to: c:\stuf\morestuff c:\othe...
This code is intended to find all possible solutions to a cryptoarithmetic problem. The description of the problem I was trying to solve is here: In cryptoarithmetic problems, we are given a problem wherein the digits are replaced with characters representing digits. A solution to such a problem is a set of digit...
I saw a sassy CSS for a rails app like this: $std-margin: 30px; @mixin solid-bg($color: #EEEEEE) { background: none repeat scroll 0 0 $color; } @mixin solid-border($direction, $width: 1px, $color: black) { @if $direction == "" { border: { color: $color ; width: $width; style: solid; } ...
I have this code in a class sharing a private static array of data. Internally it's encoded, but I need the iterator for a foreach loop to show the decoded values. Is there a native array function that can remap the keys and values via a callback function? public function getIterator( ) { $arr = array(); foreach ( ...
I have a function that takes in a controller instance, a method, and parameters (this is for a little MVC experiment I'm working on). The purpose of the function is to execute the controller method with the given parameters. However, there are a few caveats. First, if the controller has a "router" method, it will call ...
I am locating the find method of List in C# with the single Expression type parameter I am using the following ( where T is a List, in my case a SubSonic IActiveRecord ) MethodInfo info = typeof(T).GetMethods(BindingFlags.Static | BindingFlags.Public) .FirstOrDefault(m => m.Name == "Find" ...
I would like to have my code reviewed, I'm trying to get a general model I'm using for my stuff going and I don't want to keep using wrong or inefficient code if I can. My file structure is like this: In conf there's a file sitting called database.conf.php with the following content: <?php $this->host = "localhost";...
I need to subclass UIButton, however the design of UIButton makes this really painful. This is because to create a button you really need to call: [UIButton buttonWithType:UIButtonTypeRoundedRect] So if I want to subclass I really need to do whatever it is this method does. However, it is not possible to set the butto...
I'm making a simple container class for fun and education, but my rebuilding/resizing method seems rather inefficient. Is there an easier way to do this? // If FromFront is true, cells should be added or // subtracted from the front of the array rather than the back. void Rebuild(std::size_t NewSize, bool FromFront = ...
#include<stdafx.h> #include<stdio.h> #include<stdlib.h> #include<string> #include<iostream> using namespace std; string temp[10]; void extract(char * c) { int ind = 0; //char *temp = (char *)malloc(sizeof(char)); while(*c!= NULL) { if(*c!= ' ') // read all chars in a word and store in temp. ...
I have developed an application that interacts with IBM ClearQuest. The problem is that when I run everything locally, such as, run the webservice local and then ASP page local, everything is at the speed I expect. When I post the webservice (precompiled) to the server and run the web page through the server, the call ...
I'm trying to figure out a way to simplify implementing paged searching in sql server. My restrictions are: has to be in a proc. can't use dynamic sql. Here's my sample query: DECLARE @TenantId int DECLARE @MemberStatusId int DECLARE @SearchTerm varchar(50) DECLARE @ColumnName varchar(30) DECLARE @PageNum int DECL...
What do you think about this code? #include <iostream> using std::cout; using std::endl; #include <vector> using std::vector; #include <ctime> #include <cstdlib> template < typename T > vector < T > concatenate( vector < T > _a_, T piv, vector < T > _b_ ) { vector < T > v_list; v_list.insert( v_list.begin(), _a_...
I have the following code: print o # {'actor_name': [u'Keanu Reeves', u'Laurence Fishburne', u'Carrie-Anne Moss', u'Hugo Weaving', u'Glor # ia Foster', u'Joe Pantoliano', u'Marcus Chong', u'Julian Arahanga', u'Belinda McClory', u'Matt Doran # '], 'played': [u'Neo (Thomas Anderson)', u'Morfeusz', u'Trinity', u'Agent Smi...
Is this the proper method for creating an OpenGL 3.3+ forward-compatible context? // Create window WNDCLASSEX wc; ZeroMemory( &wc, sizeof( wc ) ); wc.cbSize = sizeof( wc ); wc.lpfnWndProc = _eventHandler; wc.hInstance = GetModuleHandle( NULL ); wc.hIcon = LoadIcon( NULL, IDI_APPLICATION ); wc.hIconSm = LoadIcon( NULL, ...
The title sucks, but it's really very simple - given an array and a starting element, cycle between one element above, below, then two element above, and below the starting element. For example: Start: 5 5 > 6 > 4 > 7 > 3 > 8 > 2 ... It doesn't matter if the code initially start with the element above or below. To c...
$($(this).parent().parent().parent().parent().parent().parent().children()[0]).html()
A while back I wrote a Fluid tag for Jekyll that inserts the contents of a GitHub Gist into the content of the page in <noscript> tags for RSS readers. I've noticed a couple things I'm not happy with since posting it, but I am interested in the critique it will generate here on Stack Exchange! (Obviously, some of the i...
I generally feel that the pattern I use for development is kind of wrong. I start with simple functionality, then when I realize that some pieces can be reused I usually start to write "scope root level" functions in order to be more DRY. I usually place these functions at the bottom of my "scope". Would these function...
I just realized that I could turn: import MySQLdb def main(): db = MySQLdb.connect( .. ) try: while True: do_thingy() finally: db.close() into: import MySQLdb, atexit def main(): db = MySQLdb.connect( .. ) atexit.register( db.close ) while True: do_thingy() ...
I have written these two functions that have a similar process. The first is meant to "split" a string on a given character and the second is meant to "replace-all" instances of a character in a given string. The behavior between the two seems very similar - can you think of a good way to abstract that behavior into ...
I'm learning Python and have found this problem from Google Code Jam: How many mkdir commands does it take to construct a given directory tree: Input The first line of the input gives the number of test cases, T. T test cases follow. Each case begins with a line containing two integers N and M, separated by a space. T...
I initially posted this on StackOverflow, and was redirected here. I have been playing around with Bouncy Castle (Java) for the last few days, and I've reached the point where I believe I can securely exchange secret keys with a Diffie-Hellman exchange. Having read many posts underlining the difficulty of properly impl...
I have a heading, which is an integer and from it I would like to figure out the compass direction (North, North-East,...) and return the appropriate icon. I feel like I'm probably already at the cleanest solution but I would love to be proven wrong. public GetHeadingImage(string iconName, int heading){ if (IsN...
I'll try to keep this as short as I can without losing context - we have a system for online education, where presentations often have a test. Management has access to a report used for measuring compliance. The report has a few paramaters that need to be selected: A date range to look in (e.g. From 11 March 2010 to 1...
One of my side projects is a table driven scanner/parser generator, in an effort to reduce the size of the transition table I represent the generated table A[x, y] as A'[x + I[y]] instead of A'[x + y * c]. This allows me to overlap identical parts of the table. The following is the code responsible for actually arrangi...
As you review this, please keep in mind I'm using Jython 2.1 as shipped with IBM's WebSphere 7.0 (their latest-and-greatest). I don't have decorators, properties, new style objects, or any other Python feature invented in the last decade. Problem: Using WebSphere's Jython interface to determine app server configuratio...
I have a word-wrap algorithm that basically generates lines of text that fit the width of the text. Unfortunately, it gets slow when I add too much text. I was wondering if I oversaw any major optimizations that could be made. Also, if anyone has a design that would still allow strings of lines or string pointers of li...
3.1 Write a program that computes the arithmetic sum of a constant difference sequence: D0 = A Dn+1 = Cdn + B Run the following values and compare to the closed form solution: Maximum index = 10,000, a = 1:0; c = 5; b = 2^-15 I am not sure I perfectly understand the problem above or how to confirm that I have the...
I was asked to update a business rule to allow a specific column to be added. Because our datalayer uses only DataSets as an interface to the database that is what we work with in the business layer. Here I have created a couple of DataTable and DataRow extensions to use for this businessrule and I would like your opin...
I have the following 'custom' tree data structure. This concept was to be thought of as, if given ("abb", 20) and ("abc", 30), then Tree['a']['b']['b'] == 20 Tree['a']['b']['c'] == 30 Or a \ b / \ b c With b == 30, and c == 20. Therefore taking up very limited space, and a very fast search. However, as...
4.2 Machine Epsilon Find the floating point number epsi that has the the following properties: 1.0+epsi is greater than 1.0 and Let m b e any number less than epsi. Then 1.0+m is equal to 1.0. epsi is called machine epsilon. It is of great importance in understanding floating point numbers. I have written the fo...
How can I improve this code? public class Address { public string house_no { get; set; } public string street { get; set; } public string zip { get; set; } } public class Contact { public string email { get; set; } public string ph_no { get; set; } public Address address ...
I have a model I have created to generate iCal and the necessary JSON for the jQuery calendar plugin Full Calendar to work. When I display the page, the JSON generation takes about 7 seconds. The query itself has been running in only a few microseconds. So I know my code is the problem. I was trying to get the format ...
The below code feels ugly, how can I make it better? (The part i don't like is the ||=. I also don't know if I like the resulting data structure. (An array of hashes) def survey_results @survey_results = [] unless params[:step_survey_id].blank? SurveyResult.find_by_step_survey_id(params[:step_survey_id])....
3.23 Palindromes A palindrome is a number that reads the same forwards and backwards, like 12321. Write a program that tests input integers for the palindrome property. Hint: This should not be done with the numbers in their input (character) format. For the task above, I have written the following program. ...
Typical tutorials suggest simple CoreLocation code similar to the following: Header #import<CoreLocation/CoreLocation.h> @interface MyCLController : NSObject <CLLocationManagerDelegate> { CLLocationManager *locManager; } @property (nonatomic, retain) CLLocationManager *locManager; @end Setup .... self.locManage...
After growing tired of all the ways in which a file loop can be broken (find -print | while read) or unreadable (find -exec with complex commands), I think I've managed to build a find template which can handle any and all files which could possibly exist on a Linux system (not so famous last words). Can you find a way...
I have a section of code I use to extract an event log out of a large text file. It works well, it's just my use of list(itertools.takewhile(...)) that feels a little sketchy to me. Is there a nicer way of doing this? import itertools testdata = ''' Lots of other lines... Really quite a few. ************* * Event Lo...
I figured it's about time to jump into some Haskell, so here's a first attempt at an oddly specific SVG parser: import System.Environment import Text.ParserCombinators.Parsec parseFile fname = parseFromFile (manyTill (try tag) (try readEnd)) fname tag = do manyTill anyChar . try $ lookAhead tagStart char '<...
The idea here is to implement a simple, threadsafe, observable collection that clients can bind to, whilst background threads can update. Changes in the contained items raise the CollectionChanged event. Feedback appreciated: public class ThreadSafeObservableCollection<T> : INotifyCollectionChanged where T: INotif...
How can this code be improved? using System; //using System.Linq; using System.Collections; using System.Collections.Generic; namespace Combinatorics { public class Permutation { private int[] data = null; private int order = 0; public Permutation(int n) { this.data = new int[n]; for (i...
The following block of code needs to be as fast as possible as it likely to be called many thousands of times in a run. I am also conscious that my thinking style is leaning towards a more procedural style from time to time and hence I may not be taking full advantage of all the benefits that functional programming bri...
I'm working on my graduate project and I had stumbled upon a somewhat dilemma, I've managed to solve it with some workarounds but I have my doubts that this is the most efficient way to deal with this problem. I'm writing a class to deal with the Plesk API and making it as flexible as possible for easy use. Here is the...
While working with DirectShow, I came across the need to easily recognize different known 'sets' of GUIDs. E.g.: There are different GUIDs to indicate the possible time formats: None, Byte, Field, Frame, MediaTime, Sample. Working with enums instead of GUIDs would be a lot more useful in my opinion. I decided to write ...
Given the following problem: ;3.3 Tabulate the function k = 2^n for n = 1..50. ;Do this for the fewest possible multiplications.[3] I wrote this answer: (defun k (n) (ash 2 (1- n))) (loop for n from 1 to 50 do (format t "k(~a) = ~a ~%" n (k n))) What do you think?
Given the following problem: It is conjectured that for any \$n > 0\$, \$n^2 + 3n + 5\$ is never divisible by 121. Test this conjecture for \$n = 1,2,...,9999,10000\$. I wrote the following solution: (defpackage :one-twenty-one-divisible (:use :cl)) (in-package :one-twenty-one-divisible) (defun divisible (n) (= (m...
I have successfully placed multiple jquery ui slider on a page and its transalation text too. you can check it live on: http://outsourcingnepal.com/projects/jQuery%20slider/ I have my jquery code as : var arrLabel1 = new Array('Not Good', 'OK', 'Average', 'Above Average', 'Excellent', 'Outstanding'); $(function() { ...
I've written a plugin that takes a generic approach to creating sticky headers and would like to have the code reviewed. Is this acceptable JavaScript? Demo Page It's my first plugin however and I'd like feedback about how to make it more user friendly and more readable before releasing it and putting it up on GitHub....
I have been a programmer for 12 years, mainly ERP software and C development and am looking to make a career/specialty change to Java. I've read it countless times if you want to learn a new language you need to write code, then write some more code and then finally write more code. So I've written some code! I love ...
I wrote a simple PHP script which allows the user to upload a file to the server. It works, but I'm not very sure about security. Could you give me some hints about security mistakes? In a nutshell: The user uploads a file from form.html, then a file is saved in uploads/ directory on the server, and a direct link to it...
Just as the question states and to be sure, am I missing anything on this? Something important/obvious that I overlooked? As is, I can save any functor, function pointer and member function pointer using this delegate class (copy ctor and assignment operator left out for brevity, as were the versions with parameters). ...
Inside of a folder named txt I have 138 text files (totaling 349MB) full of email addresses. I have no idea (yet) how many addresses there are. They are separated from one another by line breaks. I created the following script to read all of these files into an array, dismiss the duplicates, then sort alphabetically an...
I was trying to do a very common interview problem "Finding the max repeated word in a string " and could not find much resources in net for c/c++ implementation. So I coded it myself here. I have tried to do most of the coding from scratch for better understanding. Could you review my code and provide comments on my a...
Given the following problem (SICP Exercise 1.3): Define a procedure that takes three numbers as arguments and returns the sum of squares of the two largest numbers. I wrote the following (somewhat clumsy) solution in Scheme. How can I make it better? (define (greatest-two a b c) (cond ((> a b) (cond ((> b c)...
Given the following task: Use Newton's method to compute the square root of a number. Newton's method involves successive approximation. You start with a guess, and then continue averaging successive guesses until you reach a satisfactory level of precision. I wrote the following (rough) solution in Scheme. ...
I've implemented a let-with macro that takes an association list, keyed by symbols, that enables code to bind their corresponding values to local variables. It's designed to have a similar effect to JavaScript's with, but without with's attendant problems (by making you explicitly list the variables to bind). (define-s...
Newton's method for finding cube roots states that for any given \$x\$ and a guess \$y\$, a better approximation is \$\dfrac{(\dfrac{x}{y^2} + 2y)}{3}\$. What do you think of this code for finding a cube root in Scheme? (define (improveguess y x) ; y is a guess for cuberoot(x) (/ (+ (/ x (expt y 2)) (* 2 y)) 3)) (...
Here's my function for getting the length of a file, in characters: unsigned int GetFileLength(std::string FileName) { std::ifstream InFile(FileName.c_str()); unsigned int FileLength = 0; while (InFile.get() != EOF) FileLength++; InFile.close(); return FileLength; } How can this be improved?
I wrote the following JPA method that queries a database to return a distinct list of a String field (called mtfcc) of a Location object. I then took the list of strings to query for the associated name for that MTFCC. Could I just modify the first query to get the results, without having to use the for loop to get the...
In Python, itertools.combinations yields combinations of elements in a sequence sorted by lexicographical order. In the course of solving certain math problems, I found it useful to write a function, combinations_by_subset, that yields these combinations sorted by subset order (for lack of a better name). For example,...
I just found out about the existence of this forum and it's exactly what I needed. I just asked this question on Stack Overflow and after reading the answers I came up with a code (not the one I posted there but the one I'm posting here). First, this is my messed up code: string tempFile = Path.GetTempFileName(); usin...
The following code has one of the most confusing lines I've ever wrote. I can imagine ten other way to write it but I do not know which else could be any better. Note: Db() is very similar to PDO(), it just extends it adding few features I'm not using here. Post::addExtra() add abstract datas elaborating database data....
I have the following left join LINQ query that is returning the results that I expect, but it does not "feel" right. I need ALL records from the UserProfile table. Then the LastWinnerDate is a single record from the winner table (possible multiple records) indicating the DateTime the last record was entered in that tab...
The following working function seems a bit hacky to me as it has been pieced together from a handful of (probably poorly written) online tutorials, and I want to know if there is a better (or more standard) way to approach this. /*** * GET HTTP Operation * * @param request Request URI * @return Element Root El...
The program finds the non repeated number in a int array. I am using a count for the duplicates and making a Numcounts[] to store the count values. I am assuming the array is sorted. Then I can check the Numcounts[] for 1, and that would be the non-repeating number. The complexity is \$O(n^2)\$. Can you tell me how to ...
I have this for loop for creating a list of variables: vars <- c( 'beta.o', 'sd.y') for (x in c('ghs', 'site', 'trt')) { if(model.parms[[x]] == 1) { data <- data[, which(names(data) != x)] } else { data <- data if(x!='ghs') { vars <- c(vars, paste('sd.', x, sep = '')) } m <- min(model.par...
A function f is defined by the rule that f(n) = n if n < 3 and f(n) = f(n-1) + 2f(n-2) + 3f(n-3) if n>=3. Write a recursive and an iterative process for computing f(n). I wrote the following: (define (f_r n) ; recursive (cond ((< n 3) n) (else (+ (f_r (- n 1)) (* 2 (f_r (- n 2))...
1 1 1 1 2 1 1 3 3 1 What do you think of this solution for computing Pascal's triangle? (define (pascal row column) (cond ((or (= row column) (= 1 column)) 1) (else (+ (pascal (- row 1) (- column 1)) (pascal (- row 1) column)))))
I've always seen the IPrincipal and IIdentity interfaces separately, but I haven't seen any compelling reason for it, so I have my own interface that combines the two: public interface IUser : System.Security.Principal.IIdentity, System.Security.Principal.IPrincipal { string Role { get; set; } } Then I implement t...
From SICP's 1.24: (Exponentiation) (you may need to click through and read ~1 page to understand) Exercise 1.16. Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (...
Given the following task: Exercise 1.17 The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is ...
Just thinking if using code like this <?php abstract class helper { private static $_cycles = array(); public static function isOdd($v) { return (0 == ($v % 2)) ? false: true; } public static function isEven($v) { return !self::isOdd($v); } public static function cycl...
I am relatively new to JavaScript and JQuery. I wanted a Datepicker that has the following functionality: Weekends are not selectable Non working days (bank holidays etc.) are not selectable The first selectable day must be x number of full working days in the future, taking into account bank holidays and weekends...
I created a few forms for faculty members to nominate colleagues for awards. Many of the nominations require documentation to be submitted in order to validate the nomination. I created one form then modified it to fit the needs of many different award forms. I created it rather hastily and would like input as to how I...
As much as I try, I cannot seem to get this Coffeescript code to look beautiful (I'd like to think it is possible). I have tried both Javascript and Coffeescript. Just to be clear, this code works fine, but it is hard to read, for reasons that I am unable to pinpoint. How can it be refactored, reorganized, and what cha...
This code comes from a Wordpress plugin's forum called Vote it Up. It sort posts by vote. A lotof people say that there is more code than is needed. So I was wondering if someone have any idea about how to clean it a bit. votingfunctions.php: function ShowPostByVotes() { global $wpdb, $voteiu_databasetable; my...
I've been experimenting with Perl and MySql and wrote this code for connecting and writing to a database: # MySQL DDL to create database used by code # # CREATE DATABASE sampledb; # # USE sampledb; # # CREATE TABLE `dbtable` ( # `id` int(11) NOT NULL AUTO_INCREMENT, # `demo` longtext, # PRIMARY...
This is a collection of reasonably useful functions I put together for writing my blog. (require 'htmlize) (defvar blog-mode-map nil "Keymap for blog minor mode") (unless blog-mode-map (let ((map (make-sparse-keymap))) (define-key map "\C-cl" 'insert-link) (define-key map "\C-cp" 'insert-code-block) (...
This function changes a HashSet in the root of the class called 'commands' to a set of strings found in a file at "plugins/UC/Commands.txt" (it's what was requested by the people using the plugin). If the file doesn't exist, it copies a default file found in the zip file called "Commands.txt". This is a weird request,...
I'm cleaning build directories produced by GNOME build tool, JHBuild. This tool either downloads tarballs or clones git repositories, depending on set-up. After that, it proceeds to compilation (and then installation). Once in a while, something gets screwed up, and I need to clean the build directories so that I can s...
For an interview, I was asked to write code allocate memory for a rows*cols matrix, using a single malloc(). I want your comments about this code that I wrote: /* Allots (in effect) space for a matrix of size rows*cols using a single malloc. The whole space allotted consists of an array of size 'rows' of float ptrs, f...
I wrote an implementation of binary search in JavaScript earlier for kicks, but I noticed my version was significantly different than those found on Google. Here is an example of binary search I found on Google (copied here to combat link rot): Array.prototype.binarySearch = function(find, comparator) { var low = ...
This is a classic linked list problem. Deleting a node from linked list given the data to be deleted. Inserting a node in a sorted linked list. I saw various versions of this and here is my version. Could you check and let me know if this code is efficient? void deletenode(struct node *&first, int data) { struct...
I have built a "reset and confirm password" section on a site. It works great. I just have this suspicion that maybe it isn't the most efficient way. I am relatively new to jQuery but I can usually make things work well. I am just wanting to make sure I am doing them right. Any suggestions are appreciated. /////////...
I'm working on writing a scripting language with ANTLR and C++. This is my first actual move from ANTLR grammars into the C++ API, so I'd like to know if this would be a good way to structure the grammar (later I will be adding a tree parser or tree rewriting rules though). grammar dyst; options { language = C; ou...
Here is my PHP class for solving Sudoku: GitHub Sudoku <?php /** * Bootstrap file * * This is an example of how to use the SudokuSolver Class * Here the input array has been hardcoded. It could be send * as get or post in the real application. * * @author Anush Prem <goku.anush@gmail.com> * @package Solver * @subpacka...
In the absence of a full-fledged tutorial, I am teaching myself to program in the Factor language by writing a bunch of functions that I will eventually use in command-line scripts. One common operation I like to perform is to change the case of names of files contained in a given directory to uppercase or lowercase. ...
After reading an article on Skull Security mentioning the potential weakness of php's mt_rand function because of weak auto-seeding (http://ow.ly/4nrne), I decided to see what -- if any -- entropy I could find available from within php. The idea is to have enough (weak) sources that even if one or two are manipulated, ...
I'm making a scripting language parser and it's shaping up well but it takes about 30ms to do 30 or so odd/even checks. Profiler tells me that it's taking most of the time in the InvokeOperator.Operate function but that doesn't tell me a lot because the Operate call the Run method on the CodeBlock which in turn again c...
I have the following code for reading HTK feature files. The code below is working completely correct (verified it with unit tests and the output of the original HTK toolkit). from HTK_model import FLOAT_TYPE from numpy import array from struct import unpack def feature_reader(file_name): with open(file_name, 'rb'...
I have an extension that implements all the BinaryReader/BinaryWriter in the Stream class. I want to create generic methods for them. Is there a nicer way of doing this? public static void Write<T>(this Stream stream, T num) { if (num is byte) { stream.Write((byte)(object)num); } else if (num is...
I have the following code which uses four if statements to check the value in four different combo boxes. if (!String.IsNullOrEmpty(tx_cmb_Circuits1.Text.Trim())) emp.CircuitEmail_Group_Rels.Add( new Circuit_Email_Group_Rel { Circuits = (Circuits) tx_cmb_Circuits1.SelectedItem, ...
I have been trying to learn more about using bits/bitfields/bitmask or whatever you call them exactly in PHP for different settings and permissions. With the help of others, I have come up with this class. It has come a long way from when I started it but I am looking for any ideas on how to improve it more. <?php ab...
Given an array that is first sorted non-decreasing and then rotated right by an unspecified number of times, find the index of its minimal element efficiently. If multiple such minimal elements exist, return the index of any one. Idea: Conceptually, divide the array into two parts: the "larger" subpart (to the...
Using the property that GCD(a, b) = GCD(b, r) where r is the remainder when you compute (a / b), you can write a recursive function as follows: (define (gcd a b) ; recursive (if (= 0 b) a (gcd b (remainder a b)))) I also tried to write the following as an iterative function, but it still looks very similar t...
For my current project we are commnunicating with an old mainframish hospital information system. This system has a service called 'Facelink' which is a simple TCP connection with a fixed set of commands. The problem is that a user can only be logged in one time. As we're hosting a web frontend with a lot of links to t...
I want to use Tweets sent out by a twitter account as a command to shut down Ubuntu. For this, I've written a Python script using tweepy, a Python library for Twitter. I scheduled the script to run half past the hour every hour (for eg at 5:30, 6:30, and so on) using crontab. Here's the script: import tweepy import os...
The following code generates all \$k\$-subsets of a given array. A \$k\$-subset of set \$X\$ is a partition of all the elements in \$X\$ into \$k\$ non-empty subsets. Thus, for {1,2,3,4} a 3-subset is {{1,2},{3},{4}}. I'm looking for improvements to the algorithm or code. Specifically, is there a better way than using ...