instruction stringlengths 71 71.9k |
|---|
Question:
For a 1000-digit number, find the 13 adjacent digits which gives out the largest product.
My code goes like this:
series = '731...752963450' # the 1000 digit, simplified here.
# Set up variables.
adjacent_count = 13
pointer = 0
candidates = [], products_array = []
pointer_end = series.length - (adjacen... |
Question:
Add all prime numbers smaller than 2,000,000.
The first method is done by deriving own is_prime? method:
# First Method
def is_prime(n)
if n <= 3
return n > 1
elsif (n % 2 == 0 || n % 3 == 0)
return false
else
(5..Math.sqrt(n).ceil).step(6) do |i|
if (n % i... |
I'm combining two lists of dicts, based on the value of the key 'time'.
If have two lists, for example:
a=[{'time': '25 APR', 'total': 10, 'high': 10},
{'time': '26 APR', 'total': 5, 'high': 5}]
b=[{'time': '24 APR', 'total': 10, 'high': 10},
{'time': '26 APR', 'total': 15, 'high': 5}]
These lists contain val... |
This is a follow-up to this question.
While discussing some details about the code I posted there, I came upon a problem with thread-safety. After searching and trying different things, I reached a potential solution that I now present here. This worked without any problems during my tests, though since thread-safety i... |
Why is this code "bad"? In all of the selection sort codes I am learning from, they do it much differently. I will learn the proper code from the book, but I would love to know why this particular code is bad.
public class Main {
public static void main(String[] args) {
int[] array = {8, 3, 5, 7, 9, 2, 4, 6... |
My first FizzBuzz question (well, I asked, then deleted, one previously), and my very first VB.NET question.
Module Module1
Function FizzBuzzify(ByVal Value As Integer) As String
If Value Mod 5 = 0 And Value Mod 3 = 0 Then
Return "FizzBuzz"
End If
If Value Mod 3 = 0 Then
... |
Continuing with my VB.NET experience, I wrote a quick guess-the-number game. Any improvement suggestions?
Module GuessTheNumber
Sub Main()
Do
PlayGame()
Loop Until Not ExitGame()
Console.ReadLine()
End Sub
Private Sub PlayGame()
Dim minNumber As Integer = 1
... |
For fun, I decided to implement the quickest Quicksort I could. This is what I came up with. How can I make it better?
I know that it's slower for sorted and already reversed lists (through testing), but I'm not certain why. What I do know is that this algorithm reverses the list past the pivot, if the list was sorted/... |
I'm relatively new to Java and decided to make a Memory Match game.
Card.java:
import javax.swing.JButton;
@SuppressWarnings("serial")
public class Card extends JButton{
private int id;
private boolean matched = false;
public void setId(int id){
this.id = id;
}
public int getId(){
... |
I'm trying to develop a program that stores currency values. In my particular application I only care about two decimal of precision (cents) but have read it's a good idea (for accuracy when dealing with interest rates) to store 4 digits.
I didn't notice a "currency" class in either boost or C++14 (perhaps I overlooked... |
Does this data structure make sense? It's essentially a vector of pointers, intended to point to larger objects. In effect, it gives the benefit of a linked list, with an \$O(1)\$ lookup at the cost of maintaining an array of pointers to each element.
What edge cases am I missing, and what's the formal name of this da... |
Project Euler problem 78:
Let \$p(n)\$ represent the number of different ways in which \$n\$ coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so \$p(5)=7\$.
Find the least value of \$n\$ for which \$p(n)\$ is divisible by one million.
I used Euler... |
I am trying to multithread a for loop, and this works so far. How can it be improved? Have I done anything incorrectly?
The work is broken up into blocks and the block variable is the amount of objects to process per thread.
Test.class
public class Test extends MultiThreaded {
public static void main(String args[]... |
I'm trying to learn to program on my own with the help of books and the Internet and thought I'd start a project (a sub-project for a project).
I want to build a dictionary that allows multiple keys for one value:
d = mkdict()
d['what', 'ever'] = 'testing'
d['what'] is d['ever'] # True
I thought it would be good to ge... |
Question:
Given a 20x20 Grid of integers, find the greatest product of four adjacent numbers. (up, down, diagonal, reverse diagonal).
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 67 53 88 30 03 49 13 36 65
52 ... |
Disclaimer: It's literally the second time I write in Haskell.
The purpose of this module is to provide some basic operations with IP addresses (and networks).
At the moment I only implemented the successor operation, that returns a next address in the range if it exists.
Eg: for 192.168.1.1 in 192.168.1.0/24 it would ... |
I'm a complete newbie to Elixir, but I managed to bang together this working example of Ascii85 for a project I'm working on in my spare time.
I find some awkward repetition in here which I have tried to replace with iteration but it just made the code harder to read. There is also some lop-sided behaviour which I'm no... |
This PHP User System was built with MySQLi and I also used Composer. I'm planning to improve this, and add more stuff and release it as a sort of a module for Composer.
User.php (Controller File in the src/Controller) folder.
<?php
namespace Application\Controllers;
use Http\Request;
use Http\Response;
use Application... |
The source of the problem is here.
Given an array of integer elements, return the maximum difference of any pair of
numbers such that the larger number of the pair occurs at a higher index
than the smaller.
Here is my implementation in Java.
package algo.mindiff;
public class Main {
// http://www.careercup.... |
Please review this solution for matching parens for correctness and nesting.
def matchParens(pstring):
plist = [l for l in pstring]
newlist = []
if plist[0] == ')' or plist.count('(') != plist.count(')') or plist[-1::] == '(':
return False
while len(plist) > 0:
head, *tail = plist
... |
I think my Table class may be doing too much. I feel as though I should perhaps create a separate Input class that deals with editing the table's rows.
My main problem is knowing when to create a new class. Is it true that the table is doing too much? Which things should be made into other classes, and why?
Btw, Step i... |
If a triplet of segments A, B and C are triangle triplets if and only
if
A + B > C
A + C > B
B + C > A
Is there a better implementation for this problem?
#include<vector>
#include<iostream>
void findTriangleTriplets( std::vector<int>& vec_input, std::vector<std::vector<int>>& triplets)
{
int size = vec_input.... |
Please let me know if there is a shorter way to do it again without any kind of loops. Recursion only.
static bool isSortedArray (int[] ar, int length)
{
if (length == 0)
return true;
bool temp = isSortedArray(ar, length - 1);
if (temp && ar[length - 1] <= ar[length])
return true;
else
... |
I'm learning Rust now and created a program to solve the task General Fizzbuzz on Rosetta Code.
For example, given:
20
3 Fizz
5 Buzz
7 Baxx
where the first line indicates the upper bound and every line after that indicates the divisor and the corresponding word, the program should return:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
F... |
This is a follow up question to PyDOS shell simulation.
You might remember PyDOS from my other post. I have now updated it and it's better than ever! Post any ideas below that could make it better.
import time
import os
import sys
import random
def splash():
print ()
print ("PyDOS")
print ()
print ("Versio... |
I wrote a small script to get the probability of a given text to be spam. I downloaded some ham (good content) and spam (bad content) text from the internet. The spam corpus is a 1.8 MB txt file, and the ham corpus a 3.6 MB txt file.
My method is pretty naive: I count how many times each word appears in the ham and spa... |
I'm writing an animal shelter program, which keeps a database of different classes of animals (dog, cat, monkey). Functions that create the form and add the animals are very similar (difference is two questions and the rest is the same). Is it possible to divide this functions into parts so that the program code is not... |
I wrote a script with utilities for calculating the entropy of iterables and included a Tk GUI that shows a quick overview over a text's properties in real-time. (on GitHub)
I tried to follow PEP 8 as good as possible, but I'm not sure about other things, specificially:
I think my docstrings are sometimes overly redun... |
Here is yet another piece of Rubberduck code, this time the nasty ProcedureNotUsedInspection class, whose role is to identify all procedures that are never called anywhere, and to issue a ProcedureNotUsedInspectionResult for each one.
using System.Collections.Generic;
using System.Linq;
using Rubberduck.Parsing;
using ... |
I implemented an O(N^2) algorithmic solution but not sure it is better than my previous implementation Find Triangle Triplets from a list of given numbers
in case of performance. I adapted almost all suggestions from answer except a structure to keep the triangle triplets.The reasons to ignore the suggestion are foll... |
The below I have put together as an experiment, I have profiles on my site that are password protected. I would still like them to be crawled by google.
The script is taken from here and basically does a reverse dns lookup to verify if a googlebot is real or fake. I am then using this logic to allow google entry to my... |
I just finished my linked list library in C and I am trying to find out what should be improved. The functions provided by the library are members of the main data structure (very important).
The entire project can be found here.
Here is the source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "c... |
This is a sanitizing function. Is this function secure enough?
public function clean( $input, $fordb = true ) {
global $db;
//is it an array?
if( is_array( $input ) ) {
//yes it is! let's clean each item individually.
foreach( $input as $key => $val... |
This code calculates the distance between angles, particularly for n-tuples of angles. One example where this situation occurs is as follows:
I'm using a 2 arms, one 6 degree of freedom and the other 7 dof with revolute (rotating) joints. The position of the arm can be accurately represented as an n-d point representin... |
I'm trying to create a simple HTTP client. In order to make one that is standard compliant, I must be able to extract user information from a URI and convert it to base64 and send it via an authentication header to the server. I created this demo program to test my progress on this function I've made. Does this program... |
I am creating a simple program with multiple buttons. Is this way of checking which button was pressed is ok? Is it better to use switch..case.. statement?
public class KennelGUI extends JFrame implements ActionListener{
private String filename; // holds the name of the file
private Kennel kennel; // holds the ... |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Project2
{
class Program
{
static void Main(string[] args)
{
int[] ageForPeople = new int[10000];
int[] DistrictForCensus = new ... |
I've written a MySQL class that handles sanitization of different data types. The reason I used this (and not prepared statements) is because this can be more dynamic.
Prepared statmenets only supports four data-types:
Integer
Double
String
Blob
This limits functionality and it doesn't allow you for example to add ... |
Shamir's Secret Sharing scheme essentially splits a secret into n parts, at least k of which are needed to recover it. I'm using that to encrypt/decrypt arbitrary files (it's part of a college project).
Here's a rough idea of what I'm doing:
Take a file, and read N bytes. Treat those bytes as an integer, and encrypt i... |
The problem is that I have executed the program for the last hour and it hasn't returned a value till now for input 1022. How can I make the program a bit faster? How can I increase the efficiency of program? Is there a faster algorithm?
I have Intel Core2 Duo (2.93GHz).
#include <stdio.h>
int main() {
unsigned lon... |
There are 3 window groups to add users and the application uses MVC 4. Here's my approach to add security attributes to my controllers and pass user's role to the view in order to enable/disable controls. I'm looking for ways to approve the code.
Webauthorization.cs (the logic to check user's role & if not in any role ... |
I've compiled a simple Linux pipeline and using my C style and modularization that I will use for my own operating system. Do you have something to say about this code (partly taken from SO)? For example, are all my imports necessary? How can I improve error handling?
#include <sys/types.h>
#include <errno.h>
#includ... |
I have created this bash script for Compile And Run c++ code, car++.sh.
As I'm new to bash scripting, I'm not sure about good bash programming practices.
Please review it to see if you could find any anomaly.
#!/bin/bash
found=false;
output=;
o_is_set=false;
#retrieve output_filename from arguments as provided by use... |
I have written a simple implementation of Sieve of Erasthotenes (in C, MSVC flavour), which I believe is correct (source below). Is there a way to make it faster and more readable?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <intrin.h>
typedef unsigned long long bitmap_entry_t;
#define NUMBERS_TO... |
I have been playing around with an adjacency list implementation of a graph class, on which I'd like to be able to run a build and test several graph algorithms. The code I have below works and I have been able to implement BFS, DFS, Dijkstra and Prim's algorithms, but I'm not very satisfied with it and would very much... |
I have written a program in C to do the following:
Read a matrix (in file format, first line you have the size, then next are the entries). This is done by the "input" function.
Find the strongly connected components using the kosaraju algorithm (the one that uses the transpose). Done by the "SCCmatrix":
+) Step 1: DF... |
I'm trying to optimize the following method. Any suggestions on how this can be done better? The shipping cost is based on weight and the total cost of products. Following are the conditions for calculating cost.
When order is under $100, and all items under 10 lb, then shipping is $5 flat.
When order is $100 or more,... |
I have a class that contains defines 'magic' numbers at compile time such as basic array sizes, fixed ip address, etc. so that I have one place to edit if changes are required.
In this nested class I need to define tuples of maximum and minimum values that correspond to each of 4 bands of an IR camera. I'd like to use... |
See this this question for background. This is a live filter where results are filtered as you type. I've taken into account Kerri's answer and expanded on her recommendation. I've added a message that appears if no results are found, and a display for how many results are being displayed out of the original set. You c... |
Using an OR/M I map a lot of rows from database to array of objects (~300k). In these objects some properties are marked with special attribute [Signed]. Row-by-row I combine them in string, calculate salted MD5 of string and compare to hash I received from database.
Everything was working pretty okay for a long time, ... |
To help prepare myself for my final exam, I wrote a simple Game of Life. I want to expand it to have each sub-population represented by a character, but before I do that, I want to make it more efficient; because right now it's running at about 1 fps, which is way too slow (I'd like at least 3 fps). What I want from a ... |
The purpose of a rhythmic task controller is to accept a task and execute all the queued tasks in a cycle or "rhythm" defined by the client code. A task returns true or false depending on whether or not it is "finished". A finished task should be removed from the controller's control and won't be executed again while a... |
This is my solution to Project Euler
Problem 52 - Permuted Multiples. In the problem I'm searching for the smallest value of x such that x, 2x, 3x, 4x, 5x, and 6x use the same digits.
x = 125874
while True:
x += 1
if sorted(set(str(x))) == sorted(set(str(x * 2))) == \
sorted(set(str(x * 3))) == sorted(s... |
I am attempting to create an efficient algorithm to pull all of the similar elements between two lists. The problem is two fold. First, I can not seem to find any similar algorithms online. Second, there should be a more efficient way.
By 'similar', I mean a predesigned way to find all similar elements between two list... |
Particularly on the CSS page, in the #question_list id, you'll see I've put a transparent border. This is obviously pointless, but without that border, my footer moves up and down when the proceeding questions come in, due to their size. Any suggestions on what I can do to remove that border and have my footer stay put... |
I made this function to act sort of like jQuery's $.ajax. I intend to use it in small projects where I do not use jQuery (I don't want to load a whole framework just to facilitate http requests).
Edit: New script incorporating Bob Lauer's suggestions
"use strict";
function OM(obj){
return new ObjectManipulator(obj... |
It is a continuation of my previous question:
Find non duplicateTriangle Triplets from a list of given numbers
After I realized triplet structure using less space than std:vector<int> and there is a simple way to remove duplicates from the triplets list by modifying loops index I rewrote the code again. On top of that ... |
I'm looking for code-review, optimizations and best practices. This code is a Java adaptation of code on geeksforgeeks.org. Please verify if space complexity is \$O(n)\$ where n is number of bits, and aux complexity is \$O(1)\$, since no temporary space was needed. Whatever space was needed was used for return value no... |
I was working on some TT code generation to get rid of mundane C# codings in VS2013 Express Edition, and after researching online, created the following helper methods to facilitate Type declarations.
I am able to use it successfully in my code generation but wonder if they can be improved further or if there's any sce... |
I have recently started using React and wish to know if my code adheres to the React coding style, whether I am following the same approach towards solving any problem and is there any way I can make the code better.
var React = require('react');
var Bootstrap = require('react-bootstrap');
var xhr = require('superagent... |
In the process of writing scripts to work with CSVs and other files of the like I found myself in the need of a way to navigate and select files for various purposes. I wrote the following function for one of the scripts I needed to finish quickly and now I'm trying to get it into a more reusable form
def select_file()... |
Below is the representation and user interface fib_sequence for generating a Fibonacci sequence:
empty_rlist = None
#Representation - start
#Constructor
def rlist(first, rest):
return (first, rest)
#Selector
def first(s):
return s[0]
def rest(s):
return s[1]
#Representation - end
def fib_sequence(k):
... |
To write a Java class that reads through a text file of drawing commands and draws the appropriate shapes onto JFrames, I have input instructions as follows:
FRAME width height // sets up a new frame with given width and height (both integers)
COLOR red green blue // sets the current “pen color” to the color with the g... |
I solved the Fibonacci Golf problem on checkio.org:
The Fibonacci numbers or Fibonacci sequence are the numbers in the
following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21...
This is not the only interesting integer sequence however; there are
many various sequences like the Fibonacci numbers, where each elemen... |
I have a project in my mind for quite some time, and it requires me to create dynamic objects.
Usually, casting an array to object does the trick (e.g.: (object)array('test'=>5)). But sometimes, we still want the magic methods to fire up. For that, I have developed a class.
It supports the magic methods __construct, __... |
I've seen everybody claims the nested ternary to be an evil even when an operation couldn't be written with switch-case; and here's even more, my code could be easily written with switch-case statement.
/// <summary>
/// Control sequence character
/// </summary>
private readonly string CSI = "\u001b";
public string Co... |
I wanted to see graphically what my programme was doing so I wrote this automatic flowchart generator:
class Object
def log(previous_method)
if not DEBUGGING
return
end
repr = if self.class == Enumerator then self.to_a else self end
if [Array, String].include?(repr.class... |
The problem I am referring to is here
So basically it's about shifting an array of ints 1 position to the left and relocating the lost first int in the start of the array to the last position at the right:
\$\mathrm{shiftLeft}(\{6, 2, 5, 3\}) → \{2, 5, 3, 6\}\$
\$\mathrm{shiftLeft}(\{1, 2\}) → \{2, 1\}\$
\$\mathrm{sh... |
I am trying to optimize execution time of this function which detects cycle in a directed graph:
g = {
1: [2, 3],
2: [3]
}
cur_path = set()
def isCyclic(g, vertex):
global cur_path
cur_path.add(vertex)
for neighboor in g.get(vertex, []):
if neighboor in cur_path:
return True
... |
I am very happy because I solved this problem with very little code:
"""
100 people are standing in a circle with gun in their hands.
1 kills 2, 3 kills 4, 5 kills 6 and so on till we are
left with only one person. Who will be the last person alive?
Write code to implement this ##efficiently.## <-[ Pyt... |
This is the second part of a multi-part review. The first part, the server for this client, can be found here.
I've been building a simple C# server-client chat-style app as a test of my C#. I've picked up code from a few tutorials, and extended what's there to come up with my own spec.
In this second part, I'd like to... |
I've written an answer to HackerRank's Angry Professor problem. Please let me know if there's a quicker/better way of solving this as I think I wrote quite a bit of code for this problem (answer has to be in 1 class btw). Also, any improvements on my code in Java 8 are welcome too.
Problem statement (as written on Hack... |
I wrote a mixin to declaratively get a Bacon.js event stream. So instead of onChange={this.handleChange}, you can do changeStream={this.handleStream}, and this.handleStream will be passed an onChange Bacon.js event stream. My big concern is that I have to override React.createElement in order to make it work. I'm wo... |
I have created a calculator in Ruby. I am using Ruby 2.1.0. I'm fairly sure that someone will be able to improve this, as I am quite new to Ruby.
puts "Welcome to Calc"
puts ""
puts "Please enter the first number"
n1 = gets.to_i()
puts ""
puts "Please enter the second number"
n2 = gets.to_i()
puts ""
add = n1 + n2
s... |
Find the sum of product of all numbers in first array with all the numbers in second array.
Input Format
1st line contains 2 space separated integers N and M.
2nd line contains N space separated integers Ai.
3rd line contains M space separated integers Bi.
Output Format
1 single line containing only the require... |
I wrote a map reduce program which uses multi threads, bounded buffers, condition variables. It works perfectly for some types of inputs.
In the program there are N mappers, R reducers, 1 merger. mappers get data from input files, put each string in files to corresponding buffer-X-Y. reducers read from those buffers, ... |
Noobie to Numba here, I'm trying to get faster code from existing function but the result is not faster. 10 times faster would be heaven, but I know nothing about optimization.
This is code about parsing gaps in DNA sequences pairwise alignment and doing statistics about it.
The code looks like this:
import re
import t... |
This is my first program I can call 'something'. I would be glad to hear what you think of it, so I wouldn't pick up bad habits further on.
It catches errors, but requires numbers to be separated from operators. It ignores a lot of characters, therefore (+ 2 2) is as valid as (+ 2 blargh 2)
100 lines of code + comments... |
This will get quite clumsy if I continue down the road with this design, so I'm asking you, enlightened ones, is there a way to make this prettier and easier to understand? Primarily the run-function (Especially in the else if where self.query and self.find are set), also, I want it to be chain-able, with .run being th... |
I have made a funtion to compare text files line by line, where timestamps and jobnumbers are replaced for a identical string. By lack of experience I'm not sure if this is the best way to do this.
if (row < comparedFile.Count)
{
var regexJobNumber = @"([0-9]{4})";
var regexTimeStamp = @"([0-9]{8}_[0-9]{6})";
... |
This is problem 50 in https://wiki.haskell.org/99_questions/46_to_50. The website has more elegant Haskell solutions, but I wanted to get feedback on how the code I wrote on my own below could be improved.
import Data.List
data Tree a = Leaf a Int | Internal (Tree a) (Tree a) Int
instance (Eq a) => Eq (Tree a) where
... |
I just wrote a program which performed some elementary set operations as you can see below. It's the first time I have used input and output of text files so I am mainly looking for critique on that, and also how I use cells.
clear all;
clc;
fileID = fopen('inputseto.txt','r');
data = textscan(fileID,'%s',3,'Delimiter... |
My Cocoa event code always tends to descend into madness, I need to advice on how to reduce complexity. I've spend a few hours putting this example together.
CanvasView is a layer hosting subclass of NSView which uses Cocoa's eventing handling (-mouseDown:, -mouseDragged:, -mouseUp:) to enable clicking and dragging of ... |
This executes a predefined script on a remote host, and somehow retrieve variable values without affecting STDOUT and STDERR.
My idea was to encode the data in JSON, write it to a file, then read the data in a separate request.
The cons of this method are that:
I would need to add the following code (file_put_contents... |
I'm learning F# and functional programming, from a background in C# and imperative/OOP. I've ported a small, one-off console app from C# to F#. The port worked (the app behaves the same way), but I'd love to get some feedback on writing more stylistic F# and thinking about code in a functional way, as this was a port o... |
I'm inspecting VBA code to find obsolete code constructs - namely explicit Call statements, like this:
Call DoSomething(42)
The "correct" code construct would be to omit the Call token and drop the parentheses - my code locates the obsolete Call statements and rewrites them like this:
DoSomething 42
I have an Id... |
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:
Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
My answer is this:
var sumSquareLargest = function (x, y, z) {
var number... |
I need to extract a ID (int number) from a Url.
Example: http://www.example.com/foo/bar/12345
For this I wrote 4 methods where the first one ReadIDsFromFile() is called by my constructor and the return value is set to a properties of this class. The methods are called in the order I posted them below.
private List<stri... |
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:
Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
My answer is this:
import Data.List(sort)
sumSquareLargest :: (Ord n, Floati... |
This program is supposed to prompt the user for hours and wage of 4 employees. Then the program will use a selection sort to sort the data into ascending value using the wages. The information like employee id and hours and what not should be adjusted to match the sorted data. My program works but are there improvement... |
I want to know if there's a better way of doing a select on dropdown and selecting the items. I bound ng-click to every anchor and assign a value on click, but it just doesn't feel like a clean way to do it.
Also, is there a way to use ng-repeat to create the dropdown list dynamically? The problem I get if I use the n... |
I have the following method, which finds all the possible paths from the top left to bottom right of an N x M matrix. I was wondering what is the best way to optimize it for speed as it is a little slow right now. The resulting paths are then stored in a set.You can only move down or right to an adjacent spot, no diago... |
So far I have attempted to find the inorder successor through recursion and it seems to be working right. Can someone review the code and give suggestions?
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node * inOrderSuccessor(struct node *root, struct node *n)
{
if(root == NU... |
This is an update to my question Class for easier to read IProgress handling and includes the suggestions from @svick, with one exception.
It was also suggested to change the setter for Content, so the report object could be set directly. I didn't make this change because this could result in reporting the same instanc... |
I wanted to display 1 outcome of 1 single custom field or attribute in the category overview, using a third party customfield extension in my J! and VM website. I got it working using the code below. As this is the first time I actually write PHP and MySQL stuff myself, I was pretty proud, but also thinking 'this can p... |
This bit of code gathers data from two methods and puts it into an array. The code works fine but it doesn't look pretty and I feel like there is a better way of doing what I have done.
public static function RagUpdate()
{
$MachineOnOffStatus = self::RagOnOffStatus();
$ActiveMachine = array();
foreach ($Mac... |
I have a snippet of SQL that compares the last two records and gives the datediff in seconds. However, the way I have it is quite slow, taking up to 20 seconds to execute depending on how many controllerIDs I need to check. What would be a more efficient way of doing this?
select
T.controllerID,
... |
I was given a file of size 46KB full of names (around ~5000), in the format as shown below:
"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"..."DARRELL","ALONSO"
I wonder if my code below is optimal in doing what I want, which is to translate this txt file into an array of names.
array = []
File.readlines('names.txt').... |
I've implemented a table view controller for the purposes of subclassing. The table view controller implements a pull-to-refresh which will automatically reload the table view's data. I am looking for general feedback on my class.
DXYBaseTableViewControllerHD.h
#import "DXYBaseViewControllerHD.h"
// Displays a table... |
Here is a lazy dictionary with test cases.
"""
A dictionary whose values are only evaluated on access.
"""
from functools import partial
from UserDict import IterableUserDict
class LazyDict(IterableUserDict, object):
"""
A lazy dictionary implementation which will try
to evaluate all values on access and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.