instruction stringlengths 71 71.9k |
|---|
I've modeled the population changes for a group of agents that inhabit a 2D lattice (with wrapped boundaries) made up of M x M number of grids. At each time step:
A parent reproduces offsprings that disperse independently -- the number depends on the grid location.
The offsprings live if they land on a "patch" grid b... |
I just recently got back into C++ and did a quick and simple exercise in the Rule of Three. The code for the copy constructor, overloaded assignment operator, and destructor follows below for my class (code is also below), and I was wondering if someone could take a quick look at it and point out anything that I overlo... |
Given an array A[], write a function that segregates even and odd
numbers. The functions should put all even numbers first, and then odd
numbers.
Example:
Input = {12, 34, 45, 9, 8, 90, 3}
Output = {12, 34, 8, 90, 45, 9, 3}
Input = {6, 4, 6, 8, 1, 1, 1}
Output = {6, 4, 6, 8, 1, 1, 1}
public static void main... |
I think DB transaction should be as small as possible, and close it soon.
So I wrote a helper function like 'using' statement in C#.
function transaction($conn, $closure) {
$conn->beginTransaction();
try {
$closure($conn);
$conn->commit();
} catch (Exception $e) {
$conn->rollback();
... |
I was writing this code to check if a tree is balanced or not and I ran into a situation where I would have liked the method to return 2 values at each step. First to signify whether the tree is balanced at that level or not, and second to return the height at the level so that I can use it to check the balanced nature... |
I've added decimal (floating point) functionality to my calculator implementation; it's working but I'm having trouble making it more concise and less ugly.
I'm trying to use the same method to handle both number keys and the decimal point, and whichever way I look at it, I either have to check for the button being pre... |
I populate a ListView with Items. Each Item has data attached to its .Tag property.
Over time, I have needed to handle many cases where something would be null or missing or corrupt or whatever.
And so was born this beast:
private void PlayRecording()
{
if (list.Items.Count >= 1)
{
if (list.SelectedItem... |
I've some refactoring issue with one method.
This method has a lot of dependencies
function updateBuildChart(Filter, PagerFactory, ChartBuilder, LimitsManager) {
Filter.clearFilters();
this.currentReports = $scope.$parent.reports;
$scope.pager = PagerFactory.Create({
items: this.currentReport... |
I'm creating an update function to show my users when the next update will be available. I'm using the jQuery countdown plugin to show the time. What is a more efficient way to write this?
today = new Date();
todayDay = today.getDate();
todayYear = today.getFullYear();
todayMonth = today.getMonth();
todayMonth ++;
v... |
I have a situation where I have a ViewModel:
// Main_ViewModel
function MainViewModel()
{
var self = this;
this.customerList = ko.observableArray(GetCustomersFromServer());
}
// BIND VIEWMODEL
ko.applyBindings(new MainViewModel());
// GET CUSTOMERS FROM SERVER
function GetCustomersFromServer (){
var ... |
One of the features that is missing from C++11 are lockless queues. Therefore I have decided to write one myself.
A few remarks:
I know the code isn't technically lockless. However the lock is only used for a blocking call and can be omitted.
I have tested the code and it seems to work. However I found I had some trou... |
I've got my full program working as expected. My full program looks like this:
I'm posting a part of my code which changes the color of the circle. The user can change the color of the circle via two ways:
By selecting a JRadioButtonMenuItem from the JMenu.
By pressing one of the colors(JButtons) in the JPanel below ... |
Using a Select2, what's the best way to refactor multiple if statements.
This code returns Json to a select2 based on what information it gets in the query. The action result is used in many places so it has accommodate different parameter being passed.
public ActionResult *********(string query = "", int? id = null,... |
In these fiddles I am generating the number of textboxes and checkboxes depending on the input of user.
This first fiddle deals with the first problem generate number of textboxes onchange of the input textboxes from errand (sample).
The second one is from Guruprasad Rao that helped add an attribute value on the genera... |
Boost 1.58 has new library spreadsort, so I tried it out.
I wrote simple sample for sorting vector of pairs of int:
#include <chrono>
#include <iomanip>
#include <boost/sort/sort.hpp>
// based on http://www.boost.org/doc/libs/develop/libs/sort/doc/html/sort/sort_hpp/string_sort.html
struct lessthan
{
inline bool o... |
Is there a function or some easier way to draw this, each of this little circles should have 8 other smaller circles around them like the big circle... So far i made big circle in center with 8 smaller circles using canvas
from Tkinter import *
canvas = Canvas(width=700, height=700, bg='black')
canvas.pack(expand=YE... |
This is my very first complete, non-completely-trivial Haskell program, and I'm extremely unfamiliar with the language. I was hoping that I could get some pointers on how to make it more idiomatic. I'm especially unfamiliar with built-in functions.
I'm specifically concerned with my main function and my scrollHelp gu... |
I am processing file inside my method - basically preparing it for the download.
But I decided to split actions for setting headers and reading bytes.
As Java does not support method declaration inside methods, I decided to go with class inside method.
public static String downloadFile(final String fileBody, HttpServl... |
The following code comes from a simple Brainfuck interpreter I'm working on to learn the Rust language. Error handling is omitted for simplicity. It is tested on rustc version 1.1.0-dev (af522079a 2015-05-14) (built 2015-05-14).
The code implements just the input and output routines for the interpreter. The read_cell m... |
I'm looking to get rid of a couple dependencies that I have a sneaking suspicion are present in the code that I'm writing.
Right now I have a service class that manages my subscriptions for part of my application in Rails. The problem is that we have Recurly as our management platform right now, but I don't know if we ... |
Looking for feedback/critiques/alternatives to my solution for the 1st Project Euler question:
{-|
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
-}
import Data.List
-- Finds all mu... |
This formats HTML for use in a locally hosted iframe so that you can manipulate the content in the iframe freely, without running into cross domain issues. It uses Goutte to retrieve the HTML. I'd like to improve the code, whether it's to fit a certain design pattern or just more efficient. I don't feel like it's as cl... |
Problem Statement:
Given an Array if ints, Find out all the subsets in the Array that
sum to a given target value.
Example:
If the input array is:
{1, 3, 2, 5, 4, 9} with target as 9
The resulting subsets are:
135
324
9
54
Below is my implementation in Java. Please free to review in terms of time, space complexity... |
I just finished writing a function that computes the distance between two n-dimensional points.
The original one was written in C and it's basically a translation of this formula:
\$\text{dist}(x,y)=\sqrt{\sum_{i^1}^d{(x_i-y_i)^2}}\$
Here's the C code for completeness sake:
void distanceC(float* source, float* destinat... |
We use a student information system called Colleague that is developed by Ellucian. As far as I can tell, the system does not use any sort of session pool so rapidly opening and closing connections to the database is both expensive/slow and can use up a lot of resources on the server side. In response I developed a s... |
I have three methods in API running similar code snippets. For this reuse the code inserted a switch-case according to the API method. It's good practice that? I mean, this isn't a high coupling and low cohesion? There is another better way?
API
@ApiOperation(value = "Gerar permalinks de todos os arquivos com validaçã... |
The following code snippets are academic. I was required to make a PHP generated HTML interface for a MySQL database of a movie rental store, and the requirement was filtering the displayed movies by category.
The approach for having the filter persist across all form actions (without using a session) was to have the h... |
I currently have a code that is connecting to SQL database in VBA. The data is populating correctly. However, I was wondering if there is a way to condense the code below.
I have 4 different columns and 26 rows and I feel like if I go this route, I will be wasting a lot of time. I want the range to go from C20:C45 and... |
How can I improve this component with using event delegation rather than doing a lookup using parentNode so that I can change the markup around without having to update the JavaScript?
HTML
<div class="drop-down-wrapper">
<div class="drop-down-btn-wrapper">
<div class="drop-down-open"><img src="http://plac... |
What is the fastest Pythonic way to remove all stopwords from a list of words in a document? Right now I am using a list comprehension that contains a for loop.
from nltk.corpus import stopwords
''' Push stopwords to a list '''
stop = stopwords.words('english')
Document = ' Some huge text .......................... '
... |
I'm implementing a lock-free, multiple consumer, multiple producer FIFO queue/pipe as an exercise in thinking about atomicity in operations.
My main concern is correctness of operation, my second concern is good practices around atomics and general C++11. Performance is interesting but not important for this exercise.
... |
I have a Polygon array, and I need to get a Rectangle object which bounds all of the polygons inside the array. Think convex hull - except this is a rectangle and not a polygon.
Here's my current code which works:
public static Rectangle getBoundingBox(final Polygon[] polygons) {
if (polygons == null) {
ret... |
I have a rails application that uses Stripe for credit card processing. Currently several exceptions are being handled anywhere a transaction takes place. The code below is being used currently in 11 places. In all places it is essentially the same with the exception of the message being passed to stripe_error. Is it p... |
This post is somewhat of a follow-up to Rubberduck's "Extract Method" refactoring implementation.
A tremendous amount of things have changed since version 1.2, when this feature was first introduced - the more important thing being the advent of the Declarations API, which implies that the feature now not only gets an ... |
Right now I am using a regex to extract emails from a text document, and filter the duplicates out of this using the Distinct function from linq. After which I run the output file through a clean up of duplicates as well, as the program can be run several times over several different files.
Now my question, would ther... |
I have an excel file with 20+ separate sheets containing tables of data. My script iterates through each sheet, manipulates the data into the format I want it and then saves it to a final output file. I think it can be improved, and I've flagged sections in the code with "review this" which I think I've done more work ... |
I asked a question elsewhere on Stack Exchange and was given an answer by multiple people that checking for errors in-line was not a good practice. I have been using an
on error resume next
' do something
on error goto 0
block structure for years as kind of an improvised try-catch construct for VBA.
Here is a simpl... |
I started writing unit tests cases recently. For now, I created only "perfect case" where there is no error. However, the test seems to me difficult to maintain and difficult to understand.
How can I make it better for other people to understand?
All permalink attributes are set within the service itself I'm testing (P... |
I have a validation which checks that a string is a valid asset number. There are currently three formats it could be in, like: 001-123456, WSH002M52B, or CTR0025MLD. The way my code is set up now is like:
public bool IsValidAssetNum(string assetNum)
{
if (this.IsNorthAmericanAssetFormat(assetNum)) return true;
... |
My question is whether or not this is a good practice, and/or if there is a more efficient way to do it.
I have to access this Solidworks interop object and wait for it to return some value. The return is a string. In early testing I found I ran into issues if I didn't wait for the return, so I added a "DoEvents" wa... |
Below you will find my first attempt at a C++ implementation of the classic game Rock-paper-scissors. If someone could look it over and point out or suggest any things that I could change to improve it, that would be brilliant and I would greatly appreciate it.
Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <iostr... |
package com.raja.util;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Hashtable {
private Object[] slots;
private int capacity;
Hashtable(int size) {
capacity = size;
slots = new String[size];
Arrays.fill(slots, "-1")... |
I am working on a version of std::unique_ptr and std::make_unique for aligned memory. The purpose of this is vectorization, e.g., SSE or AVX, which has higher alignment requirements than the underlying types.
My header providing aligned::unique_ptr and aligned::make_unique (compiles with C++11, no need for C++14 suppor... |
I thought of a program where you move a square with the arrow keys. I created it and asked a question about it on Stack Overflow.
I copied the last code block of the accepted answer and tried to understand it. I think I do now. Now I wanted to add something that would check if the square would move off the screen. I ad... |
I was compelled to look into a Sudoku Solver in Java using the principles I have learned in a course, namely I wanted to make something that included backtracking and forward checking.
Has anybody else managed to produce a Sudoku solver that uses the forward checking algorithm that is more efficient than the backtracki... |
I implemented this code, looking at a dependency injection program as an example. I wanted to confirm with you all whether this implementation is the right way of doing the same.
namespace TestAsyncProjectWithDI
{
public interface IReadFileTypes
{
void ReadUsingFileSteamA... |
This is a fun one! I wrote some code to automatically get the next revision letter for a file by looking at the existing letter. It works, but I think there is room for improvement as far as simplifying it or making more efficient.
Our revision scheme follows ASME Y14.35, which specifies the following rules:
First ... |
I developed three methods that have only some similarities, and the three must remain separate. However, it seems there is a significant amount of duplicate code. They basically seek the same list and set a BasicDBObject with a few different attributes.
How can I solve it? Or is acceptable as is? These stretches of dup... |
I am trying to complete a Ruby coding exercise. The specifics of the excercise can be found on a the level_up_exercises GitHub repo. This repo also contains the CSV file used in the exercise.
I would like you to comment on how well you think I met the requirements with the exception of
loading the African dinosaur da... |
As MATLAB has a hard maximum of 10 input arguments it's possible, but ugly, to implement a curry function in this manner:
%% turns a standard function into a curried one
% if g has 3 input arguments then you can call:
% h = curry(g)
% h(1)(2)(3) == g(1, 2, 3)
% Matlab doesn't like h(1)(2)(3), but in principle it wo... |
I wrote a shell to test my understanding of processes etc. It is not supposed to comply with POSIX or anything, just to allow people to run simple commands with simple arguments.
#include <stdio.h> /* printf, fprintf */
#include <stdlib.h> /* exit */
#include <string.h> /* strtok */
#include <unistd.h> /* fork, execvp... |
I have a large application with a wide-reaching amount of views and sub-views. I have a need to decorate DOM elements with identifiers so that my framework of choice can bind views to the DOM elements.
In attempting to choose a robust convention for naming these selectors, I've encountered a few problems:
id selectors... |
The input begins with the number \$t\$ of test cases in a single line
(\$t \le 10\$). In each of the next t lines there are two or more
numbers \$m\$ and \$n\$ (\$1 \le m \le n \le 1000000000\$, \$n-m \le 100000\$) separated by a space.
Print each number in a separate line which can be used further for
summatio... |
I am very new to this and am using php and MySQLi to create a form which will create a record in a third table. This works fine but I can't help but think that there is a way to do it with a single query rather than a query for each table as I have now. The third table is called tblcars, and I will use this form to b... |
Rubberduck code inspections can take quite a while to complete, so I decided to run them on a background thread instead of locking up the IDE. The only drawback is... the IDE isn't locked-up while inspections are running, so the user can end up with inspection results that go against stale parse results - this could me... |
This is my first time writing ruby - and I was mainly hoping to get some feedback and stylistic pointers.
The algorithm is pretty straight-forward, since Google guarantees airports aren't repeated I store all the tickets in a hash table and then sort from random insertion points, which should be worst case \$O(n \log ... |
This is the To and Fro problem at SPOJ:
Mo and Larry have devised a way of encrypting messages. They first decide secretly on the number of columns and write the message (letters only) down the columns, padding with extra random letters so as to make a rectangular array of letters. For example, if the message is “Ther... |
I have some code here that I am very unhappy with. The task I am trying to accomplish is this.
Given a 2d vec like this:
[[0 2 0] [1 3 5] [3 3 0]]
which can contain positive ints including zero I want to remove all lines that are greater zero.
Where the definition of line is the following:
A line is represented by th... |
I'm going through some of the problems over on exercism and we were asked to write a program that finds the nth prime. I know Ruby has a Prime class that handles that but the exercise doesn't allow us to use that.
My code works fine but it's very, VERY slow when testing very large numbers (e.g.: the 10,001st prime num... |
I have constructed a copy constructor for an ADT queue. The copy constructor works fine. I would want to improve my code, but I don't really know how to shorten it to make it more flexible.
template <typename T>
Queue <T>::Queue(const Queue & other)
{
if (other.first == nullptr)
{
first = nullptr;
... |
This is my very simple client-server application. Client sends some commands to the server and server gives back the output to the client. However, my special concern is about the GET command sent to the server. The client request GET filename to download a named file. That file ultimately gets downloaded into the clie... |
Right now I have a list of dictionaries. In order to filter out all the entries I do not want included in the list, I am running it through multiple list comprehensions.
Is there a more Pythonic or better way to write these comprehensions that seem repetitive?
#FILTER OUT ALL EMPLOYEES WHO WILL NOT BE FACTORED INTO MET... |
This is how I can access the exact scope value, otherwise it will be $scope.type of local scope.
I am accessing this from the template in NSPopover. NSPopover directive has scope: true.
It's also inside the Angular bootstrap module.
<label ng-class="{selected: $parent.$parent.$parent.type == current.type}" >
<input... |
I'm building a news aggregator website. This is my current schema structure for a single news article. There can be more than one article per page. I'm trying to have every possible piece of data structured. Am I missing something? How can this structure be schema.org-optimized for a news article post?
<article itemsco... |
I am trying to practice objects and functions (specifically closures & higher order functions) in javascript. There is no specific reason why I chose this program but it struck my mind to work out this one.
The below code is available at my Github and it converts the number to words.
Kindly provide your feedback and s... |
Scenario "The Semantic Mind-Reader!" browser known as jhool is known
as mind-reader for a reason. Here's why:
You don't need to type 'www.' to open a website anymore. Though, you
still need to type '.com' to open a website. The browser predicts ALL
THE VOWELS in the name of the website. (Not '.com', though. Agai... |
procedure E(n, m: integer; A, B: tMatrix; var C: tMatrix);
var i, j: integer;
begin
for i:=1 to n do
for j:=1 to m do begin
if i<=j then C[i,j]:=A[i,j] + B[i,j] else C[i,j]:=A[i,j] - B[i,j];
end;
end;
Input: three matrix. Output: new matrix which created by addition or subtraction of two el... |
To start, I am in the wrong language and I think it is time learn some C++ and compile it as an add-on for NodeJS. For now, though, I have a few code snippets that work that may be interesting or may be an abomination of coding.
This code works with weather forecast data, specifically the GRIB-2 file format. GRIB-2 com... |
As I was looking through my past questions, I noticed my really old calculator question (here and here). Considering it looked like a huge mess, I decided to rewrite it. Coincidentally, the April 2015 Community Challenge was to implement a simple calculator. It might be a bit late, but here it is:
import java.util.Hash... |
Today I started to build my first platformer, first time working with collisions and stuff. Now, surprisingly, everything seems to work, but since this is my first time creating a platformer and I'm still a beginner with collisions I don't know if the way I coded it is good practise.
The game is a ball with a fixed x c... |
I have two arrays that I need to compare if their IDs are equal. This is how I am currently doing it:
PFQuery *earnedQuery = [PFQuery queryWithClassName:@"EarnedAchievement"];
[earnedQuery whereKey:@"user" equalTo:[PFUser currentUser]];
[earnedQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {... |
The code I have below swaps two tabs around. This is done through creating an array, deleting all tabs and then recreating them which seems very inefficient to me.
Private Sub SwapTabs(ByVal tabOne As Tab, ByVal tabTwo As Tab)
'get array of all tabs
Dim tabs() As Tab = Me.Children.OfType(Of Tab).ToArray
's... |
I want this code to be reviewed, please.
chatServer.java
import java.net.*;
import java.util.*;
import java.io.*;
class chatServer {
static Vector<Socket> ClientSockets;
static Vector<String> LoginNames;
chatServer() throws Exception {
ServerSocket soc = new ServerS... |
I challenged myself to implement multiplication of signed integers using only +, -, >>, <<, &, |, ^, and conditionals, though I would like to improve my method to not use conditionals if possible in the future. Any input would be very helpful.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits... |
A library that I use doesn't support SecureString in its credentials for connecting to GitHub, so I'm submitting a pull request to add it. I know it's not ideal to pull the actual string out, but the idea here is to minimize the amount of time the string is in memory. Also, allowing client code to utilize the fact that... |
I've reproduced the jQuery selector function in JavaScript.
Here are the two rules that come with this function:
You may not use any JavaScript libraries.
document.querySelector/document.querySelectorAll may not be used.
var $ = function (selector) {
var elements = [];
// get starting index position of id / clas... |
I am writing the lemonade stand game in Java but I am having a bit of trouble trying to figure out the perfect recipe. I have most of the code done, except the math logic seems a little off. Please let me know if I can improve the code.
public static void main(String[] args) {
///declaration of variables
i... |
I'm currently attempting to learn some basic JVM optimization techniques using JMH.
I created the following bench to compare mid-index insertion performance between ArrayList and LinkedList.
How exactly do I measure score vs error in the final results?
The documentation states:
Your benchmarks should be peer-re... |
Q1. Define a function reverse_list that takes a list as an argument
and returns None, but reverses the elements in the list as a side
effect. Do not use any built-in list methods (especially not reverse),
but assignment statements are fine.
Below is the iterative solution:
def reverse_list_iter(s):
"""Rever... |
Q2. Define a function make_accumulator that returns an accumulator
function, which takes one numerical argument and returns the sum of
all arguments ever passed to accumulator. Use a list and not a
nonlocal statement.
Below is the solution:
def make_accumulator():
"""Return an accumulator function that take... |
Q4. Define a function make_counter that returns a counter function,
which takes an immutable key and a numerical value argument and
returns the sum of all arguments ever passed to counter with that same
key.
Below is the solution:
def make_counter():
"""Return a counter function.
>>> c = make_counter()... |
I wrote a simply parser for Tektronix's internal binary file format .isf. The code is supposed to read in the file and return the header data as well as the actual oszi-data.
Since I mostly code by myself, I would like your opinion on whether my code follows common practice and whether it can be improved.
import numpy ... |
I'm working on a linear algebra module to improve my knowledge with mathematics and, because I'll need a lightweight linear algebra module for my future work with Vulkan!
I tried to keep a blas-like routine style, for exemple, the related functions are called like this:
template <typename T, std::size_t M, std::size_t ... |
The code snippet below examines a nuget package file (zip file with meta) and extracts all file names referenced inside. The final result should be a Set<string> with all file names. My problem is that the code looks like a nested Linq query in c# and the usage of Seq.iter blocks me to build the Set collection. Can you... |
The doctest module seemed easy to implement so I decided to write a simpler version of it.
my_doctest.py
def _doublets(lst):
for index, item in enumerate(lst[:-1]):
yield item, lst[index+1]
def _test(tests):
for prev, curr in _doublets(tests.splitlines()):
if prev.strip().startswith('>>>'):
... |
I was trying to calculate the factorial of a large number in a short time:
class TestClass {
public static void main(String args[] ) throws Exception {
BufferedReader keyboard=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(keyboard.readLine());
while(n!=0){
... |
As pyglet has no in-built method to return a vertex list of circle, I had to build one myself. This is a critical piece of code that I will use very frequently. I need it to be of very fine performance.
Here's what I've written:
""" Pyglet utilities. Designed to ease drawing of primitives with Pyglet. """
# Dependenci... |
This is a follow on to : Efficiently detect datacenter based on server hostname and return the full path.
I have a library which is running in different datacenters in production. I have three datacenters in production:
DHP, SLP, LTR
Depending on which datacenter code is running, I need to make a LinkedList (allPaths)... |
I've am trying to read a large text file and output the distinct words in it along with it's count. I've tried a couple of attempts so far, and this is by far the fastest solution I have come up with.
private static readonly char[] separators = { ' ' };
public IDictionary<string, int> Parse(string path)
{
var word... |
I am new tro programming and have chosen python 2.7 to begin with. But, I often have to deal with a TLE while competitive coding like in the problem below, where my code runs fine on all test cases but runs out of the given time bound.
My code runs fine on Ideone.com for all the given test cases, but gives a TLE on SPO... |
I'm trying to solve this fairly straight forward challenge:
Problem Statement
In computer science, a set is an abstract data type that can store
certain values, without any particular order, and no repeated
values. {1,2,3} is an example of a set, but {1,2,2} is not
a set. Today you will learn how to use sets in ... |
I want to check as fast as possible if an entity, based on PartitionKey and RowKey, exists in an Azure Table Storage.
I can do a standard TableOperation.Retrieve and check the result, like:
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");
TableResult retrievedResult = table.Ex... |
Yesterday and today I've made a very basic syntax highlight.
It creates a function in the window object that handles part of the job:
(function(window){
var f=window.highlight = function(lang, element){
var lang_defs = f[lang];
if(!lang_defs)
{
throw new TypeError( 'The langua... |
I have a Location type:
public abstract class Location implements Locatable {
private int x, y;
protected final void setX(int x) {
this.x = x;
}
protected final void setY(int y) {
this.y = y;
}
public final int getX() {
return x;
}
public final int getY() {
... |
For practice, I tried implementing Bubble sort in Ruby. I wasn't very sure how nested for loops would look like in Ruby. Is this the 'right way' to do this in Ruby? I found this question, but it looks much more complicated with stacks.
def bubble_sort(list)
n = list.length
n.downto(2) do |i|
0.upto(i-2) do |j|
... |
I've completely revamped my old syntax highlighter, and made it more flexible and easy to use. It works the same way as the previous one, wrapping <span> elements around sections of text in an element with certain styles, but it now allows for string highlighting, and is more extensible by allowing the user to define t... |
I recently came across the classic algorithm for detecting cycles in a directed graph using recursive DFS. This implementation makes use of a stack to track nodes currently being visited and an extra set of nodes which have already been explored. The second set is not strictly required, but it is an optimization to pre... |
I have a Spring @Service to asynchronously send emails. The part that seems to be a bit off to me is some code that is specific to our QA environment. We want to send and receive all emails through a test email account so that it does not impact live users if we work with real data imported to QA. I check for the en... |
I wanted to write some more JNI code and decided to (re)implement a semaphore for MacOSX. In order to assert somehow correctness of my implementation I hereby supply a (multi)consumer/(multi)producer demo.
semaphore_impl.h (autogenerated by javah):
#include <jni.h>
#ifndef MACOSX_SEMAPHORE_IMPL_H
#define MACOSX_SEMAP... |
I'm making a Chrome extension that lets you choose a size of an item and check out quickly.
I have a value called "Large" in sizePref array in my chrome.storage. And when it calls that value, it will choose an option in a dropdown based on that. However, possible labels are "Large", "L", "M/L" or "L/XL" ("Large" being ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.