instruction
stringlengths
71
71.9k
I have two different ways of populating a List with querying another List. They are: var list = _surveyList.Where(x => x.Date == selectedDate).Select(s => s.Joint).ToList(); And: var list = from s in _surveyList where s.Date.Equals(selectedDate) select s.Joint; They functionally do the same thin...
I am creating my models manually. I have five tables in my database as follows: Members MemberTypeMasters Payments Relationships StatusMasters My database looks like this: So far I have 6 files containing auto-implemented properties as below: Models |-- DBCS.cs |-- Member.cs |-- MemberTypeMaster.cs |-- Payment....
This is a typical bouncing ball program. I'm looking to improve and perhaps add to the program. For example, is it possible to be able to click on a ball and have it pause? import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.MouseEvent; imp...
I have written Java code that finds the frequency of the occurrence of a word in a sentence. It is working fine. The only thing I want to do is to optimize this code. String str = "I am a Boy I am a"; String[] splitStr = str.split(" "); int count = 0; List<String> list = new ArrayList<>(); ...
I've just written my first angularjs directive, and I was hoping to get some feedback. I already have two doubts myself. Why is it that I must use tElement.append() to append the canvas element? tElement.html() doesn't work, at all. That just returns [[object HTMLCanvasElement]] in plain text inside of the element. Sh...
I'm new to Go, and as a learning project I've been implementing RC4, attempting to follow pseudo-code in the Wikipedia links (and trying not to look at the far-superior version in the crypto package). Some questions: Wikipedia suggests computing new array indexes using mod 256 at several points throughout the implemen...
I am updating some old reports that are using mysql_ statements and trying to use the MySQL PDO stuff. I was told that PDO is far better since I was running into runtime issues with some of my reports. My old report took 91 seconds to run, and my PDO version takes 106 seconds. While 15 seconds may not seem like a bi...
This draws scanline of the image to System.Drawing.Graphics. It's quite simple and it's optimized in order to merge neigbour samples with the same color into single rectangle (instead of drawing sample-by-sample in 1x1 rectangles). I don't like the duplication of this code inside and outside the loop: updateAlpha(brush...
I'm developing a small craps game in C++, and my C++ skills are a bit rusty. I really need someone to review my code to ensure that I have correctly implemented the game according to the rules. Game rules: The player or shooter rolls a pair of standard dice If the sum is 7 or 11 the game is won If the sum is 2, ...
get_item_count calls to an API and gets a count. There are several pages to get this count from until there are no more results. How do I improve this code to remove all of the extra variables and make it easier to read? final_count = 0 page = 1 final_count = individual_count = get_item_count(config, page) while indiv...
Please help me optimize this bubble sort code. It's working fine otherwise. int[] randomIntegers = {2,3,1,1,4,5,8,-2,0}; for(int i=0;i<randomIntegers.length;i++){ for(int j=i;j<(randomIntegers.length-1);j++){ if(randomIntegers[i]>randomIntegers[j+1]){ randomIntegers[i] += randomIntegers[j+1]; randomI...
What the code does is convert an image to a bitmap without having to create 3 arrays to make the conversion. It basically uses 1/3rd of the memory that it would normally use. I'm trying to refactor this method to make it shorter, less complex and more readable. So far, I've been unsuccessful in the 4 attempts I've made...
I'm looking for remarks on pretty much anything. This has been my first project that's meant for use by others and I'd like to have it as clean as possible. I will post the main source code here but because of the size you might prefer reading it on Github instead. The code should be adequately documented so I don't th...
I have written this code to find second largest element in an array of random integers. If it needs to be optimized, then do comment on it. First of all I'm populating all the elements into the list which does not have any repeating value, then sorting, then in list.size()-2 I have second largest element. This is on...
At first it was like this: public abstract class TicTacToeViewAbstract implements TicTacToeView { private final List<OnCellClickListener> onCellClickListeners; private boolean movesBlocked; private boolean gameFinished; private TicTacToeModel model; protected TicTacToeViewAbstract(TicTacToeModel mo...
I ran a sonar analysis on my code and it told me the cyclomatic complexity is too high (sonar's limit is ten branches). Here is my code: public void myMethod(){ try{ // do something catch(SomeException e){ throw new WrappingException("issue when doing something " + e.getMessage(), e); } catch(AnotherExcep...
Originally I submitted a question here: SerialPort class for a library I cleaned up my code a bit and rewrote a few things. I've had a number of problems along the way and I've still not gotten to test this class, but I'd like to ask if there's anything major I can do to improve it. using System; using System.IO.Ports;...
I wrote this small test. I would love to know if it's possible to achieve the same result in a more "efficient" way. Before any moderator closes this question, it's not subjective because my definition of efficient here means less lines of code and less memory usage. Here is a demo: http://jsfiddle.net/YsjLp/ And here ...
I'm using Twitter Bootstrap's navbar. While testing different screen resolutions, I noticed that on lower resolutions, sometimes the submenu would get cut off by the right side of the page. In the code below, when a dropdown is opened, I'm getting the width of the dropdown menu and dropdown submenu, adding those togeth...
I am using the DatabaseHelper class to execute SQL statements e.g. ExecuteDataReader, ExecuteDataTable etc. The signature for ExecuteReader is: Public Overloads Shared Function ExecuteReader(ByVal connectionString As String, _ ByVal commandType As CommandType, _ ...
In C# I can use DateTime dt = DateTime.Now.Date; This will give the current date, without the TimeSpan value ('00:00:00'). In JavaScript I did this: var dt = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()); But is so "ugly" that there must be a better, easier and clean way to do it.
Abstract I'd like to have advice on how to : implement methods that rely on a state, when the instance is mutable and may be in an inconsistent state, in such a way that the methods either silently fail or return nil, without having to nil guard / coerce state to meaningful values everywhere. Anyway, if my design i...
I recently decided to make a LinkedList and binary search tree using JavaScript. I wanted to reach out to a wider audience and see how I did, and where could I improve. Linked List: var Node = function(value) { this.value = value; this.next=null; return this; }; var LinkedList = function(node){ this.he...
I'm pretty new to coding and I want to get an opinion on my coding. I am learning Python and I made a really simple heads and tails guessing game. import random import time import easygui import sys while True: rand = random.choice(["Heads", "Tails"]) firstguess = raw_input("Guess Heads or Tails: ") if firs...
I am new to the OOP world I have been reading as much as I can about it and have never been more confused. I understand that its great for organizing code and making it more maintainable, etc. I have written some OOP code but I am unsure if its proper, it works fine though. I am confused about public private functions ...
According to shootout.alioth.debian.org, Racket is not much slower than C#, at least in the same order of magnitude due to its JIT compiler. However, I'm seeing at least two degrees of magnitude slowdown in my implementation of the RC4 cipher in C# vs. Racket. (Disclaimer: I am not using RC4, in this case a hilariousl...
I am working on an HTML document to which I need to add certain classes to some elements. In the following code, I am adding class img-responsive. def add_img_class1(img_tag): try: img_tag['class'] = img_tag['class']+' img-responsive' except KeyError: img_tag['class'] = 'img-responsive' r...
Each row in the table has a delete and duplicate operation. The input values are passed to the new section based on the ids of each input on the row which changes dynamically based on the user's actions. The function for recreating the id's of the rows is not so good. I am not to sure how change it. HTML <table> <thea...
Here's an absolutely essential piece of C++ lore, a stack allocator, that will allow you to, say, allocate strings and vectors on the stack. There are 2 stack allocators I know of, here and here. The trouble was, neither of them were working with gcc-4.8, and both needed fixing. Here's a fixed version of Hinant's alloc...
NOTE: I'm not perfectly sure of some of the parsed data, so any corrections are more than welcome. Parser (cpuid.c): #include <stdint.h> #include <string.h> #include "cpuid.h" enum { CPU_PROC_BRAND_STRING_INTERNAL0 = 0x80000003, CPU_PROC_BRAND_STRING_INTERNAL1 = 0x80000004 }; #ifndef _MSC_VER...
I need suggestions. var textarea = document.getElementById("textarea"), filename = prompt("Name this note:", "untitled"); if (filename == null) { window.close(); } else if (filename == "") { filename = "untitled"; }; document.title = filename + ".txt"; function Rename() { // Rename note filename = doc...
I'd like your thoughts on this basic implementation of MVC. The view outputs a form, and when the page is loaded, the controller checks for a form submission and then updates the model accordingly. Finally, the view outputs the form again, grabbing the new values from the model. One problem with this is that if the use...
The background Two beginners without access to an experienced mentor write an ASP .NET MVC application, mostly simple CRUD, using Linq to SQL for the data access layer. Beginner number 1 writes the model part. I, beginner number 2, start writing controllers and views. When using the web and a textbook for learning best...
I've been trying to take image pixel data and write it out into printer code and my results are rather slow. Here is a simplified version of what I have so far (image is a PIL Image object of 1200 x 1800 pixels): # ~36 seconds on beaglebone f.write(pclhead) pix = image.getdata() for y in xrange(1800): row = '\xff'*72...
/** * Upload has a limit of 10 mb * @param string $dir $_SERVER['DOCUMENT_ROOT'] * @param string $path Path do you want to upload the file * @param string $filetype jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx * @param array $_FILES An associative array of items uploaded to the current script via the HT...
Review this code, which should return true if a port is in use or false if the port is not in use. Clarification: "In use" means that the port is already open (and used by another application). I'm trying to find a port number between (49152 and 65535) to open that is available. private boolean isPortInUse(String hostN...
The objective is to increment the page visits by one. The user should not be able to do this by refreshing. The number of visits can be incremented only if the user's last visit was later than 10 minutes or none at all. This should work regardless of multiple users behind the same IP or router. Does this need any impr...
I have this jQuery click handler function that has three jobs: Set the time interval for the refresh rate Change the color on the clicked refresh rate selection Callback the tablesort functions to resort the newly loaded data I'd like to pull out the separate functionality into named functions, but I'm unsure (being ...
I don't intend on implementing this into an application yet as I'm going to test it first. As such, it doesn't do much beyond rolling. It also overloads some "typical" operators such as == and !=. Most of all, I'm still very unsure about my random number generator. I've read about <random>'s std::uniform_int_distrib...
I have one programming question: The sine and cosine of \$x\$ can be computed as follows: \$\sin(x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \frac{x^9}{9!} - \dots\$ \$\cos(x) = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \frac{x^8}{8!} - \dots\$ Your task is to compute the sine and cosine...
I've played with jQuery for some time now but have never written my own plugin. A question was asked: "can I blur an image using jQuery?" and I thought this to be a decent candidate to play with. Here's my code so far: (function ($) { $.fn.blurStuff = function (options) { var defaults = {blurRadius:2, deblu...
I have the following oops code, I am also monitoring user activity to see if it is idle for more than 5 seconds. I am very new to oops, so just want to understand if there are better way to implement it. #!/usr/bin/python import Tkinter import time class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): ...
This is a plugin I wrote a while ago and I'm trying to improve it. Is this the best practice for jQuery plugins? Should I use options for flexibility? The initial aim was to replicate the syntax for .fadeIn() in jQuery. Any pointers would be appreciated. /* AnimateCSS - CSS transitions instead of js */ (function ($, wi...
The code takes in nodes with different start time as input and assigns the position such that they will not overlap. As I have coded with too many loops and conditions. Can anyone review the code and help me to make it efficient? Please do review the algorithm to assign positions to the rectangular blocks. <html> <he...
I wrote this partly as a learning exercise in TDD. Could I please have feedback on both how to improve the quality of the code and the completeness of the tests? I used LinqPad as my IDE for this, the code has no external dependencies (the test framework is included). void Main() { var tests = new SimpleClassTests(...
For the sake of knowledge, I wanted to convert a SQL query to a LINQ query expression. Here is the original SQL: SELECT CT.COURSE_NODE_ID AS CNID, CT.NODE_TEXT FROM COURSE_RELATED_VERSIONS AS CRV INNER JOIN COURSE_TREE AS CT ON CRV.COURSE_NODE_ID = CT.COURSE_NODE_ID WHERE (CRV.COURSE_ID = '38890') AND (CRV.C...
var _ = require("underscore"); var checkSettingsUndefined = function(settings){ if(_.isEmpty(settings)){ throw new Error("settings are empty"); } } var Class = function(settings){ checkSettingsUndefined(settings); this.settings = settings; } Class.prototype.settings = function(){ retur...
This is code from a grappling hook implementation. This is specifically code that, after a block is detected between two way points, it tries to find a path around. This particular piece of the function considers the blocks that are in the way and decides which corners are appropriate to wrap around. The point will al...
A program I wrote isn't performing quite to where I had hoped so I went looking to find where the majority of the time of the program was being spent and it was in the function below so I would like to get some eyes on it to help tune it up and make it run a little quicker. Please note I realize it isn't the most reada...
Is there is better way to do that more efficiently? onCreate(): @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout = new Layout(); Event event = new Event(layout); } Layout and Event: class Layout { publi...
I use this Timer function quite a bit lately for all sorts of stuff, and would appreciate if someone could review/analyze/criticize/verify and, of course, suggest things I can do to optimize it for high frequency execution (mainly animation). My goal was to replicate ActionScript's counterpart (Timer class) and its usa...
I been learning web development for 1.5 month now, and I am trying to improve my code. I can achieve what I want, but I think my code is really bad. For example, I have a bunch of jQuery animations and a bunch of function to 'stop' those animations when another animation is starting. The code seems very inelegant, so h...
The following function takes two numbers that are linked with a "user" and calculates an ID number based on that. I have been trying to make this as clean as possible, and would like some advice on how to make this more efficient. an example of the input would be "12195491" for the num and "3120" for the ts, which wou...
First of all, I am a beginner in Python trying to learn optimizations and proper coding standards. Here is a snippet of code that checks if a number follows the rule: first AND last N digits contain all unique numbers from 1 to N, but in any order. This also means that in either first N or last N digits, each number ap...
The below code is still far from feature complete, but am looking to have some of the sections critiqued to learn better idioms or adjustments (e.g. - yet to be implemented: handling of csv files with headers, exception handling, more robust color labeling for matplotlib graphs, etc.): """ Quantile normalization Licen...
I have this authenticate! method where I am trying to retrieve their account based on the subdomain, then find the user. if user is found & their password is matched, we return success, else fail in all other cases. here is the code: def authenticate! account = Account.find_by(subdomain: subdomain) if account ...
I have the following function to collect quota information for the given user and return the information on a "ready to use" array: /* Get User Quota Information * * Prepare and array with the user's account disk space information * by ascertaining the amount of space available on its quota, * the used space from t...
I am reading hadoop source code , Here I have a doubt "org.apache.hadoop.util.StringUtils" they reassigned a list which is already intiailized. public static Collection<String> getStringCollection(String str){ List<String> values = new ArrayList<String>(); if (str == null) return values; StringToken...
As an exercise in learning Scala, I implemented a square root function like this: def sqrt(x: Double): Double = { if (x < 0) throw new IllegalArgumentException("negative numbers not allowed") val threshold = if (x < 1) x / 1e15 else 1e-12 def sqrt(x: Double, p: Double): Double = { if (p == x / p) p ...
I'm working on my personal project and have recently had a bit of trouble with a method I wrote during the week. This method compares user input from the same JComboBox. A before and after, if you will. It then makes an appropriate adjustment to a 2nd ComboBox depending on the user's input into the first box. It took ...
My class Person has a number of boolean values: isMoving, hasEyesOpen, isTired etc. They are all independent and eight in total. These values are updated from elsewhere every second. The Person stores the last hundred historical values. My code seems to contain a lot of duplication. Is there a better way to write this ...
When a user clicks the "Move Up" button, I grab the current elements procedureid and sortOrder. I then need for "Move Up" to grab the element above it and navigate down to a link inside the <p id="btncontainer"> element and grab that procedureid and sortorder. This seems like a mess to me and I am afraid it could brea...
I've just started learning Java and went to compare my finished product to some others on Stack Overflow. Is there a reason why mine is "simple" and the others seem ridiculously hard to even understand (for me)? Link to the other palindrome checker. Can you just break it down for me (the good/bad/ugly of my code)? Con...
Failing to get a solution to my problem from other people, I got tired of waiting and wrote this (rather rushed) Text class to deal with the text problems I've been having in Pygame. I wanted the text to update itself, so that it would be unnecessary to keep track of its original position. After playing a lot with it, ...
This is a simple program that can tell you your zodiac sign (Chinese or Western) and the year in which you were born. I made this using very basic beginning knowledge with C++ as practice. I'm looking for some quick reviews on my code to see if there is anything I'm doing wrong or could be done better, making sure I'm ...
I have the following code below and I am trying to improve it. How can I know if there is any limitations/drawbacks writing this way and why? Any possible error conditions? What can be improved on this code? Thoughts? Suggestions? <!DOCTYPE html > <html> <head> <meta http-equiv="Content-Type" con...
I'm working on the third Euler problem and I've written a simple little function that returns the list of prime factors of a given number. The number for which I have to get all the factors is over 6 billion, so building this huge freakin list of numbers in memory struck me as wonky. I decided I'd build a factor funct...
I want you to pick my code apart and give me some feedback on how I could make it better or simpler. For a full tree (all nodes with 0 or 2 children) it works deterministically: public class Construct { private TreeNode root; private static class TreeNode { TreeNode left; TreeNode right; ...
I wrote a small program which shows all possible permutations of choosing m integers from the set \${1, 2, ..., n}\$, as follows: def perm(nlist, m): """ Find all possible permutations of choosing m integers from a len(n)-list. INPUT: @para nlist: a list of length n. @para m: a integer. ...
This is my first program in java. I am wondering if there would be a better way to tackle this. I am only allowed to use one class. It's not quite finished, but I am thinking it doesn't look very elegant. import java.io.*; public class CarHire { public static void main(String[] args) throws IOException { ...
Below is the current code which is used to update/insert records from Oracle view to SQL Server table using Dapper. There is not a field to check last record updated date in the oracle view so I have added a method to get hashcode by using property values. Since Oracle table has more than 15k records and each record ha...
All of the class here share these same property Country, Total and Date. Total property are integer in some classes and decimal in some classed. The extension method below has a lot of duplication. i have tried to refactor it using interface but i can't find a way to refactor it at the last step on selection since it n...
I'm trying to implement an inversion counting routine in Scala in a functional way (I don't want to port Java solution) but have real troubles with it. The sorting routine works fine but adding the code to count inversions leads to stack overflow error. Here's the code in question: object FuncSort def streamMerge(...
This is a batch program to xcopy from host PC to remote destination with multi-processing. Kepler, Python-3.x are my environment. #!/usr/bin/env python # -*- coding: utf-8 -*- # based on Carnival http://ask.python.kr/users/6970/carnival/ import os import os.path import csv import re from multiprocessing import Proces...
Just looking for some help reviewing/refactoring. For example, could the classes random/vertical be refactored into 1 class instead of 2? BouncingBalls.java import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.even...
I have implemented an IDataContractSurrogate to enable serialization of ImmutableList<T> (from the Microsoft Immutable Collections BCL) using the DataContractSerialization framework. The code is a bit wild using reflection and compiling of delegates. Are there any subtle improvements or obvious over engineering proble...
Kml uses an 8 digit HEX color format. The traditional Hex format for red looks like #FF0000. In Kml, red would look like this FFFF0000. The first 2 digits are for opacity (alpha). Color format is in AABBGGRR. I was looking for a way to set the color as well as the opacity and return it in a string to be placed in an at...
I am coding a site where users submit sporting events. When submitting an event there are a lot of fields that need to be validated. This is the method I wrote to valid the fields: class event{ private $dbh; private $post_data; public function __construct($post_data, PDO $dbh){ ...
I have a method that returns a List<Object> from any given Object containing its values. It doesn't get the values of any static or final field in the class. public List<Object> objectData(Object object) { Field[] fields = object.getClass().getDeclaredFields(); Set<String> realFields = new LinkedHashSet<String>...
I've written a piece of code. Would like to know is the below piece of code unit testable or does it need any kind of refactoring. MatchCilentUrls is the primary method for matching two urls. Based on my business logic i am matching the Urls. Appreciate your comments on this. public bool MatchClientUrls(string redi...
I'm getting back into web development, and I'm creating a mobile-friendly web app. I'm trying to make it SPA-like in the sense that I don't load new pages for each action the user takes. As my index.cshtml page will show, I have a header, and then I have a bunch of divs. Those divs serve as placeholders for each "page"...
I have been working on a character escaper for a production server that receives quite a few requests per second (sometimes in the range of 400). We forward some "query" requests to apache Lucent/SOLR, and I need to escape characters. Containing also feedback from programmers-stackexchange , the code below is the resul...
I think that the following query is preventing against SQL injection, but what other measures do I need to take to ensure my queries are 100% safe from any malicious attacks? $statement = $db->prepare( "INSERT INTO blogs (blogtitle, blogdesc, coverimage, userID, frontpage, tags) VALUES (:buildtitle, :builddesc...
Here's the query: using (var db = CreateContext()) { // performing the check for HasBeenAdded inline here, is this only one db call? return db.Subjects.Select(s => new SubjectDto(s){HasBeenAdded = db.Interests.Any(x => x.SubjectId == s.SubjectId)}).ToList(); } Basically I crea...
I'm learning C with K&R 2nd Ed. I just completed exercise 1-20 (which is the detab program). I was hoping to get some feedback on my work. I want to make sure that I am taking a good C approach and that my knowledge in other languages isn't bleeding in. /* Exercise 1-20 in K&R 2nd Edition detab: clarified here: http...
I'm writing a somewhat secure voting system. I'm aware that it won't be really secure because it's on the internet so I'm looking for feedback on any logic errors or glaring mistakes in the security implementation. The backend is ExpressionEngine CMS. So, in this system user is allowed to vote anonymously or not anonym...
I want you to pick my code apart and give me some feedback on how I could make it better or more simple. This code will traverse peripheri (clock and anticlockwise) in \$O(n)\$ just traversing the tree once. public class PeriPheri { private TreeNode root; private static class TreeNode { TreeNode left...
I've written this code for a merge sort, which is meant to implement the pseudo-code from Cormen's Introduction to Algorithms: #include <iostream> #include <cstdlib> using namespace std; const unsigned long long infinity = -1ULL; void merge(int* A,int p,const int q, const int r) { const int n_1=q-p+1; const ...
I've been working on a website status checker.. However this array that I use has around 30 sites within it, I've noticed it's taking around 6-7 seconds to load it. I was wondering if there's any kind of way of doing below, but more efficiently. I have thought of doing the below in a cron, and fetching the stored resul...
I have this if statement if (dt.Month > 3 && dt.Month < 11) { if (hours == 23 || (hours >= 0 && hours <= 6)) { session = String.Empty; } else if (hours == 7) { session = String.Empty; } else if (hours >= 8 && hours <= 11) { session = String.Empty; } else i...
I'm working through a Java textbook by Paul and Harvey Deitel and I have come across a review question (Chapter 2 - Intro to Java, Exercise 2.18 for those that have the book) which asks the user to create the following diamond: * * * * * * * * * * * * * * * * I have the follow...
I've been trying to emulate MS Windows behavior on my OS X and close processes that do not have a window. What I'd really like to do is "quit" the process on clicking the red "x" button. Instead, I've managed to code this workaround, which constantly runs in the background. (see my question here) It kind of defeat the...
I have attempted to write a method that checks that images being uploaded are valid. public function checkValidImages(){ $errors = array(); $allowedImages = array('image/jpg','image/jpeg','image/png','img/gif'); $maxFileSize = 2097152; $invalidSize...
I got tired of doing (more or less) this in my rails controllers : class ThingsController < ApplicationController def index @category = Category.find( params[:category_id] ) if params[:category_id].present? scope = @category ? @category.things : Thing.scoped @things = scope.order( :title ) end end .....
I just created a Hangman app (same game mechanics mostly) using Java. I did this mainly to test my knowledge in OOP design/coding. I'd like to know your thoughts on my code The whole project is on Github I would really appreciate the comments and criticism! public class Launcher { private static BufferedReader consoleR...
This is my first attempt at Clojure! Apart from all game related issues, how is my code? Is there anything I can do to make it more idiomatic? (ns hangman.core (:import (java.net ServerSocket Socket SocketException) ...
This is an assignment for an intro to Java course. It works with the test case given, but I would like to know if there is anything / a lot of things that should be different or could be better. Specification: Write a Java application that accepts 5 “valid” numbers from the user. A valid number is between 50 and 100 ...
Link to problem. A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 -> 32 -> 13 -> 10 -> 1 -> 1 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 Therefore any chain that arrives at 1 or 89 will become stuck...
I had to do this in a course a while back: make {1,2,3,4,5,6,7,8,9} into {{1,2,3},{6,5,4},{7,8,9}}. When doing it, I just made the inner for-loop do all the work. But most of my friends had a Boolean and an if-statement to chose between a forward or reverse loop. Which is more optimal and which is more readable? priv...
I've written a little command-line utility for filtering log files. It's like grep, except instead of operating on lines it operates on log4j-style messages, which may span multiple lines, with the first line always including the logging level (TRACE, DEBUG etc.). Example usage on a file short.log with contents like th...