instruction stringlengths 71 71.9k |
|---|
LCA = Lowest Common Ancestor
The following code finds the lowest common ancestor in tree of nodes, where a node can have two parents, left and right.
The tree looks like this:
J-K
/ \
E-F-G-H-I
And K and H input, the output is F
public TreeSet<Node> find(Node node, TreeSet<Node> nodeSet) {
nodeSet.add(... |
A day ago I have asked a question on here about Preventing email injection. I had some feedback and worked on it, and below is the latest update.
Could anyone please share their opinion? Is it secure enough? Is there a way to short-cut the code?
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST... |
The following code is intended to implement a LinFu DynamicProxy interceptor to lazy load given virtual properties from an Umbraco datastore.
My concerns:
Thread safety, Have I covered all the bases, Am I storing variables correctly?
Duplication - Getting the child type, am I safe to store a variable via my Lazy to us... |
I'm running into a problem with my code in a ASP.NET MVC application. Maybe it's not a problem and I'm just being paranoid, but it seems like a problem to me (might be because I've just read the book Clean Code).
I am using the repository-pattern with the unit of work-pattern to abstract the data access. In between my ... |
I've been doing a lot of Project Euler lately and just wanted to make sure my implementation was as good as it could be. Does anyone have any suggestions to speed this up?
def sieve(upperlimit):
# mark off all multiples of 2 so we can use 2*p as the step for the inner loop
l = [2] + [x if x % 2 != 0 else 0 for ... |
This is a bidirectional map implementation that stores the values as pairs on the heap, and uses pointer arithmetic for efficient lookup.
codepad link, may be easier to read
#include <iostream>
#include <set>
#include <utility>
#include <cstddef>
#include <SSVUtils/SSVUtils.hpp>
namespace Internal
{
template<typen... |
I'd like to see how to improve this code. I have a UITableView that I'm 'hiding' a section when the user taps on that section's header. I thought this was a pretty cool implementation I came up with, but it turns out when this section is hidden and the user pulls to refresh, about 1-2MB is added into memory every time ... |
The primary goal of this code is to convert a PDF file to images. I also create a directory under C:/Media based on a combination of the PDF name and current date and insert the uploaded PDF to the same directory as the images for safe keeping.
I am primarily concerned that I am over-complicating the process by initia... |
I was tasked at work to improve a system where through a web interface a client, which eventually became us, uploads a bunch of images with descriptions (latter coming from csv files), the images are then automatically resized yada yada for the site.
Nowt wrong with the latter, but the upload and image description dat... |
I would really appreciate some good advice on how to refactor a small app:
It basically reads a CSV (energy/heat values?), computes some stuff, and then prepares some data which should later be sent to GNUplot.
For example, I'm unsure about this:
Is it good practice to send variables into a function as pointers and man... |
I have a MouseInputHandler class that registers itself to an InputManager. When the InputManager class receives events they are forwarded to MouseInputHandler which changes its state to reflect the state of the mouse. A mouse as an input device provides a large number of different properties that should be easy to read... |
I am trying to implement an expression parser via the shunting yard algorithm about which I learnt here.
I am able to get the correct results for the cases I'm testing, but I think it would be better if someone experienced could go through it and verify it. Also, I plan to add more operators, such as '!' (factorial), s... |
I have written this simple program that is a basically a maths test. I would like to know is there any areas I can improve on and if I have any bad habits that would be useful to break now. I realise I could have written this in the main class, but I was trying to practice implementing other classes, so I tried to use ... |
This is a calculator I wrote for a student's project.
It still has a problem (one that I know of), where it can't handle inputs of the form 2*2*2... (more than one * or / sign). The case 2*2 was solved in hackish ways.
I'd appreciate any remarks or advice on the code and possibly how to solve that problem.
Relevant inp... |
I have been doing some programming 'exercises'. I'm trying to come up with the most efficient algorithm for tree traversal.
Consider the following function signature:
CNode * CNode::find(int number) const
where CNode structure is not organized as a binary search tree (otherwise obviously a faster algorithm would hav... |
I have implemented an user defined colors enumerator, and if is possible I appreciate if I will get a code review.
I want to know if my implementation is correctly or must improve it.
If there exist a better alternative (color enumerator) to my code which is?
Usage example:
HANDLE hConsole;
setTextColor(hConsole,YELL... |
I'm working on my own little library on top of jQuery to make working with tabular data easier.
Currently my script takes user clicks in a table's thead element and creates an array of all of the table cells in that column, and gives the user an animation of changing the background color of the td elements in the colum... |
I hope this isn't getting annoying, but I've asked a lot of questions about improving my game lately:
How can I improve my game project design?
Using the observer pattern with collision detection
Is this a good way to cascade a property?
How should I implement my domain model?
Setting up keyboard bindings using JSON a... |
I'm looking for general advice on my code on the following problem:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not ... |
Given an infinite stream with the property, such that after all 0's there are only all 1's, find the index of the last 0.
I'm looking for code review, best practices, optimizations etc. Verifying complexity to be O (log n) where n is the first 1 encountered in the search (not the first 1 in the stream).
/**
* An inf... |
I have attempted to make a basic version [not complete] of the std::basic_string type in C++, and I would like to make sure that I have done everything correctly, and efficiently, as I can be prone to leaking memory in my programs.
Note: I also created an allocator class, which works the same as the std equivalent, but... |
I'm trying to implement a TcpListener using the TPL. I'm not sure If I'm doing everything correctly though. I'm trying to keep the code as small as possible as well. It all works fine in a console application.
public async Task RunAsync(CancellationToken cancellationToken)
{
var listener = new TcpListener(ip, port)... |
Can you please review my PHP script below? It is for a contact form. Am I breaking any rules? Does it seem okay to you?
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset(
$_REQUEST['name'],
$_REQUEST['email'],
$_REQUEST['message'],
... |
Is there a faster way to compute the bounding area between 2 points?
// Minified Version
public static Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
double dx = p2.x - p1.x, dy = p2.y - p1.y;
return new Rectangle((int) (dx < 0 ? p2.x : p1.x),
(int) (dy < 0 ? p2.y : p1.y), (int) Math.ab... |
My goal is to save space occupied by 2D array (sea) that has 3 different values.
Ocean sea; //Ocean class has member 'private int[][] oceanMatrix;'
public final static int EMPTY = 1;
public final static int SHARK = 2;
public final static int FISH = 3;
by compressing it and place in two one dimensional array.
int[] ru... |
I have regrettably been away from C programming for a very long time, so I'd like to get a quick code review of a first proof of concept, before I get too far into adding capabilities, using the getopt library for arguments, alternate output and input character sets, a PolarSSL implementation, and so on and so forth.
T... |
The old function was:
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "N... |
I've been reading a lot about repository patterns these days. At first, the pattern seemed easy.
Most of the examples I read over the web use an ORM like below.
interface MemberRepositoryInterface {
public function find($id);
}
class MemberRepository implements MemberRepositoryInterface {
// here we're passin... |
I need to wait for short intervals of time in my program, but I really don't want to include unistd.h just to use sleep, so I'm doing it this way:
int main()
{
for(int i=0; i<=100000000000; i++); // <----- note that the loop doesn't do anything
return 0;
}
I do this when I don't really have a specific interva... |
This is the C++ code of my implementation of Knuth's algorithm M that produces mixed-radix numbers:
#include "visit.h"
void algorithmM(vector<int>& m)
{
m.insert(m.begin(),2);
const int n=m.size();
vector<int> a(n,0);
M2:
visit(false,a);
int j=n-1;
M4:
if (a[j]==m[j]-1) {a[j]=0;--j;goto M4;}
if (j==0... |
I am a very beginning in PHP and Design Patterns. I have been studying the amazing Head First Design patterns. So, I have been trying to translate the original into PHP. The class is working well, however, I would like to ask:
Is this considered good PHP?
Someone mentioned that this is not a Strategy Pattern. Head Fir... |
I'd made a project using pygame in python around 3 months ago. This was my first big project after I started learning how to program in college.
Now I'd like to know just how good my programming syntax and style is. Whether there are any weird irritants that simply defy the unwritten rules of programming in python. I'd... |
C# code
static int KEY_NOT_FOUND = -1;
private void Form1_Load(object sender, EventArgs e)
{
int[] A = createArray(1, 100000);
Stopwatch sw1 = performCalcs(1, A);
Stopwatch sw2 = performCalcs(2, A);
TimeSpan lag = TimeSpan.FromTicks(sw1.Elapsed.Ticks - sw2.Elapsed.Ticks);
}
public static int[] create... |
I'm trying to solve the Reve's puzzle (a variant of the Tower of Hanoi puzzle with four pegs). This is what I've come up with so far:
def solve(disk, source, temppeg1, temppeg2, destination):
if disk == 1:
print((source, destination))
elif disk == 2:
print((source, temppeg1))
print((sour... |
Is there a more cleaner approach to this? I'm doing the String calculator Kata posted by Roy Osherove. I realized that my calculator has no way of clearing out a previous expression after calling add. How can I handle this, and also how can I cut down the number of methods?
Here's a valid string: calc.add("//+\n1+2")
H... |
I've written some Python code to generate a random hexadecimal string using 31 playing cards drawn without replacement (so no card appears more than once). This is sufficient to provide more than 160 random bits, which is considered sufficient for a bitcoin private key.
I'm interested to know whether anything in the co... |
I would like to execute code for many views whenever the window is unloaded.
For instance, I could have something like this in a view's initialize:
initialize: function() {
$(window).unload(this.stopListening.bind(this));
}
I'm wondering if it would be better to have a manager which aggregates all of the view's re... |
I have this batch that builds some projects using msbuild.
What I want to do is to skip building my-last.proj if any of the above builds fail: my-proj1.proj to my-proj5.proj using environment variables.
I'm sure that there is another cleaner way to do this, but so far I just can't figure it out.
msbuild /target:Win32 m... |
Write the program expr, which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument.
For example:
expr 2 3 4 + *
There are 4 files:
calc.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
int main(int argc, char *argv[]) {
double tmpOp;
ch... |
For practice I decided that I wanted to write an animation class for SpriteSheets. The problem is that a single Sprite can have different widths depending on the action they are drawn to act. A tool called Sprite Sheet Packer creates a Map file documenting the index and bounds of each sprite. This file looks a little l... |
I have two files.
File 1. Has a list of all the dictionary words
File 2. Has a list of
all prepositions.
I want to remove all the prepositions from the dictionary.
I want to reduce the number of lines in my code and also make it more elegant, idiomatic and readable.
#!/usr/bin/env ruby
path = "/Users/../D... |
I need to implement something like "attached properties" from WPF that targets WinForms.
What I came up with seems to work. Can you find any issues with it? The helper class and example are shown below.
Not thread-safe since all access should be performed from the UI thread.
Attach a value (SetAttachedValue) or getter... |
I am trying to implement an AngularJS directive that would count the number of characters entered into a textarea and display it to the user.
Note: it will actually become much more complex later on and will become a full-fledged component that will be similar to the js component used by Stack Overflow for user commen... |
I have the following scenario:
The (web-) application is built with Java/Spring. I have several REST-endpoints which deliver data prepared to be consumed by a frontend by datatables.net. Each of this endpoint has a somehow similar signature (sEcho, iDisplayStart, iDisplayLength etc.) which are standardparameters necess... |
I have written a script that allows a user to walk around a dungeon pick up gold and once they have picked it all up they can exit the game through an exit.
What I am doing now is writing a bot to do the same. So far I have come up with a 'stupid' bot that is based mainly on randomness. The bot has has actions to the f... |
I got a random image rotator working by using the following script (demo). But I was told that it is a bad practice to extend Array.prototype. And it does. It conflicts with the chained select box unless I modify the selected box script. So I guess it's better to not use Array.prototype.shuffle ,isn't it?
Here's The s... |
I have written the following function to concatenate the parts of a name to produce the full name:
/**
* Returns the full name of the Person.
* @param boolean $includeTitle Whether to include the Person's title.
* @param boolean $includeMiddleNames Whether to include the Person's middle names.
* @param string $sepa... |
I'm creating a PHP website for a non-profit. They have some restrictions (no MySQL or pre-installed CMS) so I'm creating a CSS menu displayed by an unordered list where all of the elements are stored in a multi-dimensional array.
I've gotten it to work but being new to PHP, I'm certain it's not optimized to run as smoo... |
Here is an "enhanced" Listview class. You can just add it your project and you're good to go. Most of the code came from here and there. It's not perfect by any means, so any input is appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
usi... |
I wrote this quick script to convert a genotype file into a BED file. Running it seems to be taking a very long time.
#BED file format
#http://genome.ucsc.edu/FAQ/FAQformat.html#format1
#1.chrom - The name of the chromosome (e.g. chr3, chrY, chr2_random) or scaffold (e.g. scaffold10671).
#2.chromStart - The starting ... |
The Wikipedia article on the union find problem gives a very simple implementation, which I ported to C# and tested.
I know that the code should be, in the aggregate, asymptotically almost linear. But is it a practical implementation? Are there optimizations I should have used? Is there a way to cut down on the worst-c... |
I'm building a binary tree.
Example: key AAAA1.ETR, value 1.
I'm reading files with this structure:
DataLength Block-SequenceNummer FLag Start Data Ende
4 Bytes 8 Bytes 1 Byte S Datalength E
Data can be compressed or uncompressed (this is saved in flag). Data contain more messages. Could y... |
I have an array of integers and a number n. I want to sum the elements of the array and return the index where the sum passes n, as efficiently as possible.
For example, assume:
theString = "6-7-7-10-7-6"
theNumber = 33
expected result: 5
This does the trick but not very efficiently: (and error prone; will check for... |
While trying to create an "admin" backend (to allow for CMS like functionality) to a site using AngularJS on the frontend, I came across an issue with routes.
In order to allow the admin to create new content, ie install new component (view/controller), change menu item href locations etc, I would have to go in and edi... |
I was working with this problem, which is to find the number of zeros at the end of any factorial.
Here's my solution:
#include<bits/stdc++.h>
using namespace std;
int main(){
int numCases,num,zeroCount=0,mulFive,temp,i=0;
cout<<numeric_limits<int>::max()-1000000000<<endl;
cin>>numCases;
int solutionAr... |
Program must to find duplicate files (by content) in a given directory(and subdirectories).
I collect all data in Map<Long, ArrayList<String>> map where Key is the size of file and Value is the List of paths to files with the same size.
public static void main(String[] args) {
long start = System.currentTimeMilli... |
I have written an implementation of the merge sort algorithm in Java.
Here is the MergeSort class that I created.
public class MergeSort{
public static void sort(Comparable[] a){
Comparable[] b = new Comparable[a.length];
sort(a, b, 0, a.length-1);
}
private static void sort(Comparable[] a... |
The code is no longer relevant but I want to know how I can make it faster. It uses only about 10% of my CPU. Any advice about best practices, better algorithms, or how to make the existing one faster are welcome. This is purely for the purpose of personal learning.
public class BruteForce {
public static void main(Str... |
I am very beginning in PHP and Design Patterns. I have been studying the beautiful book "Head first: Design pattern" and I have been working in some of the codes originally presented in Java in order to learn more about PHP-OOP. The code below presents a kind of Observer Pattern. It is working well, however there are s... |
I am (in the process of) creating a system to store People and their details - names, date of birth (dob), addresses, phone numbers, etc. - and I'm curious how it is best achieved. Below is an an example of some of the SQL code with test data (the PHP classes match the structure in the db):
CREATE TABLE IF NOT EXISTS `... |
I'm learning C for mainly for fun and to get a better understanding of how things work under the hood (most of my experience lies with high-level languages). I've been following quite a few books and working through the exercises. For extra practice, I've implemented a linked list using the knowledge I've learned - I t... |
Here is a very basic Snake game in C, which I just want to make better. The game is working perfectly but it is very annoying because when playing it, it is always blinking. I hope that somebody could try it in their compiler to see how annoying it is. How can I improve this?
Here is a screen shot of the game:
Of cou... |
Here is what I have. I have it outputting most of the sums just so I can check there values. I think the problem is with the value of the elements in the array storing the column sums. I would greatly appreciate any feedback.
#include <iostream>
#include <cmath>
using namespace std;
void fillMatrix(int matrix[][4]... |
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
I wrote the following code with help of some Java 8, I'll explain the equivalent to Java 7 under the code. I'd like general comments. One note to give up ahead is that I did not write a program that gives the... |
I have articles on my website (built in PHP) and when an article is viewed the number of views is recorded back in the database. The SQL code snippet of my load method is:
SELECT *
FROM article
WHERE id = :id;
UPDATE article
SET views = views + 1
WHERE id = :id;
This works fine, but I've only tested it locally with on... |
I have this enum below:
public enum TestEnum {
h1, h2, h3, h4;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
System.out.println(TestEnum.h1.name());
String ss = "h3";
... |
I am trying to convert over to MySQLi and wanted expert advice. Is the enclosed code 100% OOP. Also, how secure is the code against attacks? I know nothing is 100% secure, but how good/safe is it? How and what can I make better? This is just a generic query as I wanted to get a basic model setup.
<?php
define ('DB... |
I am working on some multi-threaded code that requires a prime-number source.
The following code keeps an array of primes in memory, extending it as needed. It works in the 'int' domain, being careful to avoid overflows, and to keep the memory for storing the data relatively small.
it uses a state-based concurrency mod... |
I have a website which has reviews about games. Right now, to list the advantages (+) and disadvantages (-) of that game, there's a textarea in the admin panel with a WYSIWYG editor with only element. So my users list their (+) with list elements :
<ul>
<li>Game is too slow</li>
<li>Game is very hard</li>
</ul... |
In an effort to complete this month's code challenge, I've started off with the basics. Below I have for review, a class that I can call to create the square/button a user would click to mark a spot on a Tic Tac Toe board. I haven't done any game logic, so I could very easily be forgetting something my buttons need to ... |
I'm new to this PDO PHP and I have coded this spaghetti style. I hope you can give me idea how to improve using prepared statements. I'm not a lazy person, but I really need your help to improve my coding style.
try {
$select = "SELECT users.id, users.users_id, username, firstname, lastname, passwo... |
I would like to improve the interfaces of some polymorphic classes going from positional to named parameters and I came up with the fluent interface.
The following is the most clean, compact and compilable (-std=c++11 required) example that I have been able to come up with:
#include <iostream>
#include <cmath>
#include... |
I have implemented customized encoding mechanism for javaUTF16. Does this implementation support all the characters?
public class Encoding {
public static void main(String[] args) {
byte [] arr = new byte[1000];
String str = "abcde" ; //even this encoding works supplementary characters
... |
The word processor I've had in mind would be similar to Microsoft Word and OpenOffice. I am trying to keep my logic separated from the user Interface and that separated from the controller, basically using the MVC (Model View Controller).
Other things I would like reviewed would be code layout: should I try to abstract... |
I've been trying to learn how to use the TPL for quite some time now.
Basically I'm trying to fire off a group of Tasks, wait for them to complete and then fire off another group of tasks, waiting for them to complete before firing off the tasks that update form elements on the UI Thread.
Here's what I got. I think I'm... |
How would you DRY up this RSpec code?
require "spec_helper"
describe InvoiceMailer do
let(:user) { create(:user) }
let(:student) { create(:student, user: user) }
let(:body) { "And I for one will join with anyone, don't care what color you are. As long as you want change this miserable condition that exists on th... |
This is small piece of bigger puzzle, but usable by its own.
It an attempt to have a nonblocking queue with "unlimited" (besides memory size) buffer length.
Got unit-tests 100% statement coverage, it looks that it's ok, but I'm very new to Go and concurrency so I might miss something.
import "sync"
// Message and Mess... |
The architecture is showing a call to an external Web Service which is called by me. Then I will expose the data using WCF to be callable from another WCF client. But I really don't like how it's done. Interfaces, contracts, implementation in the BLO and implementations on the DAL.
7 time copy & paste of method which j... |
I'm writing wrapper functions for some of the functions in <algorithm>.
While the following works perfectly, I'm not sure if this is the best way to approach it:
template<class ContainerType, class Predicate>
ContainerType filter(
const ContainerType& container,
Predicate predicate
) {
ContainerType filtere... |
I have these two carousels that randomly pick up pictures. [fiddle] Each of them picks up pictures and links from their own different inner array. It works fine as it is, but I was just wondering if there's any part that I can encapsulate/shorten. The only thing I can come up with that doesn't return any error is them ... |
I have implemented a basic object class in C++, and I want to make sure that I have implemented everything efficiently and safely, as I made a few mistakes while making it, which I corrected, but I could have left a few more mistakes behind:
class object
{
private:
class dummy
{
public:
dummy()
... |
The following PHP code does exactly what I need it to do but, as a complete PHP novice, I am wondering: what can be improved here?
$theurl='./section-1.html';
function getbody1($filename) {
$file = file_get_contents($filename);
$bodypattern = ".*";
$bodyendpattern = ".*";
$thecontainer = "id=\"container\"";
$... |
I've implemented Excel's SUMIFS function in Pandas using the following code. Is there a better — more Pythonic — implementation?
from pandas import Series, DataFrame
import pandas as pd
df = pd.read_csv('data.csv')
# pandas equivalent of Excel's SUMIFS function
df.groupby('PROJECT').sum().ix['A001']
One concern I have... |
function transform(tree,fn){
var root = tree,
node = tree,
child,
parent,
is_node,
dir;
root.dir = 0;
while(true) {
is_node = typeof(node)==="object";
dir = is_node ? node.dir : 2;
if (dir < 2)
child = node[dir],
node.di... |
Interested in a review of this code, in particular the (hopefully monadic) bind. I actually put this to good use. It was a nice complement to Guava's Optional, and shorter than:
Optional.fromNullable(x).or(y);
And I threw in a bind method, which I think lifts it up into monad space.
One question I wasn't sure of the ... |
I've hacked together some code to read the content from a sequence of files:
let fileContents =
[ "filename1"; "filename2"; "etc" ]
|> Seq.map(fun file -> async {
use fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)
let data = Array.create(int fs.Length) 0uy
let... |
Recently I needed to save session state in cookies, instead of server side. I looked around and didn't see anything similar, so I decided to write something to handle the encryption, decryption, and validation of the cookies. I wanted some opinions before/if I release it on packagist.
Any feedback would be great, tha... |
I need some help reviewing this code in terms of making as fast as possible. This is a modified version of BFS that does quite a bit of processing on the side.
Use case:
I have a large graph (probably tens of thousands of nodes). Every edge is defined by three parameters currently - bandwidth, latency and cost. I need ... |
Based on my understanding of Verlet integration I tryed to use it over my Euler method to move my character in a 2D space.
I will put only the neccessery code, but if anything else is needed I will edit my post.
This is my Character class (which I probably need to rename to Charactor)
class PlayerData(object):
def ... |
I have an image and a text title that I'm trying to center in a div. I would like the image to be to the left of the title, and for both of these elements to be centered both horizontally and vertically in the div.
I've found one way to do it, by nesting the image inside of a paragraph. I'm assuming this is not the p... |
I have coded up an implementation of Conway's Game of Life and I have a performance bottleneck in it which I wish to be optimized. The main logic is in the Universe class. I have omitted all code which is not applicable here for brewity:
public class Universe {
private static final int FLIP_INDEX = 0;
private ... |
I wanted to find out which states and cities the USA hockey team was from, but I didn't want to manually count from the roster site here.
I'm really interested to see if someone has a more elegant way to do what I've done (which feels like glue and duct tape) for future purposes. I read about 12 different Stack Overflo... |
I have two divs as seen in this JSFiddle. To recreate the problem, keep clicking on the Gray container till both divisions touch each other.
The purpose is to execute a certain function once the green div touches the red one. The problem is that, this step callback as seen from the following code and demo, gets called ... |
I would love a second opinion / another pair of eyes on this.
db.customers.mapReduce(
function() {
Array.prototype.getUnique = function() {
var u = {}, a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue... |
I was wondering if there is a smarter way of doing the following code. Basically what is does is that it opens a data file with a lot of rows and columns. The columns are then sorted so each column is a vector with all the data inside.
"3.2.2 - Declare variables"
lineData = list()
for line in File:
splittedLine =... |
I have come up with a Java 8 solution for the following problem:
In the 20×20 grid below, four numbers along a diagonal line have been marked in red (bold here).
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 ... |
I am writing a ASCII dungeon creator inspired from games such as Angband, Moria etc.
The main goal of the project is to allow a user to come along and implement their own "DungeonLevelGenerator" so they can generate dungeons however they wish using the interface and tools I've provided to help speed it up.
Let me just ... |
I studied a bit and packed all the suggestions that I received here: Fluent interface and polymorphism for building a scene with shapes and I came up with this:
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
struct Figure {
string _name;
virtual double area() const=0... |
Here is the code for the QuickSort class that I created.
public class QuickSort {
public static void sort(Comparable[] a) {
quicksort(a, 0, a.length-1);
}
private static void quicksort(Comparable[] a, int lo, int hi) {
if(lo >= hi) return;
int pi = partition... |
Here is a function that I've only slightly modified from its original context, found here.
Before mentioning anything else, it should be noted that I'm desperately trying to optimize this code for speed. It presently takes about 5.25 seconds to execute and it appears as though the bottleneck is happening in the for-lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.