Sign In with GitHub…
New Snippet

Ruby

#
# Snipit is a Ruby on Rails web app that allows users to post short snippets
# of code. It was created as a school project at UNC Charlotte. 
# 
# This demo version of the site is automatically reset every 24 hours. 
# 
# See https://github.com/r-thomson/snipit
# 

Swift

func binarySearch<T: Comparable>(_ array: [T], searchFor: T) -> Int? {
	func search(low: Int, high: Int) -> Int? {
		guard low <= high else { return nil }
		
		let mid = (low + high) / 2
		if searchFor == array[mid] {
			return mid
		} else {
			if searchFor < array[mid] {
				return search(low: low, high: mid-1)
			} else {
				return search(low: mid+1, high: high)
			}
		}
	}
	
	return search(low: 0, high: arr.count-1)
}

JavaScript

document.querySelectorAll('textarea').forEach(function(textarea) {
	textarea.addEventListener('keydown', function(e) {
		if (e.key === 'Tab') {
			e.preventDefault();
			document.execCommand('insertText', false, '\t')
		}
	});
});

Java

public class TextFileReader {
	public interface ScannerOperation {
		void handleNext(Scanner sc);
	}
	
	/**
	 * @param path The path of the file as a string.
	 * @param f Lambda function to apply. Should advance to the next token in
	 *  some way.
	 * @throws IOException
	 */
	public static void readTextFile(String path, ScannerOperation f) throws IOException {
		File inputFile = new File(path);
		try (Scanner sc = new Scanner(inputFile)) {
			while (sc.hasNext()) {
				f.handleNext(sc);
			}
		}
	}
}

public class ExampleImplementation {
	public static void main(String[] args) {
		try {
			TextFileReader.readTextFile("file.txt", (sc) -> {
				System.out.println(sc.next());
			});
		} catch (IOException e) {
			System.err.println(e.toString());
			return;
		}
	}
}

C++

int main() {
	pid_t id = fork();
	
	if(id == -1) {
		std::cout << "Error creating child process\n";
		
	} else if (id == 0) {
		std::cout << "This is the child process\n";
		
	} else {
		std::cout << "This is the parent process\n";
		
	}
	
	return 0;
}